问:
Show only a certain number of contacts
I have developed a program that shows a list of contacts from my phone book.
For this I use the following code:

```<code>    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            if (phones != null) {
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        contactList.add(new Contact(name, phoneNumber, id));
                    }

                phones.close();
            }
        }
        cursor.close();
    }
    adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
    recyclerView.setAdapter(adapter);
</code>```

Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example:
I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on

答:
I assume the reason you want this is because loading all contacts is very slow.
The reason it's very slow is because you currently have 1 query per contact, so if a user has 500 contacts, you'll need to run 500 queries.

You can reduce the number of queries to just one, then I assume you won't need the limit thing.

```<code>String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor phones = getContentResolver().query(Phone.CONTENT_URI, projection, null, null, Phone.DISPLAY_NAME + " ASC");

while (phones.moveToNext()) {
    String name = phones.getString(1);
    String phone = phones.getString(2);
    Long id = phones.getLong(0);

    contactList.add(new Contact(name, phone, id));
}
phones.close();
</code>```

If you want to display only one item per contact, and not per phone, you can change your contactList field to be a HashMap<Long, Contact> instead of a List, and add newly found phones to an existing Contact object if it already exists in the Map.

Something like:

```<code>Contact contact = allContacts.get(id);
if (contact == null) {
    contact = new Contact(name, phone, id);
    allContacts.put(id, contact);
} else {
    contact.addPhone(phone); // you'll need to implement this
}
</code>```

Title: Show only a certain number of contacts

Body:
I have developed a program that shows a list of contacts from my phone book.
For this I use the following code:

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            if (phones != null) {
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        contactList.add(new Contact(name, phoneNumber, id));
                    }

                phones.close();
            }
        }
        cursor.close();
    }
    adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
    recyclerView.setAdapter(adapter);

Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example:
I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on

Body:
I assume the reason you want this is because loading all contacts is very slow.
The reason it's very slow is because you currently have 1 query per contact, so if a user has 500 contacts, you'll need to run 500 queries.

You can reduce the number of queries to just one, then I assume you won't need the limit thing.

String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor phones = getContentResolver().query(Phone.CONTENT_URI, projection, null, null, Phone.DISPLAY_NAME + " ASC");

while (phones.moveToNext()) {
    String name = phones.getString(1);
    String phone = phones.getString(2);
    Long id = phones.getLong(0);

    contactList.add(new Contact(name, phone, id));
}
phones.close();

If you want to display only one item per contact, and not per phone, you can change your contactList field to be a HashMap<Long, Contact> instead of a List, and add newly found phones to an existing Contact object if it already exists in the Map.

Something like:

Contact contact = allContacts.get(id);
if (contact == null) {
    contact = new Contact(name, phone, id);
    allContacts.put(id, contact);
} else {
    contact.addPhone(phone); // you'll need to implement this
}


来源: stackexchange

问:
OOP - inheritance [Java]
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

```<code>class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}
</code>```

output :

Derived show() called

10

答:
There is no polymorphism for fields in Java.

Variables are resolved compile-time, methods run-time. so always Base Class variables (not child’s inherited variables) will be accessed.

So whenever upcasting happens always remember

Base Class variables will be accessed.

Sub Class methods(overridden methods if overriding happened else inherited methods as it is from parent) will be called.

ContentLicense: CC BY-SA 3.0

Title: OOP - inheritance [Java]

Body:
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}

output :

Derived show() called

10


问:
.eq() out of order
I'm trying to select the 3rd element of a JQuery object, by using eq() method. But for some reason the 2nd and 3rd selections pop out in changed order:

```<code>var selection = $("[name=input0], [name=input1], [name=input2], [name=input3]");
selection.eq(1); //turns out to be input2!!
</code>```

What could be the reasons for this behavior? Can I trust acessing it by index in my script?

答:
With the help of the answers and comments and a bit of reading on the documentation.

Turns out that jQuery selects elements in the order they appear in the DOM (HTML), so:

Using a direct array access to a jQuery selection will work if you use that order, but you can only trust it if you are also responsible for the HTML, and you would need to remember this if you are ever going to change the layout.

Bottom line: not the best way to select a specific element.

Title: .eq() out of order

Body:
I'm trying to select the 3rd element of a JQuery object, by using eq() method. But for some reason the 2nd and 3rd selections pop out in changed order:

var selection = $("[name=input0], [name=input1], [name=input2], [name=input3]");
selection.eq(1); //turns out to be input2!!

What could be the reasons for this behavior? Can I trust acessing it by index in my script?


问:
App development for HP Slate (Slate, Windows tablet)
I was wondering how the SDK is or if there is one for the HP Slate.

Would the apps be better off as a WPF app or a Silverlight app running off a browser on the Slate machines?

I understand that it's just a Windows 7 tablet, but I'm not sure if there are any differences.

答:
check out here http://msdn.microsoft.com/en-us/library/ms704849(v=VS.85).aspx

i believe windows 7 has all the stuff built in for the stylus and such. As for wpf or silverlight, it all depends on what your goals are for the application. determine if it will be something that will be over the web or if it will be something done on its own LAN and go from there.

ContentLicense: CC BY-SA 2.5


问:
References in Visual Studio 2017 changing below the hood
I've got a bunch of assemblies .dll in a folder. I open a project and add references to those files.

Et voila', Visual Studio copy those dlls into the output folder (Debug/Release/Whatever), change the references so that they point there and...keeps into the prj file the original path.

Result: I update one, some, all the dll, and Visual Studio cannot care less 'cause all it want to use is the local dll. And, to add to the magic, if I do a Rebuild (which does a Clean and then a Build), the references are not valid anymore 'cause the Clean removed the copied file.

Why it's working this way?

答:
Ok, I randomly found the answer, it's just a matter of bad settings name.

