Is there a better way to do this? - scala-2.8

so i have this piece of xml code
<schedule>
<teacher name="Charles Xavier">
<activities>
<activity init="7:00" end="7:50" alias="1st period">
<days>
<monday></monday>
<tuesday>room 102</tuesday>
<wednesday></wednesday>
<thursday></thursday>
<friday>room 101</friday>
</days>
</activity>
<activity init="8:00" end="8:50" alias="2nd period">
<days>
<monday></monday>
<tuesday></tuesday>
<wednesday>room 101</wednesday>
<thursday></thursday>
<friday>room 103</friday>
</days>
</activity>
</activities>
</teacher>
<teacher name="Moira McTaggert">
<activities>
<activity init="7:00" end="7:50" alias="1st period">
<days>
<monday></monday>
<tuesday>room 102</tuesday>
<wednesday>room 102</wednesday>
<thursday>room 104</thursday>
<friday>room 101</friday>
</days>
</activity>
<activity init="8:00" end="8:50" alias="2nd period">
<days>
<monday>room 102</monday>
<tuesday>room 102</tuesday>
<wednesday>room 103</wednesday>
<thursday>room 104</thursday>
<friday>room 103</friday>
</days>
</activity>
</activities>
</teacher>
</schedule>
and scala code so far is
object WeekDay extends Enumeration("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") {
type WeekDay = Value
val Monday, Tuesday, Wednesday, Thursday, Friday = Value
}
class Teacher {
var name: String = _
var activities: ListBuffer[Activity] = _
}
class Activity {
var init: String = _
var end: String = _
var alias: String = _
var days: List[Day] = List(new Day(WeekDay.Monday), new Day(WeekDay.Tuesday), new Day(WeekDay.Wednesday),
new Day(WeekDay.Thursday), new Day(WeekDay.Friday))
}
class Day(val day: WeekDay) {
var room: String = _
}
i think this way feels very "imperative" can it be more scala code?
in the end what im trying to accomplish is a method(see below) like this, so any hints about best way to tackle this would be appreciated.
var overlappedRooms = teachers.getOverlappedRooms("7:00", WeekDay.Tuesday)
this should give us some info saying that Charles xavier's room 102 is overlapped by Moira's room 102
Note. this is just a learning purposes project. :)

Many Scala proponents try to avoid mutable objects, although some go overboard IMHO. You could try this sort of thing:
class Teacher(val name:String)
class Activity(
val init:String,
val end:String,
val alias:String,
val days:List[Day])
type Roster: Map[Teacher, List[Activity]]
Note I've moved rostering out of Teacher, since it is not really a property of a teacher. You might consider a new class for it. Possibly Activity needs to be considered separately from the days it is on too. I'm not sure why your Day class has 'room' in it. I suspect your object modelling needs some help here.

Related

Convert datetime to other runtimetype in flutter app

