问:
BottomNavigationView Does not work
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

```<code>setContentView(R.layout.activity_main);
</code>```

this is my code ( I did not do anything yet )

Main.java

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

xml file :

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

And Menu :

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />
</code>```

and finally dependacies :

```<code> implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'
</code>```

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

答:
There is Typing mistake channge <sandroid to <android

Use this

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

Instead of

```<code><sandroid.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

EDIT

use this

```<code>app:menu="@menu/bottom_navigation_main"
</code>```

instead of this

```<code>Design:menu="@menu/menu_nav">
</code>```

Title: BottomNavigationView Does not work

Body:
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

setContentView(R.layout.activity_main);

this is my code ( I did not do anything yet )

Main.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

xml file :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

And Menu :

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />

and finally dependacies :

 implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

Body:
There is Typing mistake channge <sandroid to <android

Use this

<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

Instead of

<sandroid.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

EDIT

use this

app:menu="@menu/bottom_navigation_main"

instead of this

Design:menu="@menu/menu_nav">


来源: stackexchange

问:
Amazon Echo Account Linking - how to identify echo device when generating and saving token?
I have a pre-existing web app with user accounts. I want to extend functionality with Amazon's echo.

When the user enables the skill in their Echo/Alexa dashboard, it will redirect them to the login page of my app with Authorization URL https://foo.com/auth.

I checked the incoming request that comes from Authorization URL https://foo.com/auth and there is no client id, user id, or user email on the request. It doesn't do me any good to generate a token and send it back to Amazon if I can't save that token on my webserver along with some kind of echo client device id.

From Account linking implicit granting

3 The user logs in using their normal credentials for your site.

4 Your service authenticates the user and then generates an access token
       that uniquely identifies the user in your system.

When amazon redirects users to my app to enter login credentials, how do I link their token I give back to them to their echo device for future requests?

答:
You don't do that when the user enter his credentials, but after the linking is completed.

When the user launches your skill, you can identify him with the context.System.user.userId, the access token will be in  context.System.user.accessToken and the device in context.System.device. deviceId. The same accessToken can be used for multiple devices, and the userId will change if the user disables and re-enables your skill.

More info here: Request and Response JSON Reference

ContentLicense: CC BY-SA 3.0


问:
Viewing the IL code generated from a compiled expression
Is it possible to view the IL code generated when you call Compile() on an Expression tree?  Consider this very simple example:

```<code>class Program
{
    public int Value { get; set; }

    static void Main(string[] args)
    {
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();
        lambda(p);

        //p.Value = 5;
    }
}
</code>```

Now, the expression tree does what the last line of Main says.  Compile the application, then open it in Reflector.  You can see the IL code of p.Value = 5; that does the assignment.  But the expression tree was made and compiled at runtime.  Is it possible to view the resulting IL code from the compile?

答:
Yes! Use this tool:

https://github.com/drewnoakes/il-visualizer

This was incredibly useful when I was implementing and debugging Compile, as I'm sure you can imagine.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to view the IL code generated when you call Compile() on an Expression tree?  Consider this very simple example:

class Program
{
    public int Value { get; set; }

    static void Main(string[] args)
    {
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();
        lambda(p);

        //p.Value = 5;
    }
}

Now, the expression tree does what the last line of Main says.  Compile the application, then open it in Reflector.  You can see the IL code of p.Value = 5; that does the assignment.  But the expression tree was made and compiled at runtime.  Is it possible to view the resulting IL code from the compile?

ContentLicense: CC BY-SA 4.0


问:
AudioKit MIDI Events - basic questions, sending to external synth, not sure about handling
I had some more time to play around with AudioKit, yet I have a few questions about MIDI. I tried googling and I also checked the AKMIDI class reference, but this just further confused me.

Let's keep it simple: I have a UIButton that should give out a "C" to an external synth.

```<code>import AudioKit
midiOut.openOutput()
midiOut.sendEvent(AKMIDIEvent(noteOn: 72, velocity: 80, channel: 1))
sleep(1)
midiOut.sendEvent(AKMIDIEvent(noteOff: 72, velocity: 0, channel: 1))
</code>```

Obviously this code is spread over the entire ViewController.swift and the sendEvents are inside an @IBAction, but for the sake of keeping it simple, I merged the LOCs.

So my questions are:

Will this send out MIDI signals to external machines? (I ordered the Lightning Camera Connection Kit, but it will take a few more days to arrive, so I cannot test it yet.) I cannot get anything from the iPhone Simulator, so I take it, this is not working.

Will this send out MIDI signals over wireless MIDI as well? According to what I read on some Google group, you can have Wireless MIDI on macOS. Unfortunately I didn't find anything on if and how you can use this in AudioKit.

What about MIDI over Bluetooth? Will this all be handled by AudioKit automatically or will I have to change anything? I read something about midi.createVirtualPorts(), but I am not sure what this actually does. But the word "virtual" makes me believe this is for testing?

Sorry if these questions are ridiculously noobish, but I really am confused by the exact inner workings of this.

Thanks a lot in advance!

答:
You can test your app with simulator as well. Just run your app on simulator and open the Audio MIDI Setup app on your Mac, go to network settings and connect your simulator. Here is a screenshot:

You have full control over AKMIDI.

* If you want to open all available outputs, just call midi.openOutput().

* If you want to open a specific one, like a network session, mostly named "Session 1", call midi.openOutput(name: "Session 1").

* You can get all available destinations by midi.destinationNames string array, if you want to prompt a midi dest picker to user, then just open them with their names.

* For closing them midi.endpoints.removeValue(forKey: "Session 1").

* And for virtual outputs, call sequencer.midi.createVirtualOutputPort(name: "App MIDI Out") which is useful to send MIDI to other apps living in your iOS/Mac.

* Also, you can subscribe to AKMIDIListener protocol's receivedMIDISetupChange function to get notified when a MIDI hardware/software available or not to connect.

Body:
I had some more time to play around with AudioKit, yet I have a few questions about MIDI. I tried googling and I also checked the AKMIDI class reference, but this just further confused me.

Let's keep it simple: I have a UIButton that should give out a "C" to an external synth.

import AudioKit
midiOut.openOutput()
midiOut.sendEvent(AKMIDIEvent(noteOn: 72, velocity: 80, channel: 1))
sleep(1)
midiOut.sendEvent(AKMIDIEvent(noteOff: 72, velocity: 0, channel: 1))

Obviously this code is spread over the entire ViewController.swift and the sendEvents are inside an @IBAction, but for the sake of keeping it simple, I merged the LOCs.

So my questions are:

Will this send out MIDI signals to external machines? (I ordered the Lightning Camera Connection Kit, but it will take a few more days to arrive, so I cannot test it yet.) I cannot get anything from the iPhone Simulator, so I take it, this is not working.

Will this send out MIDI signals over wireless MIDI as well? According to what I read on some Google group, you can have Wireless MIDI on macOS. Unfortunately I didn't find anything on if and how you can use this in AudioKit.

What about MIDI over Bluetooth? Will this all be handled by AudioKit automatically or will I have to change anything? I read something about midi.createVirtualPorts(), but I am not sure what this actually does. But the word "virtual" makes me believe this is for testing?

Sorry if these questions are ridiculously noobish, but I really am confused by the exact inner workings of this.

Thanks a lot in advance!


问:
React Native - how does the app determine the packager IP address, not found on device
I have a react native app, if I run it on the iOS simulator it works and can connect to the running packager that is running on localhost:8081, however if I try to run the app on an actual iOS device, it fails because it can't load the js bundle because it can't find the packager service.

My device and my dev server are on the same WIFI network, how does the app determine where the pacakger service lives?  If I modify the AppDelegate.m file and replace:

```<code>jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

//with an explicit IP address, then the app works:

jsCodeLocation = [NSURL URLWithString:@"http://192.168.0.9:8081/index.ios.bundle?platform=ios&dev=true"];
</code>```

Any tips on settings I may need to modify for running on an actual device, without having to explicitly modify this file.

Thanks.

答:
I've managed to temporarily fix this issue by adding this to the Info.plist file.</p>

```<code><key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
</code>```

Body:
I have a react native app, if I run it on the iOS simulator it works and can connect to the running packager that is running on localhost:8081, however if I try to run the app on an actual iOS device, it fails because it can't load the js bundle because it can't find the packager service.

My device and my dev server are on the same WIFI network, how does the app determine where the pacakger service lives?  If I modify the AppDelegate.m file and replace:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

//with an explicit IP address, then the app works:

jsCodeLocation = [NSURL URLWithString:@"http://192.168.0.9:8081/index.ios.bundle?platform=ios&dev=true"];

Any tips on settings I may need to modify for running on an actual device, without having to explicitly modify this file.

Thanks.

Body:
I've managed to temporarily fix this issue by adding this to the Info.plist file.

<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>


问:
Delete multiple sheets at once
I have multiple sheets with data on each sheet. I want to delete sheets from sheet number 4 to unlimited. I have tried below code:

```<code>Sub Delete_Sheets()
    Application.ScreenUpdating = False
    Dim j As Integer
    j = Worksheets.Count
    For k = 4 To j
        With Sheets(k).Delete
        End With
    Next k
    Application.ScreenUpdating = True
End Sub
</code>```