First of all Visual Studio has an option "Copy Local": you may think that setting this to "No" will do the trick, but it does not work (which is obvious, after you try it) because if he doesn't copy the dll in the output folder then when the software run it doesn't find them (unless we are talking about assemblies in the GAC, but that's a different story).

In itself the problem is that Visual Studio should copy local from the original source and keep a reference to that, instead it copies once in the output folder and from that moment on it internally change the references to the output folder. It still keeps the original references into the prj file, but then it ignore them (so that if you Clean the project or the solution there are no more dll and it doesn't compile anymore)

The solution? The setting labelled as "Specific Version". Despite its name it does not enforce the use of the specific version of the DLL you referenced, it just tell to Visual Studio (coupled with Copy Local=Yes) the equivalent of "Copy Always".


问:
Android realm can't build javax/annotation/CheckForNull.class
```<code>classpath "io.realm:realm-gradle-plugin:4.2.0"
</code>```

then

```<code>apply plugin: 'realm-android'
</code>```

then build

Error:Execution failed for task
  ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.tools.r8.errors.CompilationError: Program type already
    present: javax.annotation.CheckReturnValue

more:

```<code>Caused by: java.io.IOException: Duplicate zip entry [32.jar:javax/annotation/CheckForNull.class]
    at proguard.io.JarWriter.getOutputStream(JarWriter.java:138)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:92)
</code>```

My Gradle

```<code>dataBinding.enabled = true

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

implementation "com.android.databinding:compiler:3.1.0-alpha04"
annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04'

implementation 'com.android.support:exifinterface:27.0.2'
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'

implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:multidex:1.0.2'

implementation 'io.reactivex.rxjava2:rxjava:2.0.0-RC2'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.0-RC1'

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1'

implementation 'org.greenrobot:eventbus:3.0.0'
implementation 'com.github.bumptech.glide:glide:4.3.1'

implementation 'com.google.firebase:firebase-core:11.6.2'
implementation 'com.google.firebase:firebase-messaging:11.6.2'
implementation 'com.google.firebase:firebase-crash:11.6.2'

implementation 'com.jakewharton.rxbinding:rxbinding:0.4.0'
implementation 'com.wrapp.floatlabelededittext:library:0.0.6'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'
</code>```

some info:
everything worked like a charm, before I wanted to import the Realm library to my project

答:
You can try adding following lines of code to your build.gradle:

```<code>configurations.all {
    resolutionStrategy.force "com.google.code.findbugs:jsr305:3.0.2"
}
</code>```

If that still doesn't work, you could also add something like

```<code>implementation 'com.google.code.findbugs:jsr305:3.0.2'
</code>```

Body:
classpath "io.realm:realm-gradle-plugin:4.2.0"

then

apply plugin: 'realm-android'

then build

Error:Execution failed for task
  ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.tools.r8.errors.CompilationError: Program type already
    present: javax.annotation.CheckReturnValue

more:

Caused by: java.io.IOException: Duplicate zip entry [32.jar:javax/annotation/CheckForNull.class]
    at proguard.io.JarWriter.getOutputStream(JarWriter.java:138)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:106)
    at proguard.io.FilteredDataEntryWriter.getOutputStream(FilteredDataEntryWriter.java:92)

My Gradle

dataBinding.enabled = true

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

implementation "com.android.databinding:compiler:3.1.0-alpha04"
annotationProcessor 'com.android.databinding:compiler:3.1.0-alpha04'

implementation 'com.android.support:exifinterface:27.0.2'
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'

implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:multidex:1.0.2'

implementation 'io.reactivex.rxjava2:rxjava:2.0.0-RC2'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.0-RC1'

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1'

implementation 'org.greenrobot:eventbus:3.0.0'
implementation 'com.github.bumptech.glide:glide:4.3.1'

implementation 'com.google.firebase:firebase-core:11.6.2'
implementation 'com.google.firebase:firebase-messaging:11.6.2'
implementation 'com.google.firebase:firebase-crash:11.6.2'

implementation 'com.jakewharton.rxbinding:rxbinding:0.4.0'
implementation 'com.wrapp.floatlabelededittext:library:0.0.6'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'

some info:
everything worked like a charm, before I wanted to import the Realm library to my project

Body:
You can try adding following lines of code to your build.gradle:

configurations.all {
    resolutionStrategy.force "com.google.code.findbugs:jsr305:3.0.2"
}

If that still doesn't work, you could also add something like

implementation 'com.google.code.findbugs:jsr305:3.0.2'


问:
Replace each text match found by appending a count value - Regex (Notepad++)
My text file is as below :

```<code><number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
</code>```

I want to append a count value to each subsequent text (<number>Object</number>) that is found.

Output:

```<code><number>Object1</number>
<name>Object</name>
<number>Object2</number>
<name>Object</name>
<number>Object3</number>
<name>Object</name>
<number>Object4</number>
<name>Object</name>
<number>Object5</number>
<name>Object</name>
</code>```

Note: Need to do this using Notepad++ or any other freeware Text editor.

答:
A perl one-liner that does the job:</p>

```<code>perl -ane 's~(?<=<number>Object)(?=</number>)~++$i~e;print' inputfile > outputfile
</code>```

Body:
My text file is as below :

<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>
<number>Object</number>
<name>Object</name>

I want to append a count value to each subsequent text (<number>Object</number>) that is found.

Output:

<number>Object1</number>
<name>Object</name>
<number>Object2</number>
<name>Object</name>
<number>Object3</number>
<name>Object</name>
<number>Object4</number>
<name>Object</name>
<number>Object5</number>
<name>Object</name>

Note: Need to do this using Notepad++ or any other freeware Text editor.

Body:
A perl one-liner that does the job:

perl -ane 's~(?<=<number>Object)(?=</number>)~++$i~e;print' inputfile > outputfile


问:
How to put local branch to origin with GitKraken?

I created branches and it shows branch does not exist on origin when I pull files.

How to add my local branches to origin with GitKraken?

No cmd and GitHub.

答:
Right click on the local branch and from the context menu select Set
Upstream

Then type a name for your remote branch and click ok.

Ref: https://reganmusic.wordpress.com/2016/07/19/branching-in-gitkraken/

ContentLicense: CC BY-SA 4.0


问:
Getting the sha1 of a desired commit from a remote repository
Using git reflog, a user can only access his local reflog information?

How can one see the sha1 of a desired commit from a remote repository?

答:
Git reflog is a history of sha1s you had checked out. This is true for whatever repository you're in. If delete your repository and clone it again, you will have lost that history.

The second question doesn't make sense. I'm guessing that you want to git fetch and then browse what is on the remote that you didn't merge yet. You would do that with git log master..origin/master to see what the remote master has that you don't.


问:
Scraping multiple webpages with Python
```<code>from bs4 import BeautifulSoup
import urllib, time
class scrape(object):
    def __init__(self):
        self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6']
        self.telephones = []
    def extract_info(self):
        for link in self.urls:
            data = urllib.request.urlopen(link).read()
            soup = BeautifulSoup(data, "lxml")
            for tel in soup.findAll("span", {"class":"call"}):
                self.telephones.append(tel.text.strip())
            time.sleep(1)
        return self.telephones

to = scrape()
print(to.extract_info())
</code>```

What is wrong? This code is hanging after second website. It should extract phone numbers from each webpage in list self.urls

答:
All you need to do is put a headers in your request parameter and make a go. Try this:

```<code>from bs4 import BeautifulSoup
import requests, time

class scrape(object):

    def __init__(self):
        self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6']
        self.telephones = []

    def extract_info(self):
        for link in self.urls:
            data = requests.get(link,headers={"User-Agent":"Mozilla/5.0"}) #it should do the trick
            soup = BeautifulSoup(data.text, "lxml")
            for tel in soup.find_all("span",{"class":"call"}):
                self.telephones.append(tel.text.strip())
            time.sleep(1)
        return self.telephones

crawl = scrape()
print(crawl.extract_info())
</code>```

Title: Scraping multiple webpages with Python

Body:
from bs4 import BeautifulSoup
import urllib, time
class scrape(object):
    def __init__(self):
        self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6']
        self.telephones = []
    def extract_info(self):
        for link in self.urls:
            data = urllib.request.urlopen(link).read()
            soup = BeautifulSoup(data, "lxml")
            for tel in soup.findAll("span", {"class":"call"}):
                self.telephones.append(tel.text.strip())
            time.sleep(1)
        return self.telephones

to = scrape()
print(to.extract_info())

What is wrong? This code is hanging after second website. It should extract phone numbers from each webpage in list self.urls

Body:
All you need to do is put a headers in your request parameter and make a go. Try this:

from bs4 import BeautifulSoup
import requests, time

class scrape(object):

    def __init__(self):
        self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6']
        self.telephones = []

    def extract_info(self):
        for link in self.urls:
            data = requests.get(link,headers={"User-Agent":"Mozilla/5.0"}) #it should do the trick
            soup = BeautifulSoup(data.text, "lxml")
            for tel in soup.find_all("span",{"class":"call"}):
                self.telephones.append(tel.text.strip())
            time.sleep(1)
        return self.telephones

crawl = scrape()
print(crawl.extract_info())


问:
Xamarin: Cant register for location updates. "Specified cast not valid"
so i was working on an app, that would simply give your coordinates back to the user. This worked fine as long as I had it in my main activity.
Now i changed all of this into its own class. Now, when I start this class the first thing that happens is this line of code:

```<code>public void StartLocationUpdates()
{
    _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
</code>```

This SHOULD now have my phone start to listen for location updates. But when i call this line, I get:

System.InvalidCastException: Specified cast is not valid.

Why is this happening?
Also, Do I even need this code? Because the method "InitializeLocationManager()" should do this for me, right?

Thanks :)

答:
I ahd the same error today and found the solution: make sure the service you're passing to

```<code>_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
</code>```

as the last arguments inherits from Java.Lang.Object, like:

```<code>public class GpsService : Java.Lang.Object, ILocationListener
{
    ...
}
</code>```

Body:
so i was working on an app, that would simply give your coordinates back to the user. This worked fine as long as I had it in my main activity.
Now i changed all of this into its own class. Now, when I start this class the first thing that happens is this line of code:

public void StartLocationUpdates()
{
    _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}

This SHOULD now have my phone start to listen for location updates. But when i call this line, I get:

System.InvalidCastException: Specified cast is not valid.

Why is this happening?
Also, Do I even need this code? Because the method "InitializeLocationManager()" should do this for me, right?

Thanks :)

Body:
I ahd the same error today and found the solution: make sure the service you're passing to

_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);

as the last arguments inherits from Java.Lang.Object, like:

public class GpsService : Java.Lang.Object, ILocationListener
{
    ...
}


问:
Change phone number
I'm trying to understand how to access the phone number here:

```<code><div class="address__location">
  <p>
    Siddals Road
    <br> Derby DE1 2QD
  </p>
  <p>Main Phone:
    <a href="tel:0800123123
         ">0800123123</a>
  </p>
</div>
</code>```

I need to find the html element of the phone number so I can replace it with another number.

So if I were to use getElementbyID"xxx" it would return the phone number.

答:
There is no id attribute set on that element.

You could use another selector, though, by using document.querySelector and passing a[href^="tel:"]. This will search for a elements that have an href attribute that starts-with (that is what ^= means) the text tel:.

so

```<code>var telephoneNode = document.querySelector('a[href^="tel:"]');

telephoneNode.textContent = 'some other phone'; // change the displayed text
telephoneNode.href = 'some other url'; // change the href and in effect where the link points to
</code>```

Title: Change phone number

Body:
I'm trying to understand how to access the phone number here:

    Siddals Road

 Derby DE1 2QD

Main Phone:
    0800123123

I need to find the html element of the phone number so I can replace it with another number.

So if I were to use getElementbyID"xxx" it would return the phone number.

Body:
There is no id attribute set on that element.

