Getting date value from an array hash - ruby

I have a hash that looks like
tagArray = { :"2014Date"=>["11/22/2014"], :"2015Date"=>["03/21/2015"] }
Since i already know for a given key, there is only one element in the array of 'values', how can you get just the value not as an array?
value = tagArray[:"2015Date"]
=>
value = ["04/12/2015"]
You can just index the array then and get the date like
value = value.fetch(0).to_s
=>
value = "04/12/2015"
However I am looking for a more elegant way of doing it.
Note: I am using Ruby 2.2, so need to 'strp' the date first to change it from mm/dd/yyyy format which is the end goal.

This is a bit simpler:
value = tagArray[:"2015Date"].last
=>
value = "03/21/2015"

Related

flutter Sorting arraylist by Date

In My streamBuilder I have Array list contains dates having format(dd-MM-yyyy).
I want to arrange the list in ascending order.
The code I used in StreamBuilder after getting Datasnapshot
Map<dynamic, dynamic> data = snap.data.snapshot.value;
List item = [];
data.forEach(
(index, data) => item.add(
{"key": index, ...data}
)
);
item..sort((a,b)=>a['key'].compareTo(b['key']));
I am expecting result as
16-06-2020
17-06-2020
18-06-2020
19-06-2020
22-06-2020
04-07-2020
The result I am getting is
04-07-2020
16-06-2020
17-06-2020
18-06-2020
19-06-2020
22-06-2020
You'll need to parse your Strings to DateTimes. Since DateTime parse() method won't accept Strings in the format you provided, you can do something like this:
List<String> strings = ['04-07-2020', '17-06-2020', '16-06-2020', '19-06-2020', '18-06-2020', '22-06-2020'];
List<DateTime> dateTimes = [];
strings.forEach((string) {
var splitted = string.split('-');
var day = splitted[0];
var month = splitted[1];
var year = splitted[2];
var formatted = '$year-$month-$day';
dateTimes.add(DateTime.parse(formatted));
});
dateTimes.sort((a, b) => a.compareTo(b));
Just adapt it for your structure!
Storing the data as Timestamps in Firebase would make it much simpler, then you can sort it by this Timestamp.
If you need the dates formatted as a String (dd-MM-yyyy) you can just parse it to Datetime and use the Intl-Package to convert it to a formatted String.

Converting epoch time to date in logstash using ruby filter

