how to sort Array with UnixTime stamp - ios

I want to sort an array by time. But the problem is that the time is in Form UNIX time stamp in the another array (sub array of array).
here is the format. Please can any one help me in sorting it .
(
group,
"The Comic Corner",
""
),
(
group,
"Home Alone",
""
),
(
group,
"Romantic Movies",
""
),
(
group,
"Thriller Movies",
""
),
(
group,
Badminton,
""
),
(
group,
"Celebrity Gossip",
""
),
(
group,
"Dark Night",
""
),
(
group,
"Graphics Designer",
""
),
(
group,
"I Just Wanna....",
""
),
(
group,
Religion,
""
),
(
group,
"English Movies",
""
),
(
group,
"Music World",
""
),
(
group,
"Actions Movies",
""
),
(
group,
"Bed & Breakfast",
""
),
(
group,
"Strategic Games",
""
),
(
group,
"Beer Lovers",
""
),
(
group,
Hackers,
""
),
(
group,
"Darkroom-Darkroom",
""
),
(
group,
"Arcade Games",
""
),
(
group,
"Hindi Movies",
""
),
(
mood,
Anxious,
1386749684146
),
(
"profilepic_time",
1386545975408
),
(
"status_msg",
" *z32_ hell0",
1386635654457
),
(
Broadcast,
3,
11,
1372945566365
),
(
Broadcast,
3,
11,
3
),
(
Broadcast,
3,
11,
3
),
(
Broadcast,
3,
11,
1372858799160
),
(
Broadcast,
6,
11,
1372920363550
),
(
Broadcast,
6,
30,
1373012360303
),
(
Broadcast,
6,
30,
1373015204935
),
(
Broadcast,
6,
30,
1373018547181
),
(
Broadcast,
6,
30,
1373018768064
),
(
Broadcast,
7,
37,
1373025360112
),
(
Broadcast,
3,
37,
1373031270639
),
(
Broadcast,
3,
42,
1373868972980
),
(
Broadcast,
3,
29,
1372936645430
),
(
Broadcast,
3,
29,
1372935983470
),
(
Broadcast,
3,
101,
1374150527293
),
(
bulletin,
"dbxjsbxdijxjdjxichdjdixhdbdjx hdjdbdh",
1382331040766
),
(
bulletin,
"aaabbb ccc dddd eee ffff",
1382510132316
),
(
bulletin,
"dvxishhxxbbosihdjxibididhxososjshsisos dijfjeosksn osjdjkd",
1382510521856
),
(
bulletin,
tsotdo,
1382707279159
),
(
bulletin,
84saurzuzri,
1382707293764
),
(
bulletin,
aiaktsktzyodld,
1382707305875
),
(
bulletin,
uarsistoso,
1382707326326
),
(
bulletin,
2e58e8etisististi,
1382707335278
),
(
bulletin,
ztkzktzgtkktotk,
1382707484453
),
(
bulletin,
ztkzktzgtkktotk9e85a4a47a48a37ariz,
1382707491619
),
(
bulletin,
"dbxidj didcxj",
1384173984019
),
(
bulletin,
"testing testing testing testing",
1384589761276
),
(
bulletin,
"testing testing testing testing",
1384589772960
),
(
bulletin,
"testing testing testing testing",
1384589788706
),
(
bulletin,
"testing testing testing testing",
1384589822861
),
(
bulletin,
"testing testing testing testing",
1384589871332
),
(
bulletin,
"testing testing testing testing",
1384589875364
),
(
bulletin,
"testing testing testing testing",
1384589910927
),
(
bulletin,
hey,
1384589984774
),
(
bulletin,
"heya ",
1384590016235
),
(
bulletin,
ok,
1384597237610
),
(
bulletin,
"hey ",
1384605812061
),
(
bulletin,
fhjfs,
1384757502287
),
There is timestamp for some array and no timestamp for some array
It is very complex for me. Can any one help me with that
Thanks