You could use another selector, though, by using document.querySelector and passing a[href^="tel:"]. This will search for a elements that have an href attribute that starts-with (that is what ^= means) the text tel:.

so

var telephoneNode = document.querySelector('a[href^="tel:"]');

telephoneNode.textContent = 'some other phone'; // change the displayed text
telephoneNode.href = 'some other url'; // change the href and in effect where the link points to


问:
Not Auto launching app when I run thru android studio
I right click my project-> Run -> All Tests

Its Building and Installing in my Devices.

But app is not automatically launching like in eclipse.

It seems like I installed it through adb install in terminal. Need to manually open each time I installed.

答:
Try this:

Open your MainActivity.

Right button of the mouse and select 'Run MainActivity'


问:
Building a trusted Silverlight OOB app on a build server
I am trying to build an Out Of Browser Silverlight app with Elevated permissions required. I've followed these instructions to create a code signing certificate and I've checked the box to 'Sign the Xap File' in the properties pane in VS2010. I'm able to build and test out the functionality on my local machine. When I try to build with msbuild on the build server though, I get these errors:

error MSB3326: Cannot import the following key file: . The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store.

error MSB3321: Importing key file "MySPC.pfx" was canceled.

I've installed the "MyCA.cer" (self signed CA) to the Trusted Root Certificate Athorities store on the build server and I have tried installing the "MySPC.pfx" the the same store and to the Trusted Publishers store to no avail.

Has anyone had any experience doing this?

答: I ended up having to sign the .xap with a certificate from our CA server. This way we don't have to install a certificate on any of the users machines that run the silverlight app out of browser.</p>


问:
Using Get-ADUser with Import-Csv for future expansion to update user using Set-ADUser
At the end of this project, I am trying to use a CSV file to update users personal details within AD. I plan to use Get-ADUser piped into Set-ADUser

My current problem is returning the user records from AD using Get-ADUser

My CSV file is as follows

```<code>FirstName,LastName,DisplayName,CompanyName,EmailAddress
John,Doe,John Doe,Test Company,john.doe@company.com
Jane,Doe,Jane Doe,Test Company,jane.doe@company.com
</code>```

My PowerShell script looks like this

```<code>Import-Csv .\Users.csv | ForEach {

Write-Host $_.EmailAddress
Write-Host $_.DisplayName

"`"$($_.EmailAddress)`""

