Flutter convert List<List<dynamic>> - list

I have a Flutter app in which I make an http request, which brings me json data. Afer formatting it with a package I get a list of lists of dynamic type. Here´s what it looks like:
[[2016-04-01, 85.5254], [2016-05-01, 89.1118], [2016-06-01, 91.8528], [2016-07-01, 93.7328], [2016-08-01, 93.9221], [2016-09-01, 95.0014], [2016-10-01, 97.2428], [2016-11-01, 98.8166]]
So I created a class named IpcData, which recieves a String and a double.
class IpcData {
final String date;
final double value;
IpcData(this.date, this.value);
}
So we could guess that an IpcData instance would look like the following:
IpcData(2016-08-01, 93.9221)
I can´t figure out how, but I´d like to have a method that using the information from the List<List<dynamic>> to return a List<IpcData>, that would looke like:
[IpcData(2016-08-01, 93.9221), IpcData(2016-08-01, 93.9221), IpcData(2016-08-01, 93.9221),]

You can use .map function on the original list to construct the new one. Something like this.
class IpcData {
final String date;
final double value;
IpcData(this.date, this.value);
#override
String toString() {
return '$date -> $value';
}
}
void main() {
List<List<dynamic>> initList = [
['2016-04-01', 85.5254], ['2016-05-01', 89.1118], ['2016-06-01', 91.8528],
['2016-07-01', 93.7328], ['2016-08-01', 93.9221], ['2016-09-01', 95.0014],
['2016-10-01', 97.2428], ['2016-11-01', 98.8166], ['2016-12-01', 99.8166]
];
List<IpcData> ipcList = initList.map((e) => IpcData(e[0], e[1])).toList();
print(ipcList);
}

Related

Create List<Dynamic> from List<Stuff>

I am trying to create a .csv file using a List<Stuff> type list. In order to use ListToCsvConverter(), I need a List<Dynamic>.
How do I convert a List<Stuff> to a List<Dynamic> so that I can convert it to .csv with ListToCsvConverter()?
"Stuff" model below:
class Stuff {
int id;
String stuffType;
String stuffSize;
String stuffTime;
Stuff({this.id, this.stuffType, this.stuffSize, this.stuffTime});
}
Your problem is that ListToCsvConverter() is not accepting a List<Stuff> but a List<List<dynamic>>.
The first level List is the list of rows for your csv, while the second level List is the list of cells in each row.
I added a getter csvRow in your Stuff class and map to the rows just before calling ListToCsvConverter():
Full source code:
import 'package:faker/faker.dart';
import 'package:csv/csv.dart';
void main() {
String csv = const ListToCsvConverter()
.convert(stuffList.map((stuff) => stuff.csvRow).toList());
print(csv);
}
class Stuff {
int id;
String stuffType;
String stuffSize;
String stuffTime;
Stuff({this.id, this.stuffType, this.stuffSize, this.stuffTime});
List<dynamic> get csvRow => [id, stuffType, stuffSize, stuffTime];
}
final faker = Faker();
final stuffList = List.generate(
100,
(index) => Stuff(
id: faker.randomGenerator.integer(999999, min: 100000),
stuffType: faker.person.name(),
stuffSize: '${faker.randomGenerator.integer(1000)}MB',
stuffTime: faker.date.toString(),
));
Posting a clear answer for people to see.
Initial List is "stuffList".
How do I convert a List<Stuff> to a List<Dynamic> so that I can convert it to .csv with ListToCsvConverter()?
//Create a new dynamic list
List<List<dynamic>> rows = List<List<dynamic>>();
//Convert stuffList to List<List<dynamic>>
for (int i = 0; i < listStuff.length; i++) {
List<dynamic> row = List();
row.add(listStuff[i].id);
row.add(listStuff[i].stuffType);
row.add(listStuff[i].stuffSize);
row.add(listStuff[i].stuffTime);
rows.add(row);
}
//convert the list to csv
final csv = const ListToCsvConverter().convert(rows);

Check invocation static method on Grails

I have some static method:
class WebUtils {
static httpPostRequest(String url, Map data, Map headers) {
//some code here
}
}
And service:
class ChatService {
void sendMessage(String text) {
//some preparing code
WebUtils.httpPostRequest(url, data, headers)
}
}
Now I want to check invocation of static method in the service by unit-test. Somehow like this:
void "test sending message"() {
given:
String text = 'Test'
def mockedWebUtils = Mock(WebUtils)
when:
service.sendMessage(message)
then:
1*mockedWebUtils.httpPostRequest(_, [text: message], _)
}
But code above is not working. Is there legal way?
Try something like:
void "test sending message"() {
given:
WebUtils.metaClass.static.httpPostRequest = { String url, Map data, Map headers ->
return 'done' // you can do what you want here, just returning a string as example
}
when:
service.sendMessage( 'Test' )
then:
1
// test for something your method has done
}
The correct way is using GroovyMock instead Mock:
void "test sending message"() {
given:
String text = 'Test'
GroovyMock(global:true, WebUtils)
when:
service.sendMessage(text)
then:
1*WebUtils.httpPostRequest(_, [text: text], _)
}
I've found here:http://spockframework.org/spock/docs/1.3-RC1/interaction_based_testing.html#_mocking_static_methods