The problem is, every time the code ask my permission to delete sheet and finally saw deletes only few sheets. Someone help.

答:
Turn off confirmations and loop the delete worksheet command until you are left with three worksheets.

```<code>Option Explicit

Sub qwea()
    Application.DisplayAlerts = False
    Do While Worksheets.Count > 3
        Worksheets(Worksheets.Count).Delete
    Loop
    Application.DisplayAlerts = True
End Sub
</code>```

Your code would have worked correctly if you had reversed the increment of the For ... Next like For k = j To 4 step - 1. You were 'stepping over' worksheets while deleting.

Title: Delete multiple sheets at once

Body:
I have multiple sheets with data on each sheet. I want to delete sheets from sheet number 4 to unlimited. I have tried below code:

Sub Delete_Sheets()
    Application.ScreenUpdating = False
    Dim j As Integer
    j = Worksheets.Count
    For k = 4 To j
        With Sheets(k).Delete
        End With
    Next k
    Application.ScreenUpdating = True
End Sub

The problem is, every time the code ask my permission to delete sheet and finally saw deletes only few sheets. Someone help.

Body:
Turn off confirmations and loop the delete worksheet command until you are left with three worksheets.

Option Explicit

Sub qwea()
    Application.DisplayAlerts = False
    Do While Worksheets.Count > 3
        Worksheets(Worksheets.Count).Delete
    Loop
    Application.DisplayAlerts = True
End Sub

Your code would have worked correctly if you had reversed the increment of the For ... Next like For k = j To 4 step - 1. You were 'stepping over' worksheets while deleting.


问:
"Could not find the main class. The program will exit"
I m trying to test sending email in java using java6. The code is this:

```<code>import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Sending_email {

final String senderEmail = "ttttt@gmail.com";
final String senderPassword = "123456";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;

public Sending_email(String receiverEmail, String Subject, String message) {
    this.receiverEmail = receiverEmail;
    this.emailSubject = Subject;
    this.emailBody = message;

    Properties props = new Properties();
    props.put("mail.smtp.user", senderEmail);
    props.put("mail.smtp.host", emailSMTPserver);
    props.put("mail.smtp.port", emailServerPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", emailServerPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    //SecurityManager security = System.getSecurityManager();

    try {
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getInstance(props, auth);

        Message msg = new MimeMessage(session);
        msg.setText(emailBody);
        msg.setSubject(emailSubject);
        msg.setFrom(new InternetAddress(senderEmail));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(receiverEmail));
        Transport.send(msg);
        System.out.println("send successfully");
    } catch (Exception ex) {
        System.err.println("Error occurred while sending.!");
    }

}

private class SMTPAuthenticator extends javax.mail.Authenticator {

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(senderEmail, senderPassword);
    }
}

public static void main(String[] args) {
    new Sending_email("tttt@gmail.com", "suerjanct", "erjan lsjflsjdfsldjf");
}
</code>```

}

However, Eclipse can't compile it. It says

"java.lang.UnsupportedClassVersionError: javax/mail/Authenticator : Unsupported major.minor version 51.0"

51.0 means I run jdk 1.7. but I only have 1.8 and 1.6 installed on my computer!

答: This is because you have used higher JDK during compile time and lower JDK during runtime, as you said you have  java 1.8, try to compile the code using the same

Body:
I m trying to test sending email in java using java6. The code is this:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Sending_email {

final String senderEmail = "ttttt@gmail.com";
final String senderPassword = "123456";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;

public Sending_email(String receiverEmail, String Subject, String message) {
    this.receiverEmail = receiverEmail;
    this.emailSubject = Subject;
    this.emailBody = message;

    Properties props = new Properties();
    props.put("mail.smtp.user", senderEmail);
    props.put("mail.smtp.host", emailSMTPserver);
    props.put("mail.smtp.port", emailServerPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", emailServerPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    //SecurityManager security = System.getSecurityManager();

    try {
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getInstance(props, auth);

        Message msg = new MimeMessage(session);
        msg.setText(emailBody);
        msg.setSubject(emailSubject);
        msg.setFrom(new InternetAddress(senderEmail));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(receiverEmail));
        Transport.send(msg);
        System.out.println("send successfully");
    } catch (Exception ex) {
        System.err.println("Error occurred while sending.!");
    }

}

private class SMTPAuthenticator extends javax.mail.Authenticator {

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(senderEmail, senderPassword);
    }
}

public static void main(String[] args) {
    new Sending_email("tttt@gmail.com", "suerjanct", "erjan lsjflsjdfsldjf");
}

}

However, Eclipse can't compile it. It says

"java.lang.UnsupportedClassVersionError: javax/mail/Authenticator : Unsupported major.minor version 51.0"

51.0 means I run jdk 1.7. but I only have 1.8 and 1.6 installed on my computer!


问:
Change delimiter in a csv from ; to ,
I cannot seem to change the delimiter in a .csv from ; to ,.

The issue is that one of our overseas customers have a default delimiter of ; because of regional settings, but our system requires the , separator.

I cannot use the -replace because there are semicolons in some string entries that need to be kept there.

Here are the options I have tried:

```<code>Import-Csv -path $home\ | Export-Csv C:\Users\Dean\Desktop\test.csv -useculture

Import-Csv -path $home | Export-Csv C:\Users\Dean\Desktop\test\test.csv -Delimiter ","

Import-Csv -path $home | Export-Csv C:\Users\Dean\Desktop\test.csv -Replace "^\"|\"$", ""
</code>```

I have also tried

```<code>Import-Csv -UseCulture | ConvertTo-Csv | Out-File and Import-Csv -Delimiter | ConvertTo-Csv | Out-File
</code>```

None of these options are throwing out errors but the delimiter is still ; when checking the csv again. The only time I have seen these args work are if I export or outfile a csv to a location without the -delimiter or -useculture arg.

答:
Creating a csv using ; as the delimiter:

```<code>Get-ChildItem c:\ | Select-Object FullName, Name, LastWriteTime |Export-Csv c:\temp\test.csv -Delimiter ';' -notypeinformation
</code>```

Sample of the csv:

```<code>"FullName";"Name";"LastWriteTime"
"C:\APP-V_Global";"APP-V_Global";"8/5/2013 12:45:04 PM"
"C:\Program Files";"Program Files";"10/4/2017 7:48:06 AM"
"C:\Program Files (x86)";"Program Files (x86)";"10/10/2017 1:44:51 PM"
"C:\Temp";"Temp";"12/5/2017 1:29:34 PM"
"C:\Users";"Users";"9/6/2017 8:30:00 AM"
"C:\Windows";"Windows";"11/17/2017 4:16:43 PM"
</code>```

Import the csv telling powershell what the delimiter is:

```<code>$imported = Import-Csv c:\temp\test.csv -Delimiter ';'
</code>```

Sample output:

```<code>$imported
FullName                             Name                                 LastWriteTime
--------                             ----                                 -------------
C:\APP-V_Global                      APP-V_Global                         8/5/2013 12:45:04 PM
C:\Program Files                     Program Files                        10/4/2017 7:48:06 AM
C:\Program Files (x86)               Program Files (x86)                  10/10/2017 1:44:51 PM
C:\Temp                              Temp                                 12/5/2017 1:29:34 PM
C:\Users                             Users                                9/6/2017 8:30:00 AM
C:\Windows                           Windows                              11/17/2017 4:16:43 PM
</code>```

Export the information back out:

```<code>$imported | Export-Csv C:\temp\test.csv -delimiter ',' -notypeinformation
</code>```

File Contains:

```<code>"FullName","Name","LastWriteTime"
"C:\APP-V_Global","APP-V_Global","8/5/2013 12:45:04 PM"
"C:\Program Files","Program Files","10/4/2017 7:48:06 AM"
"C:\Program Files (x86)","Program Files (x86)","10/10/2017 1:44:51 PM"
"C:\Temp","Temp","12/5/2017 1:29:34 PM"
"C:\Users","Users","9/6/2017 8:30:00 AM"
"C:\Windows","Windows","11/17/2017 4:16:43 PM"
</code>```

The basic process works so I'm wondering if your input files are the issue. If this isn't working please considering sanitizing and posting a sample csv.

Title: Change delimiter in a csv from ; to ,

Body:
I cannot seem to change the delimiter in a .csv from ; to ,.

The issue is that one of our overseas customers have a default delimiter of ; because of regional settings, but our system requires the , separator.

I cannot use the -replace because there are semicolons in some string entries that need to be kept there.

Here are the options I have tried:

Import-Csv -path $home\ | Export-Csv C:\Users\Dean\Desktop\test.csv -useculture

Import-Csv -path $home | Export-Csv C:\Users\Dean\Desktop\test\test.csv -Delimiter ","

Import-Csv -path $home | Export-Csv C:\Users\Dean\Desktop\test.csv -Replace "^\"|\"$", ""

I have also tried

Import-Csv -UseCulture | ConvertTo-Csv | Out-File and Import-Csv -Delimiter | ConvertTo-Csv | Out-File