Get-ADUser -Filter { userPrincipalName -eq "`"$($_.EmailAddress)`""}
}
</code>```

What is returned is

```<code>john.doe@company.com
John Doe
"john.doe@company.com"
jane.doe@company.com
Jane Doe
"jane.doe@company.com"
</code>```

Running Get-ADUser without using variables like below, returns the user account as it should, whereas the above code does not.

```<code>Get-ADUser -Filter { userPrincipalName -eq "john.doe@company.com"}
</code>```

Where am I going wrong?

答:
The $_ is a variable for the current value in the pipe line or current object that the cmd-let returns. When you use $_ in Get-ADUser, it $_ will be the object returned from Get-ADUser cmd-let. Just create a variable and assign $_.EmailAddress inside foreach loop and pass this variable to filter.</p>

```<code>Import-Csv .\Users.csv | ForEach {
    $emailAddress = $_.EmailAddress
    Write-Host $_.EmailAddress
    Write-Host $_.DisplayName
    Get-ADUser -Filter { userPrincipalName -eq $emailAddress }
}
</code>```

Body:
At the end of this project, I am trying to use a CSV file to update users personal details within AD. I plan to use Get-ADUser piped into Set-ADUser

My current problem is returning the user records from AD using Get-ADUser

My CSV file is as follows

FirstName,LastName,DisplayName,CompanyName,EmailAddress
John,Doe,John Doe,Test Company,john.doe@company.com
Jane,Doe,Jane Doe,Test Company,jane.doe@company.com

My PowerShell script looks like this

Import-Csv .\Users.csv | ForEach {

Write-Host $_.EmailAddress
Write-Host $_.DisplayName

"`"$($_.EmailAddress)`""

Get-ADUser -Filter { userPrincipalName -eq "`"$($_.EmailAddress)`""}
}

What is returned is

john.doe@company.com
John Doe
"john.doe@company.com"
jane.doe@company.com
Jane Doe
"jane.doe@company.com"

Running Get-ADUser without using variables like below, returns the user account as it should, whereas the above code does not.

Get-ADUser -Filter { userPrincipalName -eq "john.doe@company.com"}

Where am I going wrong?

Body:
The $_ is a variable for the current value in the pipe line or current object that the cmd-let returns. When you use $_ in Get-ADUser, it $_ will be the object returned from Get-ADUser cmd-let. Just create a variable and assign $_.EmailAddress inside foreach loop and pass this variable to filter.

Import-Csv .\Users.csv | ForEach {
    $emailAddress = $_.EmailAddress
    Write-Host $_.EmailAddress
    Write-Host $_.DisplayName
    Get-ADUser -Filter { userPrincipalName -eq $emailAddress }
}


问:
additional modules for python in tkinter issue

I'm making a tkinter app in python which requires a few python modules (for example paramiko) that need to be installed additionally.

When I will be done with the whole app and create an executable version of the app (.exe extension), and send this app to one of my friends' computer, can he run the app without having python, paramiko, etc. on his computer?

2nd question: What is the exe equivavelent in mac for that I could make my app runnable instantly (I think of some kind of portable version.)

Thanks!

答:
You want Cx_Freeze

Yes the idea is to turn it into an application that can be run on computers without Python installed.  If it does not run correctly then the script has not been properly "frozen".

Cx_Freeze works on all major platforms as described in their front page (see link above for details) but you must freeze it on each platform you wish to develop for (Windows on Windows, Mac on a Mac and so on)  There is no executable that can run on all platforms.

There are alternatives such as Pyinstaller and Py2app.  The latter works only for Python 2 and is no longer maintained.  I would recommend Cx_Freeze or Pyinstaller because they are the only two still being maintained.

Pyinstaller is easier but cx_Freeze also offers a lot of options when building.


问:
Cost of developing a Google Assistant App?
What costs are involved with developing and/or releasing a Google Assistant App? </p>

<p>eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn? </p>

答:
First of all - you don't need to use Dialogflow or Firebase to develop your action. Both are suggested, but neither are required. You can use any NLP you want, or none at all if you use the Actions SDK (but you want an NLP). You can use any backend at all, including running it off your local machine and tunneling to it via ngrok, but you don't want to do that for production.

But, during development (and even during a light deployment before your action becomes massively popular and a stand-out hit), you have lots of solutions that will be free.

Dialogflow is free for use with the Google Assistant. Period. There is an Enterprise edition which offers additional services and support for a cost, but you won't need them. There are restrictions, but you won't bump into them until you hit 3 requests per second - which you shouldn't during development.

Firebase's free tier (the Spark Plan) is good for very simple experimentation, but once you start doing network calls to outside Google's network (if you are trying to call the network API for other services), you will be blocked. No worries! The "Blaze Plan" paid tier does require a way to bill you, but they don't start billing you until you get quite a bit of usage: 2 million function calls / month and similarly scaled usage of CPU, memory, and network. So even the "Blaze Plan" will be free during development (and for basic usage).

Updated, December 2020

Things have changed a bit since the original answer was posted, but the underlying basics remain true - there is no charge to develop for Actions on Google.

Dialogflow now has an "Essentials" edition and a more advanced "CX" edition. While you can still use both to build Actions, they're not really intended for this purpose anymore.

Instead, Google has included the Actions Builder into the Actions Console to handle the NLP work. The Actions SDK works with this, but can also just pass along all the STT information to your webhook. Both are also free to use.

Body:
What costs are involved with developing and/or releasing a Google Assistant App?

eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn?


问:
Memoization javascript

I'm studying JavaScript from the book JavaScript: The Good Parts, in the memoization section there is an example about using memoize technique to do Fibonacci problem

We create a general function call memoizer, it takes an memo array and the fundamental function, returns a shell function that manages the memo and calls fundamental function

```<code> var memoizer = function(memo, fundamental) {
  var shell = function(n) {
    var result = memo[n];
    if (typeof result !== 'number') {
      result = fundamental(shell, n);
      memo[n] = result;
    }
    return result;
  };
  return shell;
};
</code>```

And then create fibonacci like this:

```<code>var fibonacci = memoizer([0, 1], function(shell, n) {
    return shell(n-1) + shell(n-2);
});
</code>```

If I run fibonacci(10), the result will be displayed exactly.

But the thing that makes me confused is the n parameter shell function in memoizer function. I know that it is the value that we want to compute. But where is it come from? How can I call fibonacci(10), for example, can pass the value 10 to n? And what is exactly the var fibonacci? Is it a function or points to a function object as memoizer?

Thanks for any help!

答:
So, to understand this fully, you need to understand things below as fundamental pieces.

Closure How do JavaScript closures work?

Scope What is the scope of variables in JavaScript?

First class object What is meant by 'first class object'?

So, now look at the code.

var memoizer is assigned as a function that returns an another function inside.

```<code>var memoizer = function(memo, fundamental) {
  var shell = function(n) {
    ... do some works ...
  };
  return shell;
};
</code>```

Can you see it? var shell is returned at the end of the line in memoizer

And whatever the inner logic is in memoizer, the result of it is assigned to var fibonacci

```<code>var fibonacci = memoizer([0, 1], function(shell, n) {
    return shell(n-1) + shell(n-2);
});
</code>```

So, it means fibonacci equals the result of memoizer (Since we excuted it), and the result of memoizer equals shell function. If you read those links given to you by me well, you can understand what is going on behind the scenes.

By the way, the code you've given isn't the best way. Because anyway closure makes an activated object alive that isn't necessary.

This code below is an another way of making fibonacci, this isn't the absolute best way, however, I recommend you to compare this code with your code, and figure the differences out.

var result = [];
result[0] = 1;
result[1] = 1;

function fibonacci(n){
    var i;

    for(i = 2; i < n; i++){
      if(!result[i]){
        result[i] = result[i-1] + result[i-2];
      }
    }
    return result[i-1];
}

console.log(fibonacci(10));```

Title: Memoization javascript

Body:
I'm studying JavaScript from the book JavaScript: The Good Parts, in the memoization section there is an example about using memoize technique to do Fibonacci problem

We create a general function call memoizer, it takes an memo array and the fundamental function, returns a shell function that manages the memo and calls fundamental function

 var memoizer = function(memo, fundamental) {
  var shell = function(n) {
    var result = memo[n];
    if (typeof result !== 'number') {
      result = fundamental(shell, n);
      memo[n] = result;
    }
    return result;
  };
  return shell;
};

And then create fibonacci like this:

var fibonacci = memoizer([0, 1], function(shell, n) {
    return shell(n-1) + shell(n-2);
});

If I run fibonacci(10), the result will be displayed exactly.

But the thing that makes me confused is the n parameter shell function in memoizer function. I know that it is the value that we want to compute. But where is it come from? How can I call fibonacci(10), for example, can pass the value 10 to n? And what is exactly the var fibonacci? Is it a function or points to a function object as memoizer?

Thanks for any help!

Body:
So, to understand this fully, you need to understand things below as fundamental pieces.

Closure How do JavaScript closures work?

Scope What is the scope of variables in JavaScript?

First class object What is meant by 'first class object'?

So, now look at the code.

var memoizer is assigned as a function that returns an another function inside.

var memoizer = function(memo, fundamental) {
  var shell = function(n) {
    ... do some works ...
  };
  return shell;
};

Can you see it? var shell is returned at the end of the line in memoizer

And whatever the inner logic is in memoizer, the result of it is assigned to var fibonacci

var fibonacci = memoizer([0, 1], function(shell, n) {
    return shell(n-1) + shell(n-2);
});

So, it means fibonacci equals the result of memoizer (Since we excuted it), and the result of memoizer equals shell function. If you read those links given to you by me well, you can understand what is going on behind the scenes.

By the way, the code you've given isn't the best way. Because anyway closure makes an activated object alive that isn't necessary.

This code below is an another way of making fibonacci, this isn't the absolute best way, however, I recommend you to compare this code with your code, and figure the differences out.

var result = [];
result[0] = 1;
result[1] = 1;

function fibonacci(n){
    var i;

    for(i = 2; i < n; i++){
      if(!result[i]){
        result[i] = result[i-1] + result[i-2];
      }
    }
    return result[i-1];
}

console.log(fibonacci(10));


问:
How to disable authorization for /restart endpoint?
I try to implement restart feature in my web application.

I've added following dependencies:

```<code>compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")
</code>```

In start logs I found that post /restart was registered.

I decided to request this url:

But result is fail. I understand that this url should be protected but I have custom authorization/authentication mechanism and I don't have rights to change it.

Is there way to disable protection for this url? A better way - to have service which I can inject inside my controller and invoke. Is there something inside the spring to solve my problem?

答:
Reason is that spring cloud enabled the security for endpoints by default.You need disable security for management (because /restart endpoint is an additional endpoint for management), in properties:

```<code>management.security.enabled=false
</code>```

to remap endpoints from ../restart to /foo/restart, you need to add additional property:

```<code>management.context-path=/foo
</code>```

To implement your custom end point, you just have to implement interface Endpoint and override its methods.

to disable default restart endpoint:

```<code>endpoints.restart.enabled=false
</code>```

Body:
I try to implement restart feature in my web application.

I've added following dependencies:

compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")

In start logs I found that post /restart was registered.

I decided to request this url:

But result is fail. I understand that this url should be protected but I have custom authorization/authentication mechanism and I don't have rights to change it.

Is there way to disable protection for this url? A better way - to have service which I can inject inside my controller and invoke. Is there something inside the spring to solve my problem?

Body:
Reason is that spring cloud enabled the security for endpoints by default.You need disable security for management (because /restart endpoint is an additional endpoint for management), in properties:

management.security.enabled=false

to remap endpoints from ../restart to /foo/restart, you need to add additional property:

management.context-path=/foo

To implement your custom end point, you just have to implement interface Endpoint and override its methods.

to disable default restart endpoint:

endpoints.restart.enabled=false


问:
beep in WinCE , it possible ?
is it possible to make beep in WinCE ?

i try and i get an error

答: Yes.  P/Invoke PlaySound or sndPlaySound or MessageBeep.  See this or this or this.  It's amazing what 30 seconds with a search engine can turn up.</p>

OwnerDisplayName: Gold

Title: beep in WinCE , it possible ?

LastEditorDisplayName: ctacke

OwnerDisplayName: ctacke


问:
How can I obtain the case-sensitive path on Windows?
I need to know which is the real path of a given path.

For example:

The real path is: d:\src\File.txt

And the user give me: D:\src\file.txt

I need as a result: d:\src\File.txt

答:
On Windows, paths are case-insensitive. So both paths are equally real.

If you want to get some kind of a path with canonical capitalization (i. e. how Windows thinks it should be capitalized), you can call FindFirstFile() with the path as a mask, then take the full name of the found file. If the path is invalid, then you won't get a canonical name, natually.


问:
Observe each element of RecyclerView (Architecture components)
I'm trying to figure out what is the best way to create a list of elements (each elements use databinding to set the data) and observe each one for changes. Actually I have a ViewModel with a MutableLiveData List MutableLiveData<List<ElementModel>>.

The thing is that in each element there are actions like upload a file or enter a password so I have to change the UI once the actions are finished or when are loading. I tried with notifyItemChanged in the RecyclerView adapter but the animations are really bad, it's better when you update the layout with executePendingBindings

Does anyone witch is the best way to approach this problem?

答:
If you use equals, your object must properly override Object#equals().
Incorrectly returning false here will result in too many animations.

```<code> public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
            @Override
            public boolean areItemsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // User properties may have changed if reloaded from the DB, but ID is fixed
                return oldUser.getId() == newUser.getId();
            }
            @Override
            public boolean areContentsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // NOTE: if you use equals, your object must properly override Object#equals()
                // Incorrectly returning false here will result in too many animations.
                return oldUser.equals(newUser);
            }
</code>```

User class as below

```<code>public class UserInfo{
    @PrimaryKey
    @NonNull
    private String number;

    private String name;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UserInfo(String number, String name) {
        this.number = number;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        UserInfo user = (UserInfo) obj;

        return user.number == this.number && user.name == this.name;
    }

    public static DiffCallback<UserInfo> DIFF_CALLBACK = new DiffCallback<UserInfo>() {
        @Override
        public boolean areItemsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return oldItem.number.equals(newItem.number);
        }

        @Override
        public boolean areContentsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            // If this comparisons  wrong then to many UI changes in RecycleView
            return oldItem.equals(newItem);
        }

        @Override
        public Object getChangePayload(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return super.getChangePayload(oldItem, newItem);
        }
    };
}
</code>```

please refer link

Body:
If you use equals, your object must properly override Object#equals().
Incorrectly returning false here will result in too many animations.

 public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
            @Override
            public boolean areItemsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // User properties may have changed if reloaded from the DB, but ID is fixed
                return oldUser.getId() == newUser.getId();
            }
            @Override
            public boolean areContentsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // NOTE: if you use equals, your object must properly override Object#equals()
                // Incorrectly returning false here will result in too many animations.
                return oldUser.equals(newUser);
            }

User class as below

public class UserInfo{
    @PrimaryKey
    @NonNull
    private String number;

    private String name;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UserInfo(String number, String name) {
        this.number = number;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        UserInfo user = (UserInfo) obj;

        return user.number == this.number && user.name == this.name;
    }

    public static DiffCallback<UserInfo> DIFF_CALLBACK = new DiffCallback<UserInfo>() {
        @Override
        public boolean areItemsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return oldItem.number.equals(newItem.number);
        }

        @Override
        public boolean areContentsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            // If this comparisons  wrong then to many UI changes in RecycleView
            return oldItem.equals(newItem);
        }

        @Override
        public Object getChangePayload(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return super.getChangePayload(oldItem, newItem);
        }
    };
}

please refer link


问:
Laravel eloquent multiple whereNotIn
I'm trying to make a query where I use multiple whereNotIn arrays. For some reason, they block each other and ignores the other query parameters.

Any clues on how to solve this?

```<code>$products = Products::orderBy('id','DESC')
    ->where('status', '=', 4)
    ->whereNotIn('category', $excluded)
    ->whereNotIn('location', ['New York', 'Boston', 'Washington, DC', 'Charlotte'])
    ->take(400)
    ->get();