Using Univocity, how can I convert a date string value to a Date type in Java

I'll like to parse column zero in a csv file to a particular datatype, in this example a Date Object.
The method below is what I use currently to parse a csv file but I don't know how to incorporate this requirement.
import java.sql.Date;
public class Data {
#Parsed(index = 0)
private Date date;
}
}
public <T> List<T> convertFileToData(File file, Class<T> clazz) {
BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
CsvParserSettings settings = new CsvParserSettings();
settings.setProcessor(rowProcessor);
settings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(settings);
parser.parseAll(file);
return rowProcessor.getBeans();
}
All you need is to define the format(s) of your date and you are set:
#Format(formats = {"dd-MMM-yyyy", "yyyy-MM-dd"})
#Parsed(index = 0)
private Date date;
}
As an extra suggestion, you can also replace a lot of your code by using the CsvRoutines class. Try this:
List<T> beanList = new CsvRoutines(settings).parseAll(clazz, file);
Hope it helps.

Neo4j Spring Data Query Builder

Is there a way of dynamically building a cypher query using spring data neo4j?
I have a cypher query that filters my entities similar to this one:
#Query("MATCH (n:Product) WHERE n.name IN {0} return n")
findProductsWithNames(List<String> names);
#Query("MATCH (n:Product) return n")
findProductsWithNames();
When the names list is empty or null i just want to return all products. Therefore my service impl. checks the names array and calls the correct repository method. The given example is looks clean but it really gets ugly once the cypher statements are more complex and the code starts to repeat itself.
You can create your own dynamic Cypher queries and use Neo4jOperations to execute them. Here is it an example (with a query different from your OP) that I think can ilustrate how to do that:
#Autowired
Neo4jOperations template;
public User findBySocialUser(String providerId, String providerUserId) {
String query = "MATCH (n:SocialUser{providerId:{providerId}, providerUserId:{providerUserId}})<-[:HAS]-(user) RETURN user";
final Map<String, Object> paramsMap = ImmutableMap.<String, Object>builder().
put("providerId", providerId).
put("providerUserId", providerUserId).
build();
Map<String, Object> result = template.query(query, paramsMap).singleOrNull();
return (result == null) ? null : (User) template.getDefaultConverter().convert(result.get("user"), User.class);
}
Hope it helps
Handling paging is also possible this way:
#Test
#SuppressWarnings("unchecked")
public void testQueryBuilding() {
String query = "MATCH (n:Product) return n";
Result<Map<String, Object>> result = neo4jTemplate.query(query, Collections.emptyMap());
for (Map<String, Object> r : result.slice(1, 3)) {
Product product = (Product) neo4jTemplate.getDefaultConverter().convert(r.get("n"), Product.class);
System.out.println(product.getUuid());
}
}

How do I provide ObjectContent that is a string

I'm writing a unit test which tests the scenario where a body is sent in the request which is a plain string, i.e. not parseable as JSON.
In this test, I'm setting the HttpRequestMessage something like this:
var ojectContent = new ObjectContent(typeof(string)
, "aaaaa"
, new JsonMediaTypeFormatter());
httpRequestMessage.Content = objectContent;
The problem is, when I debug the code, the request body has been set to "aaaaa" (note the additional quotes) which is enough to cause the deserialisation code to treat the request body differently, meaning I can't test what I mean to test. I need the request body to be aaaaa.
Can anyone advise how I can set up the test so that the request body does not contain these quotes?
Edit: I have also tried new ObjectContent(typeof(object)... and it gives the same result.
Another way is to bypass the MediaTypeFormatter by using StringContent instead of ObjectContent:
var content = new StringContent("aaaaa");
httpRequestMessage.Content = content;
Okay, so I needed to create a media type formatter that didn't interfere with the input in any way. I used this:
private class DoNothingTypeFormatter : MediaTypeFormatter
{
public override bool CanReadType(Type type)
{
return false;
}
public override bool CanWriteType(Type type)
{
if (type == typeof(string))
{
return true;
}
return false;
}
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
var myString = value as string;
if (myString == null)
{
throw new Exception("Everything is supposed to be a string here.");
}
var length = myString.Length;
var bytes = System.Text.Encoding.UTF8.GetBytes(myString);
return Task.Factory.StartNew(() => writeStream.Write(bytes, 0, length));
}
}
Then, when I want to generate the body of the `HttpRequestMessage', I do so like this:
objectContent = new ObjectContent(typeof(string)
, "not json"
, new DoNothingTypeFormatter());