None of these options are throwing out errors but the delimiter is still ; when checking the csv again. The only time I have seen these args work are if I export or outfile a csv to a location without the -delimiter or -useculture arg.

Body:
Creating a csv using ; as the delimiter:

Get-ChildItem c:\ | Select-Object FullName, Name, LastWriteTime |Export-Csv c:\temp\test.csv -Delimiter ';' -notypeinformation

Sample of the csv:

"FullName";"Name";"LastWriteTime"
"C:\APP-V_Global";"APP-V_Global";"8/5/2013 12:45:04 PM"
"C:\Program Files";"Program Files";"10/4/2017 7:48:06 AM"
"C:\Program Files (x86)";"Program Files (x86)";"10/10/2017 1:44:51 PM"
"C:\Temp";"Temp";"12/5/2017 1:29:34 PM"
"C:\Users";"Users";"9/6/2017 8:30:00 AM"
"C:\Windows";"Windows";"11/17/2017 4:16:43 PM"

Import the csv telling powershell what the delimiter is:

$imported = Import-Csv c:\temp\test.csv -Delimiter ';'

Sample output:

$imported
FullName                             Name                                 LastWriteTime
--------                             ----                                 -------------
C:\APP-V_Global                      APP-V_Global                         8/5/2013 12:45:04 PM
C:\Program Files                     Program Files                        10/4/2017 7:48:06 AM
C:\Program Files (x86)               Program Files (x86)                  10/10/2017 1:44:51 PM
C:\Temp                              Temp                                 12/5/2017 1:29:34 PM
C:\Users                             Users                                9/6/2017 8:30:00 AM
C:\Windows                           Windows                              11/17/2017 4:16:43 PM

Export the information back out:

$imported | Export-Csv C:\temp\test.csv -delimiter ',' -notypeinformation

File Contains:

"FullName","Name","LastWriteTime"
"C:\APP-V_Global","APP-V_Global","8/5/2013 12:45:04 PM"
"C:\Program Files","Program Files","10/4/2017 7:48:06 AM"
"C:\Program Files (x86)","Program Files (x86)","10/10/2017 1:44:51 PM"
"C:\Temp","Temp","12/5/2017 1:29:34 PM"
"C:\Users","Users","9/6/2017 8:30:00 AM"
"C:\Windows","Windows","11/17/2017 4:16:43 PM"

The basic process works so I'm wondering if your input files are the issue. If this isn't working please considering sanitizing and posting a sample csv.


问:
Getting Chrome to accept self-signed localhost certificate
I have created a self-signed SSL certificate for the localhost CN. Firefox accepts this certificate after initially complaining about it, as expected. Chrome and IE, however, refuse to accept it, even after adding the certificate to the system certificate store under Trusted Roots. Even though the certificate is listed as correctly installed when I click "View certificate information" in Chrome's HTTPS popup, it still insists the certificate cannot be trusted.

What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?

答:
Click anywhere on the page and type a BYPASS_SEQUENCE:

BYPASS_SEQUENCE
Chrome Version

thisisunsafe
65 - ?

badidea
62 - 64

danger
? - 61

You don't need to look for input field, just type it. It feels strange but it works. I tried it on Mac High Sierra.

To double check if they changed it again, go to the latest Chromium source code. At the moment the BYPASS_SEQUENCE looks like this:

var BYPASS_SEQUENCE = window.atob('dGhpc2lzdW5zYWZl');
```
<p>Now they have it camouflaged, but to see the real <code>BYPASS_SEQUENCE</code> you can run following line in a browser console.</p>
<pre class="lang-js prettyprint-override"><code>console.log(window.atob('dGhpc2lzdW5zYWZl'));
</code>```

OR

Alternatively to typing phrase you can paste the part of code in console

```<code>sendCommand(SecurityInterstitialCommandId.CMD_PROCEED)
</code>```

Body:
Click anywhere on the page and type a BYPASS_SEQUENCE:

BYPASS_SEQUENCE
Chrome Version

thisisunsafe
65 - ?

badidea
62 - 64

danger
? - 61

You don't need to look for input field, just type it. It feels strange but it works. I tried it on Mac High Sierra.

To double check if they changed it again, go to the latest Chromium source code. At the moment the BYPASS_SEQUENCE looks like this:

var BYPASS_SEQUENCE = window.atob('dGhpc2lzdW5zYWZl');

Now they have it camouflaged, but to see the real BYPASS_SEQUENCE you can run following line in a browser console.

console.log(window.atob('dGhpc2lzdW5zYWZl'));

OR

Alternatively to typing phrase you can paste the part of code in console

sendCommand(SecurityInterstitialCommandId.CMD_PROCEED)


问:
How can I pass a variable to a URL?
I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:

```<code>sendinvite() {
      var user = firebase.auth().currentUser;
      var uid = user.uid;

      firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
        var hashKey = (snapshot.val());
        console.log(hashKey)
      });

      var bcc = [];
      for(var e in this.emailinputs){
        if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("@") || !this.emailinputs[e].email.includes("."))
        {
          let alert = this.alerCtrl.create({
            title: 'Error!',
            message: 'There was an error with an email address you entered.',
            buttons: ['Ok']
          });
          alert.present()
        }else {
          bcc.push(this.emailinputs[e].email);
        }
      }
      if(bcc.length > 0) {
        let email = {
          bcc: bcc,
          subject: 'Nudget Invite',
          body: '<a href="https://nudget-72ee4.firebaseapp.com/?hashkey='+hashKey+'">Join my grocery list!</a>',
          isHtml: true
        };
        this.emailComposer.open(email);
      }
}
</code>```

I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.

Edit 1

Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.

答:
I think the problem is here:

```<code>firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
    var hashKey = (snapshot.val());
    console.log(hashKey)
});
</code>```

You are creating the var named hashKey within an anonymous function then trying to access hashKey outside of that function.

Try the following instead:

```<code>var user = firebase.auth().currentUser;
var uid = user.uid;
var hashKey = null;

firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
    hashKey = (snapshot.val());
    console.log(hashKey)
});

... snip ...

    body: '<a href="https://nudget-72ee4.firebaseapp.com/?hashkey='+ ((hashKey == null) ? 'no-key' : hashKey) +'">Join my grocery list!</a>',

... snip ...
</code>```

Title: How can I pass a variable to a URL?

Body:
I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:

sendinvite() {
      var user = firebase.auth().currentUser;
      var uid = user.uid;

      firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
        var hashKey = (snapshot.val());
        console.log(hashKey)
      });

      var bcc = [];
      for(var e in this.emailinputs){
        if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("@") || !this.emailinputs[e].email.includes("."))
        {
          let alert = this.alerCtrl.create({
            title: 'Error!',
            message: 'There was an error with an email address you entered.',
            buttons: ['Ok']
          });
          alert.present()
        }else {
          bcc.push(this.emailinputs[e].email);
        }
      }
      if(bcc.length > 0) {
        let email = {
          bcc: bcc,
          subject: 'Nudget Invite',
          body: 'Join my grocery list!',
          isHtml: true
        };
        this.emailComposer.open(email);
      }
}

I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.

Edit 1

Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.

Body:
I think the problem is here:

firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
    var hashKey = (snapshot.val());
    console.log(hashKey)
});

You are creating the var named hashKey within an anonymous function then trying to access hashKey outside of that function.

Try the following instead:

var user = firebase.auth().currentUser;
var uid = user.uid;
var hashKey = null;

firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
    hashKey = (snapshot.val());
    console.log(hashKey)
});

... snip ...

    body: '<a href="https://nudget-72ee4.firebaseapp.com/?hashkey='+ ((hashKey == null) ? 'no-key' : hashKey) +'">Join my grocery list!</a>',

... snip ...


问:
Given a latitude and longitude, Get the location name
I am developing an application wherein I get the latitude, longitude in my android device and post them to a web server.

and in a web application I show the location details with the help of google maps.

Here I have huge collection of lat long values which i loop it in my jsp and create multiple markers with info windows.

Now the problem is that I need to show the location name of the particular latitude and longitude in the Info Window of google maps.

Can anyone help me with the google maps script or how can i get the location name from the lat long values in my android phone itself, so that I can post that to my web server.

答:
```<code>   private String getAddress() {
        GPSTracker   gps = new GPSTracker(ProductList.this);
        Geocoder geocoder = new Geocoder(ProductList.this, Locale.getDefault());
        String address="";
        try {
            List<Address> addresses = geocoder.getFromLocation(gps.getLatitude(), gps.getLongitude(), 1);
            Address obj = addresses.get(0);
            String  add = obj.getAddressLine(0);
//optional
          /*  add = add + "\n" + obj.getCountryName();
            add = add + "\n" + obj.getCountryCode();
            add = add + "\n" + obj.getAdminArea();
            add = add + "\n" + obj.getPostalCode();
            add = add + "\n" + obj.getSubAdminArea();
            add = add + "\n" + obj.getLocality();
            add = add + "\n" + obj.getSubThoroughfare();*/

            Log.e("Location", "Address" + add);
            address=add;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return address;
    }
</code>```


问:
How to read lines of a stream in Codename One
In Java standard I can read a stream, line by line, using, for instance, the readLine() method of the BufferedReader class. In the com.codename1.io package that class is not present.