</code>```

答:
You need to group condtions orWhereNotIn inside where to exclude both condition, try this

```<code>$locations = ['New York', 'Boston', 'Washington, DC', 'Charlotte'];
$products = Products::orderBy('id','DESC')
->where('status', '=', 4)
->where(function($q) use ($locations,$excluded) {
    $q->orWhereNotIn('category', $excluded);
    $q->orWhereNotIn('location', $locations);
})
->take(400)
->get();
</code>```

Title: Laravel eloquent multiple whereNotIn

Body:
I'm trying to make a query where I use multiple whereNotIn arrays. For some reason, they block each other and ignores the other query parameters.

Any clues on how to solve this?

$products = Products::orderBy('id','DESC')
    ->where('status', '=', 4)
    ->whereNotIn('category', $excluded)
    ->whereNotIn('location', ['New York', 'Boston', 'Washington, DC', 'Charlotte'])
    ->take(400)
    ->get();

Body:
You need to group condtions orWhereNotIn inside where to exclude both condition, try this

$locations = ['New York', 'Boston', 'Washington, DC', 'Charlotte'];
$products = Products::orderBy('id','DESC')
->where('status', '=', 4)
->where(function($q) use ($locations,$excluded) {
    $q->orWhereNotIn('category', $excluded);
    $q->orWhereNotIn('location', $locations);
})
->take(400)
->get();


问:
Android DataBinding 3.0.1 calling method on observable variable causes wrong code generated that leads to NPE
I've written such layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable name="vm"
                  type="example.Vm" />
    </data>

    <android.support.constraint.ConstraintLayout android:id="@+id/root"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent">

        <ImageView android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_marginEnd="16dp"
                   android:layout_marginRight="16dp"
                   android:onClick="@{() -> vm.observableField.buttonClicked()}"
                   app:layout_constraintBottom_toBottomOf="parent"
                   app:layout_constraintRight_toRightOf="parent"
                   app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>
</layout>
</code>```

In onClick parameter I'm calling method on example.Vm that has such field:

```<code>public ObservableField<SomeClass> observableField = new ObservableField<>();
</code>```

Android databinding generated such code:

```<code>// Listener Stub Implementations
// callback impls
public final void _internalCallbackOnClick(int sourceId , android.view.View callbackArg_0) {
    // localize variables for thread safety
    // vm != null
    boolean vmJavaLangObjectNull = false;
    // vm.someClassObservable
    android.databinding.ObservableField<biz.i20.fire_android.feature.act.SomeClass> vmSomeClassObservable = null;
    // vm
    biz.i20.fire_android.feature.actscreen.ActVm vm = mVm;
    // vm.someClassObservable != null
    boolean vmSomeClassObservableJavaLangObjectNull = false;
    // vm.someClassObservable.get()
    biz.i20.fire_android.feature.act.SomeClass vmSomeClassObservableGet = null;

    vmJavaLangObjectNull = (vm) != (null);
    if (vmJavaLangObjectNull) {

        vmSomeClassObservable = vm.someClassObservable;

        vmSomeClassObservableJavaLangObjectNull = (vmSomeClassObservable) != (null);
        if (vmSomeClassObservableJavaLangObjectNull) {

            vmSomeClassObservableGet.buttonClicked();
        }
    }
}
</code>```

As you can see here, databinding compiler initializes variable vmSomeClassObservableGet with null value, and then does not get it's value from vmSomeClassObservable.
I can fix this issue by explicitly calling .get() on ObservableField, however it leads to compiler warning:

Warning:warning: Do not explicitly call 'get()' on ObservasbleFields
  in an expression. This support will be removed soon.
  'vm.observableField.get()'

How can i fix this issue? Seems like bug.

答:
You don't need to wrap the class with ObservableField in order to call it from your layout.

I would replace your field with:

```<code>public SomeClass observableField = referenceToSomeClass;
</code>```

(I would rename observableField to a more appropriate name, but I left it like this to make the answer more clear)

Body:
I've written such layout:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable name="vm"
                  type="example.Vm" />
    </data>

    <android.support.constraint.ConstraintLayout android:id="@+id/root"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent">

        <ImageView android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_marginEnd="16dp"
                   android:layout_marginRight="16dp"
                   android:onClick="@{() -> vm.observableField.buttonClicked()}"
                   app:layout_constraintBottom_toBottomOf="parent"
                   app:layout_constraintRight_toRightOf="parent"
                   app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>
</layout>

In onClick parameter I'm calling method on example.Vm that has such field:

public ObservableField<SomeClass> observableField = new ObservableField<>();

Android databinding generated such code:

// Listener Stub Implementations
// callback impls
public final void _internalCallbackOnClick(int sourceId , android.view.View callbackArg_0) {
    // localize variables for thread safety
    // vm != null
    boolean vmJavaLangObjectNull = false;
    // vm.someClassObservable
    android.databinding.ObservableField<biz.i20.fire_android.feature.act.SomeClass> vmSomeClassObservable = null;
    // vm
    biz.i20.fire_android.feature.actscreen.ActVm vm = mVm;
    // vm.someClassObservable != null
    boolean vmSomeClassObservableJavaLangObjectNull = false;
    // vm.someClassObservable.get()
    biz.i20.fire_android.feature.act.SomeClass vmSomeClassObservableGet = null;

    vmJavaLangObjectNull = (vm) != (null);
    if (vmJavaLangObjectNull) {

        vmSomeClassObservable = vm.someClassObservable;

        vmSomeClassObservableJavaLangObjectNull = (vmSomeClassObservable) != (null);
        if (vmSomeClassObservableJavaLangObjectNull) {

            vmSomeClassObservableGet.buttonClicked();
        }
    }
}

As you can see here, databinding compiler initializes variable vmSomeClassObservableGet with null value, and then does not get it's value from vmSomeClassObservable.
I can fix this issue by explicitly calling .get() on ObservableField, however it leads to compiler warning:

Warning:warning: Do not explicitly call 'get()' on ObservasbleFields
  in an expression. This support will be removed soon.
  'vm.observableField.get()'

How can i fix this issue? Seems like bug.

Body:
You don't need to wrap the class with ObservableField in order to call it from your layout.

I would replace your field with:

public SomeClass observableField = referenceToSomeClass;

(I would rename observableField to a more appropriate name, but I left it like this to make the answer more clear)


问:
Only counting data that fits certain criteria in SQL on Microsoft Access
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have. </p>

```<code>SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;
</code>```

<p>I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them. </p>

答:
You can't use WHERE the way you're using it. You're looking for IIF to do comparisons.

Since Count is rather inflexible, using Sum and assigning ones and zeroes on a comparison is easier.

```<code>SELECT
StudDetails.CurrClass as 'class',
Sum(IIF(StudDetails.sex="M", 1, 0)) AS malecount,
Sum(IIF(StudDetails.sex="M", 0, 1))  AS femalecount
FROM StudDetails
GROUP BY StudDetails.CurrClass;
</code>```

Body:
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have.

SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;

I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them.

Body:
You can't use WHERE the way you're using it. You're looking for IIF to do comparisons.

Since Count is rather inflexible, using Sum and assigning ones and zeroes on a comparison is easier.

SELECT
StudDetails.CurrClass as 'class',
Sum(IIF(StudDetails.sex="M", 1, 0)) AS malecount,
Sum(IIF(StudDetails.sex="M", 0, 1))  AS femalecount
FROM StudDetails
GROUP BY StudDetails.CurrClass;


