问:
How not to load javascript files when javascript is disabled
[SOLVED]

I use to build pages normally without javascript and only then to add javascipt features. This way, I can set all divs with tools that require javascript with display:none and then in the first line on javascript to turn it visible:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('#jsdivs').show();
    });
</script>
</code>```

Doing so I get out of the way of people who for any reason have their browsers javascript disabled.

Following this spirit, I'd like to find a way to not load any javascript by default and then, if javascript is enabled have instructions to load the javascript files.

Right now I am loading JQuery like this (for cache reasons, many people may already have this cached):

```<code><script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</code>```

And another file with all the other javascript minimized. All in the end, just before the HTML body tag.

I saw many opinions here and here but none that help me with this. At first, I'd like to know if that's a good way of getting this done. Thanks a lot.

UPDATE:

@Lèse majesté indicated me an old discussion saying that browsers do not load javascript files when it is disabled. As I didn't think the information was enough conclusive, I made some tests disabling javascript in Firefox via the plugin "Web Developer" and YSlow (another FF plugin for Firebug) keeps on showing all javascript information, not mentioning that "Live Headers" (another fantastic FF plugin that shows the headers in realtime) also showed that a _utmc cookie (by the Google Analytics script) was present in the request.

@Marcel Korpel made a very good (though apparentely snob) comment, which opened the way for a real solution. he said that Google Analytics uses a "method to dynamically include ga.js. The closing tag (and immediately opening tag) is needed to let the browser update the DOM tree and actually load and execute the added script."

With the information on his indication I could come up with this PHP code (I had to put the PHP code in Pastie.org because Stackoverflow was messing with it):

http://pastie.org/1487432

That prints:

```<code><script language="javascript" type="text/javascript">
    document.write('\<script src\="js\/minified\.js" type\="text\/javascript"\>\<\/script\>');
</script>
</code>```

This time YSlow and Live Headers say nothing about any javascript file.

I have just found out this: http://code.google.com/speed/page-speed/docs/rtt.html#AvoidDocumentWrite

答:
Most browsers don't download linked .js files if JavaScript is disabled. See this question:

Does a browser download JS files if the user has JS disabled?

Body:
[SOLVED]

I use to build pages normally without javascript and only then to add javascipt features. This way, I can set all divs with tools that require javascript with display:none and then in the first line on javascript to turn it visible:

Doing so I get out of the way of people who for any reason have their browsers javascript disabled.

Following this spirit, I'd like to find a way to not load any javascript by default and then, if javascript is enabled have instructions to load the javascript files.

Right now I am loading JQuery like this (for cache reasons, many people may already have this cached):

And another file with all the other javascript minimized. All in the end, just before the HTML body tag.

I saw many opinions here and here but none that help me with this. At first, I'd like to know if that's a good way of getting this done. Thanks a lot.

UPDATE:

@Lèse majesté indicated me an old discussion saying that browsers do not load javascript files when it is disabled. As I didn't think the information was enough conclusive, I made some tests disabling javascript in Firefox via the plugin "Web Developer" and YSlow (another FF plugin for Firebug) keeps on showing all javascript information, not mentioning that "Live Headers" (another fantastic FF plugin that shows the headers in realtime) also showed that a _utmc cookie (by the Google Analytics script) was present in the request.

@Marcel Korpel made a very good (though apparentely snob) comment, which opened the way for a real solution. he said that Google Analytics uses a "method to dynamically include ga.js. The closing tag (and immediately opening tag) is needed to let the browser update the DOM tree and actually load and execute the added script."

With the information on his indication I could come up with this PHP code (I had to put the PHP code in Pastie.org because Stackoverflow was messing with it):

http://pastie.org/1487432

That prints:

This time YSlow and Live Headers say nothing about any javascript file.

I have just found out this: http://code.google.com/speed/page-speed/docs/rtt.html#AvoidDocumentWrite


来源: stackexchange

问:
print statement delays printing when followed by comma
In Python 2.7, if I use print statement followed by comma as the following:

```<code>print('Generation ...'),
X, y = generate_dataset(num_samples)
print('Done!')
</code>```

The first print print('Generation ...'), will NOT show up in the terminal until X, y = generate_dataset(num_samples) is finished! How can I force the print to immediately step by step with the existence of comma?

答:
```<code>import sys

print "I'm going to do something that takes a long time...",
sys.stdout.flush()
really_time_consuming_function()
print "done!"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Python 2.7, if I use print statement followed by comma as the following:

print('Generation ...'),
X, y = generate_dataset(num_samples)
print('Done!')

The first print print('Generation ...'), will NOT show up in the terminal until X, y = generate_dataset(num_samples) is finished! How can I force the print to immediately step by step with the existence of comma?


问:
How does next() method on iterators work?
I have a doubt with the next() method on iterators.  If I have as a part of my code this lines (with arrayOfStrings size = 4):

```<code>Iterator<String> it = arrayOfStrings.iterator(); //arrayOfString is ArrayList<String>

while(it.hasNext()) {
    String e = it.next();
    System.out.println(e);
}
</code>```

At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?

I ask because as far as I know the next() method returns the next element in the collection.

So, if at the very first iteration the iterator starts at index 0 when next() is invoked, it returns the element at index 1 and I won´t be able to do nothing with the element at index 0?

答:
The code you show will correctly print all elements of the ArrayList. The it.next() call will, at its first call, also the first element. This element is usually denoted with index 0.

Note that you might want to rename arrayOfStrings as technically it's no array, it's more a List. A user might due the name think that it is an array.

Documentation

In my opinion you are right that the documentation of the method can be a bit confusing since it is so compact:

Returns the next element in the iteration.

However the description probably needs to be so undetailed since Iterator is a very frequently used interface, not only for collections. I could imagine a class where the first iteration element should not be the first element of the underlying structure. For example some kind of stream that was already read until a given point. So basically it is up to the implementing class to decide what the first element is. But for collections it will truly be the first element (index 0).

For-each

Also note that the iteration you show is equivalent to how the extended for-loop (for-each) works in Java. So a syntax like

```<code>for (Item item : items) {
    ...
}
</code>```

will be treated like

```<code>Iterator<Item> iter = items.iterator();
while(iter.hasNext()) {
    Item item = iter.next();
    ...
}
</code>```

In fact this is the reason why you can use everything that implements Iterable in extended for loops.

Knowing this it would rather be confusing if iter.next() would skip the first element. I mean by the name for-each is supposed to iterate all elements.

Insights

Let's take a closer look at how the method is implemented. Therefore we will first see what ArrayList#iterator does. Take a look at its source code:

```<code>public Iterator<E> iterator() {
    return new Itr();
}
</code>```

The Itr class is a private class of ArrayList (source code). And here is the Itr#next method:

```<code>@SuppressWarnings("unchecked")
public E next() {
    checkForComodification();
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();

    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();

    cursor = i + 1;
    return (E) elementData[lastRet = i];
}
</code>```

So what it essentially returns is the element at index i which is where the cursor was at the point of calling the method. It also already advances the cursor by one for the next call of the method.

The cursor however is implicitly initialized with 0 due to:

```<code>int cursor; // Default value for int is 0
</code>```

So the first call of next will indeed return the element at index 0 which is the first element.

Body:
I have a doubt with the next() method on iterators.  If I have as a part of my code this lines (with arrayOfStrings size = 4):

Iterator<String> it = arrayOfStrings.iterator(); //arrayOfString is ArrayList<String>

while(it.hasNext()) {
    String e = it.next();
    System.out.println(e);
}

At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?

I ask because as far as I know the next() method returns the next element in the collection.

So, if at the very first iteration the iterator starts at index 0 when next() is invoked, it returns the element at index 1 and I won´t be able to do nothing with the element at index 0?

Body:
The code you show will correctly print all elements of the ArrayList. The it.next() call will, at its first call, also the first element. This element is usually denoted with index 0.

Note that you might want to rename arrayOfStrings as technically it's no array, it's more a List. A user might due the name think that it is an array.

Documentation

In my opinion you are right that the documentation of the method can be a bit confusing since it is so compact:

Returns the next element in the iteration.

However the description probably needs to be so undetailed since Iterator is a very frequently used interface, not only for collections. I could imagine a class where the first iteration element should not be the first element of the underlying structure. For example some kind of stream that was already read until a given point. So basically it is up to the implementing class to decide what the first element is. But for collections it will truly be the first element (index 0).

For-each

Also note that the iteration you show is equivalent to how the extended for-loop (for-each) works in Java. So a syntax like

for (Item item : items) {
    ...
}

will be treated like

Iterator<Item> iter = items.iterator();
while(iter.hasNext()) {
    Item item = iter.next();
    ...
}

In fact this is the reason why you can use everything that implements Iterable in extended for loops.

Knowing this it would rather be confusing if iter.next() would skip the first element. I mean by the name for-each is supposed to iterate all elements.

Insights

Let's take a closer look at how the method is implemented. Therefore we will first see what ArrayList#iterator does. Take a look at its source code:

public Iterator<E> iterator() {
    return new Itr();
}

The Itr class is a private class of ArrayList (source code). And here is the Itr#next method:

@SuppressWarnings("unchecked")
public E next() {
    checkForComodification();
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();

    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();

    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

So what it essentially returns is the element at index i which is where the cursor was at the point of calling the method. It also already advances the cursor by one for the next call of the method.

The cursor however is implicitly initialized with 0 due to:

int cursor; // Default value for int is 0

So the first call of next will indeed return the element at index 0 which is the first element.


问:
Xamarin.Android TextView doesn't raise change events when "Link SDK Assemblies" is selected
I'm working on a project in Xamarin with MvvmCross, trying to use the linker to get the app size down for release on Android and iOS (no Forms.)

On Android, when I selected "Link SDK Assemblies Only", the project builds and runs with no crashes or error messages. But none of the EditText controls responds correctly when their text changes, their data bindings don't get updated, and their Changed event handlers don't get called.

When I select "Don't Link", everything works fine. Bindings are updated and event handlers are called.

I have looked at the Xamarin Linker documentation, and I'm aware of how to ensure various assemblies, types and methods are preserved. My problem is I simply don't know what needs to be preserved, nor do I have any idea how to find out. I've tried tools like bitdiffer with no success.

Can anyone help me figure out what I need to preserve if anything?

答: This behavior is often seen if the LinkerPleaseInclude file is missing a reference to your EditText. The reason is that the linker strips everything not referenced/ used from your app. With a reference in the LinkerPleaseInclude file the linker will notice the usage and keeps the event handler.</p>


问:
Maven spotbugs plugin failing with Out of Memory Error
I am trying to use spotbugs-maven-plugin like below

```<code><build>
...
<plugin>
        <groupId>com.github.spotbugs</groupId>
        <artifactId>spotbugs-maven-plugin</artifactId>
        <version>3.1.0-RC8</version>
        <configuration>
                <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j<groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                </plugins>
                <includeFilterFile>./spotbugIncludeFilter.xml</includeFilterFile>
                <onlyAnalyze>com.vnera.-</onlyAnalyze>
                <argLine>-Xmx1024m</argLine>
        </configuration>
</plugin>
</build>
</code>```

But each time it is failing with the below error

```<code>[INFO] Fork Value is true
     [java] Out of memory
     [java] Total memory: 482M
     [java]  free memory: 43M
</code>```

Stacktrace look like below

```<code>[java]  at java.util.ArrayList.<init>(ArrayList.java:152)
[java]     at edu.umd.cs.findbugs.ba.Frame.<init>(Frame.java:113)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberFrame.<init>(ValueNumberFrame.java:90)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberAnalysis.createFact(ValueNumberAnalysis.java:181)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberAnalysis.createFact(ValueNumberAnalysis.java:58)
[java]     at edu.umd.cs.findbugs.ba.BasicAbstractDataflowAnalysis.lookupOrCreateFact(BasicAbstractDataflowAnalysis.java:185)
[java]     at edu.umd.cs.findbugs.ba.BasicAbstractDataflowAnalysis.getStartFact(BasicAbstractDataflowAnalysis.java:70)
[java]     at edu.umd.cs.findbugs.ba.Dataflow.execute(Dataflow.java:234)
[java]     at edu.umd.cs.findbugs.classfile.engine.bcel.ValueNumberDataflowFactory.analyze(ValueNumberDataflowFactory.java:76)
[java]     at edu.umd.cs.findbugs.classfile.engine.bcel.ValueNumberDataflowFactory.analyze(ValueNumberDataflowFactory.java:46)
[java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.analyzeMethod(AnalysisCache.java:369)
[java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.getMethodAnalysis(AnalysisCache.java:322)
[java]     at edu.umd.cs.findbugs.ba.ClassContext.getMethodAnalysis(ClassContext.java:1005)
[java]     at edu.umd.cs.findbugs.ba.ClassContext.getValueNumberDataflow(ClassContext.java:336)
[java]     at edu.umd.cs.findbugs.detect.FindInconsistentSync2.analyzeMethod(FindInconsistentSync2.java:638)
[java]     at edu.umd.cs.findbugs.detect.FindInconsistentSync2.visitClassContext(FindInconsistentSync2.java:413)
[java]     at edu.umd.cs.findbugs.DetectorToDetector2Adapter.visitClass(DetectorToDetector2Adapter.java:76)
[java]     at edu.umd.cs.findbugs.FindBugs2.analyzeApplication(FindBugs2.java:1079)
[java]     at edu.umd.cs.findbugs.FindBugs2.execute(FindBugs2.java:280)
[java]     at edu.umd.cs.findbugs.FindBugs.runMain(FindBugs.java:401)
[java]     at edu.umd.cs.findbugs.FindBugs2.main(FindBugs2.java:1187)
</code>```

I have also tried setting <argLine>-XX:MaxPermSize=1024m</argLine>. Still getting same error.

Can someone let me know how can I get around this?

Java 8

Maven 3

答:
Have you looked at maxHeap ? This should help out with increasing the memory problem that you have.

Also from their FAQ it states:

You can increase this using the -maxHeap n option, where n is the
  number of megabytes of heap space to allocate.

Body:
I am trying to use spotbugs-maven-plugin like below

<build>
...
<plugin>
        <groupId>com.github.spotbugs</groupId>
        <artifactId>spotbugs-maven-plugin</artifactId>
        <version>3.1.0-RC8</version>
        <configuration>
                <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j<groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                </plugins>
                <includeFilterFile>./spotbugIncludeFilter.xml</includeFilterFile>
                <onlyAnalyze>com.vnera.-</onlyAnalyze>
                <argLine>-Xmx1024m</argLine>
        </configuration>
</plugin>
</build>

But each time it is failing with the below error

[INFO] Fork Value is true
     [java] Out of memory
     [java] Total memory: 482M
     [java]  free memory: 43M

Stacktrace look like below

[java]  at java.util.ArrayList.<init>(ArrayList.java:152)
[java]     at edu.umd.cs.findbugs.ba.Frame.<init>(Frame.java:113)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberFrame.<init>(ValueNumberFrame.java:90)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberAnalysis.createFact(ValueNumberAnalysis.java:181)
[java]     at edu.umd.cs.findbugs.ba.vna.ValueNumberAnalysis.createFact(ValueNumberAnalysis.java:58)
[java]     at edu.umd.cs.findbugs.ba.BasicAbstractDataflowAnalysis.lookupOrCreateFact(BasicAbstractDataflowAnalysis.java:185)
[java]     at edu.umd.cs.findbugs.ba.BasicAbstractDataflowAnalysis.getStartFact(BasicAbstractDataflowAnalysis.java:70)
[java]     at edu.umd.cs.findbugs.ba.Dataflow.execute(Dataflow.java:234)
[java]     at edu.umd.cs.findbugs.classfile.engine.bcel.ValueNumberDataflowFactory.analyze(ValueNumberDataflowFactory.java:76)
[java]     at edu.umd.cs.findbugs.classfile.engine.bcel.ValueNumberDataflowFactory.analyze(ValueNumberDataflowFactory.java:46)
[java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.analyzeMethod(AnalysisCache.java:369)
[java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.getMethodAnalysis(AnalysisCache.java:322)
[java]     at edu.umd.cs.findbugs.ba.ClassContext.getMethodAnalysis(ClassContext.java:1005)
[java]     at edu.umd.cs.findbugs.ba.ClassContext.getValueNumberDataflow(ClassContext.java:336)
[java]     at edu.umd.cs.findbugs.detect.FindInconsistentSync2.analyzeMethod(FindInconsistentSync2.java:638)
[java]     at edu.umd.cs.findbugs.detect.FindInconsistentSync2.visitClassContext(FindInconsistentSync2.java:413)
[java]     at edu.umd.cs.findbugs.DetectorToDetector2Adapter.visitClass(DetectorToDetector2Adapter.java:76)
[java]     at edu.umd.cs.findbugs.FindBugs2.analyzeApplication(FindBugs2.java:1079)
[java]     at edu.umd.cs.findbugs.FindBugs2.execute(FindBugs2.java:280)
[java]     at edu.umd.cs.findbugs.FindBugs.runMain(FindBugs.java:401)
[java]     at edu.umd.cs.findbugs.FindBugs2.main(FindBugs2.java:1187)

I have also tried setting <argLine>-XX:MaxPermSize=1024m</argLine>. Still getting same error.

Can someone let me know how can I get around this?

Java 8

Maven 3


问:
How to always run some ansible roles after previous failures?
I have a set of playbooks that do look like

```<code>- name: Run test
  hosts: tester
  roles:
    - { role: setup_repos }
    - { role: setup_environment }
    - { role: install_packages }
    - { role: run_tests }
    - { role: collect_logs }
</code>```

The current problem is that all over the first 4 roles we have ignore_errors: true which is not a good practice as it makes very hard to read the output and to debug.

The only reason why ignore_errors was abused was because we wanted to be able to perform the collect_logs at the end, regardless the outcome.

How can we refactor this in order to remove the ignore_errors and have a more of a fail-fast strategy.

Please note that we have lots of playbooks calling collect_logs role, so "moving code inside playbook" is not really a way to reuse it.

答:
I belive handlers and notify would help you achive what you want.
You wont need to change your roles behavior (although it might be a good idea).

You should notify at the end of each of your roles, the handler would only run once.

http://docs.ansible.com/ansible/latest/playbooks_intro.html#handlers-running-operations-on-change

Also if you choose to start handleing errors you could use the --force-handlers to force handler execution even when the playbook failed.

http://docs.ansible.com/ansible/latest/playbooks_error_handling.html#handlers-and-failure

Body:
I have a set of playbooks that do look like

- name: Run test
  hosts: tester
  roles:
    - { role: setup_repos }
    - { role: setup_environment }
    - { role: install_packages }
    - { role: run_tests }
    - { role: collect_logs }

The current problem is that all over the first 4 roles we have ignore_errors: true which is not a good practice as it makes very hard to read the output and to debug.

The only reason why ignore_errors was abused was because we wanted to be able to perform the collect_logs at the end, regardless the outcome.

How can we refactor this in order to remove the ignore_errors and have a more of a fail-fast strategy.

Please note that we have lots of playbooks calling collect_logs role, so "moving code inside playbook" is not really a way to reuse it.


问:
JBPM - Process instance XXX is disconnected
We are facing error 'Process instance XXX is disconnected' very frequently in our project and holding up the tasks operations.

We are using SynchronizedTaskService for task operation:

Code snippet are below:

```<code>final RuntimeManager runtimeManager = RuntimeEngineFacory.getRuntimeManager();
final RuntimeEngine engine = runtimeManager.getRuntimeEngine(EmptyContext.get());
SynchronizedTaskService taskService = (SynchronizedTaskService) engine.GetTaskService();
</code>```

It was raised in one of JBPM bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=1161574

Please help if anyone has any clue.

答:
Finally I am able to resolved this issue.

For benefit of whoever facing issue:
 - This issue appears whenever you have not properly managed transactions

There were some place we were managed transaction incorrectly and somehow JBPM internally InternalKnowledgeRuntime set to null.

By the way this errors throws from

class: ProcessInstanceImpl

method: getProcess()

```<code>public Process getProcess(){
   if(this.process == null){
     if(processXml == null){
       if(kruntime == null){
          throw new RuntimeException("Process instance " + id + "[" + processId + "] is disconnected. "));
      }else{
         other code ...........
      }
    }
  }
}
</code>```

Body:
We are facing error 'Process instance XXX is disconnected' very frequently in our project and holding up the tasks operations.

We are using SynchronizedTaskService for task operation:

Code snippet are below:

final RuntimeManager runtimeManager = RuntimeEngineFacory.getRuntimeManager();
final RuntimeEngine engine = runtimeManager.getRuntimeEngine(EmptyContext.get());
SynchronizedTaskService taskService = (SynchronizedTaskService) engine.GetTaskService();

It was raised in one of JBPM bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=1161574

Please help if anyone has any clue.

Body:
Finally I am able to resolved this issue.

For benefit of whoever facing issue:
 - This issue appears whenever you have not properly managed transactions

There were some place we were managed transaction incorrectly and somehow JBPM internally InternalKnowledgeRuntime set to null.

By the way this errors throws from

class: ProcessInstanceImpl

method: getProcess()

public Process getProcess(){
   if(this.process == null){
     if(processXml == null){
       if(kruntime == null){
          throw new RuntimeException("Process instance " + id + "[" + processId + "] is disconnected. "));
      }else{
         other code ...........
      }
    }
  }
}


问:
Unable to save data in child activity android studio
After entering the details in EditText in child activity when I go back to parent activity and comes back to child activity the EditText value is becoming blank. I have used below mentioned code, but no use.

Below mentioned is childactivity.java details.

Can anyone help in this.

```<code>import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class NotesActivity extends AppCompatActivity {
    String typedText;
    EditText inputTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        inputTxt = (EditText) findViewById(R.id.notes1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        typedText = inputTxt.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        inputTxt.setText(typedText);
    }
}
</code>```

答:
In parent call startActivityForResult(getApplicationContext(), NotesActivity.class) to call child activity which is NotesActivity.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        String typedText = "" + extras.getString("TypedText");

    }
}
</code>```

In the Child activity use below function to return 'typedText'

```<code>private void returnText() {
    Intent result = new Intent();
    String typedText = inputTxt.getText().toString();
    result.putExtra("TypedText", typedText);
    setResult(RESULT_OK, result);
}