How can I achieve the same goal in Codename One?

答:
There is no support for readline in our current stream code as it's not the most efficient way to read streams. I would suggest using a method such as Util.readToString and then parse the String which will probably be more efficient.

However, if you want to replace readLine you can do something like this (didn't test it):

```<code>private String readLine(Reader is) throws IOException {
   int nextChar = is.read();
   if(nextChar == -1) {
       return null;
   }
   StringBuilder ret = new StringBuilder();
   while(nextChar > -1) {
       ret.append((char)nextChar);
       nextChar = is.read();
       if(nextChar == '\n') {
          return ret.toString();
       }
   }
   return ret.toString();
}
</code>```

Body:
There is no support for readline in our current stream code as it's not the most efficient way to read streams. I would suggest using a method such as Util.readToString and then parse the String which will probably be more efficient.

However, if you want to replace readLine you can do something like this (didn't test it):

private String readLine(Reader is) throws IOException {
   int nextChar = is.read();
   if(nextChar == -1) {
       return null;
   }
   StringBuilder ret = new StringBuilder();
   while(nextChar > -1) {
       ret.append((char)nextChar);
       nextChar = is.read();
       if(nextChar == '\n') {
          return ret.toString();
       }
   }
   return ret.toString();
}


问:
JS Array.every alway return false on comparing strings
I'm trying to complete an assignment using every, I tried everything and after and after 1 hour I decided to ask your help.

This function should return true if all the words in the array start with a case-insensitive but always return false, no matter what.

Thank you

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => {word[0] === /"a"/i }) : true;
};

allStartingWithA(["abbb","aee", "aee", "avvv"]);```

答:
Issue is you are not returning anything from callback.

Anonymous functions using arrow function can be written as

```<code>() = > expression
</code>```

or

```<code>() => { function body; }
</code>```

Approach 1 by defaults return the value of expression and approach 2 by defaults return undefined.

Since you are using second approach, you will either have to manually return value or switch to first approach.

Another problem in your code is expression. When you have to test using a regex, you should use method test.

So your expression should be /^a/i.test(word).

If you want to compare first character only, you can so word[0] === "a" but this will be case sensitive.

Another optimization can be, since you want to return true if array is empty, you can return an expression that evaluates as:

Either array should be blank or all words should start with some characters.

So your final code would be:

var allStartingWithA = function(words) {
  return words.length === 0 || words.every((word) => /a/i.test(word));
};

console.log(allStartingWithA([]));
console.log(allStartingWithA(["abbb", "aee", "aee", "avvv"]));
console.log(allStartingWithA(["bbb", "aee", "aee", "avvv"]));```

References:

string.charAt(x) or string[x]?

Use dynamic (variable) string as regex pattern in JavaScript

Arrow functions - MDN

Body:
Issue is you are not returning anything from callback.

Anonymous functions using arrow function can be written as

() = > expression

or

() => { function body; }

Approach 1 by defaults return the value of expression and approach 2 by defaults return undefined.

Since you are using second approach, you will either have to manually return value or switch to first approach.

Another problem in your code is expression. When you have to test using a regex, you should use method test.

So your expression should be /^a/i.test(word).

If you want to compare first character only, you can so word[0] === "a" but this will be case sensitive.

Another optimization can be, since you want to return true if array is empty, you can return an expression that evaluates as:

Either array should be blank or all words should start with some characters.

So your final code would be:

var allStartingWithA = function(words) {
  return words.length === 0 || words.every((word) => /a/i.test(word));
};

console.log(allStartingWithA([]));
console.log(allStartingWithA(["abbb", "aee", "aee", "avvv"]));
console.log(allStartingWithA(["bbb", "aee", "aee", "avvv"]));

References:

string.charAt(x) or string[x]?

Use dynamic (variable) string as regex pattern in JavaScript

Arrow functions - MDN


问:
Can python class variables become instance variables when altered in __init__?
As far as I understand var is a class variable here:

```<code>class MyClass:
    var = 'hello'

    def __init__(self):
        print(self.var)
</code>```

And thats an instance variable:

```<code>class MyClass:

    def __init__(self, var):
        self.var = var
        print(self.var)
</code>```

I had the problem, that I was looking for a method to make type hinting possible for instance variables. I can of course typehint the parameter with def __init__(self, var: str): but that would not effect the instance variable itself.

Then I noticed in some descriptions (like here) that they used the term instance variable for a var like this:

```<code>class MyClass:
    var : str = 'hello'

    def __init__(self, var : str = None):
        self.var = var if var
        print(self.var)
</code>```

That would be the solution indeed, but is that still an instance variable? Because it is defined in the class body, it would be a class variable in my understanding. If you would use a list for var, all alterations to this list-var would be shared over the instances.

But in this case there would be no problem, because the string is replaced and would not be shared for other instances. However, it seems wrong to me if you call it an instance variable and I don't know if I should use it like this just to have the type hinting working.

答:
That would be the solution indeed, but is that still an instance variable? Because it is defined in the class body, it would be a class variable in my understanding. [...snip...] However, it seems wrong to me if you call it an instance variable and I don't know if I should use it like this just to have the type hinting working.

For what it's worth, I also share the same discomfort. It seems like we're conceptually mixing two concepts there just for the sake of having cleaner type annotations.

However, I've asked Guido one or two times about this, and it seems like he does indeed prefers treating those class attributes as if they were instance attributes.

In any case, to answer your core question, if we do this:

```<code>class Test:
    field1: int
    field2: str = 'foo'
</code>```

Then...

PEP 484 and 526 compliant type checkers will treat this class as if:

It has an instance attribute named field1

It has an instance attribute named field2 that has a default value of 'foo' (as per PEP 526).

At runtime, ignoring type hints, Python will:

Add a class annotation named field1 to Test, but not a class attribute. (Class annotations are not automatically turned into class attributes.)

Add both a class annotation named field2 to Test as well as a class attribute named field2 containing the value 'foo'.

So, it can get a bit muddled.

But regardless, this then begs the question: how do we indicate to a type checker that we want some field to genuinely be a class attribute?

Well, it turns out PEP 484 was amended semi-recently to contain the ClassVar type annotation, which does exactly that.

So, if we wanted to add a new class attribute, we could do this:

```<code>from typing import ClassVar

class Test:
    field1: int
    field2: str = 'foo'
    field3: ClassVar[int] = 3
</code>```

So now, field3 should be treated as a class attribute with a default value of '3'.