答:
The way to get the actual path of a file (this won't work for folders) is to follow these steps:

Call CreateFileMapping to create a mapping for the file.

Call GetMappedFileName to get the name of the file.

Use QueryDosDevice to convert it to an MS-DOS-style path name.

If you feel like writing a more robust program that also works with directories (but with more pain and a few undocumented features), follow these steps:

Get a handle to the file/folder with CreateFile or NtOpenFile.

Call NtQueryObject to get the full path name.

Call NtQueryInformationFile with FileNameInformation to get the volume-relative path.

Using the two paths above, get the component of the path that represents the volume itself. For example, if you get \Device\HarddiskVolume1\Hello.txt for the first path and \Hello.txt for the second, you now know the volume's path is \Device\HarddiskVolume1.

Use either the poorly-documented Mount Manager I/O Control Codes or QueryDosDevice to convert substitute the volume portion of the full NT-style path with the drive letter.

Now you have the real path of the file.

Title: How can I obtain the case-sensitive path on Windows?

Body:
I need to know which is the real path of a given path.

For example:

The real path is: d:\src\File.txt

And the user give me: D:\src\file.txt

I need as a result: d:\src\File.txt


问:
Bash: for interprets ".*" and transforms it into "." and ".."
I am trying to write a script that will iterate over all arguments and performs a search for each of them. Example of usage:

```<code>./myScript "java" "chrome" "daemon"
./myScript "java" ".*"
</code>```

The problem occurs when .* is used.

First approach:

```<code>patterns=$@
for pattern in ${patterns}; do
      ..
done
</code>```

interprets .* as being . and .. (I wasn't able to find out why).

Second approach:

```<code>patterns=$@
for pattern in "${patterns}"; do
      ..
done
</code>```

Considers all arguments as a single word (instead searching once for java and once for chrome, it will search for "java chrome").

Thanks!

答:
If you don't need to store the patterns, you can just use this:</p>

```<code>for pattern in "$@"; do
     ...
done
</code>```

Body:
I am trying to write a script that will iterate over all arguments and performs a search for each of them. Example of usage:

./myScript "java" "chrome" "daemon"
./myScript "java" ".*"

The problem occurs when .* is used.

First approach:

patterns=$@
for pattern in ${patterns}; do
      ..
done

interprets .* as being . and .. (I wasn't able to find out why).

Second approach:

patterns=$@
for pattern in "${patterns}"; do
      ..
done

Considers all arguments as a single word (instead searching once for java and once for chrome, it will search for "java chrome").

Thanks!

Body:
If you don't need to store the patterns, you can just use this:

for pattern in "$@"; do
     ...
done


问:
Runtime Error updating firebase data
I am relatively new to ionic and firebase, its been a smooth ride until I bumped into this error, am trying to update a boolean data in firebase from my ionic app, below is my component code.

```<code>import { AngularFireDatabase,AngularFireList  } from 'angularfire2/database';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController ,AlertController} from 'ionic-angular';
//import { HelloIonicPage } from "../hello-ionic/hello-ionic";
import { User } from "../../models/user";
import {AngularFireAuth} from 'angularfire2/auth';
import {LoginPage} from '../login/login';
import { BillsPage } from "../bills/bills";
import { MomentModule } from 'angular2-moment';

@IonicPage()
@Component({
  selector: 'page-welcome',
  templateUrl: 'welcome.html',

})
export class WelcomePage {
  listBills: AngularFireList<any>;
  user = {} as User;
  username: string;
  password: string;
  billListRef: any;
  constructor(public navCtrl: NavController,
    private afauth: AngularFireAuth,
    private toastCtrl: ToastController,
    public navParams: NavParams,
    public afDb: AngularFireDatabase,
    private alertCtrl: AlertController
  ) {
    this.billListRef= afDb.list('/bills').valueChanges();
    this.listBills = this.billListRef;
    }

  promptPayment(billId: string){
    let alert = this.alertCtrl.create({
      message: "Mark as Paid",
      buttons:[
        {
          text: "Cancel"
        },
        {
          text: "Mark as Paid",
          handler: data=>{
            this.listBills.update(billId, {paid: true});
            // this.toastCtrl.create({
            //   message: "Mark as paid clikcked",
            //   duration: 3000,
            //   position: "middle",
            //   cssClass: "toast"

            // }).present();

          }
        }
      ]

    });
    alert.present();
  }
</code>```

html code

```<code> <ion-card>
        <ion-card-header>PENDING BILLS</ion-card-header>
        <ion-list>
            <ion-item text-wrap *ngFor="let bill of listBills | async" (click)="promptPayment(bill.id)" [class.hide]="bill.paid == true">
                <ion-icon name="timer" danger item-left></ion-icon>
                <h2>{{bill.name}}</h2>
                <h3>Total:<strong>${{bill.amount}}</strong></h3>
                <p>Pay Before <strong>{{bill.dueDate}}</strong></p>
            </ion-item>
        </ion-list>
    </ion-card>
</code>```

I expect the update to be successful, but I keep getting this error, the update function is called in the promptPayment function in the component below.

"Runtime error _this.listBills.update is not a function"

答:
valueChanges() gives you an Observable and not a reference to Firebase list.

Change:

```<code>this.billListRef= afDb.list('/bills').valueChanges();
this.listBills = this.billListRef;
</code>```

to:

```<code>this.billListRef= afDb.list('/bills');//save reference to the list
this.listBills = this.billListRef.valueChanges();//get observable for the ngFor
</code>```

Your update function needs to be called on the reference.

```<code>this.billListRef.update(billId, {paid: true})
</code>```

Title: Runtime Error updating firebase data

Body:
I am relatively new to ionic and firebase, its been a smooth ride until I bumped into this error, am trying to update a boolean data in firebase from my ionic app, below is my component code.

import { AngularFireDatabase,AngularFireList  } from 'angularfire2/database';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController ,AlertController} from 'ionic-angular';
//import { HelloIonicPage } from "../hello-ionic/hello-ionic";
import { User } from "../../models/user";
import {AngularFireAuth} from 'angularfire2/auth';
import {LoginPage} from '../login/login';
import { BillsPage } from "../bills/bills";
import { MomentModule } from 'angular2-moment';

@IonicPage()
@Component({
  selector: 'page-welcome',
  templateUrl: 'welcome.html',

})
export class WelcomePage {
  listBills: AngularFireList<any>;
  user = {} as User;
  username: string;
  password: string;
  billListRef: any;
  constructor(public navCtrl: NavController,
    private afauth: AngularFireAuth,
    private toastCtrl: ToastController,
    public navParams: NavParams,
    public afDb: AngularFireDatabase,
    private alertCtrl: AlertController
  ) {
    this.billListRef= afDb.list('/bills').valueChanges();
    this.listBills = this.billListRef;
    }

  promptPayment(billId: string){
    let alert = this.alertCtrl.create({
      message: "Mark as Paid",
      buttons:[
        {
          text: "Cancel"
        },
        {
          text: "Mark as Paid",
          handler: data=>{
            this.listBills.update(billId, {paid: true});
            // this.toastCtrl.create({
            //   message: "Mark as paid clikcked",
            //   duration: 3000,
            //   position: "middle",
            //   cssClass: "toast"

            // }).present();

          }
        }
      ]

    });
    alert.present();
  }

html code

 <ion-card>
        <ion-card-header>PENDING BILLS</ion-card-header>
        <ion-list>
            <ion-item text-wrap *ngFor="let bill of listBills | async" (click)="promptPayment(bill.id)" [class.hide]="bill.paid == true">
                <ion-icon name="timer" danger item-left></ion-icon>

{{bill.name}}

Total:${{bill.amount}}

Pay Before {{bill.dueDate}}

            </ion-item>
        </ion-list>
    </ion-card>

I expect the update to be successful, but I keep getting this error, the update function is called in the promptPayment function in the component below.

"Runtime error _this.listBills.update is not a function"

Body:
valueChanges() gives you an Observable and not a reference to Firebase list.

Change:

this.billListRef= afDb.list('/bills').valueChanges();
this.listBills = this.billListRef;

to:

this.billListRef= afDb.list('/bills');//save reference to the list
this.listBills = this.billListRef.valueChanges();//get observable for the ngFor

Your update function needs to be called on the reference.

this.billListRef.update(billId, {paid: true})


问:
Refresh ng-repeat data
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

```<code><div ng-controller="BrainRegionsCtrl">

    <div ng-repeat="region in brain_regions">

        <label>

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           <b>{/region.name/}</b>

         </label>

    </div>
</div>
</code>```

Selected regions list:

```<code><div ng-controller="BrainRegionsCtrl">

    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        <b>{/region.name/}</b>
    </label>

 </div>
</code>```

Controller:

```<code>ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});
</code>```

Here is a jsfiddle
Thank you.

答:
Please check with this code and let me know whether it solves your issue. Also please check this working plnkr of your example scenario.

Template:

```<code>    <div ng-repeat="region in brain_regions">
        <label>
           <input type="checkbox"
              name="checkbox_brain_region[$index]"
              id="checkbox_brain_region[region.id]"
              value="region.id"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">
           <b>{{region.name}}</b>
         </label>
    </div>
    <br>
    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma[$index]"
        ng-model="region.show" value="region.id">
        <b>{{region.name}}</b>
    </label>
</code>```

Controller:

```<code>$scope.update_selected_Brain_regions = function (region) {
    for (var i = 0; i < $scope.brain_regions.length; i++) {
        var current_region = $scope.brain_regions[i];
        if (current_region.id === region.id) {
            if (region.show) {
                $scope.selected_brain_regions.push(current_region);
            } else {
                var index = $scope.selected_brain_regions.map(function(x){ return x.id; }).indexOf(current_region.id);
                $scope.selected_brain_regions.splice(index,1);
            }
        }
    }
};
</code>```

Title: Refresh ng-repeat data

Body:
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           {/region.name/}

Selected regions list:

        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        {/region.name/}

Controller:

ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});

Here is a jsfiddle
Thank you.

Body:
Please check with this code and let me know whether it solves your issue. Also please check this working plnkr of your example scenario.

Template:

    <div ng-repeat="region in brain_regions">
        <label>
           <input type="checkbox"
              name="checkbox_brain_region[$index]"
              id="checkbox_brain_region[region.id]"
              value="region.id"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">
           <b>{{region.name}}</b>
         </label>
    </div>
    <br>
    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma[$index]"
        ng-model="region.show" value="region.id">
        <b>{{region.name}}</b>
    </label>

Controller:

$scope.update_selected_Brain_regions = function (region) {
    for (var i = 0; i < $scope.brain_regions.length; i++) {
        var current_region = $scope.brain_regions[i];
        if (current_region.id === region.id) {
            if (region.show) {
                $scope.selected_brain_regions.push(current_region);
            } else {
                var index = $scope.selected_brain_regions.map(function(x){ return x.id; }).indexOf(current_region.id);
                $scope.selected_brain_regions.splice(index,1);
            }
        }
    }
};


问:
File transfer on Raspberry Pi using pscp
I am trying to send file from windows local system to QEMU raspberry pi emulator.But every time I am getting "access denied".I have downloded pscp.exe.
I have tried the following commands:

```<code>pscp.exe -scp myfile.txt pi@192.168.1.3:/home/pi

pscp.exe -scp myfile.txt pi@192.168.1.3:~/home/pi

pscp.exe -scp myfile.txt pi@192.168.1.3:~/Desktop

pscp.exe -scp myfile.txt pi@192.168.1.3:~
</code>```

Every time it's giving Access Denied.Please tell me where I am going wrong.

答:
I am probably late, but anyway this may help someone.

The syntax of pscp is

pscp [options] source [user@]host:target

Target is the destination file and you are inputting a folder. Also, you are using a file syntax /home/pi and not a folder syntax /home/pi/ (note the / slash at the end). So you are asking pscp to overwrite your entire user folder and put the source file instead. Needless to say this could have result in a massive catastrophe, deleting your entire home folder.

Your command should be:

pspc myfile.txt pi@192.168.1.3:/home/pi/myfile.txt

You can even hard code your password so that the transfer occurs without prompting.

pspc -pw yourpassword myfile.txt pi@192.168.1.3:/home/pi/myfile.txt

Body:
I am trying to send file from windows local system to QEMU raspberry pi emulator.But every time I am getting "access denied".I have downloded pscp.exe.
I have tried the following commands:

pscp.exe -scp myfile.txt pi@192.168.1.3:/home/pi

pscp.exe -scp myfile.txt pi@192.168.1.3:~/home/pi

pscp.exe -scp myfile.txt pi@192.168.1.3:~/Desktop

pscp.exe -scp myfile.txt pi@192.168.1.3:~

Every time it's giving Access Denied.Please tell me where I am going wrong.


问:
Download a file from a link on a WPF Browser Application application
How do I download a file from a link on a
WPF Browser Application application, I am using
the method NavigationService.Navigate(http://www.google.com/docs/Arquivo.xlsx ") Works for download window opens but after that
download was completed or canceled I can not
but enter navigate the pages using method
NavigationService.Navigate, I noticed that the
Content property of NavigationService is null
when I navigate to a file path, someone
know what's going on?</p>

答:
I don't actually understand what are your goals.

If you need to download file it's better to use WebRequest rather than NavigationService:

```<code>        var request = WebRequest.Create("http://www.farmanager.com/files/Far20b1777.x86.20110108.msi");
        using (var stream = request.GetResponse().GetResponseStream())
        {
            using (var reader = new StreamReader(stream))
            {
                var fileContent = reader.ReadToEnd();
            }
        }
</code>```

Body:
I don't actually understand what are your goals.

If you need to download file it's better to use WebRequest rather than NavigationService:

        var request = WebRequest.Create("http://www.farmanager.com/files/Far20b1777.x86.20110108.msi");
        using (var stream = request.GetResponse().GetResponseStream())
        {
            using (var reader = new StreamReader(stream))
            {
                var fileContent = reader.ReadToEnd();
            }
        }


问:
the sum of Big decimal values should be equal after division in java
I have 6 BigDecimals, let say

a,b,c,d,e,f and tot
The sum of all these values(a,b,c,d,e,f) are equal to tot
I am calculating average and storing in other variable of type BigDecimal, just say avgA, avgB, avgC, avgD, avgE, avgF and avgTot. now if I add all these

```<code>avgA, avgB, avgC, avgD, avgE, avgF
</code>```

this sum should be equal to avgTot

But sum of all the averages(avgA, avgB, avgC, avgD, avgE, avgF) is not equal to totAvg

here is sample code

```<code>BigDecimal avgA = a.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgB = b.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgTot = tot.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);

BigDecimal trimA = avgA.setScale(4, RoundingMode.CEILING);
BigDecimal trimB = avgB.setScale(4, RoundingMode.CEILING);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.CEILING);
</code>```

Sample Values:-

```<code>trimA 0.0004
trimB 0.0000
trimC 0.0022
trimD 0.0047
trimE 0.0000
trimF 0.0002
trimTot 0.0076
</code>```

The problem is sum(TrimA..F) is not equal to trimTot. I have to make sure that sum(TrimA..F) should be equal to trimTot

答:
The devious thing is that RoundingMode.CEILING ensures a maximal error on addition instead of RoundingMode.HALF_UP:

CEILING

```<code>0.00031 => 0.0004
0.00211 => 0.0022
-------    ------ +
0.00242    0.0026
</code>```

HALF_UP (the norm)

```<code>0.00033 => 0.0003
0.00216 => 0.0022
-------    ------ +
0.00249    0.0025
</code>```

FLOOR

```<code>0.00043 => 0.0004
0.00216 => 0.0021
-------    ------ +
0.00259    0.0025
</code>```

So

```<code>BigDecimal trimA = avgA.setScale(4, RoundingMode.HALF_UP);
BigDecimal trimB = avgB.setScale(4, RoundingMode.HALF_UP);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.HALF_UP);
</code>```

would minimize the rounding error, but not necessarily always remove it.

So what do you think, to have no rounding upto the 4th decimal. When going from 15 positions to 4.

Body:
I have 6 BigDecimals, let say

a,b,c,d,e,f and tot
The sum of all these values(a,b,c,d,e,f) are equal to tot
I am calculating average and storing in other variable of type BigDecimal, just say avgA, avgB, avgC, avgD, avgE, avgF and avgTot. now if I add all these

avgA, avgB, avgC, avgD, avgE, avgF

this sum should be equal to avgTot

But sum of all the averages(avgA, avgB, avgC, avgD, avgE, avgF) is not equal to totAvg

here is sample code

BigDecimal avgA = a.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgB = b.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgTot = tot.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);

BigDecimal trimA = avgA.setScale(4, RoundingMode.CEILING);
BigDecimal trimB = avgB.setScale(4, RoundingMode.CEILING);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.CEILING);

