How to store and use opening hour information in flutter firebase? - list

I am building an app in flutter which requires the storage of opening hours in firebase. I have decided to store the data in this format:
0: [9,17], //Monday
1: Null, //Tuesday
Etc Etc. The openingHours field is a list of map values. The key corresponds to the day, then the hours are the value, being a list of integers if open, or a null value if closed. I am struggling however to take the list from the json file from firebase and store it in a list of maps value in flutter, in a class called "business", and similarly upload the data to flutter.
The business object looks like this:
class Business{
String businessId;
String name;
String photoUrl;
Map<int, List<int>> openingHours;
CommentModel({
this.name,
this.businessId,
this.photoUrl,
this.openingHours
});
CommentModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
businessId = json['businessId'];
photoUrl = json['photoUrl'];
openingHours = json['openingHours'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['businessId'] = this.businessId;
data['photoUrl'] = this.photoUrl;
data['openingHours'] = this.openingHours;
return data;
}
}
I am pretty aware I'm quite far off the mark with this one and would appreciate any help before I fully try and implement this into my currently working elsewhere design and cause some irreversible damage XD.

0: {"open": "7:00","close: "20:00"}
1: null,
2: {"open": "7:00","close: "20:00"}

Related

How to store List<DateTime> in variable from firestore all single field time stampdata in flutter?

how to get firestore single field time stamp data to store in a List variable to use in somewhere else that need List?
DocumentReference documentReference =
FirebaseFirestore.instance.collection('crud').doc();
documentReference.get().then((dataSnapshot) {
// Map<String, dynamic> documentFields = snapshot.data.data;
List<DateTime> dateStamp = (dataSnapshot.data()['bookDate'].toDate());
return dateStamp;

How to start with IOTA application

i want to develop an IOTA application, but not a messaging application or coin based system. I want an simple example of how to store data in IOTA. For example i want to build an SCM or even an simple login/registration app. Can anyone guide me? Any sample application? i try to run https://github.com/domschiener/leaderboard-example But getting same error like https://github.com/domschiener/leaderboard-example/issues/6 How to run this.
Storing text data on the tangle is not that difficult. The following are snippets from my tangle-based app. I used IOTA's API Java wrapper library Jota.
1) Connect to IOTA node. You can find a list of nodes here https://nodes.iota.works. Also you can set up your own full node and use it instead of an external one.
final String protocol = "https";
final String url = "tuna.iotasalad.org";
final String port = "14265";
IotaAPI iotaServer = new IotaAPI.Builder().protocol(protocol).host(host).port(port).build();
2) Covert your text into trytes
String trytes = TrytesConverter.toTrytes("my text");
3) Prepare and send transaction to tangle
private static final String SEED = "IHDEENZYITYVYSPKAURUZAQKGVJERUZDJMYTANNZZGPZ9GKWTEOJJ9AAMXOGZNQLSNMFDSQOTZAEETA99";//just a random one
private static final int MIN_WEIGHT_MAGNITUDE = 14;
private static final int DEPTH = 9;
private static final int TAG = "mytag"; //optional
String tangleHash = prepareTransfer(createAddress(), trytes);
public String createAddress() throws ArgumentException {
GetNewAddressResponse res = iotaServer.getNewAddress(SEED, 2, 0, false, 1, false);
return res.getAddresses().get(0);
}
public String prepareTransfer(String address_seclevel_2, String trytes) throws ArgumentException {
List<Transfer> transfers = new ArrayList<Transfer>();
transfers.add(new Transfer(address_seclevel_2, 0, trytes, TAG));
SendTransferResponse str = iotaServer.sendTransfer(SEED, 2, DEPTH, MIN_WEIGHT_MAGNITUDE, transfers, null,
null, false, false);
if(str.getSuccessfully()!=null){
//Transfer successfully!
for(Transaction tx: str.getTransactions()) {
return tx.getHash();
}
}
return "Handle error here. Something went wrong!";
}

#Validate not skipping invalid rows when used with CsvRoutines in UniVocity parser

I am using Univocity parser version 2.7.3. I have a CSV file that has 1 Million records and might grow in future. I am reading only a few specific columns from the file and below are my requirements:
DO NOT store the CSV contents into memory at any point
Ignore/skip bean creation if either of latitude or longitude columns
in CSV are null/blank
To meet these requirements, I tried implementing CsvRoutines so that the CSV data is not copied over to memory. I am using #Validate annotation on both "Latitude" and "Longitude" fields and have used error handler to not throw back any exception so that the record will be skipped on validation failure.
Sample CSV:
#version:1.0
#timestamp:2017-05-29T23:22:22.320Z
#brand:test report
network_name,location_name,location_category,location_address,location_zipcode,location_phone_number,location_latitude,location_longitude,location_city,location_state_name,location_state_abbreviation,location_country,location_country_code,pricing_type,wep_key
"1 Free WiFi","Test Restaurant","Cafe / Restaurant","Marktplatz 18","1233","+41 263 34 05","1212.15","7.51","Basel","test","BE","India","DE","premium",""
"2 Free WiFi","Test Restaurant","Cafe / Restaurant","Zufikerstrasse 1","1111","+41 631 60 00","11.354","8.12","Bremgarten","test","AG","China","CH","premium",""
"3 Free WiFi","Test Restaurant","Cafe / Restaurant","Chemin de la Fontaine 10","1260","+41 22 361 69","12.34","11.23","Nyon","Vaud","VD","Switzerland","CH","premium",""
"!.oist*~","HoistGroup Office","Office","Chemin de I Etang","CH-1211","","","","test","test","GE","Switzerland","CH","premium",""
"test","tess's Takashiro","Cafe / Restaurant","Test 1-10","870-01","097-55-1808","","","Oita","Oita","OITA","Japan","JP","premium","1234B"
TestDTO.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class TestDTO implements Serializable {
#Parsed(field = "location_name")
private String name;
#Parsed(field = "location_address")
private String addressLine1;
#Parsed(field = "location_city")
private String city;
#Parsed(field = "location_state_abbreviation")
private String state;
#Parsed(field = "location_country_code")
private String country;
#Parsed(field = "location_zipcode")
private String postalCode;
#Parsed(field = "location_latitude")
#Validate
private Double latitude;
#Parsed(field = "location_longitude")
#Validate
private Double longitude;
#Parsed(field = "network_name")
private String ssid;
}
Main.java
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.detectFormatAutomatically();
parserSettings.setLineSeparatorDetectionEnabled(true);
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setSkipEmptyLines(true);
parserSettings.selectFields("network_name", "location_name","location_address", "location_zipcode",
"location_latitude", "location_longitude", "location_city","location_state_abbreviation", "location_country_code");
parserSettings.setProcessorErrorHandler(new RowProcessorErrorHandler() {
#Override
public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) {
//do nothing
}
});
CsvRoutines parser = new CsvRoutines(parserSettings);
ResultIterator<TestDTO, ParsingContext> iterator = parser.iterate(TestDTO.class, new FileReader("c:\\users\\...\\test.csv")).iterator();
int i=0;
while(iterator.hasNext()) {
TestDTO dto = iterator.next();
if(dto.getLongitude() == null || dto.getLatitude() == null)
i++;
}
System.out.println("count=="+i);
Problem:
I actually expected the count to be zero since I have added error handler and haven't thrown back the data validation exception but seems thats not the case. I thought #Validate will throw back an exception when it encounters a record with either Latitude or Longitude as null (both the columns may be null in same record as well) which is handled and ignored/skipped at error handler.
Basically I do not want UniVocity to create and map unnecessary DTO objects in heap (and lead to out of memory) since there are chances that the incoming CSV file might have more than 200 or 300k records with either Latitude/Longitude as null.
I even tried adding custom validator in #Validate as well but in vain.
Could someone please let me know what am I missing here?
Author of the library here. You are doing everything right. This is a bug and I just opened this issue here to be resolved today.
The bug appears when you select fields: the reordering of values makes the validation run against something else (in my test, it validated the city instead of latitude).
In your case, just add the following line of code and it will work fine:
parserSettings.setColumnReorderingEnabled(false);
This will make the rows be generated with nulls where fields were not selected, instead of removing the nulls and reordering the values in the parsed row. It will avoid the bug and also make your program run slightly faster.
You will also need to test for null in the iteration bit:
TestDTO dto = iterator.next();
if(dto != null) { // dto may come null here due to validation
if (dto.longitude == null || dto.latitude == null)
i++;
}
}
Hope this helps and thank you for using our parsers!

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());
}
}

Retrieve count of SelectList items?

Problem: I can't access the count of items in a SelectList
I have an HtmlHelper method that returns a SelectList:
public static SelectList FilterSelectList(this HtmlHelper helper, List<Stuff> eList, string dept)
{
List<Stuff> returnList = new List<Stuff>();
//Do Stuff
return new SelectList(returnList, "ID", "Name");
}
I then have a test which confirms that the filter was done correctly:
// Arrange
List<Stuff> eList = MVCMocks.GetList();
string dept = "T";
int expectedCount = eList.FindAll(e => e.Dept == dept).Count;
// Act
var actual = HtmlHelpers.FilterSelectList(helper, eList, dept);
// Assert
Assert.AreEqual(expectedCount, actual.Count, "The list was not properly filtered.");
Calling actual.Count results in an error.
I'm hoping this is just a case of me having a stupid oversight, but I've been banging my head on this for a while. Prove me right! :)
EDIT: Stuff I've Tried
actual.Count
actual.Count()
actual.Items.Count()
actual.GetEnumerator().?
You need actual.Count() (note parens!) not actual.Count.