(Note: ClassVar was added to typing for Python 3.5.3 -- if you're using the older version of typing bundled with Python 3.5, you can get a "backport" of the type by installing the typing_extensions third part module via pip and importing ClassVar from there instead.)

I think whether you decide to embrace this approach or not use it is a personal preference.

On one hand, Guido's opinion, pretty much by definition, defines what's "Pythonic" or not, so from that stance, there's no issue adopting this new idiom. Furthermore, the language itself is slowly but surely shifting to adopt this new idiom -- see the very recently accepted PEP 557, for example, which ends up following this same idiom of treating class attributes/class annotations as instance attributes.

On the other hand, it's difficult to shake off the nagging worry that this subtle difference will lead to issues down the line. In that case, you could stick with the standard approach of just setting all your fields inside __init__. This approach also has the benefit of keeping your code compatible with Python 2 and 3.x - 3.5.

A middle ground might be to just simply never use class attributes, in any way, shape, or form, and just stick to using class annotations. This is slightly restrictive, since we can no longer give our instance variables default values, but we can now avoid conflating class attributes with instance attributes entirely. (As previously stated, and as pointed out in the comments, class annotations are not added as class attributes.)

Body:
As far as I understand var is a class variable here:

class MyClass:
    var = 'hello'

    def __init__(self):
        print(self.var)

And thats an instance variable:

class MyClass:

    def __init__(self, var):
        self.var = var
        print(self.var)

I had the problem, that I was looking for a method to make type hinting possible for instance variables. I can of course typehint the parameter with def __init__(self, var: str): but that would not effect the instance variable itself.

Then I noticed in some descriptions (like here) that they used the term instance variable for a var like this:

class MyClass:
    var : str = 'hello'

    def __init__(self, var : str = None):
        self.var = var if var
        print(self.var)

That would be the solution indeed, but is that still an instance variable? Because it is defined in the class body, it would be a class variable in my understanding. If you would use a list for var, all alterations to this list-var would be shared over the instances.

But in this case there would be no problem, because the string is replaced and would not be shared for other instances. However, it seems wrong to me if you call it an instance variable and I don't know if I should use it like this just to have the type hinting working.

Body:
That would be the solution indeed, but is that still an instance variable? Because it is defined in the class body, it would be a class variable in my understanding. [...snip...] However, it seems wrong to me if you call it an instance variable and I don't know if I should use it like this just to have the type hinting working.

For what it's worth, I also share the same discomfort. It seems like we're conceptually mixing two concepts there just for the sake of having cleaner type annotations.

However, I've asked Guido one or two times about this, and it seems like he does indeed prefers treating those class attributes as if they were instance attributes.

In any case, to answer your core question, if we do this:

class Test:
    field1: int
    field2: str = 'foo'

Then...

PEP 484 and 526 compliant type checkers will treat this class as if:

It has an instance attribute named field1

It has an instance attribute named field2 that has a default value of 'foo' (as per PEP 526).

At runtime, ignoring type hints, Python will:

Add a class annotation named field1 to Test, but not a class attribute. (Class annotations are not automatically turned into class attributes.)

Add both a class annotation named field2 to Test as well as a class attribute named field2 containing the value 'foo'.

So, it can get a bit muddled.

But regardless, this then begs the question: how do we indicate to a type checker that we want some field to genuinely be a class attribute?

Well, it turns out PEP 484 was amended semi-recently to contain the ClassVar type annotation, which does exactly that.

So, if we wanted to add a new class attribute, we could do this:

from typing import ClassVar

class Test:
    field1: int
    field2: str = 'foo'
    field3: ClassVar[int] = 3

So now, field3 should be treated as a class attribute with a default value of '3'.

(Note: ClassVar was added to typing for Python 3.5.3 -- if you're using the older version of typing bundled with Python 3.5, you can get a "backport" of the type by installing the typing_extensions third part module via pip and importing ClassVar from there instead.)

I think whether you decide to embrace this approach or not use it is a personal preference.

On one hand, Guido's opinion, pretty much by definition, defines what's "Pythonic" or not, so from that stance, there's no issue adopting this new idiom. Furthermore, the language itself is slowly but surely shifting to adopt this new idiom -- see the very recently accepted PEP 557, for example, which ends up following this same idiom of treating class attributes/class annotations as instance attributes.

On the other hand, it's difficult to shake off the nagging worry that this subtle difference will lead to issues down the line. In that case, you could stick with the standard approach of just setting all your fields inside __init__. This approach also has the benefit of keeping your code compatible with Python 2 and 3.x - 3.5.

A middle ground might be to just simply never use class attributes, in any way, shape, or form, and just stick to using class annotations. This is slightly restrictive, since we can no longer give our instance variables default values, but we can now avoid conflating class attributes with instance attributes entirely. (As previously stated, and as pointed out in the comments, class annotations are not added as class attributes.)


问:
how to have puma send logs to stdout
i want my RoR/puma logs to just go to stdout instead of a log file. is it as simple as removing the stdout_redirect line from my puma configs (aka, puma.rb)?

答: If you are running Rails 5, just set RAILS_LOG_TO_STDOUT=1 from command line</p>

Title: how to have puma send logs to stdout


问:
Wrong Position after Filtering and on Click in Recyclerview
I have Implemented SearchView in my App. But the Problem I am facing is the recycler view returns the wrong position after filtering. How can i get the exact position after filtering.

Here is my code of Adapter:-

```<code>public class UserListAdapter extends Adapter<UserListAdapter.DataObjectHolder> implements Filterable {
private static MyClickListener myClickListener;
public Activity activity;
Bitmap bitmap;
ImageView imgUserBig;
TextView txtUserName;
RelativeLayout userProfileView;
private ArrayList<DataObject> mArrayList;
private ArrayList<DataObject> mFilteredList;

public UserListAdapter(Activity a, ArrayList<DataObject> d, ImageView mImgUserBig, RelativeLayout viewLinear, TextView txtUsername) {

    this.activity = a;
    this.mArrayList = d;
    this.mFilteredList = d;
    this.imgUserBig = mImgUserBig;
    this.userProfileView = viewLinear;
    this.txtUserName = txtUsername;
}

public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new DataObjectHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_user_list, parent, false));
}

public void onBindViewHolder(final DataObjectHolder holder, final int position) {
    holder.txtName.setText((mFilteredList.get(position)).getmName());
    holder.txtUserName.setText((mFilteredList.get(position)).getmUsername());
    Glide.with(activity.getApplicationContext()).load((mFilteredList.get(position)).getmImage()).into(holder.imgUser);
    Glide.with(activity).load((mFilteredList.get(position)).getmImage()).asBitmap().into(new SimpleTarget<Bitmap>(Integer.MIN_VALUE, Integer.MIN_VALUE) {
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            bitmap = resource;
            (mFilteredList.get(position)).setBitmap(bitmap);
        }
    });
    holder.imgUser.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if ((mFilteredList.get(position)).getBitmap() != null && imgUserBig != null) {
                zoomImageFromThumb(holder.imgUser, (mFilteredList.get(position)).getBitmap(), (mFilteredList.get(position)).getmImage(), (mFilteredList.get(position)).getmUsername());
            }
        }
    });
}

public int getItemCount() {
    return mFilteredList.size();
}

public void setOnItemClickListener(MyClickListener myClickListener) {
    UserListAdapter.myClickListener = myClickListener;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                mFilteredList = mArrayList;
            }else {
                ArrayList<DataObject> filteredList = new ArrayList<>();
                for (DataObject userData : mArrayList) {
                    if (userData.getmUsername().toLowerCase().contains(charString) || userData.getmName().toLowerCase().contains(charString)) {
                        filteredList.add(userData);
                    }
                }
                mFilteredList = filteredList;
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = mFilteredList;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mFilteredList = (ArrayList<DataObject>) results.values;
            notifyDataSetChanged();
        }
    };
}

public interface MyClickListener {
    void onItemClick(int i, View view);
}

public Object getItem(int position) {
    return mFilteredList.get(position);
}

public class DataObjectHolder extends ViewHolder implements OnClickListener {
    ImageView imgUser;
    TextView txtName;
    TextView txtUserName;

    public DataObjectHolder(View itemView) {
        super(itemView);
        txtName = (TextView) itemView.findViewById(R.id.txtname);
        txtUserName = (TextView) itemView.findViewById(R.id.txtusername);
        imgUser = (ImageView) itemView.findViewById(R.id.img_user);
        itemView.setOnClickListener(this);
    }

    public void onClick(View v) {
        UserListAdapter.myClickListener.onItemClick(getPosition(), v);
    }
}}
</code>```

I am calling getPosition() Method to get the position of the item, but it returns the old position, not the filtered one. Any Help will be Appreciated.

答: Use getAdapterPosition() in your onClick method because then at the time of the click u want to know the position of the item. If u check at the time of the creation it will (most of the times) be inaccurate</p>

Body:
I have Implemented SearchView in my App. But the Problem I am facing is the recycler view returns the wrong position after filtering. How can i get the exact position after filtering.

Here is my code of Adapter:-

public class UserListAdapter extends Adapter<UserListAdapter.DataObjectHolder> implements Filterable {
private static MyClickListener myClickListener;
public Activity activity;
Bitmap bitmap;
ImageView imgUserBig;
TextView txtUserName;
RelativeLayout userProfileView;
private ArrayList<DataObject> mArrayList;
private ArrayList<DataObject> mFilteredList;

public UserListAdapter(Activity a, ArrayList<DataObject> d, ImageView mImgUserBig, RelativeLayout viewLinear, TextView txtUsername) {

    this.activity = a;
    this.mArrayList = d;
    this.mFilteredList = d;
    this.imgUserBig = mImgUserBig;
    this.userProfileView = viewLinear;
    this.txtUserName = txtUsername;
}

public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new DataObjectHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_user_list, parent, false));
}

public void onBindViewHolder(final DataObjectHolder holder, final int position) {
    holder.txtName.setText((mFilteredList.get(position)).getmName());
    holder.txtUserName.setText((mFilteredList.get(position)).getmUsername());
    Glide.with(activity.getApplicationContext()).load((mFilteredList.get(position)).getmImage()).into(holder.imgUser);
    Glide.with(activity).load((mFilteredList.get(position)).getmImage()).asBitmap().into(new SimpleTarget<Bitmap>(Integer.MIN_VALUE, Integer.MIN_VALUE) {
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            bitmap = resource;
            (mFilteredList.get(position)).setBitmap(bitmap);
        }
    });
    holder.imgUser.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if ((mFilteredList.get(position)).getBitmap() != null && imgUserBig != null) {
                zoomImageFromThumb(holder.imgUser, (mFilteredList.get(position)).getBitmap(), (mFilteredList.get(position)).getmImage(), (mFilteredList.get(position)).getmUsername());
            }
        }
    });
}

public int getItemCount() {
    return mFilteredList.size();
}

public void setOnItemClickListener(MyClickListener myClickListener) {
    UserListAdapter.myClickListener = myClickListener;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                mFilteredList = mArrayList;
            }else {
                ArrayList<DataObject> filteredList = new ArrayList<>();
                for (DataObject userData : mArrayList) {
                    if (userData.getmUsername().toLowerCase().contains(charString) || userData.getmName().toLowerCase().contains(charString)) {
                        filteredList.add(userData);
                    }
                }
                mFilteredList = filteredList;
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = mFilteredList;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mFilteredList = (ArrayList<DataObject>) results.values;
            notifyDataSetChanged();
        }
    };
}

public interface MyClickListener {
    void onItemClick(int i, View view);
}

public Object getItem(int position) {
    return mFilteredList.get(position);
}

public class DataObjectHolder extends ViewHolder implements OnClickListener {
    ImageView imgUser;
    TextView txtName;
    TextView txtUserName;