@Override
protected void onPause() {
    super.onPause();
    returnText();
}
</code>```

Body:
After entering the details in EditText in child activity when I go back to parent activity and comes back to child activity the EditText value is becoming blank. I have used below mentioned code, but no use.

Below mentioned is childactivity.java details.

Can anyone help in this.

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class NotesActivity extends AppCompatActivity {
    String typedText;
    EditText inputTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        inputTxt = (EditText) findViewById(R.id.notes1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        typedText = inputTxt.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        inputTxt.setText(typedText);
    }
}

Body:
In parent call startActivityForResult(getApplicationContext(), NotesActivity.class) to call child activity which is NotesActivity.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        String typedText = "" + extras.getString("TypedText");

    }
}

In the Child activity use below function to return 'typedText'

private void returnText() {
    Intent result = new Intent();
    String typedText = inputTxt.getText().toString();
    result.putExtra("TypedText", typedText);
    setResult(RESULT_OK, result);
}

@Override
protected void onPause() {
    super.onPause();
    returnText();
}


问:
Canvas Size HTML
I want to dynamically resize the canvas size according to the content of a DIV. i am using the following Code but it doesn't seems to work.

```<code><canvas id="canvas1" width="800" height="2000"  > <canvas>
</code>```

Javascript

```<code>document.getElementById("canvas1").style.height = document.getElementById("div").style.height;
document.getElementById("canvas1").style.width= document.getElementById("div").style.width;
</code>```

Also i want that the canvas is loaded automatically , How should i do that ? on a $(document).ready event ?

How shall i do that too ?

答:
Use offsetWidth to get the dimensions of the element (including borders).

```<code>// loaded automatically on page load
window.onload = function() {
    var div = document.getElementById("div");
    var canvas = document.getElementById("canvas1");
    canvas.height = div.offsetHeight;
    canvas.width  = div.offsetWidth;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Canvas Size HTML

Body:
I want to dynamically resize the canvas size according to the content of a DIV. i am using the following Code but it doesn't seems to work.

<canvas id="canvas1" width="800" height="2000"  > <canvas>

Javascript

document.getElementById("canvas1").style.height = document.getElementById("div").style.height;
document.getElementById("canvas1").style.width= document.getElementById("div").style.width;

Also i want that the canvas is loaded automatically , How should i do that ? on a $(document).ready event ?

How shall i do that too ?

Body:
Use offsetWidth to get the dimensions of the element (including borders).

// loaded automatically on page load
window.onload = function() {
    var div = document.getElementById("div");
    var canvas = document.getElementById("canvas1");
    canvas.height = div.offsetHeight;
    canvas.width  = div.offsetWidth;
}


问:
Error when adding product with custom pricing to cart - WooCommerce
I have set up a custom user role with a slug of performance_customer. I am checking to see if the current user is a "performance customer" and apply certain price discounts to products in specific categories.

Here is my code:

```<code>function return_custom_performance_dealer_price($price, $product) {

    global $woocommerce;
    global $post;
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ) $categories[] = $term->slug;

    $origPrice = get_post_meta( get_the_ID(), '_regular_price', true);
    $price = $origPrice;

    //check if user role is performance dealer
    $current_user = wp_get_current_user();
    if( in_array('performance_customer', $current_user->roles)){
        //if is category performance hard parts
        if(in_array( 'new-hard-parts-150', $categories )){
            $price = $origPrice * .85;
        }
        //if is category performance clutches
        elseif(in_array( 'performance-clutches-and-clutch-packs-150', $categories )){
            $price = $origPrice * .75;
        }
        //if is any other category
        else{
            $price = $origPrice * .9;
        }
    }
    return $price;
}
add_filter('woocommerce_get_price', 'return_custom_performance_dealer_price', 10, 2);
</code>```

The function works perfectly in the product loop, but when I added a product to the cart it blew up and gave me this error for each line containing if(in_array( 'CATEGORY_NAME_HERE', $categories )){.

Error: Warning: in_array() expects parameter 2 to be array, null given in…

I'm guessing this has to do with the 5th line of the code above where I use wp_get_post_terms() to form an array of the categories that each product belongs to. I'm not sure how to make this work.

答:
First, the filter hook woocommerce_product_get_price is now replacing deprecated hook woocommerce_get_price…

To avoid the error you got you should use Wordpress conditional dedicated function has_term()

I have revisited your code a bit, so please try this instead:

```<code>add_filter('woocommerce_product_get_price', 'return_custom_performance_dealer_price', 10, 2);
function return_custom_performance_dealer_price( $price, $product ) {

    $price = $product->get_regular_price();

    //check if user role is performance dealer
    $current_user = wp_get_current_user();
    if( in_array('performance_customer', $current_user->roles) ){

        //if is category performance hard parts
        if( has_term( 'new-hard-parts-150', 'product_cat', $product->get_id() ) ){
            $price *= .85;
        }
        //if is category performance clutches
        elseif( has_term( 'performance-clutches-and-clutch-packs-150', 'product_cat', $product->get_id() ) ){
            $price *= .75;
        }
        //if is any other category
        else{
            $price *= .9;
        }
    }
    return $price;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested for WooCommerce 3+… It should work now…

Body:
I have set up a custom user role with a slug of performance_customer. I am checking to see if the current user is a "performance customer" and apply certain price discounts to products in specific categories.

Here is my code:

function return_custom_performance_dealer_price($price, $product) {

    global $woocommerce;
    global $post;
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ) $categories[] = $term->slug;

    $origPrice = get_post_meta( get_the_ID(), '_regular_price', true);
    $price = $origPrice;

    //check if user role is performance dealer
    $current_user = wp_get_current_user();
    if( in_array('performance_customer', $current_user->roles)){
        //if is category performance hard parts
        if(in_array( 'new-hard-parts-150', $categories )){
            $price = $origPrice * .85;
        }
        //if is category performance clutches
        elseif(in_array( 'performance-clutches-and-clutch-packs-150', $categories )){
            $price = $origPrice * .75;
        }
        //if is any other category
        else{
            $price = $origPrice * .9;
        }
    }
    return $price;
}
add_filter('woocommerce_get_price', 'return_custom_performance_dealer_price', 10, 2);

The function works perfectly in the product loop, but when I added a product to the cart it blew up and gave me this error for each line containing if(in_array( 'CATEGORY_NAME_HERE', $categories )){.

Error: Warning: in_array() expects parameter 2 to be array, null given in…

I'm guessing this has to do with the 5th line of the code above where I use wp_get_post_terms() to form an array of the categories that each product belongs to. I'm not sure how to make this work.

Body:
First, the filter hook woocommerce_product_get_price is now replacing deprecated hook woocommerce_get_price…

To avoid the error you got you should use Wordpress conditional dedicated function has_term()

I have revisited your code a bit, so please try this instead:

add_filter('woocommerce_product_get_price', 'return_custom_performance_dealer_price', 10, 2);
function return_custom_performance_dealer_price( $price, $product ) {

    $price = $product->get_regular_price();

    //check if user role is performance dealer
    $current_user = wp_get_current_user();
    if( in_array('performance_customer', $current_user->roles) ){

        //if is category performance hard parts
        if( has_term( 'new-hard-parts-150', 'product_cat', $product->get_id() ) ){
            $price *= .85;
        }
        //if is category performance clutches
        elseif( has_term( 'performance-clutches-and-clutch-packs-150', 'product_cat', $product->get_id() ) ){
            $price *= .75;
        }
        //if is any other category
        else{
            $price *= .9;
        }
    }
    return $price;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested for WooCommerce 3+… It should work now…


问:
Python How to influence running program
Button Start alarm starts ringing of alarm. I want to stop ringing by button Stop alarm. I don't know to influece running program. How must I repair function stop_alarm?

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget

import winsound

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self. start_alarm)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)

    def stop_alarm(self, obj):
        self.alarm_status = False

class LifeApp(App):
    def build(self):
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()
</code>```

答:
The main problem with your code is that you have a while loop on your main GUI thread. So what you need to do is to run the start_alarm on a different thread than your main GUI thread for the GUI thread to be responsive.

As for not being able to play alarm next time, you didn't set the alarm_status flag to True again.Once you have that you can start and stop the sound as many times you want.

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
import time
import winsound
import threading

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self.start_thread)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)
        #Set Alarm_Status True so that next time it works
        self.alarm_status = True

    def stop_alarm(self, obj):
        self.alarm_status = False

    #Function to run your start_alarm on a different thread
    def start_thread(self,obj):
        t1 = threading.Thread(target=self.start_alarm,args=(obj,))
        t1.start()