Sample Values:-

trimA 0.0004
trimB 0.0000
trimC 0.0022
trimD 0.0047
trimE 0.0000
trimF 0.0002
trimTot 0.0076

The problem is sum(TrimA..F) is not equal to trimTot. I have to make sure that sum(TrimA..F) should be equal to trimTot

Body:
The devious thing is that RoundingMode.CEILING ensures a maximal error on addition instead of RoundingMode.HALF_UP:

CEILING

0.00031 => 0.0004
0.00211 => 0.0022
-------    ------ +
0.00242    0.0026

HALF_UP (the norm)

0.00033 => 0.0003
0.00216 => 0.0022
-------    ------ +
0.00249    0.0025

FLOOR

0.00043 => 0.0004
0.00216 => 0.0021
-------    ------ +
0.00259    0.0025

So

BigDecimal trimA = avgA.setScale(4, RoundingMode.HALF_UP);
BigDecimal trimB = avgB.setScale(4, RoundingMode.HALF_UP);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.HALF_UP);

would minimize the rounding error, but not necessarily always remove it.

So what do you think, to have no rounding upto the 4th decimal. When going from 15 positions to 4.


问:
store data in drupal 8
I have created form using twig template, the form has first name,last name and email.I need to save those values to database.

how can I create new table and store data in it??