I'm trying to convert a DateTime runtimetype value to Expression<DateTime, DateTimeType>. I've been trying to achieve this for almost three days now. I have tried different approaches but non is working.
The reason I want to achieve this is because moor_flutter library in some cases uses and accepts the library's custom runtimetypes on methods and and the parameter values on those methods.
Below is the sample code;
final DateTime dateToday = new DateTime.now(); // convert DateTime to Expression<DateTime, DateTimeType>
var dateWithNewRuntimetype; // assign the converted value to this variable
I thought I fixed this issue by adding as as Expression<DateTime, DateTimeType> to the value of dateWithNewRuntimetype variable value but no this is not the solution either.
The solution will work on the code below
Stream<List> getLoansWithTomorrowDueDate(int dayInFuture) {
return (select(loans)
..where((l) => l.due_date.isBetween(
dateToday, // it should be Expression<DateTime, DateTimeType> not DateTIme
futureDate, // it should be Expression<DateTime, DateTimeType> not DateTIme)))
.watch();
}
If you want me to provide more info on this I will do so.
Thank you, so much Love.
The isBetween is compared withSqlType.
You must use isBetweenValues.
/// Defines extension functions to express comparisons in sql
extension ComparableExpr<DT, ST extends ComparableType<DT>>
on Expression<DT, ST> {
Expression<bool, BoolType> isBetween(
Expression<DT, ST> lower, Expression<DT, ST> higher,
{bool not = false});
Expression<bool, BoolType> isBetweenValues(DT lower, DT higher,
{bool not = false});
}

How to display month using ```DateTime``` in flutter

I have a calendar where i want to display the month above the calendar. Is there anyway to display only the current month?
(credits to https://github.com/adamstyrc/ for the image)
it should look like this :
Use the below package for DateFormat.
https://pub.dev/packages/intl
String returnMonth(DateTime date) {
return new DateFormat.MMMM().format(date);
}
Just pass the date, the function will return Month. For ex. April,January
Get intl dependency from here pubdev-intl.
Import the dependency by adding it to pubspec.yaml.
import 'package:intl/intl.dart';
List months =
['jan', 'feb', 'mar', 'apr', 'may','jun','jul','aug','sep','oct','nov','dec'];
var now = new DateTime.now();
current_mon = now.month;
print(months[current_mon-1]);
It´s very easy with date_formatter;
Install date_format: ^2.0.2 in pubspec. link
use this code:
String returnThisMonth(){
var month = DateTime.now();
final formatted = formatDate(month, [mm]);
print(formatted);
return formatted;
}
It will return you a string like 01, 02, 03, as january, february or march. Then you can use it freely.
You can try table_calendar from the pub which is fully customizable and also you can able get current date current month selected date
table_calender
You can use the DateFormat class:
String getMonth(int currentMonthIndex) {
return DateFormat('MMM').format(DateTime(0, currentMonthIndex)).toString();
}
//currentMonthIndex 1 => "Jan", 2 => "Feb", ...
The docs give a list of all skeletons (M, MMM, m, MMMM) and named constructors that can be used. ex. (MONTH, NUM_MONTH, ABBR_MONTH)
So alternatively:
String languageCode = Localizations.localeOf(context).languageCode;
DateFormat dateformat1 = DateFormat.MMMM(languageCode);
DateFormat dateformat2 = DateFormat.MMM(languageCode);
String this_month = dateformat1.format(DateTime.now());
//ex => August
String next_month = dateformat2.format(DateTime.now().add(Duration(days: 30)));
//ex => Sep

How do I convert a date/time string to a DateTime object in Dart?

Say I have a string
"1974-03-20 00:00:00.000"
It is created using DateTime.now(),
how do I convert the string back to a DateTime object?
DateTime has a parse method
var parsedDate = DateTime.parse('1974-03-20 00:00:00.000');
https://api.dartlang.org/stable/dart-core/DateTime/parse.html
There seem to be a lot of questions about parsing timestamp strings into DateTime. I will try to give a more general answer so that future questions can be directed here.
Your timestamp is in an ISO format. Examples: 1999-04-23, 1999-04-23 13:45:56Z, 19990423T134556.789. In this case, you can use DateTime.parse or DateTime.tryParse. (See the DateTime.parse documentation for the precise set of allowed inputs.)
Your timestamp is in a standard HTTP format. Examples: Fri, 23 Apr 1999 13:45:56 GMT, Friday, 23-Apr-99 13:45:56 GMT, Fri Apr 23 13:45:56 1999. In this case, you can use dart:io's HttpDate.parse function.
Your timestamp is in some local format. Examples: 23/4/1999, 4/23/99, April 23, 1999. You can use package:intl's DateFormat class and provide a pattern specifying how to parse the string:
import 'package:intl/intl.dart';
...
var dmyString = '23/4/1999';
var dateTime1 = DateFormat('d/M/y').parse(dmyString);
var mdyString = '04/23/99';
var dateTime2 = DateFormat('MM/dd/yy').parse(mdyString);
var mdyFullString = 'April 23, 1999';
var dateTime3 = DateFormat('MMMM d, y', 'en_US').parse(mdyFullString));
See the DateFormat documentation for more information about the pattern syntax.
DateFormat limitations:
DateFormat cannot parse dates that lack explicit field separators. For such cases, you can resort to using regular expressions (see below).
Prior to version 0.17.0 of package:intl, yy did not follow the -80/+20 rule that the documentation describes for inferring the century, so if you use a 2-digit year, you might need to adjust the century afterward.
As of writing, DateFormat does not support time zones. If you need to deal with time zones, you will need to handle them separately.
Last resort: If your timestamps are in a fixed, known, numeric format, you always can use regular expressions to parse them manually:
var dmyString = '23/4/1999';
var re = RegExp(
r'^'
r'(?<day>[0-9]{1,2})'
r'/'
r'(?<month>[0-9]{1,2})'
r'/'
r'(?<year>[0-9]{4,})'
r'$',
);
var match = re.firstMatch(dmyString);
if (match == null) {
throw FormatException('Unrecognized date format');
}
var dateTime4 = DateTime(
int.parse(match.namedGroup('year')!),
int.parse(match.namedGroup('month')!),
int.parse(match.namedGroup('day')!),
);
See https://stackoverflow.com/a/63402975/ for another example.
(I mention using regular expressions for completeness. There are many more points for failure with this approach, so I do not recommend it unless there's no other choice. DateFormat usually should be sufficient.)
import 'package:intl/intl.dart';
DateTime brazilianDate = new DateFormat("dd/MM/yyyy").parse("11/11/2011");
you can just use : DateTime.parse("your date string");
for any extra formating, you can use "Intl" package.
void main() {
var dateValid = "30/08/2020";
print(convertDateTimePtBR(dateValid));
}
DateTime convertDateTimePtBR(String validade)
{
DateTime parsedDate = DateTime.parse('0001-11-30 00:00:00.000');
List<String> validadeSplit = validade.split('/');
if(validadeSplit.length > 1)
{
String day = validadeSplit[0].toString();
String month = validadeSplit[1].toString();
String year = validadeSplit[2].toString();
parsedDate = DateTime.parse('$year-$month-$day 00:00:00.000');
}
return parsedDate;
}
a string can be parsed to DateTime object using Dart default function DateTime.parse("string");
final parsedDate = DateTime.parse("1974-03-20 00:00:00.000");
Example on Dart Pad
String dateFormatter(date) {
date = date.split('-');
DateFormat dateFormat = DateFormat("yMMMd");
String format = dateFormat.format(DateTime(int.parse(date[0]), int.parse(date[1]), int.parse(date[2])));
return format;
}
I solved this by creating, on the C# server side, this attribute:
using Newtonsoft.Json.Converters;
public class DartDateTimeConverter : IsoDateTimeConverter
{
public DartDateTimeConverter()
{
DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
}
}
and I use it like this:
[JsonConverter(converterType: typeof(DartDateTimeConverter))]
public DateTimeOffset CreatedOn { get; set; }
Internally, the precision is stored, but the Dart app consuming it gets an ISO8601 format with the right precision.
HTH

How to format DateTime to local users locale in short time format using MonoTouch

I've tried multiple approaches, this is one of them:
System.Globalization.DateTimeFormatInfo format = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
return dt.Value.ToString (format.ShortTimePattern);
The problem with this one is that .NET 3.5 returns a "." as the time seperator which is most likely a bug (since my Norwegian locale uses a colon):
.NET (3.5) formats times using dots instead of colons as TimeSeparator for it-IT culture?
I also looked here:
Retrieving current local time on iPhone?
But MT doesn't seem to have setTimeStyle on the NSDateFormatter?
So, anyone have any magic tricks up their sleeves?
My goal is to output:
21:00 / 9:00 PM
10:09 / 10:09 AM
like the statusbar in iPhone.
Try this:
var formatter = new NSDateFormatter ();
formatter.TimeStyle = NSDateFormatterStyle.Short;
Console.WriteLine (formatter.ToString (DateTime.Now));
That said, the bug with dot/colon as the time separator for Norwegian locales has been fixed in Mono 2.12, so when MonoTouch switches to use Mono 2.12 instead of Mono 2.10 (hopefully early next year) you will be able to use this managed alternative too:
Console.WriteLine (DateTime.Now.ToString (new CultureInfo ("nb-NO").DateTimeFormat.ShortTimePattern));
I made a small research on mono sources and found that ShortTimePattern and TimeSeperator are not relate on each other (please Mono-guru's correct me if I'm wrong).
So, I tried to make iOS-only (not cross-platform) solution. That is is:
using MonoTouch.Foundation;
...
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
var d = DateTime.Now;
Console.WriteLine("NSDate: " + GetCorrectTime(d));
}
...
// iOS-only (not cross-platform)
public string GetCorrectTime (DateTime d)
{
var nsdate = DateTimeToNSDate(d);
var nsdateformatter = new .NSDateFormatter();
nsdateformatter.DateStyle = NSDateFormatterStyle.None;
nsdateformatter.TimeStyle = NSDateFormatterStyle.Short;
return nsdateformatter.ToString(nsdate);
}
...
// DateTime to NSDate was taken from [that post][2]
public static NSDate DateTimeToNSDate(DateTime date)
{
return NSDate.FromTimeIntervalSinceReferenceDate((date-(new DateTime(2001,1,1,0,0,0))).TotalSeconds);
}
Output:
NSDate: 17:40
Please note that I'd test it with simulator and "nn-NO" (Norwegian Nynorsk (Norway)) locale.

regexp not working...arghhhh

I'm using Flex 4. I'm driving myself crazy. Why won't the following work?
// in my Application tag:
creationComplete="replaceMe(event)"
// in my script block:
public function replaceMe(event:Event):void{
var str:String = "She sells seashells by the seashore.";
var pattern:RegExp = /sh/gi;
str.replace(pattern, "sch");
test.text = str;
}
my text area (id="test") says "She sells seashells by the seashore."...
it should say "sche sells seaschells by the seaschore."
Because Strings are immutable objects. So, str.replace() just returns new string, without modifying str. Try
str = str.replace(pattern, "sch")
Assign the new string value back to the old string like so:
str = str.replace(pattern, "sch");
Edit: Dzmitry answered first. =P

Resources