class LifeApp(App):
    def build(self):
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()
</code>```

Hope this helps!

Title: Python How to influence running program

Body:
Button Start alarm starts ringing of alarm. I want to stop ringing by button Stop alarm. I don't know to influece running program. How must I repair function stop_alarm?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget

import winsound

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self. start_alarm)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)

    def stop_alarm(self, obj):
        self.alarm_status = False

class LifeApp(App):
    def build(self):
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()

Body:
The main problem with your code is that you have a while loop on your main GUI thread. So what you need to do is to run the start_alarm on a different thread than your main GUI thread for the GUI thread to be responsive.

As for not being able to play alarm next time, you didn't set the alarm_status flag to True again.Once you have that you can start and stop the sound as many times you want.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
import time
import winsound
import threading

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self.start_thread)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)
        #Set Alarm_Status True so that next time it works
        self.alarm_status = True

    def stop_alarm(self, obj):
        self.alarm_status = False

    #Function to run your start_alarm on a different thread
    def start_thread(self,obj):
        t1 = threading.Thread(target=self.start_alarm,args=(obj,))
        t1.start()

class LifeApp(App):
    def build(self):
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()

Hope this helps!


问:
How to convert JSON object to JavaScript array?
I need to convert JSON object string to a JavaScript array.

This my JSON object:

```<code>{"2013-01-21":1,"2013-01-22":7}
</code>```

And I want to have:

```<code>var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');

data.addRows([
    ['2013-01-21', 1],
    ['2013-01-22', 7]
]);
</code>```

How can I achieve this?

答:
As simple as this !</p>

```<code>var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to convert JSON object string to a JavaScript array.

This my JSON object:

{"2013-01-21":1,"2013-01-22":7}

And I want to have:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');

data.addRows([
    ['2013-01-21', 1],
    ['2013-01-22', 7]
]);

How can I achieve this?

Body:
As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);


问:
Bundle to add attribute to another entity

Hi,

I have an entity A :

id

att1

att2

Now, I'd like to add a new Bundle (which will add new functionality) and here especially I'd like to add an attribute to A. A must be like :

id

att1

att2

newAtt3

newAtt4

In order to do that, I was thinking to create a new entity which will extend A and add the new attribute.

But then, what I don't know is how can I prepare the first bundle to use the 2nd entity (and controller/view) if the 2nd bundle is installed?

I guess I need to add configuration in the first bundle, but I have no idea what to add...

Thanks !

答:
Please read Best Practices for Reusable Bundles

and Doctrine Inheritance Mapping

You can also think about Traits but often the best way is to use Interfaces. With the help of interfaces you can make your bundle highly configurable on a clean way like this:

make a configuration variabele that tells the bundle what class should be used. This can be the default class A from the Bundle but may also be class A from your AppBundle.

```<code>    $rootNode
        ->children()
            ->scalarNode('a_entity')
                ->defaultValue('AppBundle\\Entity\\A')
            ->end()
        ->end()
    ;
</code>```

Then make a interface for class A with all the functions that are mandatory:

```<code>interface AInterface
{
    public function setVariable($name, $var);
    public function getHtml($template);
}
</code>```

and implement the interface in the class:

```<code>class A implements AInterface
{
    // ...
}
</code>```

Every time if you pass the class as a paramter use AInterface instead of A:

```<code>class B
{
    private $a;

    public function __construct(AInterface $a)
    {
        $this->a = $a;
    }
}
</code>```

Right now you can change the configuration variabele a_entity to another class. This other class still needs to implement the interface AInterface.

Body:
Please read Best Practices for Reusable Bundles

and Doctrine Inheritance Mapping

You can also think about Traits but often the best way is to use Interfaces. With the help of interfaces you can make your bundle highly configurable on a clean way like this:

make a configuration variabele that tells the bundle what class should be used. This can be the default class A from the Bundle but may also be class A from your AppBundle.

    $rootNode
        ->children()
            ->scalarNode('a_entity')
                ->defaultValue('AppBundle\\Entity\\A')
            ->end()
        ->end()
    ;

Then make a interface for class A with all the functions that are mandatory:

interface AInterface
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

and implement the interface in the class:

class A implements AInterface
{
    // ...
}

Every time if you pass the class as a paramter use AInterface instead of A:

class B
{
    private $a;

    public function __construct(AInterface $a)
    {
        $this->a = $a;
    }
}

Right now you can change the configuration variabele a_entity to another class. This other class still needs to implement the interface AInterface.


问:
git: fatal: I don't handle protocol 'http'
I copy and pasted an git clone command from a web page: https://fedorahosted.org/ibus-typing-booster/

I got this:

```<code>user@host> git clone http://git.fedorahosted.org/git/ibus-typing-booster.git

Cloning into 'ibus-typing-booster'...
fatal: I don't handle protocol 'http'
</code>```

答:
clonning below :

```<code>git clone https://github.com/zendframework/ZendSkeletonApplication.git
</code>```

gives error:

```<code>Cloning into 'ZendSkeletonApplication'...
fatal: I don't handle protocol 'https'
</code>```

Modified it to:

```<code>git clone https://github.com/zendframework/ZendSkeletonApplication
</code>```

works perfectly or you can just git clone the url.
I am using os windows 10 and gitbash.

Body:
I copy and pasted an git clone command from a web page: https://fedorahosted.org/ibus-typing-booster/

I got this:

user@host> git clone http://git.fedorahosted.org/git/ibus-typing-booster.git

Cloning into 'ibus-typing-booster'...
fatal: I don't handle protocol 'http'

Body:
clonning below :

git clone https://github.com/zendframework/ZendSkeletonApplication.git

gives error:

Cloning into 'ZendSkeletonApplication'...
fatal: I don't handle protocol 'https'

Modified it to:

git clone https://github.com/zendframework/ZendSkeletonApplication

works perfectly or you can just git clone the url.
I am using os windows 10 and gitbash.


问:
Add to a "null" list in java
I am trying to add an item to a list of card objects, and I get a nullpointer exception if I run this code. I believe I can't add to a 'null' list, but how do I fix this? (The error occurs at 'cards.add(...);')</p>

```<code>public class Deck {

    private List<Card> cards;
    public Deck(String[] ranks, String[] suits, int[] values) {
        for (int i = 0; i < ranks.length; i++) {
            for (int j = 0; j < suits.length; j++){
                cards.add(new Card(ranks[i], suits[j], values[i]));
            }
        }
    }
</code>```

答:
You need to initialize your list...</p>

```<code>private List<Card> cards = new ArrayList<>();
</code>```

Title: Add to a "null" list in java

Body:
I am trying to add an item to a list of card objects, and I get a nullpointer exception if I run this code. I believe I can't add to a 'null' list, but how do I fix this? (The error occurs at 'cards.add(...);')

public class Deck {

    private List<Card> cards;
    public Deck(String[] ranks, String[] suits, int[] values) {
        for (int i = 0; i < ranks.length; i++) {
            for (int j = 0; j < suits.length; j++){
                cards.add(new Card(ranks[i], suits[j], values[i]));
            }
        }
    }

Body:
You need to initialize your list...

private List<Card> cards = new ArrayList<>();


答:
My way to imagine the way iterators work is to think about it as the thing that is placed between the indexes. So when the first next() is being called you can return the value stored under the [0] index and after that call, iterator waits between index [0] and [1] for the next call to return for you value stored at index [1]. After the second next() call iterator waits between [1] and [2] and so on...

It is just my way to get used to iterators but it might be helpful for you some way.

Title: How does next() method on iterators work?

Body:
I have a doubt with the next() method on iterators.  If I have as a part of my code this lines (with arrayOfStrings size = 4):

Iterator<String> it = arrayOfStrings.iterator(); //arrayOfString is ArrayList<String>

while(it.hasNext()) {
    String e = it.next();
    System.out.println(e);
}

At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?

I ask because as far as I know the next() method returns the next element in the collection.

So, if at the very first iteration the iterator starts at index 0 when next() is invoked, it returns the element at index 1 and I won´t be able to do nothing with the element at index 0?


问:
How to perform double sort inside an array?
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

```<code>class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1
</code>```

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

```<code>bar.sort(key=foo.sort,reverse=True)
</code>```

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

```<code>foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2
</code>```

How can I do this?

答:
Sort already do this if you have a tuple of values.
If you change the method sort to return a tuple:

```<code> class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1, self.attrb2
</code>```

Then the solution is really simple:

bar.sort(key=foo.sort, reverse=True)

Body:
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

bar.sort(key=foo.sort,reverse=True)

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2

How can I do this?

Body:
Sort already do this if you have a tuple of values.
If you change the method sort to return a tuple:

 class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1, self.attrb2

Then the solution is really simple:

bar.sort(key=foo.sort, reverse=True)


问:
jQuery inserting html as text instead of DOM object
I'm trying to insert a DOM element using jQuery but it keeps being inserted as text instead.</p>

```<code>var newImg = "<h1>Hi</h1>";
    $("li").each(function myFn(){
        this.addEventListener("mouseover", function myFn2 () {
                             this.before(newImg);
                              })
    });
</code>```

答:
If you console.log(this) you should find that it is not a jQuery object inside the event handler.  You will want to wrap it with $() before you use the before method to use the jQuery method.

```<code>$(this).before(newImg);
</code>```

var newImg = "
Hi
";
$("li").each(function myFn() {
  this.addEventListener("mouseover", function myFn2() {
    $(this).before(newImg);
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Wee</li>
</ul></code>```

Body:
I'm trying to insert a DOM element using jQuery but it keeps being inserted as text instead.

var newImg = "
Hi
";
    $("li").each(function myFn(){
        this.addEventListener("mouseover", function myFn2 () {
                             this.before(newImg);
                              })
    });

Body:
If you console.log(this) you should find that it is not a jQuery object inside the event handler.  You will want to wrap it with $() before you use the before method to use the jQuery method.

$(this).before(newImg);

var newImg = "<h1>Hi</h1>";
$("li").each(function myFn() {
  this.addEventListener("mouseover", function myFn2() {
    $(this).before(newImg);
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Wee</li>
</ul>


问:
dplyr tidyeval equivalent of underscore function versions
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

```<code>library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )
</code>```

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

```<code>microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10
</code>```

There is another answer for mutate_ using even more complex syntax.

答:
```<code># option D: uses formula instead of string
df %>% filter( UQ(f_rhs(~id)) == "a" )
</code>```

Still quite verbose, but avoids the double quotes.

The microbenchmark is equal (or a mini tick faster) than option B, i.e. the as.name solution.

Body:
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10

There is another answer for mutate_ using even more complex syntax.

Body:
# option D: uses formula instead of string
df %>% filter( UQ(f_rhs(~id)) == "a" )

Still quite verbose, but avoids the double quotes.

The microbenchmark is equal (or a mini tick faster) than option B, i.e. the as.name solution.


问:
ESLint React-Router v4 - How to validate Match params props?
I'm using React-Router v4's Match object to pass down params to the next component. Where my Routing is like:

```<code><Switch>
  <Route exact path="/" component={ExperimentListPage} />
  <Route path="/experiment/:experiment" component={ExperimentResultsPage} />
</Switch>
</code>```

and my subcomponent looks like:

```<code>const ExperimentResultsPage = props => (
   <ExperimentResultsContainer experimentName={props.match.params.experiment} />
);

export default withRouter(ExperimentResultsPage);
</code>```

And it all works as intended, however ESLint is really unhappy with me using match.params.experiment and it errors with [eslint] 'match.params.experiment' is missing in props validation (react/prop-types)

I saw in the React docs that I could use PropTypes.shape however my params object but I was hoping there is a better way especially because the Match object contains a lot of fields.

Is there a better way of adding your Match route object to the props validation? How would that look like? If not, am I missing some other approach that could help solve this?

答:
I ran into something similar, eslint seems fine with only declaring what Im using as props and ignoring unused fields from match: </p>

```<code>  match: PropTypes.shape({
    params: PropTypes.shape({
      experiment: PropTypes.string,
    }),
  }).isRequired,
</code>```

Body:
I'm using React-Router v4's Match object to pass down params to the next component. Where my Routing is like:

<Switch>
  <Route exact path="/" component={ExperimentListPage} />
  <Route path="/experiment/:experiment" component={ExperimentResultsPage} />
</Switch>

and my subcomponent looks like:

const ExperimentResultsPage = props => (
   <ExperimentResultsContainer experimentName={props.match.params.experiment} />
);

export default withRouter(ExperimentResultsPage);

And it all works as intended, however ESLint is really unhappy with me using match.params.experiment and it errors with [eslint] 'match.params.experiment' is missing in props validation (react/prop-types)

I saw in the React docs that I could use PropTypes.shape however my params object but I was hoping there is a better way especially because the Match object contains a lot of fields.

Is there a better way of adding your Match route object to the props validation? How would that look like? If not, am I missing some other approach that could help solve this?

Body:
I ran into something similar, eslint seems fine with only declaring what Im using as props and ignoring unused fields from match:

  match: PropTypes.shape({
    params: PropTypes.shape({
      experiment: PropTypes.string,
    }),
  }).isRequired,


问:
How to get the RGB matrix from an image?
how to create matrix R,G,B from image in openCv .
matSrcBRG is Mat variable . and my image is img_about</p>

```<code> try {
            matSrcBGR = Utils.loadResource(context, R.raw.img_about);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int rows = matSrcBGR.rows(); //Calculates number of rows
        int cols = matSrcBGR.cols(); //Calculates number of columns
        int ch = matSrcBGR.channels(); //Calculates number of channels (Grayscale: 1, RGB: 3, etc.)
        double[] bgrColor = matSrcBGR.get(matSrcBGR.rows(), matSrcBGR.cols());
</code>```

答:
my answer is </p>

```<code>        int rows = matSrcBGR.rows(); //Calculates number of rows
        int cols = matSrcBGR.cols(); //Calculates number of columns
        int channels = matSrcBGR.channels(); //Calculates number of channels
        //channel2=red , channel1=green ,channel0=blue
        int[][][] matrix = new int[cols][rows][channels];

        for (int col = 0; col < cols; col++) {
            for (int row = 0; row < rows; row++) {
                for (int channel = 0; channel < channels; channel++) {
                    matrix[col][row][channel] = (int) matSrcBGR.get(row, col)[channel];
                }
            }
        }
</code>```

Body:
how to create matrix R,G,B from image in openCv .
matSrcBRG is Mat variable . and my image is img_about

 try {
            matSrcBGR = Utils.loadResource(context, R.raw.img_about);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int rows = matSrcBGR.rows(); //Calculates number of rows
        int cols = matSrcBGR.cols(); //Calculates number of columns
        int ch = matSrcBGR.channels(); //Calculates number of channels (Grayscale: 1, RGB: 3, etc.)
        double[] bgrColor = matSrcBGR.get(matSrcBGR.rows(), matSrcBGR.cols());

Body:
my answer is

        int rows = matSrcBGR.rows(); //Calculates number of rows
        int cols = matSrcBGR.cols(); //Calculates number of columns
        int channels = matSrcBGR.channels(); //Calculates number of channels
        //channel2=red , channel1=green ,channel0=blue
        int[][][] matrix = new int[cols][rows][channels];

        for (int col = 0; col < cols; col++) {
            for (int row = 0; row < rows; row++) {
                for (int channel = 0; channel < channels; channel++) {
                    matrix[col][row][channel] = (int) matSrcBGR.get(row, col)[channel];
                }
            }
        }


问:
Angular : sanitizing HTML stripped some content on css style

I am using a wysiwyg editor in my Angular component, when i try to preview the content of the editor, (after i apply center to the text),
i get this warning:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

platform-browser.es5.js:1015

when i inspect the html:

```<code><p>Text Here...</p>
</code>```

but when i try to use console.log() to preview the content of the editor i get:

```<code><p style="text-align: center;">Text Here...</p>
</code>```

答:
This is by design in Angular 2+ for security reasons. You can workaround it by using the DomSanitizer class.

For example you can make a pipe that prevents sanitization of the value:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'noSanitize' })
export class NoSanitizePipe implements PipeTransform {
   constructor(private domSanitizer: DomSanitizer) {

   }
   transform(html: string): SafeHtml {
      return this.domSanitizer.bypassSecurityTrustHtml(html);
   }
}
</code>```

Then you can use it in binding for example like this:

```<code><div [innerHTML]="htmlText | noSanitize">
</div>
</code>```

Body:
I am using a wysiwyg editor in my Angular component, when i try to preview the content of the editor, (after i apply center to the text),
i get this warning:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

platform-browser.es5.js:1015

when i inspect the html:

Text Here...

but when i try to use console.log() to preview the content of the editor i get:

Text Here...

Body:
This is by design in Angular 2+ for security reasons. You can workaround it by using the DomSanitizer class.

For example you can make a pipe that prevents sanitization of the value:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'noSanitize' })
export class NoSanitizePipe implements PipeTransform {
   constructor(private domSanitizer: DomSanitizer) {

   }
   transform(html: string): SafeHtml {
      return this.domSanitizer.bypassSecurityTrustHtml(html);
   }
}

Then you can use it in binding for example like this:

<div [innerHTML]="htmlText | noSanitize">
</div>


问:
Sql join two tables with another that has no common column
I have this subquery where I am getting the posts of users that a user is following. This is the subquery.

```<code>$query = "SELECT * FROM `Posts` WHERE UserID IN
    (
    SELECT Followed FROM `Follow` WHERE Follower = ?
    )
    ORDER BY PostDate DESC
    ";

// on bind_param ? will be $userID
</code>```

This works fine but I also want to get the user's own posts and then data from a profiles table so I'm probably going to ditch the subquery for some sort of join. I've used inner joins before however the profile/posts table have a common id 'UserID' but the Follow table does not. Would a full join work or would I have to use an AS ?

答:
A union might be best.

```<code>SELECT * FROM posts WHERE UserID = ?
UNION ALL
SELECT P.*
FROM posts P
INNER JOIN follow F ON F.followed = P.UserID
WHERE F.follower = ?
</code>```

Body:
I have this subquery where I am getting the posts of users that a user is following. This is the subquery.

$query = "SELECT * FROM `Posts` WHERE UserID IN
    (
    SELECT Followed FROM `Follow` WHERE Follower = ?
    )
    ORDER BY PostDate DESC
    ";

// on bind_param ? will be $userID

This works fine but I also want to get the user's own posts and then data from a profiles table so I'm probably going to ditch the subquery for some sort of join. I've used inner joins before however the profile/posts table have a common id 'UserID' but the Follow table does not. Would a full join work or would I have to use an AS ?

Body:
A union might be best.

SELECT * FROM posts WHERE UserID = ?
UNION ALL
SELECT P.*
FROM posts P
INNER JOIN follow F ON F.followed = P.UserID
WHERE F.follower = ?


问:
Use multiple WITH tablename AS (...) statements SQL Server
I'm trying to create two temporary tables and join them with a permanent table.  For example: </p>

```<code>WITH temp1 AS (COUNT(*) AS count_sales, ID FROM table1 GROUP BY ID)
WITH temp2 AS (COUNT(*) AS count_somethingelse, ID FROM table2 GROUP BY ID)
SELECT *
FROM table3 JOIN table2 JOIN table1
     ON table1.ID = table2.ID = table3.ID
</code>```

<p>but there seems to be an issue having multiple WITH tablename AS (...) statments.  I tried a semicolon.  </p>

答:
I'm trying to create two temporary tables

Just for clarity... you used a CTE which is not quite the same thing as a temporary table.  You've also tagged 'temp tables', so you want a temp table?  You can store query results in a declared table variable or an actual temp table.

An example of declared table variables:

```<code>DECLARE @table1 TABLE(id int, count_sales int)

INSERT INTO @table1 (id, count_sales)
SELECT ID, COUNT(*)
  FROM table1
GROUP BY ID
--or however you populate temp table1

DECLARE @table2 TABLE(id int, count_somethingelse int)

INSERT INTO @table2 (id, count_somethingelse)
SELECT ID, COUNT(*)
  FROM table2
GROUP BY ID
--or however you populate temp table2

SELECT T3.id
      --,T2.(some column)
      --,T1.(some column)
      --,etc...
FROM table3 T3 INNER JOIN @table2 T2 ON T3.id = T2.id
               INNER JOIN @table1 T1 ON T3.id = T1.id
</code>```

Body:
I'm trying to create two temporary tables and join them with a permanent table.  For example:

WITH temp1 AS (COUNT(*) AS count_sales, ID FROM table1 GROUP BY ID)
WITH temp2 AS (COUNT(*) AS count_somethingelse, ID FROM table2 GROUP BY ID)
SELECT *
FROM table3 JOIN table2 JOIN table1
     ON table1.ID = table2.ID = table3.ID

but there seems to be an issue having multiple WITH tablename AS (...) statments.  I tried a semicolon.

Body:
I'm trying to create two temporary tables

Just for clarity... you used a CTE which is not quite the same thing as a temporary table.  You've also tagged 'temp tables', so you want a temp table?  You can store query results in a declared table variable or an actual temp table.

An example of declared table variables:

DECLARE @table1 TABLE(id int, count_sales int)

INSERT INTO @table1 (id, count_sales)
SELECT ID, COUNT(*)
  FROM table1
GROUP BY ID
--or however you populate temp table1

DECLARE @table2 TABLE(id int, count_somethingelse int)

INSERT INTO @table2 (id, count_somethingelse)
SELECT ID, COUNT(*)
  FROM table2
GROUP BY ID
--or however you populate temp table2

SELECT T3.id
      --,T2.(some column)
      --,T1.(some column)
      --,etc...
FROM table3 T3 INNER JOIN @table2 T2 ON T3.id = T2.id
               INNER JOIN @table1 T1 ON T3.id = T1.id


答:
Initialize the List cards as follows with the specified element type:</p>

```<code>private List<Card> cards = new ArrayList<Card>();
</code>```

Title: Add to a "null" list in java

Body:
I am trying to add an item to a list of card objects, and I get a nullpointer exception if I run this code. I believe I can't add to a 'null' list, but how do I fix this? (The error occurs at 'cards.add(...);')

public class Deck {

    private List<Card> cards;
    public Deck(String[] ranks, String[] suits, int[] values) {
        for (int i = 0; i < ranks.length; i++) {
            for (int j = 0; j < suits.length; j++){
                cards.add(new Card(ranks[i], suits[j], values[i]));
            }
        }
    }

Body:
Initialize the List cards as follows with the specified element type:

private List<Card> cards = new ArrayList<Card>();


问:
Pandas- creating a table that inserts new rows based on column values?
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

```<code> name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667
</code>```

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

```<code>   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667
</code>```

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

答:
You could go for

```<code>def myfunc(row):
    return pd.Series({'name': 'ex_{}'.format(row['name']),
                      'value1': row['ex_value1'],
                      'value2': row['ex_value2']})

df2 = df[~df['name'].astype(str).str.startswith('ex_')].apply(myfunc,axis =1)
df = pd.concat([df[['name', 'value1', 'value2']], df2])
</code>```

This applies the function myfunc only to those rows where name does not start with ex_. myfunc() returns a new dataframe which is then concatenated to df.

For one-liner-lovers (though not advisable, really):

```<code>df = pd.concat([df[['name', 'value1', 'value2']],
                df[~df['name'].astype(str).str.startswith('ex_')].apply(myfunc,axis = 1)])
</code>```

Body:
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

 name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

Body:
You could go for

def myfunc(row):
    return pd.Series({'name': 'ex_{}'.format(row['name']),
                      'value1': row['ex_value1'],
                      'value2': row['ex_value2']})

df2 = df[~df['name'].astype(str).str.startswith('ex_')].apply(myfunc,axis =1)
df = pd.concat([df[['name', 'value1', 'value2']], df2])

This applies the function myfunc only to those rows where name does not start with ex_. myfunc() returns a new dataframe which is then concatenated to df.

For one-liner-lovers (though not advisable, really):

df = pd.concat([df[['name', 'value1', 'value2']],
                df[~df['name'].astype(str).str.startswith('ex_')].apply(myfunc,axis = 1)])


问:
Ionic - Unexpected token ILLEGAL only when running in Android 5 emulator
I'm developing an Ionic application and I'm facing the following problem:

```<code>Unexpected token ILLEGAL
</code>```

The strange thing is that it only occurs when I run the application in Genymotion emulator with Android 5 and bellow, using ionic cordova run android. If I run the same code in Android 6 and above the application runs correctly.

The console is saying the problem is near the '{' character:

I tryied rewrite this piece of code, but it only change the error to another line, if I delete all white spaces.

The weird thing here is that it only occurs when running in the emulator, so I'm suspecting from something in project configuration, like webpack.

Ionic version: 3.19.0
  cordova-android: ^6.2.3

This is my package.json

```<code>{
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
    "dependencies": {
        "@angular/common": "5.0.1",
        "@angular/compiler": "5.0.1",
        "@angular/compiler-cli": "5.0.1",
        "@angular/core": "5.0.1",
        "@angular/forms": "5.0.1",
        "@angular/http": "5.0.1",
        "@angular/platform-browser": "5.0.1",
        "@angular/platform-browser-dynamic": "5.0.1",
        "@ionic-native/camera": "^4.4.2",
        "@ionic-native/core": "4.3.2",
        "@ionic-native/date-picker": "^4.4.2",
        "@ionic-native/facebook": "^4.4.2",
        "@ionic-native/globalization": "^4.4.2",
        "@ionic-native/google-plus": "^4.4.2",
        "@ionic-native/onesignal": "^4.4.2",
        "@ionic-native/splash-screen": "4.3.2",
        "@ionic-native/status-bar": "4.3.2",
        "@ionic/storage": "^2.1.3",
        "@ngx-translate/core": "^9.0.1",
        "@ngx-translate/http-loader": "^2.0.0",
        "cordova-android": "^6.2.3",
        "cordova-plugin-camera": "^2.4.1",
        "cordova-plugin-compat": "^1.2.0",
        "cordova-plugin-datepicker": "^0.9.3",
        "cordova-plugin-device": "1.1.4",
        "cordova-plugin-facebook4": "^1.9.1",
        "cordova-plugin-globalization": "^1.0.8",
        "cordova-plugin-googleplus": "^5.1.1",
        "cordova-plugin-ionic-webview": "^1.1.11",
        "cordova-plugin-splashscreen": "~4.0.1",
        "cordova-plugin-whitelist": "1.3.1",
        "cordova-sqlite-storage": "^2.1.2",
        "font-awesome": "^4.7.0",
        "ionic-angular": "3.9.2",
        "ionic-plugin-keyboard": "~2.2.1",
        "ionicons": "3.0.0",
        "moment": "^2.19.2",
        "ngx-cookie-service": "^1.0.9",
        "onesignal-cordova-plugin": "^2.2.2",
        "rxjs": "5.5.2",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.18"
    },
    "devDependencies": {
        "@ionic/app-scripts": "3.1.0",
        "typescript": "2.4.2"
    },
    "config": {
        "ionic_copy": "./config/copy.config.js"
    },
    "cordova": {
        "plugins": {
            "cordova-plugin-device": {},
            "cordova-plugin-ionic-webview": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-plugin-facebook4": {
                "APP_ID": "",
                "APP_NAME": ""
            },
            "cordova-plugin-datepicker": {},
            "cordova-plugin-googleplus": {
                "REVERSED_CLIENT_ID": ""
            },
            "cordova-plugin-globalization": {},
            "cordova-plugin-camera": {},
            "onesignal-cordova-plugin": {},
            "cordova-sqlite-storage": {}
        },
        "platforms": [
            "android"
        ]
    }
}
</code>```

Ionic info:

```<code>cli packages: (/opt/nvm/versions/node/v7.10.0/lib/node_modules)

@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.0.1

local packages:

    @ionic/app-scripts : 3.1.0
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v7.10.0
    npm               : 4.2.0
    OS                : Linux 4.4

Environment Variables:

    ANDROID_HOME : /opt/android-sdk-linux

Misc:

    backend : pro
</code>```

答:
It appears there's an adjustment to make in

node_modules/@ionic/app-scripts/dist/template.js

change to this:

return getTemplatePrefix(htmlFilePath) + "'" + content + "'" +
  getTemplateSuffix(htmlFilePath);

some backticks to remove. I read here: [Module parse failed: Unexpected token ionic 3

Body:
I'm developing an Ionic application and I'm facing the following problem:

Unexpected token ILLEGAL

The strange thing is that it only occurs when I run the application in Genymotion emulator with Android 5 and bellow, using ionic cordova run android. If I run the same code in Android 6 and above the application runs correctly.

The console is saying the problem is near the '{' character:

I tryied rewrite this piece of code, but it only change the error to another line, if I delete all white spaces.

The weird thing here is that it only occurs when running in the emulator, so I'm suspecting from something in project configuration, like webpack.

Ionic version: 3.19.0
  cordova-android: ^6.2.3

This is my package.json

{
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
    "dependencies": {
        "@angular/common": "5.0.1",
        "@angular/compiler": "5.0.1",
        "@angular/compiler-cli": "5.0.1",
        "@angular/core": "5.0.1",
        "@angular/forms": "5.0.1",
        "@angular/http": "5.0.1",
        "@angular/platform-browser": "5.0.1",
        "@angular/platform-browser-dynamic": "5.0.1",
        "@ionic-native/camera": "^4.4.2",
        "@ionic-native/core": "4.3.2",
        "@ionic-native/date-picker": "^4.4.2",
        "@ionic-native/facebook": "^4.4.2",
        "@ionic-native/globalization": "^4.4.2",
        "@ionic-native/google-plus": "^4.4.2",
        "@ionic-native/onesignal": "^4.4.2",
        "@ionic-native/splash-screen": "4.3.2",
        "@ionic-native/status-bar": "4.3.2",
        "@ionic/storage": "^2.1.3",
        "@ngx-translate/core": "^9.0.1",
        "@ngx-translate/http-loader": "^2.0.0",
        "cordova-android": "^6.2.3",
        "cordova-plugin-camera": "^2.4.1",
        "cordova-plugin-compat": "^1.2.0",
        "cordova-plugin-datepicker": "^0.9.3",
        "cordova-plugin-device": "1.1.4",
        "cordova-plugin-facebook4": "^1.9.1",
        "cordova-plugin-globalization": "^1.0.8",
        "cordova-plugin-googleplus": "^5.1.1",
        "cordova-plugin-ionic-webview": "^1.1.11",
        "cordova-plugin-splashscreen": "~4.0.1",
        "cordova-plugin-whitelist": "1.3.1",
        "cordova-sqlite-storage": "^2.1.2",
        "font-awesome": "^4.7.0",
        "ionic-angular": "3.9.2",
        "ionic-plugin-keyboard": "~2.2.1",
        "ionicons": "3.0.0",
        "moment": "^2.19.2",
        "ngx-cookie-service": "^1.0.9",
        "onesignal-cordova-plugin": "^2.2.2",
        "rxjs": "5.5.2",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.18"
    },
    "devDependencies": {
        "@ionic/app-scripts": "3.1.0",
        "typescript": "2.4.2"
    },
    "config": {
        "ionic_copy": "./config/copy.config.js"
    },
    "cordova": {
        "plugins": {
            "cordova-plugin-device": {},
            "cordova-plugin-ionic-webview": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-plugin-facebook4": {
                "APP_ID": "",
                "APP_NAME": ""
            },
            "cordova-plugin-datepicker": {},
            "cordova-plugin-googleplus": {
                "REVERSED_CLIENT_ID": ""
            },
            "cordova-plugin-globalization": {},
            "cordova-plugin-camera": {},
            "onesignal-cordova-plugin": {},
            "cordova-sqlite-storage": {}
        },
        "platforms": [
            "android"
        ]
    }
}

Ionic info:

cli packages: (/opt/nvm/versions/node/v7.10.0/lib/node_modules)

@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.0.1

local packages:

    @ionic/app-scripts : 3.1.0
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v7.10.0
    npm               : 4.2.0
    OS                : Linux 4.4

Environment Variables:

    ANDROID_HOME : /opt/android-sdk-linux

Misc:

    backend : pro


问:
Chart.JS Global Options
I seem to be getting errors in Chart.JS for some reason.  It's related to the global options that you can set.

The is as follows

Here is my code

```<code>var chart1 = document.getElementById("chart1").getContext("2d"),
chart2 = document.getElementById("chart2").getContext("2d"),
chart3 = document.getElementById("chart3").getContext("2d"),

datatest1 = document.getElementById("datatest1").value,
datatest2 = document.getElementById("datatest2").value,

color_bg = "#00b5e4",
color_fg = "#007799",

data1 = [{ value: Math.floor(Math.random() * 100), color: color_bg}, { value: Math.floor(Math.random() * 100), color: color_fg}],
data2 = [{ value: datatest1, color: color_bg}, { value: datatest2, color: color_fg}],
data3 = {
    labels: ["Jan", "Feb", "Mar"],
    datasets: [
        {
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};

//
// #Global Chart Settings
var options = Chart.defaults.global = {
animation: true,
animationSteps: 160,
animationEasing: "easeOutQuart",
responsive: true,
showTooltips: true,
segmentShowStroke: false,
maintainAspectRatio: true,
percentageInnerCutout: 70,
onAnimationComplete: function () {
    "use strict";
    //console.log("Animation Done");
}
};

$(document).ready(function () {
"use strict";

//
// #Initialise and bind to data and global options
new Chart(chart1).Doughnut(data1, options);
new Chart(chart2).Doughnut(data2, options);
new Chart(chart3).Radar(data3);
});
</code>```

If you remove the options from the charts they work, if you add options and set them globally as per their documentation you get the error I've mentioned.  Am I missing something obvious or is there an issue here?

答:
First it must be understood that the main property to be tweaked so as to handle the animations is "Chart.defaults.global.animation".

Then keeping this as the base, you will need to adjust the sub-properties as mentioned above and in the documentation page.

So, You can change as follows:

```<code>Chart.defaults.global.animation.animationSteps=160;
Chart.defaults.global.animation.duration=5000;
...
</code>```

For positioning of these lines of code, follow the first answer by potatopeelings.

I have tried changing in this way and it works !!!

Title: Chart.JS Global Options

Body:
I seem to be getting errors in Chart.JS for some reason.  It's related to the global options that you can set.

The is as follows

Here is my code

var chart1 = document.getElementById("chart1").getContext("2d"),
chart2 = document.getElementById("chart2").getContext("2d"),
chart3 = document.getElementById("chart3").getContext("2d"),

datatest1 = document.getElementById("datatest1").value,
datatest2 = document.getElementById("datatest2").value,

color_bg = "#00b5e4",
color_fg = "#007799",

data1 = [{ value: Math.floor(Math.random() * 100), color: color_bg}, { value: Math.floor(Math.random() * 100), color: color_fg}],
data2 = [{ value: datatest1, color: color_bg}, { value: datatest2, color: color_fg}],
data3 = {
    labels: ["Jan", "Feb", "Mar"],
    datasets: [
        {
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};

//
// #Global Chart Settings
var options = Chart.defaults.global = {
animation: true,
animationSteps: 160,
animationEasing: "easeOutQuart",
responsive: true,
showTooltips: true,
segmentShowStroke: false,
maintainAspectRatio: true,
percentageInnerCutout: 70,
onAnimationComplete: function () {
    "use strict";
    //console.log("Animation Done");
}
};

$(document).ready(function () {
"use strict";

//
// #Initialise and bind to data and global options
new Chart(chart1).Doughnut(data1, options);
new Chart(chart2).Doughnut(data2, options);
new Chart(chart3).Radar(data3);
});

If you remove the options from the charts they work, if you add options and set them globally as per their documentation you get the error I've mentioned.  Am I missing something obvious or is there an issue here?

Body:
First it must be understood that the main property to be tweaked so as to handle the animations is "Chart.defaults.global.animation".

Then keeping this as the base, you will need to adjust the sub-properties as mentioned above and in the documentation page.

So, You can change as follows:

Chart.defaults.global.animation.animationSteps=160;
Chart.defaults.global.animation.duration=5000;
...

For positioning of these lines of code, follow the first answer by potatopeelings.

I have tried changing in this way and it works !!!


问:
How to authenticate and authorize the token from Angular 2 web app using Azure ad b2c at ASP.net Web API?
I am using angular 2 at client side and I want to allow the consumers to login using the social accounts like Google, Facebook etc.

For that I am using the Azure ad b2c.

I want to secure the Web API with a token from the angular 2 web app.

How can I achieve that?

I have tried msal library (preview) in Angular 2 for authenticating the user using Azure ad b2c. But I am not able to authorize the token at Web API.

答:
See this Angular 4 example w/ MSAL.js.

Also, this blog post is a good guide for securing Web API.  There's also a good sample project on GitHub: An ASP.NET Core 2.0 web API with Azure AD B2C.


问:
How can I press keyboard keys while the computer is locked
I would like to be able to "press" the Scroll Lock key (from an application),
so that the scroll lock led on the keyboard will turn on or off.

I've used the DllImport on the function keybd_event (from user32.dll) to do so,
and my app runs as a service on win xp.

It's works fine, but when I lock the computer (win+L) that function stops working.

I've tried running the service as Local Service and as Admin but it made no difference.

any suggestions?

thanks.

答:
thanks for the help guys.

what I end up doing, was replacing msgina.dll, with my own dll (ginastub.dll),
and in it opened a new thread (that run in the winlogon session).
my service can communicate with that thread using named pipe, and send it commands to "press" the key.

it took a while but it seem to work :)


问:
numpy stacking matrices together of same sub dimension
Suppose I have a matrix

```<code>mat = np.empty((0, 3, 5))
</code>```

and I have a another matrix of shape (3, 5), how can I add that matrix to mat[0]?

I've tried different combinations of stack, vstack, hstack, concatenate and insert and they don't seem to work

答:
I suggest you to do this to create your matrix. :)

Your matrix is empty in your current state. Like [].

```<code>import numpy as np

rows = 5
cols = 3
mat = np.array([[0] * cols] * rows)
mat_2 = np.empty((0, 3, 5))

print mat
print mat_2
# out for mat:
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
# out for mat_2:
[]
</code>```

To make my answer final, as I stated in comments,  just add the two matrices you want to add like m1 + m2.

```<code>rows = 5
cols = 3
mat = np.array([[1] * cols] * rows)
mat_2 = np.array([[2] * cols] * rows)

print mat + mat_2
# out :
[[3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]]
</code>```

Body:
Suppose I have a matrix

mat = np.empty((0, 3, 5))

and I have a another matrix of shape (3, 5), how can I add that matrix to mat[0]?

I've tried different combinations of stack, vstack, hstack, concatenate and insert and they don't seem to work

Body:
I suggest you to do this to create your matrix. :)

Your matrix is empty in your current state. Like [].

import numpy as np

rows = 5
cols = 3
mat = np.array([[0] * cols] * rows)
mat_2 = np.empty((0, 3, 5))

print mat
print mat_2
# out for mat:
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
# out for mat_2:
[]

To make my answer final, as I stated in comments,  just add the two matrices you want to add like m1 + m2.

rows = 5
cols = 3
mat = np.array([[1] * cols] * rows)
mat_2 = np.array([[2] * cols] * rows)

print mat + mat_2
# out :
[[3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]]


问:
MySQL New Value of Column A by Comparing Current Year vs. Previous Year (Column B)
I have a MySQL table with two columns, Column A and Column B.

Column A is distinct product ID# and Column B represents Year.

I want to compare current year with previous year to see which product is new and didn't sell in the previous year.

How can I do this?

So for a table like below, what query can I put to select the records with Year 2013 and Product ID CC since CC does not appear in 2012.

```<code>+-------------+------------+
| Year        | Product ID |
+-------------+------------+
| 2012        | AA         |
| 2012        | BB         |
| 2013        | AA         |
| 2013        | BB         |
| 2013        | CC         |
+-------------+------------+
</code>```

答:
Here is a simple select statement that will allow you to search for the ProductID of an item where the year corresponding to that id is 2017.

```<code>SELECT Product ID
FROM Table
WHERE Product ID = 'CC' AND Year = 2013;
</code>```

will return the correct result for you.

If the year represents the year the product was added, I don't see why you would need to compare it to other years, versus just searching that year specifically.

Body:
I have a MySQL table with two columns, Column A and Column B.

Column A is distinct product ID# and Column B represents Year.

I want to compare current year with previous year to see which product is new and didn't sell in the previous year.

How can I do this?

So for a table like below, what query can I put to select the records with Year 2013 and Product ID CC since CC does not appear in 2012.

+-------------+------------+
| Year        | Product ID |
+-------------+------------+
| 2012        | AA         |
| 2012        | BB         |
| 2013        | AA         |
| 2013        | BB         |
| 2013        | CC         |
+-------------+------------+

Body:
Here is a simple select statement that will allow you to search for the ProductID of an item where the year corresponding to that id is 2017.

SELECT Product ID
FROM Table
WHERE Product ID = 'CC' AND Year = 2013;

will return the correct result for you.

If the year represents the year the product was added, I don't see why you would need to compare it to other years, versus just searching that year specifically.