<!DOCTYPE html>

<form action="/action_page.php">
First name: <input type="text" name="FirstName">

Last name: <input type="text" name="LastName">

Email: <input type="text" name="email" value="Mouse">

<input type="submit" value="Submit">
</form>

```

Can anyone help on that please??

答:
You should use drupal's form api to create the form. Your way is not really "drupalish" way. Then you can define custom content type, with all the fields you need and if form submission handler of your form you can create new nodes in that type with data your form collected.

So google a bit, check some tutorial on form api, and how to make custome form and also on custom content types in drupal. Not that scare as it maybe looks to you right now.

Or, check on webform module that comes with D8 default installation, maybe you can use it instead!

Title: store data in drupal 8

Body:
I have created form using twig template, the form has first name,last name and email.I need to save those values to database.

how can I create new table and store data in it??

<!DOCTYPE html>

<form action="/action_page.php">
First name: <input type="text" name="FirstName">

Last name: <input type="text" name="LastName">

Email: <input type="text" name="email" value="Mouse">

<input type="submit" value="Submit">
</form>

Can anyone help on that please??


问:
Eclipse Juno - IWAB0489E Error when deploying Web service to Axis runtime
I am following the steps in the tutorial : http://javapapers.com/web-service/java-web-service-using-eclipse/#comment-21575

But when trying to “select service implementation”, I am getting the error “IWAB0489E Error when deploying web service to Axis runtime axis-admin failed with  {http://xml.apache.org/axis/}HTTP (502)Proxy Error ( Forefront TMG denied the specified Uniform Resource Locator (URL).  )”.

I have not downloaded Axis2 plugin and suppose it comes with Eclipse juno.

I am using the same eclipse version and release the author is using in his tutorial. Kindly provide any pointer;its urgent!!

TIA!

答:
Try stopping the other web-services running on the same port.
If found any, we can stop it by running this command twice in cmd(command prompt)

To stop any server/port that is already being used in eclipse/other.

1) netstat -ano | findstr :yourPortNumber

2) taskkill /PID typeyourPIDhere /F

then restart your server.


问:
Python Selenium Explict wait doen not raise TimeoutException
```<code>browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)
</code>```

About is my code. Sometimes this may get stuck for quite long time and I expect there should be TimeOutException if it get stuck for 30 seconds because I have this code wait = WebDriverWait(browser, 30)
But this never happens, the program just wait there...What's the question?

答:
use try,except</p>

```<code>   from selenium.common.exceptions import TimeoutException
   from selenium.webdriver.support.ui import WebDriverWait
   from selenium.webdriver.support import expected_conditions as EC

   timeout=30

   try:
       element_present1 = EC.presence_of_element_located((By.XPATH, "//input[@name='username']"))
       WebDriverWait(driver, timeout).until(element_present1)
   except TimeoutException:
       print "Timed out waiting for login page to load"
</code>```

Body:
browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)

About is my code. Sometimes this may get stuck for quite long time and I expect there should be TimeOutException if it get stuck for 30 seconds because I have this code wait = WebDriverWait(browser, 30)
But this never happens, the program just wait there...What's the question?

Body:
use try,except

   from selenium.common.exceptions import TimeoutException
   from selenium.webdriver.support.ui import WebDriverWait
   from selenium.webdriver.support import expected_conditions as EC

   timeout=30

   try:
       element_present1 = EC.presence_of_element_located((By.XPATH, "//input[@name='username']"))
       WebDriverWait(driver, timeout).until(element_present1)
   except TimeoutException:
       print "Timed out waiting for login page to load"


问:
Modify SQL Trigger to work with BULK INSERT
I have a SQL Trigger that doesn't fire because the records in the table are inserted through a BULK INSERT. I do not have access to the code that inserts the records so I need to modify this trigger to handle the BULK INSERT. This is the trigger:

```<code>    USE [testdata]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[Trigger_test] ON [dbo].[test]
    AFTER INSERT , UPDATE
AS

BEGIN

    DECLARE @BatchId int, @Ethanol decimal(18,6), @Glucose decimal(18,6), @SampleAge varchar(50);

    SELECT @BatchId = CONVERT(int,bd.[BatchId]),
           @Ethanol = CONVERT(decimal(18,2),[Ethanol]),
           @Glucose= CONVERT(decimal(18,2),[Glucose]),
           @SampleAge = bd.SampleCode
    from INSERTED bd

    update [dbo].[DeSchedule]
    SET
            [Ethanol] = @Ethanol,
            [Glucose] = @Glucose,
            [SampleCompleted] = 1
    WHERE [BatchID] = @BatchId AND [SampleAge] = @SampleAge
END
</code>```

Can anyone help me in modifying this trigger to handle the BULK INSERT.

答:
the problem is it selected only the last row of the inserted table ,i think  if you change the query like this it would work </p>

```<code>update [dbo].[DeSchedule]
    SET
            [Ethanol] =(select CONVERT(int,bd.[Ethanol]) from inserted bd),
            [Glucose] = (select CONVERT(decimal(18,2),[Glucose]) from inserted bd),
            [SampleCompleted] = 1
    WHERE [BatchID] = (select CONVERT(int,bd.[BatchId]) from inserted bd) AND [SampleAge] = (select bd.SampleCode from inserted bd)
</code>```

Body:
I have a SQL Trigger that doesn't fire because the records in the table are inserted through a BULK INSERT. I do not have access to the code that inserts the records so I need to modify this trigger to handle the BULK INSERT. This is the trigger:

    USE [testdata]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[Trigger_test] ON [dbo].[test]
    AFTER INSERT , UPDATE
AS

BEGIN

    DECLARE @BatchId int, @Ethanol decimal(18,6), @Glucose decimal(18,6), @SampleAge varchar(50);

    SELECT @BatchId = CONVERT(int,bd.[BatchId]),
           @Ethanol = CONVERT(decimal(18,2),[Ethanol]),
           @Glucose= CONVERT(decimal(18,2),[Glucose]),
           @SampleAge = bd.SampleCode
    from INSERTED bd

    update [dbo].[DeSchedule]
    SET
            [Ethanol] = @Ethanol,
            [Glucose] = @Glucose,
            [SampleCompleted] = 1
    WHERE [BatchID] = @BatchId AND [SampleAge] = @SampleAge
END

Can anyone help me in modifying this trigger to handle the BULK INSERT.

Body:
the problem is it selected only the last row of the inserted table ,i think  if you change the query like this it would work

update [dbo].[DeSchedule]
    SET
            [Ethanol] =(select CONVERT(int,bd.[Ethanol]) from inserted bd),
            [Glucose] = (select CONVERT(decimal(18,2),[Glucose]) from inserted bd),
            [SampleCompleted] = 1
    WHERE [BatchID] = (select CONVERT(int,bd.[BatchId]) from inserted bd) AND [SampleAge] = (select bd.SampleCode from inserted bd)


问:
Can you remove Identity from a primary key with Entity Framework 6?
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }
```
<p>And an annotation:</p>
<pre class="lang-cs prettyprint-override"><code>    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }
</code>```

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }
```
<p>However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?</p>
<p>I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:</p>
<pre class="lang-cs prettyprint-override"><code>AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));
</code>```

Is there another way to tell SQL to remove the Identity?

答:
If you want to remove the Identity from a Primary Key, you’re going to need to Drop and Recreate the table and any associated Foreign Keys along with it.

Removing an identity specification from a column can only be done by re-creating the table. Look at the ALTER TABLE - ALTER COLUMN statement: there is no syntax to change (add or remove) an identity specification.

Refer flowing sites:

Cant remove identity attribute from PK

Entering keys manually with Entity Framework

EF6: Switching Identity On/Off with a Custom Migration Operation

Remove Identity from Primary Key with Drop and Recreate Table

Body:
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }

And an annotation:

    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }

However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?

I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:

AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));

Is there another way to tell SQL to remove the Identity?


问:
best practice for trigger a method by user's input in angular2
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

```<code><div class="col-md-8">
   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>
</code>```

My ts file:

```<code>populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}
</code>```

答:
You are looking for ngModelChange:

```<code><div class="col-md-8">
    <input type="text" class="form-control" [ngModel]="workOrder" (ngModelChange)="populate($event)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>
</code>```

Component

```<code>populate(value: any){
  console.log(value);
  this._lookup.getIcrData().subscribe(res => {
        console.log(res);
  });
}
</code>```

Body:
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

My ts file:

populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}

Body:
You are looking for ngModelChange:

<div class="col-md-8">
    <input type="text" class="form-control" [ngModel]="workOrder" (ngModelChange)="populate($event)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>

Component

populate(value: any){
  console.log(value);
  this._lookup.getIcrData().subscribe(res => {
        console.log(res);
  });
}