    public DataObjectHolder(View itemView) {
        super(itemView);
        txtName = (TextView) itemView.findViewById(R.id.txtname);
        txtUserName = (TextView) itemView.findViewById(R.id.txtusername);
        imgUser = (ImageView) itemView.findViewById(R.id.img_user);
        itemView.setOnClickListener(this);
    }

    public void onClick(View v) {
        UserListAdapter.myClickListener.onItemClick(getPosition(), v);
    }
}}

I am calling getPosition() Method to get the position of the item, but it returns the old position, not the filtered one. Any Help will be Appreciated.


问:
program breaks when allocating dynamic memory to store copy of string
I am trying to see if all of my functions work correctly and the program runs to black screen and it closes and it gives me an error with yellow triangle exclammation mark inside the triangle saying that

"Exception thrown 0x01971FD0 (ucrtbased.dll) in milestone2.exe 0xC0000005: Access violation reading location 0x0000000"

arrow indicating .cpp file  m_message = new char [strlen(str) + 1 ] located at void ErrorMessage::message(const char* str) at

im guessing it is some kind of memory issue, anyone knows the solution?

Header file

```<code>#ifndef SICT_ERROR_H_
#define SICT_ERROR_H_
namespace sict {
    class ErrorMessage {
        char* m_message;
    public:

        ErrorMessage(const char* errorMessage = nullptr);
        ErrorMessage(const ErrorMessage& em) = delete;
        ErrorMessage& operator=(const ErrorMessage& em) = delete;
        virtual ~ErrorMessage();
        void clear();
        bool isClear() const;
        void message(const char* str);
        const char* message() const;
    };
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage);
}
#endif
</code>```

Cpp file

```<code>#include "ErrorMessage.h"
#include <iostream>
namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
        m_message = nullptr;
        message(errorMessage);
    }
    void ErrorMessage::clear() {
        delete[] m_message;
        m_message = nullptr;
    }
    void ErrorMessage::message(const char* str) {
        delete[] m_message;
        m_message = new char[strlen(str) + 1];
        strcpy(m_message, str);
    }
    const char* ErrorMessage::message() const {
        return m_message;
    }
    ErrorMessage::~ErrorMessage() {
        clear();
    }
    bool ErrorMessage::isClear() const {
        if (m_message == nullptr) {
            return true;
        }
        return false;
    }
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage error) {
        if (!(error.isClear())) {
            ostr << error.message();
        }
        return ostr;
    }

}
</code>```

Main.cpp

```<code>#include <iostream>
#include "ErrorMessage.h"

using namespace std;
using namespace sict;

int main() {
    ErrorMessage T("Testing Error Message Module");
    ErrorMessage e;
    int ret = 0;
    bool ok = true;
    cout << T << endl << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;
    cout << "===========| Long Message\r";
    for (int i = 0; i < 10000000; i++) {
        if (i % 1000000 == 0) {
            cout << "*";
            cout.flush();
        }
        e.message("Some error message that is really long long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long");
    }
    cout << '*' << endl;
    cout << e << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;
    cout << endl;

    e.message("Short Message");
    cout << e << endl << e.message() << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;

    e.clear();
    cout << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;

    if (ok) {
        cout << "You passed all the tests!" << endl;
    }
    else {
        cout << "You did not pass all the tests" << endl;
        ret = 1;
    }

    return ret;
}
</code>```

答:
In your main() you have:

```<code>ErrorMessage e;
</code>```

Which will call your constructor with a null pointer:

```<code>ErrorMessage::ErrorMessage(const char* errorMessage) {
    m_message = nullptr;
    message(errorMessage);
}
</code>```

Your constructor will then call message() and pass that null pointer to it:

```<code>void ErrorMessage::message(const char* str) {
    delete[] m_message;
    m_message = new char[strlen(str) + 1];
    strcpy(m_message, str);
}
</code>```

Hence, you are trying to do strlen() on a null pointer. This is why it's giving segfault.

Body:
I am trying to see if all of my functions work correctly and the program runs to black screen and it closes and it gives me an error with yellow triangle exclammation mark inside the triangle saying that

"Exception thrown 0x01971FD0 (ucrtbased.dll) in milestone2.exe 0xC0000005: Access violation reading location 0x0000000"

arrow indicating .cpp file  m_message = new char [strlen(str) + 1 ] located at void ErrorMessage::message(const char* str) at

im guessing it is some kind of memory issue, anyone knows the solution?

Header file

#ifndef SICT_ERROR_H_
#define SICT_ERROR_H_
namespace sict {
    class ErrorMessage {
        char* m_message;
    public:

        ErrorMessage(const char* errorMessage = nullptr);
        ErrorMessage(const ErrorMessage& em) = delete;
        ErrorMessage& operator=(const ErrorMessage& em) = delete;
        virtual ~ErrorMessage();
        void clear();
        bool isClear() const;
        void message(const char* str);
        const char* message() const;
    };
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage);
}
#endif

Cpp file

#include "ErrorMessage.h"
#include <iostream>
namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
        m_message = nullptr;
        message(errorMessage);
    }
    void ErrorMessage::clear() {
        delete[] m_message;
        m_message = nullptr;
    }
    void ErrorMessage::message(const char* str) {
        delete[] m_message;
        m_message = new char[strlen(str) + 1];
        strcpy(m_message, str);
    }
    const char* ErrorMessage::message() const {
        return m_message;
    }
    ErrorMessage::~ErrorMessage() {
        clear();
    }
    bool ErrorMessage::isClear() const {
        if (m_message == nullptr) {
            return true;
        }
        return false;
    }
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage error) {
        if (!(error.isClear())) {
            ostr << error.message();
        }
        return ostr;
    }

}

Main.cpp

#include <iostream>
#include "ErrorMessage.h"

using namespace std;
using namespace sict;

int main() {
    ErrorMessage T("Testing Error Message Module");
    ErrorMessage e;
    int ret = 0;
    bool ok = true;
    cout << T << endl << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;
    cout << "===========| Long Message\r";
    for (int i = 0; i < 10000000; i++) {
        if (i % 1000000 == 0) {
            cout << "*";
            cout.flush();
        }
        e.message("Some error message that is really long long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long");
    }
    cout << '*' << endl;
    cout << e << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;
    cout << endl;

    e.message("Short Message");
    cout << e << endl << e.message() << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;

    e.clear();
    cout << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;

    if (ok) {
        cout << "You passed all the tests!" << endl;
    }
    else {
        cout << "You did not pass all the tests" << endl;
        ret = 1;
    }

    return ret;
}

Body:
In your main() you have:

ErrorMessage e;

Which will call your constructor with a null pointer:

ErrorMessage::ErrorMessage(const char* errorMessage) {
    m_message = nullptr;
    message(errorMessage);
}

Your constructor will then call message() and pass that null pointer to it:

void ErrorMessage::message(const char* str) {
    delete[] m_message;
    m_message = new char[strlen(str) + 1];
    strcpy(m_message, str);
}

Hence, you are trying to do strlen() on a null pointer. This is why it's giving segfault.


问:
Prism v4: Does it already include a way to handle value converters (as singletons)?
I found this little snippet of code on the web:

```<code>public abstract class ConverterExtension<T>: MarkupExtension, IValueConverter
    where T: class, new()
{
    private static T _converter = null;

    public override Object ProvideValue(IServiceProvider serviceProvider)
    {
        return _converter ?? (_converter = new T());
    }

    public abstract Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture);

    public abstract Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture);
}
</code>```

It basically does 2 things:

 1. creates a singleton (very handy)

 2. Allows you to use the converter without creating a static control (MarkupExtension)

What I'm wondering is if I use Prism v4 as my framework, is something like this already built in. I'd rather use whatever tools Prism has built in it than to write similar or duplicate code. I'm not that familiar with Prism, but I couldn't find anything like this in there. Oh, and I have a similar function for IMultiValueConverter.

答:
IMHO  the need for a singleton with regards to your converters to avoid the multiple instances is a bit of overkill as they are a resource of the View which they reside and will be GC'ed with the View and are in and of themselves very lightweight.

To your question though...Prism is geared towards building modular applications and is not in the realm of providing utility type classes/methods if that is what you were assuming. In terms of registering a singleton within Prism; this is certainly possible.

```<code>IUnityContainer container;
container.RegisterType<ISingleton, Singleton>(new ContainerControlledLifetimeManager());
</code>```

The above code will associate any resolution for ISingleton with Singleton and by use of the ContainerControlledLifetimeManager() parameter will provide a single instance throughout the containers lifetime.

Body:
I found this little snippet of code on the web:

public abstract class ConverterExtension<T>: MarkupExtension, IValueConverter
    where T: class, new()
{
    private static T _converter = null;

    public override Object ProvideValue(IServiceProvider serviceProvider)
    {
        return _converter ?? (_converter = new T());
    }

    public abstract Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture);

    public abstract Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture);
}

It basically does 2 things:

 1. creates a singleton (very handy)

 2. Allows you to use the converter without creating a static control (MarkupExtension)

What I'm wondering is if I use Prism v4 as my framework, is something like this already built in. I'd rather use whatever tools Prism has built in it than to write similar or duplicate code. I'm not that familiar with Prism, but I couldn't find anything like this in there. Oh, and I have a similar function for IMultiValueConverter.