I have a field name "timestamp" in my configuration. It holds an array of data in epoch time (miliseconds). I want to use Ruby filter to convert each epoch time in the array and convert into Date format consumable by Kibana. I am trying to convert each date field and store in a new field as an array. I am getting syntax errors. Can anyone help me out ? I am new to Ruby.
ruby {
code => {'
event.get("timestamp").each do |x| {
event["timestamp1"] = Time.at(x)
}
'}
}
I don't know about logstash, but the Ruby code you include within quotes is invalid. Try this:
ruby {
code => {'
event.get("timestamp").each { |x| event["timestamp1"] = Time.at(x) }
'}
}
If you intend your timestamp key to increment, then you need to include an index:
ruby {
code => {'
event.get("timestamp").each_with_index { |x, i| event["timestamp#{i}"] = Time.at(x) }
'}
}
//This will take an timestamp array with values in milliseconds from epoch time and create a new field with parsed time. This code is part of ruby filter Note : This does not convert into Date field format
code => '
timestamps = Array.new
event.get("timestamp").each_with_index { |x, i|
timestamps.push(Time.at(x.to_i / 1000)) }
event.set( "timestamp1" , timestamps)
'

RadSpreadsheet Cell Values for DateTime returning Number values (Telerik)

I have a CSV file with Dates ("MM/DD/YYYY"). I wish to parse these values within the active worksheet as string values, but they're converted to number format (i.e. "22532"). I'm unable to get these values in the original string format.
CellSelection selection = sheet.Cells[0, 0];
ICellValue value = selection.GetValue().Value;
Is it possible to ensure all cell values are in String format, representing exactly how they are in a CSV file?
You could use the following code:
CellSelection selection = sheet.Cells[0, 0];
string value = selection.GetValue().Value.GetResultValueAsString(new CellValueFormat("mm/d/yyyy"));
This will return a string formatted as a date. In the case with "22532" the result will be "09/8/1961".
This is not the exact answer you are looking for, but you can convert the int value to a datetime with the following code:
public static DateTime FromExcelSerialDate(this int serialDate)
{
if (serialDate > 59) serialDate -= 1; //Excel/Lotus 2/29/1900 bug
return new DateTime(1899, 12, 31).AddDays(serialDate);
}

Set array elements (string) as variable name in Ruby

I have the following array, that I use to later write the header on an Excel file.
fields = ["fileName", "type", "id"]
And then I have the following code that reads values from an XML:
filename = xml.xpath('//path/filename').text
type = xml.xpath('//path/type').text
id = xml.xpath('//path/id').text
The I iterate the initial array (fields) in order to set the Excel cells to the values extracted in the previous step:
row = 2
c = 1
fields.each do |content|
ws.Cells(row,c).Value = content
c = c + 1
I'm trying to have the array's (fields) contents to variable names instead of strings in order to be able to reuse the head fields.
Can anyone recommend a way of making it possible?
This sounds like you need to use a Hash to associate field names to the values you extracted:
fields = {
"fileName" => xml.xpath('//path/filename').text,
"type" => xml.xpath('//path/type').text,
"id" => xml.xpath('//path/id').text
}
row=2
c=1
fields.each do |key,value|
ws.Cells(row,c).Value = value
c=c+1
end

How to order integers according to size and track their positions by variable name

I have a program with multiple int variables where individual counts are added to the specific variable each time a set fail condition is encountered. I want the user to be able to track how many failures of each category they have encountered by a button click. I want to display the range on a datagridview in order from highest value integer down to lowest. I also need to display in the adjacent column the name of the test step that relates to the value. My plan was to use Array.sort to order the integers but i then lose track of their names so cant assign the adjacent string column. I tried using a hashtable but if i use the string as a key it sorts alphabetically not numerically and if i use the integer as a key i get duplicate entries which dont get added to the hash table. here is some of the examples i tried but they have the aforementioned problems. essentially i want to end with two arrays where the order matches the naming and value convention. FYI the variables were declared before this section of code, variables ending in x are the string name for the (non x) value of the integer.
Hashtable sorter = new Hashtable();
sorter[download] = downloadx;
sorter[power] = powerx;
sorter[phase] = phasex;
sorter[eeprom] = eepromx;
sorter[upulse] = upulsex;
sorter[vpulse] = vpulsex;
sorter[wpulse] = wpulsex;
sorter[volts] = voltsx;
sorter[current] = currentx;
sorter[ad] = adx;
sorter[comms] = commsx;
sorter[ntc] = ntcx;
sorter[prt] = prtx;
string list = "";
string[] names = new string[13];
foreach (DictionaryEntry child in sorter)
{
list += child.Value.ToString() + "z";
}
int[] ordered = new int[] { download, power, phase, eeprom, upulse, vpulse, wpulse, volts, current, ad, comms, ntc, prt };
Array.Sort(ordered);
Array.Reverse(ordered);
for (int i = 0; i < sorter.Count; i++)
{
int pos = list.IndexOf("z");
names[i] = list.Substring(0, pos);
list = list.Substring(pos + 1);
}
First question here so hope its not too longwinded.
Thanks
Use a Dictionary. And you can order it by the value : myDico.OrderBy(x => x.Value).Reverse(), the sort will be numerical descending. You just have to enumerate the result.
I hope I understand your need. Otherwise ignore me.
You want to be using a
Dictionary <string, int>
to store your numbers.I'm not clear on how you're displaying results at the end - do you have a grid or a list control?
You ask about usings. Which ones do you already have?
EDIT for .NET 2.0
There might be a more elegant solution, but you could implement the logic by putting your rows in a DataTable. Then you can make a DataView of that table and sort by whichever column you like, ascending or descending.
See http://msdn.microsoft.com/en-us/library/system.data.dataview(v=VS.80).aspx for example.
EDIT for .NET 3.5 and higher
As far as sorting a Dictionary by its values:
var sortedEntries = myDictionary.OrderBy(pair => pair.Value);
If you need the results to be a Dictionary, you can call .ToDictionary() on that. For reverse order, use .OrderByDescending(pair => pair.Value).

Resources