You need to specify a custom comparator block, like this (you'll need to adjust the indices according to your data structure):
NSArray *array = #[#[#"a", #456], #[#"b", #123], #[#"c", #""]];
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(NSArray *a, NSArray *b) {
if ([a.lastObject isKindOfClass:[NSNumber class]] &&
[b.lastObject isKindOfClass:[NSNumber class]]) {
return [a.lastObject compare:b.lastObject];
}
return NSOrderedAscending;
}];
NSLog(#"%#", sorted);
You can change NSOrderedAscending to NSOrderedDescending if you want the non-timestamped records to appear before the timestamped ones.
In addition, I recommend you to avoid storing your data in NSArray of NSArrays, and create a proper DTO (that can define it's own sorting function, if needed) for your items.

Related

How to handle TextField validation in password in Flutter

I created a login page and I need to add these things to my password. How do I do it with validation alert message?
Minimum 1 Upper case
Minimum 1 lowercase
Minimum 1 Numeric Number
Minimum 1 Special Character
Common Allow Character ( ! # # $ & * ~ )
Your regular expression should look like:
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$
Here is an explanation:
r'^
(?=.*[A-Z]) // should contain at least one upper case
(?=.*[a-z]) // should contain at least one lower case
(?=.*?[0-9]) // should contain at least one digit
(?=.*?[!##\$&*~]) // should contain at least one Special character
.{8,} // Must be at least 8 characters in length
$
Match above expression with your password string. Using this method-
String? validatePassword(String value) {
RegExp regex =
RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$');
if (value.isEmpty) {
return 'Please enter password';
} else {
if (!regex.hasMatch(value)) {
return 'Enter valid password';
} else {
return null;
}
}
}
You need to use Regular Expression to validate the structure.
bool validateStructure(String value){
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value);
}
output:
Vignesh123! : true
vignesh123 : false
VIGNESH123! : false
vignesh# : false
12345678? : false
This function will validate the passed value is having the structure or not.
var _usernameController = TextEditingController();
String _usernameError;
...
#override
Widget build(BuildContext context) {
return
...
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
hintText: "Username", errorText: _usernameError),
style: TextStyle(fontSize: 18.0),
),
Container(
width: double.infinity,
height: 50.0,
child: RaisedButton(
onPressed: validate,
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
color: Theme.of(context).primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
),
),
...
}
...
validate(){
if(!validateStructure(_usernameController.text)){
setState(() {
_usernameError = emailError;
_passwordError = passwordError;
});
// show dialog/snackbar to get user attention.
return;
}
// Continue
}
You have to use TextFormField widget with validator property.
TextFormField(
validator: (value) {
// add your custom validation here.
if (value.isEmpty) {
return 'Please enter some text';
}
if (value.length < 3) {
return 'Must be more than 2 charater';
}
},
),
Take a look on official docs: https://flutter.dev/docs/cookbook/forms/validation
You can achieve this using below flutter plugin.
wc_form_validators
You can use it something like this:
TextFormField(
decoration: InputDecoration(
labelText: 'Password',
),
validator: Validators.compose([
Validators.required('Password is required'),
Validators.patternString(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$', 'Invalid Password')
]),
),
Its documentation is really good. You can read it for more util functions like this.
By using extension in dart
extension PasswordValidator on String {
bool isValidPassword() {
return RegExp(
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$')
.hasMatch(this);
}
}
You can apply this in your textfield like
TextFormField(
autovalidate: true,
validator: (input) => input. isValidPassword() ? null : "Check your password...",
)
here is the complete answer
Write a Dart program to check whether a string is a valid password. a. A password must have at least ten characters. b. A password
consists of only letters and digits. c. A password must contain at
least two digits.
import 'dart:io';
main() {
var password;
stdout.write("Enter You'r Password: ");
password=stdin.readLineSync();
if(password.length>=10 && !password.contains(RegExp(r'\W')) && RegExp(r'\d+\w*\d+').hasMatch(password))
{
print(" \n\t$password is Valid Password");
}
else
{
print("\n\t$password is Invalid Password");
}
Flutter Login Validation
///creating Username and Password Controller.
TextEditingController username=TextEditingController();
TextEditingController password=TextEditingController();
Form(
child: Builder(
builder: (context) {
return Column(
children: [
TextFormField(
controller: username,
validator: (CurrentValue){
var nonNullValue=CurrentValue??'';
if(nonNullValue.isEmpty){
return ("username is required");
}
if(!nonNullValue.contains("#")){
return ("username should contains #");
}
return null;
},
),
TextFormField(
controller: password,
validator: (PassCurrentValue){
RegExp regex=RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$');
var passNonNullValue=PassCurrentValue??"";
if(passNonNullValue.isEmpty){
return ("Password is required");
}
else if(passNonNullValue.length<6){
return ("Password Must be more than 5 characters");
}
else if(!regex.hasMatch(passNonNullValue)){
return ("Password should contain upper,lower,digit and Special character ");
}
return null;
},
),
ElevatedButton(onPressed: (){
if(Form.of(context)?.validate()?? false){
Navigator.of(context).push(MaterialPageRoute(builder: (_)=>loginpage()));
}
}, child: Text("Login"))
],
);
}
),
)
in this picture you can see when you Enter inValid username and password it will not Navigate to another page.
when you Enter Valid Username and Password it will Navigate to another Page.
this is the best regx
bool passValid = RegExp("^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##\$%^&*(),.?:{}|<>]).*").hasMatch(value);
if (value.isEmpty ||!passValid)
{
return 'error';
}

How can i achieve this in flutter?

I'm trying to implement same layout in flutter how can i achieve it, i have already tried using wrap widget but Textfield getting full width and changing textfield width dynamically based on content is not possible
I don't know if this is too late. But this library is exactly what you need. You have all steps on the website.
It's a library called Flutter Chips. There are the steps and I'll put the link from the library too.
https://pub.dev/packages/flutter_chips_input
First of all install the library:
dependencies:
flutter_chips_input: ^1.9.4
Here is the code part:
ChipsInput(
initialValue: [
AppProfile('John Doe', 'jdoe#flutter.io', 'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg')
],
decoration: InputDecoration(
labelText: "Select People",
),
maxChips: 3,
findSuggestions: (String query) {
if (query.length != 0) {
var lowercaseQuery = query.toLowerCase();
return mockResults.where((profile) {
return profile.name.toLowerCase().contains(query.toLowerCase()) || profile.email.toLowerCase().contains(query.toLowerCase());
}).toList(growable: false)
..sort((a, b) => a.name
.toLowerCase()
.indexOf(lowercaseQuery)
.compareTo(b.name.toLowerCase().indexOf(lowercaseQuery)));
} else {
return const <AppProfile>[];
}
},
onChanged: (data) {
print(data);
},
chipBuilder: (context, state, profile) {
return InputChip(
key: ObjectKey(profile),
label: Text(profile.name),
avatar: CircleAvatar(
backgroundImage: NetworkImage(profile.imageUrl),
),
onDeleted: () => state.deleteChip(profile),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
},
suggestionBuilder: (context, state, profile) {
return ListTile(
key: ObjectKey(profile),
leading: CircleAvatar(
backgroundImage: NetworkImage(profile.imageUrl),
),
title: Text(profile.name),
subtitle: Text(profile.email),
onTap: () => state.selectSuggestion(profile),
);
},
)

Flutter reading from JSON if value matches

I have a json of customers:
customer.json
[
{
"name": "Customer 1",
"id": "1"
},
{
"name": "Customer 2",
"id": "2"
},
{
"name": "Customer 3",
"id": "3"
}
]
This is the dart file using this json data:
customerslist.dart
Future Method
Future<String> loadCustomers() async{
var res = await http.get(
Uri.encodeFull(url),
headers: {"Accept": "application/json"});
return res.body;
}
Widget
widgets.add(new FutureBuilder(
future: loadCustomers(),
builder: (context, snapshot){
if(snapshot.hasData){
//get snapshot data from JSON tree
var jsondecode = json.decode(snapshot.data);
return new ListView.builder(
shrinkWrap: true,
itemCount: jsondecode.length,
itemBuilder: (context, index){
String name = jsondecode[index]["name"];
String id = jsondecode[index]["id"];
if(name == "Customer 2"){
return new Column(
children: <Widget>[
new ListTile(
title: new Text("Name"),
trailing: new Text(name),
),
new ListTile(
title: new Text("ID"),
trailing: new Text(id),
)
],
);
}
});
}else{
return new Center(
child: new CircularProgressIndicator(),
);
}
}));
What I am trying to do is bringing out the values if the name matches as you can see from if(name == "Customer 2").
But the problem I am having is:
When i change the if statement to if(name == "Customer 1"), the output is as you would expect:
But if i were to change it to if(name == "Customer 2"), the output turns out blank as such:
Could someone explain why is it turning out like this or is there another method I could go about doing to fix this issue?
I think it's because Column widget is taking full height. You could try using the minimum height for your column and add else condition.
if(name == "Customer 2"){
return new Column(
children: <Widget>[
new ListTile(
title: new Text("Name"),
trailing: new Text(name),
),
new ListTile(
title: new Text("ID"),
trailing: new Text(id),
)
],
);
} else {
return new Container();
}
When you use 'Customer 1' it works fine because your first element is 'Customer 1' , probably you have an error on your console because for other items there are no returning widgets.
In the case of 'Customer 2' the first item is not returned, so check your console log.
itemBuilder expects you return a widget for all the cases.
You just convert the var string to list
var jsondecode = json.decode(snapshot.data);
List list = jsondecode;
String name = list[index]["name"];
String id = list[index]["id"];
then pass the list to get the index may be this will work bocasue the var type may be get the first json string only
enter code here

Flutter: 'NoSuchMethodError' is not a subtype of type String

I currently have an app that pulls a list of providers through JSON.
This is the JSON file.
hospitals.json
{
"Johor": [
{
"Name": "KLINIK TAJ (MUAR)",
"TPA Customer ID": "1168",
"Organization Type": "Clinic",
"Organization Subtype": "GP",
"Street (Billing)": "35a, jalan abdullah ",
"City (Billing)": "muar",
"Postal Code (Billing)": "84000",
"State (Billing)": "Johor",
"Country (Billing)": "Malaysia",
"Coordinates": {
"Latitude": "2.041875",
"Longitude": "102.568235"
}
},
{
"Name": "KLINIK TAJ (PAGOH)",
"TPA Customer ID": "1169",
"Organization Type": "Clinic",
"Organization Subtype": "GP",
"Street (Billing)": "100 Main Road Pagoh",
"City (Billing)": "Muar",
"Postal Code (Billing)": "84600",
"State (Billing)": "Johor",
"Country (Billing)": "Malaysia",
"Coordinates": {
"Latitude": "2.148342",
"Longitude": "102.771002"
}
}
],
"Kedah": [
{
"Name": "KLINIK TAN",
"TPA Customer ID": "8423",
"Organization Type": "Clinic",
"Organization Subtype": "GP",
"Street (Billing)": "62 Jalan Raya",
"City (Billing)": "Kulim",
"Postal Code (Billing)": "9000",
"State (Billing)": "Kedah",
"Coordinates": {
"Latitude": "5.366739",
"Longitude": "100.553988"
}
},
{
"Name": "KLINIK SHAN",
"TPA Customer ID": "1685",
"Organization Type": "Clinic",
"Organization Subtype": "GP",
"Street (Billing)": "L. C. 19, Jalan Lunas,",
"City (Billing)": "Padang Serai",
"Postal Code (Billing)": "9000",
"State (Billing)": "Kedah",
"Coordinates": {
"Latitude": "5.402193",
"Longitude": "100.555209"
}
}
]
}
This is the model class of the JSON
new_accounts_model.dart
class Johor {
List<AccountInfo> accountinfo;
Johor({this.accountinfo});
factory Johor.fromJson(Map<String, dynamic> json){
var accJson = json["Johor"] as List;
List<AccountInfo> accList = accJson.map((i) => AccountInfo.fromJson(i)).toList();
return Johor(
accountinfo: accList
);
}
}
class AccountInfo{
String name;
String id;
String orgtype;
String subtype;
String street;
String city;
String country;
Coordinates coordinates;
AccountInfo({this.name, this.id, this.orgtype, this.subtype, this.street, this.city, this.country, this.coordinates});
factory AccountInfo.fromJson(Map<String, dynamic> json){
return AccountInfo(
name: json["Name"],
id: json["TPA Customer ID"],
orgtype: json["Organization Type"],
subtype: json["Organization Subtype"],
street: json["Street (Billing)"],
city: json["City (Billing)"],
country: json["State (Billing)"],
coordinates: Coordinates.fromJson(json["Coordinate"])
);
}
}
class Coordinates{
String lat;
String lng;
Coordinates({this.lat, this.lng});
factory Coordinates.fromJson(Map<String, dynamic> json){
return Coordinates(
lat: json["Latitude"],
lng: json["Longitude"]
);
}
}
And this is the dart file used to bring out the JSON file.
list.dart
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:emas_app/model/new_accounts_model.dart';
Future<String> _loadAsset() async{
return await rootBundle.loadString('Assets/hospitals.json');
}
//Not working future
Future<Johor> loadJohor() async{
final response = await _loadAsset();
final jsonResponse = json.decode(response);
Johor johor = new Johor.fromJson(jsonResponse);
return johor;
}
class ProviderList extends StatefulWidget {
#override
ListState createState() {
return new ListState();
}
}
class ListState extends State<ProviderList> {
#override
Widget build(BuildContext context) {
List<Widget> widgets = [];
launchMapUrl(String lat, String lng) async{
String geoUri = "https://maps.google.com/maps?q=loc:$lat,$lng";
if (await canLaunch(geoUri)) {
print("Can launch");
await launch(geoUri);
} else {
print("Could not launch");
throw 'Could not launch Maps';
}
}
//method to bring out dialog
makeDialog(String address){
showDialog(
context: context,
builder: (_) => new SimpleDialog(
contentPadding: EdgeInsets.only(left: 30.0, top: 30.0),
children: <Widget>[
new Text("Address: $address",
style: TextStyle(
fontWeight: FontWeight.bold
),
),
new ButtonBar(
children: <Widget>[
new IconButton(
icon: Icon(Icons.close),
onPressed: (){
Navigator.pop(context);
}
)
],
)
],
)
);
}
widgets.add(new ExpansionTile(
title: new Text("Not working state"),
children: <Widget>[
new FutureBuilder<Johor>(
future: loadJohor(),
builder: (context, snapshot){
if(snapshot.hasData){
return new ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.accountinfo.length,
itemBuilder: (context, index){
String username = snapshot.data.accountinfo[index].name;
String address = snapshot.data.accountinfo[index].street;
String lat = snapshot.data.accountinfo[index].coordinates.lat;
String lng = snapshot.data.accountinfo[index].coordinates.lng;
return new ListTile(
title: new Text(username),
trailing: new Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new IconButton(
icon: Icon(Icons.info),
onPressed: (){
makeDialog(address);
}
),
new IconButton(
icon: Icon(Icons.directions),
onPressed: (){
launchMapUrl(lat, lng);
}
)
],
)
);
});
}else if(snapshot.hasError){
return new Center(
child: new Text(snapshot.error),
);
}
})
]
));
//empty list
widgets.add(new ExpansionTile(
title: new Text("Pahang")));
return new Scaffold(
appBar: new AppBar(title: new Text("Providers")),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: widgets,
)
);
}
}
This is the error currently faced:
As the title says, the error is saying its a NoSuchMethodError. Therefore I am unsure as to what is causing this error in the first place.
My current guess is that I am not doing the Model class correctly but it could be something else.
I could really use some help in this case.
You are using wrong key for Coordinates.
You should use Coordinates as its name of key in json. But you are using Coordinate in method factory AccountInfo.fromJson
Update your last line of that method
coordinates: Coordinates.fromJson(json["Coordinates"])

How to include CJuiAutoComplete in a CGridView filter?

I have a grid view that lists contents of a table, table has column author_id.
Now I'm displaying usernames using relation name column syntax author.username.
Is it possible to allow user to type in a username in column filter, with support of CJuiAutoComplete, some examples hints?
My code sample:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->with('author')->search(),
'filter'=>$model,
'columns'=>array(
// ...
array(
'name'=>'author.username',
'filter'=> // ?
),
// ...
),
));
The widget has a 3rd parameter that can be set to true which means that will return a string and will not render the widget CJuiAutoComplete.
widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->with('author')->search(),
'filter'=>$model,
'columns'=>array(
// ...
array(
'name'=>'author.username',
'filter'=> $this->widget('zii.widgets.jui.CJuiAutoComplete', $array_params, true),
),
// ...
),
));
and $array_params can be replaced with similar as following ex :
array(
'name'=>'author_username',
//'model'=>$model,
'attribute'=>'city_eve',
'sourceUrl'=>"/controller/action/",
'options'=>array(
'minLength'=>'2',
),
'htmlOptions'=>array(
'size'=>'36'
),
)
and also you have to put in your model search method some checks :
if($request->getQuery("author_username")){
$criteria->addCondition(author.username=:author_username");
$criteria->params[':author_username'] = $request->getQuery("author_username");
}

Resources