Body:
IMHO  the need for a singleton with regards to your converters to avoid the multiple instances is a bit of overkill as they are a resource of the View which they reside and will be GC'ed with the View and are in and of themselves very lightweight.

To your question though...Prism is geared towards building modular applications and is not in the realm of providing utility type classes/methods if that is what you were assuming. In terms of registering a singleton within Prism; this is certainly possible.

IUnityContainer container;
container.RegisterType<ISingleton, Singleton>(new ContainerControlledLifetimeManager());

The above code will associate any resolution for ISingleton with Singleton and by use of the ContainerControlledLifetimeManager() parameter will provide a single instance throughout the containers lifetime.


问:
How to use sequelize(mysql) to count datas with angularjs + nodejs?
I have three tables in mysql

Contact

Group

ContactGroup

Here is my table structure:

```<code>var Contact = sequelize.define('contact', {
    gsm: {
        type: Sequelize.STRING,
        unique: true,
        required: true
    },
    firstName: Sequelize.STRING,
    lastName: Sequelize.STRING,
    street: Sequelize.STRING,
    city: Sequelize.STRING,
    region: Sequelize.STRING,
    postcode: Sequelize.STRING,
    dob: Sequelize.DATE,
    email: {
        type: Sequelize.STRING,
        unique: true,
        defaultValue: true
    },
    company: Sequelize.STRING,
    url: Sequelize.STRING,
    country: Sequelize.STRING,
    data1: Sequelize.STRING,
    data2: Sequelize.STRING,
    data3: Sequelize.STRING,
    //  resetPasswordToken: Sequelize.STRING,
    //  resetPasswordExpires: Sequelize.DATE,
    //  lastLoggedIn: Sequelize.DATE
})

var Group = sequelize.define('group', {
    groupname: {
        type: Sequelize.STRING,
        unique: true,
        required: true
    },
})

var ContactGroup = sequelize.define('contactgroup', {
    /* Empty */
})

ContactGroup.belongsTo(Contact, {
    onDelete: 'CASCADE'
});
ContactGroup.belongsTo(Group, {
    onDelete: 'CASCADE'
});

Group.hasMany(ContactGroup, {
    onDelete: 'CASCADE'
});
</code>```

My Scenario:
I have two UI in my project:

1.Contact
2.Group

STEP 1: First User can add group,then user will go to create new contact, this contact may contain many groups or with no groups (groups data come as dropdown from the group table, which user done this operation on STEP 1)

For example-real-time scenario:

I am the User who enters into application,

Step 1: I will add new group called 'angulargroup'.

Step 2: I will add my details in contact and select angulargroup in dropdown, so i can belong to angulargroup
Now user interaction over.

Now i got contact id and group id, i stored this group id and contact id in my table called ContactGroup which looks like:

So finally help me to show counts of groups:

I added only one contact in angulargroup, so i want to display CONTACT COUNT as 1 in the below image:

If i added two contacts in angulargroup in the place of contactcount i want to show contactcount as 2

my api.js code:

```<code>exports.getNewGroup = function(req, res) {
    Group.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')),
            'contactCount'
        ]],
        include: [{
            model: ContactGroup,
        }]
    }).then(function(data) {
        return res.status(200).send(data);
    }).catch(function(err) {
        return res.status(400).send(err.message);
    });
};
</code>```

and now how to display this in UI:

```<code>table.table
 tr
  th(style='display : none;') S.no
  th Name
  th Contacts Count
 tr(ng-repeat='group in groups | filter:test')
  td(style='display : none;') {{$index+1}}
  td {{group.groupname}}
  td {{group.contactId}}
</code>```

答:
Finally i got it:

Here is the answer:

my api.js:

```<code>exports.getNewGroup = function (req, res) {
    Group.findAll({
        attributes: {
            include: [
                [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')), 'contactsCount']
            ],
        },
        include: [{
            model: ContactGroup,
            attributes: [],
        }],
        group: ['Group.id'],
        raw: true
    }).then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};
</code>```

Body:
I have three tables in mysql

Contact

Group

ContactGroup

Here is my table structure:

var Contact = sequelize.define('contact', {
    gsm: {
        type: Sequelize.STRING,
        unique: true,
        required: true
    },
    firstName: Sequelize.STRING,
    lastName: Sequelize.STRING,
    street: Sequelize.STRING,
    city: Sequelize.STRING,
    region: Sequelize.STRING,
    postcode: Sequelize.STRING,
    dob: Sequelize.DATE,
    email: {
        type: Sequelize.STRING,
        unique: true,
        defaultValue: true
    },
    company: Sequelize.STRING,
    url: Sequelize.STRING,
    country: Sequelize.STRING,
    data1: Sequelize.STRING,
    data2: Sequelize.STRING,
    data3: Sequelize.STRING,
    //  resetPasswordToken: Sequelize.STRING,
    //  resetPasswordExpires: Sequelize.DATE,
    //  lastLoggedIn: Sequelize.DATE
})

var Group = sequelize.define('group', {
    groupname: {
        type: Sequelize.STRING,
        unique: true,
        required: true
    },
})

var ContactGroup = sequelize.define('contactgroup', {
    /* Empty */
})

ContactGroup.belongsTo(Contact, {
    onDelete: 'CASCADE'
});
ContactGroup.belongsTo(Group, {
    onDelete: 'CASCADE'
});

Group.hasMany(ContactGroup, {
    onDelete: 'CASCADE'
});

My Scenario:
I have two UI in my project:

1.Contact
2.Group

STEP 1: First User can add group,then user will go to create new contact, this contact may contain many groups or with no groups (groups data come as dropdown from the group table, which user done this operation on STEP 1)

For example-real-time scenario:

I am the User who enters into application,

Step 1: I will add new group called 'angulargroup'.

Step 2: I will add my details in contact and select angulargroup in dropdown, so i can belong to angulargroup
Now user interaction over.

Now i got contact id and group id, i stored this group id and contact id in my table called ContactGroup which looks like:

So finally help me to show counts of groups:

I added only one contact in angulargroup, so i want to display CONTACT COUNT as 1 in the below image:

If i added two contacts in angulargroup in the place of contactcount i want to show contactcount as 2

my api.js code:

exports.getNewGroup = function(req, res) {
    Group.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')),
            'contactCount'
        ]],
        include: [{
            model: ContactGroup,
        }]
    }).then(function(data) {
        return res.status(200).send(data);
    }).catch(function(err) {
        return res.status(400).send(err.message);
    });
};

and now how to display this in UI:

table.table
 tr
  th(style='display : none;') S.no
  th Name
  th Contacts Count
 tr(ng-repeat='group in groups | filter:test')
  td(style='display : none;') {{$index+1}}
  td {{group.groupname}}
  td {{group.contactId}}

Body:
Finally i got it:

Here is the answer:

my api.js:

exports.getNewGroup = function (req, res) {
    Group.findAll({
        attributes: {
            include: [
                [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')), 'contactsCount']
            ],
        },
        include: [{
            model: ContactGroup,
            attributes: [],
        }],
        group: ['Group.id'],
        raw: true
    }).then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};


问:
How to get exact latitude and longitude using GPS tracker?
I am getting lat-long using GPS tracker but I am not getting my exact current location what I am getting is location 50 meter away from my current location I am using GPS Tracker only.each and every answer will be appreciable.my location is not getting varied from device to device as per mentioned in previous question.and i did not get any helpful answer their.  </p>

答:
Use google client api for accurate location

you can refer-
https://www.androidhive.info/2015/02/android-location-api-using-google-play-services/


问:
Dynamic Theming Ionic- not working for model view
Im used  this https://devdactic.com/dynamic-theming-ionic/ for  my university project app ,Theme background change are working but  ihave some issue, (theme.dark not work)  Ionic Modals  for not working theme option , other pages are working , How to fix that issue
Thanks

my-code

providers - settings.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/Rx';

@Injectable()
export class SettingsProvider {

  private theme: BehaviorSubject<String>;

  constructor() {
    this.theme = new BehaviorSubject('dark-light');

  }
  setActiveTheme(val) {
    this.theme.next(val);
  }

  getActiveTheme() {
    return this.theme.asObservable();
  }
}
</code>```

page/setting.html

```<code><ion-content padding>
  <p text-center>Theme settings</p>
  <button ion-button full icon-left (click)="toggleAppTheme()" (click)="presentLoading()" style="background: lightgrey;color: #263447;">
    <ion-icon  name="sunny"></ion-icon>Light
  </button>

 <button ion-button full icon-left (click)="toggleAppThemes()" (click)="presentLoading()" style="background: #263447;color: white;">
    <ion-icon  name="bulb"></ion-icon>Dark
  </button>
</ion-content>
</code>```

setting.ts

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams , LoadingController} from 'ionic-angular';
import {SettingsProvider} from "../../providers/settings/settings";

@IonicPage()
@Component({
  selector: 'page-settings',
  templateUrl: 'settings.html',
})
export class SettingsPage {
  selectedTheme: String;
  constructor(public navCtrl: NavController, private settings: SettingsProvider,public loadingCtrl: LoadingController) {
    this.settings.getActiveTheme().subscribe(val => this.selectedTheme = val);

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SettingsPage');
  }
  to

  toggleAppTheme() {

      this.settings.setActiveTheme('light-theme');

  }
  toggleAppThemes() {
 this.settings.setActiveTheme('dark-theme');

  }
}
</code>```

app.html

```<code>ion-menu  id="myMenu" [content]="content" side="right" persistent="true">
  <ion-header>
    <ion-toolbar>
      <ion-grid>

        <ion-row>
          <ion-col col-6>
            <div text-left  style="color: #000000; font-size: 2rem;">
       Car-Rent</div>
          </ion-col>
          <ion-col >
            <div  class="t-setting" style="text-align: right;font-size: 2rem; color:#a57958;" ><ion-icon ios="ios-settings-outline" md="md-settings"></ion-icon></div>

            </ion-col>
          <ion-col>
            <div  class="t-logout" style="font-size: 2rem; color:#a57958; text-indent: 0rem;  text-align: right;"  ><ion-icon ios="ios-log-out" md="md-log-out"></ion-icon></div>
          </ion-col>
        </ion-row>
      </ion-grid>

    </ion-toolbar>
  </ion-header>
  <ion-content >
    <ion-list >
      <button menuClose ion-item *ngFor="let p of pages"[class.activeHighlight]="checkActive(p)" (click)="openPage(p)" > <ion-icon [name]="p.icon" item-left></ion-icon>{{p.title}}</button>

    </ion-list>
  </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"  [class]="selectedTheme" ></ion-nav>
</code>```

答:
Its because you haven't wrote css for Models.

As I can see they asking you to theme your app,

```<code>.dark-theme {
  ion-content {
    background-color: #090f2f;
    color: #fff;
  }

  .toolbar-title {
    color: #fff;
  }

  .header .toolbar-background {
    border-color: #ff0fff;
    background-color: #090f2f;
  }
      // Define model customization scss here
      ion-modal ion-content{
         background-color:#000;
      }
 }
</code>```

So it should work fine.
if it is still not working add :host /deep/ and it should work like a charm.

```<code>:host /deep/ ion-modal ion-content{
   background-color:#000;
}
</code>```

Body:
Im used  this https://devdactic.com/dynamic-theming-ionic/ for  my university project app ,Theme background change are working but  ihave some issue, (theme.dark not work)  Ionic Modals  for not working theme option , other pages are working , How to fix that issue
Thanks

my-code

providers - settings.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/Rx';

@Injectable()
export class SettingsProvider {

  private theme: BehaviorSubject<String>;

  constructor() {
    this.theme = new BehaviorSubject('dark-light');

  }
  setActiveTheme(val) {
    this.theme.next(val);
  }

  getActiveTheme() {
    return this.theme.asObservable();
  }
}

page/setting.html

<ion-content padding>

Theme settings

  <button ion-button full icon-left (click)="toggleAppTheme()" (click)="presentLoading()" style="background: lightgrey;color: #263447;">
    <ion-icon  name="sunny"></ion-icon>Light
  </button>

 <button ion-button full icon-left (click)="toggleAppThemes()" (click)="presentLoading()" style="background: #263447;color: white;">
    <ion-icon  name="bulb"></ion-icon>Dark
  </button>
</ion-content>

setting.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams , LoadingController} from 'ionic-angular';
import {SettingsProvider} from "../../providers/settings/settings";

@IonicPage()
@Component({
  selector: 'page-settings',
  templateUrl: 'settings.html',
})
export class SettingsPage {
  selectedTheme: String;
  constructor(public navCtrl: NavController, private settings: SettingsProvider,public loadingCtrl: LoadingController) {
    this.settings.getActiveTheme().subscribe(val => this.selectedTheme = val);

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SettingsPage');
  }
  to

  toggleAppTheme() {

      this.settings.setActiveTheme('light-theme');

  }
  toggleAppThemes() {
 this.settings.setActiveTheme('dark-theme');

  }
}

app.html

ion-menu  id="myMenu" [content]="content" side="right" persistent="true">
  <ion-header>
    <ion-toolbar>
      <ion-grid>

        <ion-row>
          <ion-col col-6>

       Car-Rent

          </ion-col>
          <ion-col >

<ion-icon ios="ios-settings-outline" md="md-settings"></ion-icon>

            </ion-col>
          <ion-col>

<ion-icon ios="ios-log-out" md="md-log-out"></ion-icon>

          </ion-col>
        </ion-row>
      </ion-grid>

    </ion-toolbar>
  </ion-header>
  <ion-content >
    <ion-list >
      <button menuClose ion-item *ngFor="let p of pages"[class.activeHighlight]="checkActive(p)" (click)="openPage(p)" > <ion-icon [name]="p.icon" item-left></ion-icon>{{p.title}}</button>

    </ion-list>
  </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"  [class]="selectedTheme" ></ion-nav>

Body:
Its because you haven't wrote css for Models.

As I can see they asking you to theme your app,

.dark-theme {
  ion-content {
    background-color: #090f2f;
    color: #fff;
  }

  .toolbar-title {
    color: #fff;
  }

  .header .toolbar-background {
    border-color: #ff0fff;
    background-color: #090f2f;
  }
      // Define model customization scss here
      ion-modal ion-content{
         background-color:#000;
      }
 }

So it should work fine.
if it is still not working add :host /deep/ and it should work like a charm.

:host /deep/ ion-modal ion-content{
   background-color:#000;
}


问:
h5py create_dataset loop slow
I'm trying to create a hdf5 file where each dataset is a 90x18 numpy array.  I'm looking to create 2704332 total datasets for the file with an approximate final size of 40 GB.

```<code>with h5py.File('allDaysData.h5', 'w') as hf:
    for x in list:
        start = datetime.datetime.now()
        hf.create_dataset(x, data=currentData)
        end = datetime.datetime.now()
        print(end-start)
</code>```

When running this the create_dataset command takes no longer then .0004 seconds in the beginning.  Once the file hits around 6 GB it abruptly switches to taking 0.08 seconds per dataset.

Is there some sort of limit on datasets for hdf5 files?

答:
There is a related answer.

In this answer, you can see the performance of create_dataset is decreasing with the increasing of iterations. As h5py stores data in special structure, I think it is because h5py need more time to index the datasets.

There are two solutions, One is to use key word libver='latest'. It will improve the performance significantly even though the generated file will be incompatible with old ones. Second one is to aggregate your arrays into several aggregations. For example, aggregate every 1024 arrays into one.

Title: h5py create_dataset loop slow

Body:
I'm trying to create a hdf5 file where each dataset is a 90x18 numpy array.  I'm looking to create 2704332 total datasets for the file with an approximate final size of 40 GB.

with h5py.File('allDaysData.h5', 'w') as hf:
    for x in list:
        start = datetime.datetime.now()
        hf.create_dataset(x, data=currentData)
        end = datetime.datetime.now()
        print(end-start)

When running this the create_dataset command takes no longer then .0004 seconds in the beginning.  Once the file hits around 6 GB it abruptly switches to taking 0.08 seconds per dataset.

Is there some sort of limit on datasets for hdf5 files?


答:
Why are you returning true if length is 0 ? You should return false instead.

If you're going to use regex, it's better to use match() or test(). Or you can just use .toLowerCase().

When testing your code, use different scenarios to make sure your code works correctly. ["abbb","aee", "aee", "avvv"] always gonna return true. Try adding strings starting with A or starting with other letters to test that your function will return false as well.

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => word[0].toLowerCase() == 'a' ) : false;
};

allStartingWithA(["abbb","aee", "aee", "avvv"]);
allStartingWithA(["Abbb","aee", "aee", "avvv"]);
allStartingWithA(["notStartingWithA","aee", "aee", "avvv"]);```

Title: JS Array.every alway return false on comparing strings

Body:
I'm trying to complete an assignment using every, I tried everything and after and after 1 hour I decided to ask your help.

This function should return true if all the words in the array start with a case-insensitive but always return false, no matter what.

Thank you

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => {word[0] === /"a"/i }) : true;
};

allStartingWithA(["abbb","aee", "aee", "avvv"]);


问:
Fonts not displayed on HTML email and underline comes for hyperlinks
I have an HTML email code as given in the below link:

https://privatebin.net/?1ca92ace7be6c777#LLNgtdGPXCC4Si0Ui7jsEt7P/g+PsZ1gRq08qBTOljo=

The issue is the fonts linked by link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet" type="text/css" is not displayed correctly even though I have added inline styles to all tags.
Also an underline is displayed for the renew button. I tried by adding text-decoration:none style with !important. but was of no use.
Any opinions?

答:
Actually, I didn't get you what exactly you're trying I think you want this applying text-decoration: none; to an anchor. try like this

```<code>a:hover { text-decoration:none; }
</code>```

And if you want font to the body then apply this

```<code>body{ font-family: 'Source Sans Pro', sans-serif;}
</code>```

Body:
Actually, I didn't get you what exactly you're trying I think you want this applying text-decoration: none; to an anchor. try like this

a:hover { text-decoration:none; }

And if you want font to the body then apply this

body{ font-family: 'Source Sans Pro', sans-serif;}