问:
Python dict, extracting values
I am having trouble to query my database maybe someone could give me a hand.
I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value

```<code>b = Answer.objects.get(id = 23)
</code>```

which give me an output of :

```<code><Answer: Answer to questionID '4' : AnswerID '23'>
</code>```

when I do :

```<code>b.values
</code>```

I get a dict in the form :

```<code> ['{
    "1)Long descriptive text":Score,
    "2)Long descriptive text":Score,
    "3)Long descriptive text":Score,
    "4)Long descriptive text":Score
    }']
</code>```

with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85

I need to extract the score using a query but I can't manage to do it
Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it

could you give me a hand
Thx you very much

答:
This looks suspiciously like Django If so:

so b = Answer.objects.get(id = 23) is not truely that - what you are seeing is the str function of the Answer when you print it off. because you used .get rather then a .filter you get the object rather then a QuerySet (which you can think of as being a list).

Basically, I suspect you shouldn't be using values, but accessing the data... something like

```<code>b = Answer.objects.get(id=..)
b.score
</code>```

or if you wanted to loop over other answers:

```<code>answers = Answer.objects.filter(...)
for a in answers:
    a.score
</code>```

for what the .score is, look in your models.py file - look what parameters is has (things looking like score = models.IntegerField() etc, then you would use a.score)

Title: Python dict, extracting values

Body:
I am having trouble to query my database maybe someone could give me a hand.
I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value

b = Answer.objects.get(id = 23)

which give me an output of :

<Answer: Answer to questionID '4' : AnswerID '23'>

when I do :

b.values

I get a dict in the form :

 ['{
    "1)Long descriptive text":Score,
    "2)Long descriptive text":Score,
    "3)Long descriptive text":Score,
    "4)Long descriptive text":Score
    }']

with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85

I need to extract the score using a query but I can't manage to do it
Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it

could you give me a hand
Thx you very much

Body:
This looks suspiciously like Django If so:

so b = Answer.objects.get(id = 23) is not truely that - what you are seeing is the str function of the Answer when you print it off. because you used .get rather then a .filter you get the object rather then a QuerySet (which you can think of as being a list).

Basically, I suspect you shouldn't be using values, but accessing the data... something like

b = Answer.objects.get(id=..)
b.score

or if you wanted to loop over other answers:

answers = Answer.objects.filter(...)
for a in answers:
    a.score

for what the .score is, look in your models.py file - look what parameters is has (things looking like score = models.IntegerField() etc, then you would use a.score)


来源: stackexchange

问:
Toggle "ActionController::Parameters.action_on_unpermitted_parameters = :raise" on specific controller methods?
I want to use

```<code>ActionController::Parameters.action_on_unpermitted_parameters = :raise
</code>```

To raise an exception unpermitted parameters are passed in, but I only want to do this on specific controller methods, instead of setting it in /config/ and having it apply to the whole environment. Is there any way to do so?

答:
Update: (taking inspiration from Mike's answer)

To restrict the change only for a set of controller actions and to revert it back to the original value that the class attribute was holding before the action being invoked, we can use around_action

class SomeController < ApplicationController
  around_action :raise_action_on_unpermitted_parameters, only: %i[create update]

  def index
    # ...
  end

  def create
    # ...
  end

  def update
    # ...
  end

  private

  def raise_action_on_unpermitted_parameters
    original = ActionController::Parameters.action_on_unpermitted_parameters
    ActionController::Parameters.action_on_unpermitted_parameters = :raise
    yield
  ensure
    ActionController::Parameters.action_on_unpermitted_parameters = original
  end
end
```

ContentLicense: CC BY-SA 3.0

Body:
I want to use

ActionController::Parameters.action_on_unpermitted_parameters = :raise

To raise an exception unpermitted parameters are passed in, but I only want to do this on specific controller methods, instead of setting it in /config/ and having it apply to the whole environment. Is there any way to do so?

ContentLicense: CC BY-SA 4.0


问:
JAVA - SCANNER to get user input
I have the following block code:

```<code>    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }
</code>```

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

```<code>Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next
</code>```

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

答:
This is the correct version of the same using Java8

```<code>import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScannerExample {

public static void main(String[] args) {
    boolean run = true;
    try (Scanner sc = new Scanner(System.in)) {
        while (run) {

            System.out.println("Another action? [Y/N]");
            String option = sc.next();
            Pattern patter = Pattern.compile("[YyNn]");
            Matcher m = patter.matcher(option);
            while (!m.matches()) {
                System.out.println("Incorrect input");
                option = sc.next();
                m = patter.matcher(option);
            }
            option = sc.next();
            if (option.toLowerCase().equals("f")) {
                run = false;
            }

        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
</code>```

}

output:

```<code>Another action? [Y/N]
Y
N
Another action? [Y/N]
Y
N
Another action? [Y/N]
f
Incorrect input
Y
N
Another action? [Y/N]
f
Incorrect input
Y
f
</code>```

Title: JAVA - SCANNER to get user input

Body:
I have the following block code:

    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

Body:
This is the correct version of the same using Java8

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScannerExample {

public static void main(String[] args) {
    boolean run = true;
    try (Scanner sc = new Scanner(System.in)) {
        while (run) {

            System.out.println("Another action? [Y/N]");
            String option = sc.next();
            Pattern patter = Pattern.compile("[YyNn]");
            Matcher m = patter.matcher(option);
            while (!m.matches()) {
                System.out.println("Incorrect input");
                option = sc.next();
                m = patter.matcher(option);
            }
            option = sc.next();
            if (option.toLowerCase().equals("f")) {
                run = false;
            }

        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}

}

output:

Another action? [Y/N]
Y
N
Another action? [Y/N]
Y
N
Another action? [Y/N]
f
Incorrect input
Y
N
Another action? [Y/N]
f
Incorrect input
Y
f


问:
Impact of creating index after DML operation
I have created one table and loaded data. This data was loaded last year.

And today we have created a primary key. Will the primary key

uses row id for the the past records. Or should I rebuild index?

答:
"primary key will create index automatically."

Yes. Unless there is an existing index on the primary key column(s) in which case Oracle will use that to enforce the key. There is no need to rebuild an existing index. This remains true even if the existing index is non-unique (Oracle's clever that way).

"Will the index gets created for past data"

Yes (*). The index applies to all the records in the table, not just ones add after the index is created.

(*) Strictly that should have been 'By default yes' as 12c introduced the concept of partial indexes for partitioned tables. Find out more.


问:
How can I remove default button class of a dataTables button?
I am using Data table with Button. I want to show Success button rather default.
I tried this Code

```<code>buttons: [
{
extend: "excel",
className: "btn-sm btn-success",
titleAttr: 'Export in Excel',
text: 'Excel'
}]
</code>```

This code is working but this is adding btn-success class, But I want to remove the btn-default class first and then add the success class.

Current Classes: "btn btn-default buttons-excel buttons-html5 btn-sm btn-success"

What I want : "btn buttons-excel buttons-html5 btn-sm btn-success"

答:
Use this code to hide Excel text on button:</p>

```<code> extend: 'excel',

 text: '',

 className: "btn btn-info btn-sm  glyphicon glyphicon-list-alt",
</code>```

Body:
I am using Data table with Button. I want to show Success button rather default.
I tried this Code

buttons: [
{
extend: "excel",
className: "btn-sm btn-success",
titleAttr: 'Export in Excel',
text: 'Excel'
}]

This code is working but this is adding btn-success class, But I want to remove the btn-default class first and then add the success class.

Current Classes: "btn btn-default buttons-excel buttons-html5 btn-sm btn-success"

What I want : "btn buttons-excel buttons-html5 btn-sm btn-success"

Body:
Use this code to hide Excel text on button:

 extend: 'excel',

 text: '',

 className: "btn btn-info btn-sm  glyphicon glyphicon-list-alt",


问:
How to refer Spark RDD element multiple times using underscore notation?
How to refer Spark RDD element multiple times using underscore notations.
For example I need to convert RDD[String] to RDD[(String, Int)]. I can create anonymous function using function variables but I would like to do this using Underscore notation. How I can achieve this.

PFB sample code.

```<code>val x = List("apple", "banana")
val rdd1 = sc.parallelize(x)
// Working
val rdd2 = rdd1.map(x => (x, x.length))

// Not working
val rdd3 = rdd1.map((_, _.length))
</code>```

Why does the last line above not work?

答:
An underscore or (more commonly) a placeholder syntax is a marker of a single input parameter. It's nice to use for simple functions, but can get tricky to get right with two or more.

You can find the definitive answer in the Scala language specification's Placeholder Syntax for Anonymous Functions:

An expression (of syntactic category Expr) may contain embedded underscore symbols _ at places where identifiers are legal. Such an expression represents an anonymous function where subsequent occurrences of underscores denote successive parameters.

Note that one underscore references one input parameter, two underscores are for two different input parameters and so on.

With that said, you cannot use the placeholder twice and expect that they'll reference the same input parameter. That's not how it works in Scala and hence the compiler error.

```<code>// Not working
val rdd3 = rdd1.map((_, _.length))
</code>```

The above is equivalent to the following:

```<code>// Not working
val rdd3 = rdd1.map { (a: String, b: String) => (a, b.length)) }
</code>```

which is clearly incorrect as map expects a function of one input parameter.

Body:
How to refer Spark RDD element multiple times using underscore notations.
For example I need to convert RDD[String] to RDD[(String, Int)]. I can create anonymous function using function variables but I would like to do this using Underscore notation. How I can achieve this.

PFB sample code.

val x = List("apple", "banana")
val rdd1 = sc.parallelize(x)
// Working
val rdd2 = rdd1.map(x => (x, x.length))

// Not working
val rdd3 = rdd1.map((_, _.length))

Why does the last line above not work?

Body:
An underscore or (more commonly) a placeholder syntax is a marker of a single input parameter. It's nice to use for simple functions, but can get tricky to get right with two or more.

You can find the definitive answer in the Scala language specification's Placeholder Syntax for Anonymous Functions:

An expression (of syntactic category Expr) may contain embedded underscore symbols _ at places where identifiers are legal. Such an expression represents an anonymous function where subsequent occurrences of underscores denote successive parameters.

Note that one underscore references one input parameter, two underscores are for two different input parameters and so on.

With that said, you cannot use the placeholder twice and expect that they'll reference the same input parameter. That's not how it works in Scala and hence the compiler error.

// Not working
val rdd3 = rdd1.map((_, _.length))

The above is equivalent to the following:

// Not working
val rdd3 = rdd1.map { (a: String, b: String) => (a, b.length)) }

which is clearly incorrect as map expects a function of one input parameter.


问:
Protobuf-net file or assembly not found when referencing assembly over COM interop
I am trying to write a wrapper in C# for the protobuf-net package to enable me to access protocol buffer files directly from VBA in excel.
I have written my code with references to protobuf-net added through the nuget package manager.  I have made my assembly COM visible and from VBA I am able to access my classes.

However when I try to load a protobuffer file, I get the following message:

"Could not load file or assembly 'protobuf-net, Version=2.0.0.668,
  Culture=neutral, PublicKeyToken=257b51d87d2e4d67' or one of its
  dependencies. The system cannot find the file specified.
  (ProtoBufInterface.OutputData)"

I have checked that the protobuf-net.dll file is being copied to the assembly directory.  Any ideas what is causing this or what I can do to fix it?

Many thanks!

答:
I found the problem using .NET Reflector.
I am referencing two other libraries, one is protobuf-net.dll and the other is a third party library which itself references protobuf-net.dll.
The problem was that the version referenced in the third party library (2.0.0.668) was different to the one I had installed (2.3.3).  Actually in hindsight the error message told me everything I needed.
Replacing my protobuf-net.dll reference with teh 2.0.0.668 version fixed my problem.  I did not need to separately register protobuf-net.dll in the GAC.

Thank you all for the help along the way.  Very much appreciated.


问:
Listing all the files inside a folder in Javascript FileReader API
I have an interesting problem I thought I could solve easily but it turned out to be a massive work. Basically I need to enumerate all the files inside a given folder, even files inside subfolders of course.

I wrote a recursive function using readEntries() just to find out that the function doesn't necessarily return all the entries, it has to be called again until the returned array is empty (I guess they made it like this for performance reasons)

So here my recursive function:

```<code>var listOfFiles = [];

function readcontents(folder) {
    function readsome(reader) {
        reader.readEntries(function(entries) {
            for (var entry of entries) {
                if (entry.isDirectory) {
                    readsome(entry.createReader())
                } else {
                    listOfFiles.push(entry);
                }
            }
            if (entries.length) {
                readsome(reader)
            }
        })
    }
    readsome(folder.createReader())
}

readcontents(folder);
// here I should wait and then use the listOfFiles array
</code>```

Now, readEntries() is asynchronous so how can I detect when the tree parsing is done? I need to wait for all the asynchronous calls to end and only then proceed with using the listOfFiles

EDIT

So far I received comments about using promises which sounds "promising".. so here my first guess on how to use it, feel free to comment

```<code>   var listOfFiles = [];

    function readcontents(folder) {
      function readsome(reader) {
        reader.readEntries(function(entries) {
          for(var entry of entries) {
            if(entry.isDirectory) {
              readsome(entry.createReader())
            } else {
                listOfFiles.push(entry);
                defer.resolve();
            }
          }
          if(entries.length) {
            readsome(reader)
          }
        })
      }
      readsome(folder.createReader())

      return defer.promise;
    }

    defer = $q.defer(); // <- global object
    readcontents(item).then(function(){
       // use the array
    }
</code>```

Is that correct so far?

答:
If your's problem is how to behave with the asynchronous callback, that's the solution:
Promise

Basically you need to put in the function.then(callbackfunction); all the work need to be done after the returned value.
If you want to do your work after the line

```<code>readcontents(folder);

// here I should wait and then use the listOfFiles array
</code>```

you can return a promise from this function then again apply a asynchronous callback logic.

Body:
I have an interesting problem I thought I could solve easily but it turned out to be a massive work. Basically I need to enumerate all the files inside a given folder, even files inside subfolders of course.

I wrote a recursive function using readEntries() just to find out that the function doesn't necessarily return all the entries, it has to be called again until the returned array is empty (I guess they made it like this for performance reasons)

So here my recursive function:

var listOfFiles = [];

function readcontents(folder) {
    function readsome(reader) {
        reader.readEntries(function(entries) {
            for (var entry of entries) {
                if (entry.isDirectory) {
                    readsome(entry.createReader())
                } else {
                    listOfFiles.push(entry);
                }
            }
            if (entries.length) {
                readsome(reader)
            }
        })
    }
    readsome(folder.createReader())
}

readcontents(folder);
// here I should wait and then use the listOfFiles array

Now, readEntries() is asynchronous so how can I detect when the tree parsing is done? I need to wait for all the asynchronous calls to end and only then proceed with using the listOfFiles

EDIT

So far I received comments about using promises which sounds "promising".. so here my first guess on how to use it, feel free to comment

   var listOfFiles = [];

    function readcontents(folder) {
      function readsome(reader) {
        reader.readEntries(function(entries) {
          for(var entry of entries) {
            if(entry.isDirectory) {
              readsome(entry.createReader())
            } else {
                listOfFiles.push(entry);
                defer.resolve();
            }
          }
          if(entries.length) {
            readsome(reader)
          }
        })
      }
      readsome(folder.createReader())

      return defer.promise;
    }

    defer = $q.defer(); // <- global object
    readcontents(item).then(function(){
       // use the array
    }

Is that correct so far?

Body:
If your's problem is how to behave with the asynchronous callback, that's the solution:
Promise

Basically you need to put in the function.then(callbackfunction); all the work need to be done after the returned value.
If you want to do your work after the line

readcontents(folder);

// here I should wait and then use the listOfFiles array

you can return a promise from this function then again apply a asynchronous callback logic.


问:
Throw an exception without reference its host assembly?
I have an assembly that is a plugin to a system A (it implements IASystemPlugin interface). The system A is a component of a system B. I want to throw an exception from the plugin to the System B level. Unfortunately, both systems A and B handle all known exceptions and re-throw all unknown ones, so I have to throw B.SystemBException instance.

As a system A client, I had no references to B classes and it's better if I will not (all references, except system ones, should be registered on the level A, it means 30+ B assemblies to be registered). In this case, am I able to instantiate the looking-very-simple B.SystemBException class?

Any hacking methods will be appreciated.

Regards,

答:
I am guessing you might be able find the class through Reflection and create an instance of it. But, Are you sure you want to do this? I am assuming that the system interfaces were built to accomodate such content?

In any event, I assume you have access to that class since you are getting loaded by the other assembly. See this for starting it out: http://www.codeproject.com/KB/dotnet/Reflection.aspx

Let me know if you need more details.

ContentLicense: CC BY-SA 2.5


问:
How to send data back to C app from Java app launched via Invocation API using JNI?
I have a Java app acting as GUI launched via the Invocation API for C

```<code>MyApp.c -> Main application - compiled to MyApp
MyGUI.java -> Java GUI launched programmatically from the C main application - compiled to MyGUI.class
MyGUI_Print.c -> holds JNI method for testing purpose, called from Java GUI - compiled to libMyGUI_Print.so
</code>```

The main C (MyApp) file looks like.:

```<code> #include <jni.h>
//...
JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
//...
(*env)->CallStaticVoidMethod(env, cls, mid, args);
</code>```

the last line method call makes me able to send data from C to the programmatically launched Java GUI. But how do I send data (boolean or string) back to the actual C app (MyApp) from Java - let's say on a button click in the Java GUI?

It's clear that I can call C methods from within Java via JNI. The Java GUI app (MyGUI) holds for testing purposes:

```<code>private native void print();
static {
   System.loadLibrary("MyGUI_Print");
}
</code>```

But the corresponding C file has to be compiled as so/dll file, so I have of course no connection between this library file (MyGUI_Print) and the actual c program (MyApp) I need the data in. From the MyGUI_Print I'm however able to print like this:

```<code>#include <jni.h>
#include <stdio.h>
#include "MyGUI.h"

JNIEXPORT void JNICALL Java_MyGUI_print (JNIEnv *env, jobject obj)
{
    printf("Hello World!");
    fflush(stdout);
}
</code>```

This output is also reaching the actual C app's console output. But the C app itself has so far no knowledge of the "incoming" data. Any way I can programmatically access this string on the other side (C app)? Or is there any better solution?

Theoretically I could of course do polling - i.e. asking from the C app every few seconds the current state of some variable in the Java environment. But I don't think that's a nice way of doing it.

答:
Actually you do have a connection between your executable and a hypothetical JNI library. They're in the same process so you can always pass some handle from C code to Java code and then from Java code to the C code in your JNI library. And the library can use it to call stuff from you main module.

That said, I would skip the JNI part altogether. You could pass a function address to Java, then use JNA (https://github.com/java-native-access/jna) to call that function. It uses libffi internally.

(If you don't want to pass function pointers around, JNA can also help you get the module handle for wherever your function is and then get the function via its name)

Body:
I have a Java app acting as GUI launched via the Invocation API for C

MyApp.c -> Main application - compiled to MyApp
MyGUI.java -> Java GUI launched programmatically from the C main application - compiled to MyGUI.class
MyGUI_Print.c -> holds JNI method for testing purpose, called from Java GUI - compiled to libMyGUI_Print.so

The main C (MyApp) file looks like.:

 #include <jni.h>
//...
JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
//...
(*env)->CallStaticVoidMethod(env, cls, mid, args);

the last line method call makes me able to send data from C to the programmatically launched Java GUI. But how do I send data (boolean or string) back to the actual C app (MyApp) from Java - let's say on a button click in the Java GUI?

It's clear that I can call C methods from within Java via JNI. The Java GUI app (MyGUI) holds for testing purposes:

private native void print();
static {
   System.loadLibrary("MyGUI_Print");
}

But the corresponding C file has to be compiled as so/dll file, so I have of course no connection between this library file (MyGUI_Print) and the actual c program (MyApp) I need the data in. From the MyGUI_Print I'm however able to print like this:

#include <jni.h>
#include <stdio.h>
#include "MyGUI.h"

JNIEXPORT void JNICALL Java_MyGUI_print (JNIEnv *env, jobject obj)
{
    printf("Hello World!");
    fflush(stdout);
}

This output is also reaching the actual C app's console output. But the C app itself has so far no knowledge of the "incoming" data. Any way I can programmatically access this string on the other side (C app)? Or is there any better solution?

Theoretically I could of course do polling - i.e. asking from the C app every few seconds the current state of some variable in the Java environment. But I don't think that's a nice way of doing it.


问:
rescaling time difference between video frames
I have a video of transport happening. Each frame looks like this:

I have calculated something time-derivative like. if f(i) is the i-th frame, the following image is 2*f(i)-f(i+1)-f(i-1):

The moving particles have a more distinct signature in this time derivative video. The problem is I cannot actually make it a video, since linear combinations of float images (with intensities on [-1,1]) are not necessarily float images (because intensities are not on the range [-1,1]). Therefore I would like to rescale the images to be on [-1,1].

I tried to use sklearn's preprocessing module:

```<code>from sklearn import preprocessing

images = [image1, image2, ...]
#each imagek is a 1D image array

scaler = preprocessing.MinMaxScaler([-1,1])
scaler.fit(images)

rescaled_images = scaler.transform(images)
</code>```

This method amplifies noise and removes the contrast.

Any recommendation as to how I can rescale these time derivative images to [-1,1] without losing information? Any help is appreciated !

(I asked yesterday, but deleted the question because I didn't have the time to properly indicate the problem with graphics)

答:
As mentioned in my comment the reason that it's not working is because MinMaxScaler is for feature scaling, but you want to scale you entire image. Assuming your image are numpy arrays, your easiest way would be as follows:

```<code># create a 128x128 image to work with
image = np.random.random((128, 128),)
# scale to [0, 1]
newimage = (image - image.min()) / (image.max() - image.min())
# Now scale to [-1, 1]
newimage = newimage*2-1
print(newimage.min(), newimage.max())
</code>```

Output: -1.0, 1.0

Body:
I have a video of transport happening. Each frame looks like this:

I have calculated something time-derivative like. if f(i) is the i-th frame, the following image is 2*f(i)-f(i+1)-f(i-1):

The moving particles have a more distinct signature in this time derivative video. The problem is I cannot actually make it a video, since linear combinations of float images (with intensities on [-1,1]) are not necessarily float images (because intensities are not on the range [-1,1]). Therefore I would like to rescale the images to be on [-1,1].

I tried to use sklearn's preprocessing module:

from sklearn import preprocessing

images = [image1, image2, ...]
#each imagek is a 1D image array

scaler = preprocessing.MinMaxScaler([-1,1])
scaler.fit(images)

rescaled_images = scaler.transform(images)

This method amplifies noise and removes the contrast.

Any recommendation as to how I can rescale these time derivative images to [-1,1] without losing information? Any help is appreciated !

(I asked yesterday, but deleted the question because I didn't have the time to properly indicate the problem with graphics)

Body:
As mentioned in my comment the reason that it's not working is because MinMaxScaler is for feature scaling, but you want to scale you entire image. Assuming your image are numpy arrays, your easiest way would be as follows:

# create a 128x128 image to work with
image = np.random.random((128, 128),)
# scale to [0, 1]
newimage = (image - image.min()) / (image.max() - image.min())
# Now scale to [-1, 1]
newimage = newimage*2-1
print(newimage.min(), newimage.max())

Output: -1.0, 1.0


问:
Android install apk programmatically
Is it possible to install an apk programmatically in the background or does the user have to accept the installation.

My scenario is that I want my employees to all have the same set of applications installed.

Of course they can install applications by them self, but I want them all to have at least some applications installed.

I'm not talking about installing applications from the market.

答:
Let me get this straight, you want to remotely put an app on a large number of phones and have it install itself?  I don't think that's possible.  If it were, think of the virus possibilities!

I think you can email the APK to the phones and have the user use something like Apps-Installer to install it, but I've heard of problems with that method.  For your situation though, I would recommend trying it.

The only other alternative I can see beside putting them in the market would be to manually collect all the phones you want it on and manually put it on each one with the ADB, but that would be a huge pain.

Title: Android install apk programmatically


问:
jquery only firing on second click
i have a dropdown box that when i click it the arrow rotates.how ever the arrow only rotates on the second click.what am i doing wrong?

```<code><div class="dropdown">
 <a onclick="UserdropDownDetails()"><div class="triangle1"></div></a>
  <div id="myDropdown" class="dropdown-content ">
    <ul>
     // drop down elements
    </ul>
  </div>
</div>
</code>```

css

```<code>.triangle1 {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;
}

.triangle-up {
    transform: rotate(180deg);
}
</code>```

code:

```<code>function flipTriangle() {
                $('.triangle1').on('click', function () {
                    $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
                });
            }

function UserdropDownDetails() {
            flipTriangle(); i need this to fire the first time its clicked
            document.getElementById("myDropdown").classList.toggle("show"); //this shows my drop down,which works fine.

        }
</code>```

what am i doing wrong?

答:
As far as i understand this, UserdropDownDetails() function won't fire the $(this).toggleClass("triangle-up");  as it is placed in an onclick event.The functions should be something like</p>

```<code>function flipTriangle(){

                $(".triangle1").toggleClass("triangle-up");

}
$('.triangle1').on('click',flipTriangle);
function UserdropDownDetails() {
        flipTriangle();
        document.getElementById("myDropdown").classList.toggle("show");
    }
</code>```

Title: jquery only firing on second click

Body:
i have a dropdown box that when i click it the arrow rotates.how ever the arrow only rotates on the second click.what am i doing wrong?

     // drop down elements

css

.triangle1 {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;
}

.triangle-up {
    transform: rotate(180deg);
}

code:

function flipTriangle() {
                $('.triangle1').on('click', function () {
                    $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
                });
            }

function UserdropDownDetails() {
            flipTriangle(); i need this to fire the first time its clicked
            document.getElementById("myDropdown").classList.toggle("show"); //this shows my drop down,which works fine.

        }

what am i doing wrong?

Body:
As far as i understand this, UserdropDownDetails() function won't fire the $(this).toggleClass("triangle-up");  as it is placed in an onclick event.The functions should be something like

function flipTriangle(){

                $(".triangle1").toggleClass("triangle-up");

}
$('.triangle1').on('click',flipTriangle);
function UserdropDownDetails() {
        flipTriangle();
        document.getElementById("myDropdown").classList.toggle("show");
    }


问:
Xamarin Forms: ScrollView with KeyBoard
I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a grid that has a scrollview that has a stacklayout that contains some image and Entry inputs and some Buttons. When I touch the Entry to enter text, the keyboard covers the Buttons so I can't press the button. This isn't scrollable and I don't know why. Anybody can help me?

Here is my XAML code:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<Grid>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                    <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</Grid>
</code>```

Here is the solution

答:
The Solution is Here

It wasn't scrollable because in the stacklayout doesn't have enough content.
I able to do this. This is not a very nice solution but works.
I put a label width HeighRequest and same color with StackLayout and now the page is scrollable when I type my password.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<ContentPage.Content>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                    <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
                <Label BackgroundColor="#302138" HeightRequest="160"/>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</ContentPage.Content>
</code>```

Title: Xamarin Forms: ScrollView with KeyBoard

Body:
I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a grid that has a scrollview that has a stacklayout that contains some image and Entry inputs and some Buttons. When I touch the Entry to enter text, the keyboard covers the Buttons so I can't press the button. This isn't scrollable and I don't know why. Anybody can help me?

Here is my XAML code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<Grid>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">

                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</Grid>

Here is the solution

Body:
The Solution is Here

It wasn't scrollable because in the stacklayout doesn't have enough content.
I able to do this. This is not a very nice solution but works.
I put a label width HeighRequest and same color with StackLayout and now the page is scrollable when I type my password.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<ContentPage.Content>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                    <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
                <Label BackgroundColor="#302138" HeightRequest="160"/>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</ContentPage.Content>


问:
HTTP get requests in ajax
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

```<code> $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})
</code>```

The response JSON code looks like this:

```<code>{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
</code>```

When im running this I only get the error function. Any suggestions or solution is appreciated :)

答:
You should pass two argument for error:function(jqXHR, exception) as below.

And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.

```<code> $(document).ready(function () {
            $("#LoginUser").click(function () {
            $.ajax({
                url: 'http://website/api/user/Mikkel1337',
                dataType: 'json',
                type: 'GET',
                contentType: 'application/json',
                success: function (data) {
                    var jsonStr = JSON.stringify(data);
                    //also try this way to get JSON data:
                    // var jsonStr =JSON.parse(data);
                    alert(jsonStr['password']);
                },
                error: function (jqXHR, exception) {
                        alert("An error had occurred");
                },
            });
        });
    });
</code>```

Title: HTTP get requests in ajax

Body:
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

 $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})

The response JSON code looks like this:

{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}

When im running this I only get the error function. Any suggestions or solution is appreciated :)

Body:
You should pass two argument for error:function(jqXHR, exception) as below.

And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.

 $(document).ready(function () {
            $("#LoginUser").click(function () {
            $.ajax({
                url: 'http://website/api/user/Mikkel1337',
                dataType: 'json',
                type: 'GET',
                contentType: 'application/json',
                success: function (data) {
                    var jsonStr = JSON.stringify(data);
                    //also try this way to get JSON data:
                    // var jsonStr =JSON.parse(data);
                    alert(jsonStr['password']);
                },
                error: function (jqXHR, exception) {
                        alert("An error had occurred");
                },
            });
        });
    });


问:
CodeIgniter throwing "The URI you submitted has disallowed characters..." and I can't see what's causing it
I'm getting this error from CodeIgniter:

"The URI you submitted has disallowed characters. ..."

On this JSON string:

```<code>{"from":"feedback@myapp.com","to":"support@myapp.com","cc":"myadmin@ myapp.com, myfellowadmin@myapp.com","subject":"FROM APP: User Feedback","message":"FROM USER: testy.testerson@testme.com:\nHere's a test comment"}
</code>```

When I try to encode it using:

```<code>URLreadyJSON = encodeURIComponent(JSON.stringify(JsonObj));
</code>```

(JsonObj being the JSON string mentioned above.)

URLreadyJSON resolves to:

```<code>https://127.0.0.1/Xhr/email/%7B%22from%22%3A%22feedback%40myapp.com%22%2C%22to%22%3A%22support%40myapp.com%22%2C%22cc%22%3A%22myadmin%40myapp.com%2C%20myfellowadmin%40myapp.com%22%2C%22subject%22%3A%22FROM%20APP%3A%20User%20Feedback%22%2C%22message%22%3A%22FROM%20USER%3A%20testy.testerson%40testme.com%3A%5CnHere's%20a%20test%20comment%22%7D
</code>```

The relevant code:

```<code>function sendFeedback() {
    JsonObj = {
        'from': 'feedback@myapp.com',
        'to': 'support@myapp.com',
        'cc': 'myadmin@myapp.com, myfellowadmin@myapp.com',
        'subject': 'FROM APP: User Feedback',
        'message': 'FROM USER: ' + $('#feedback_email').val() + ":\n" + $('#feedback_message').val()
    }

    URLreadyJSON = encodeURIComponent(JSON.stringify(JsonObj));

    $.ajax({
        url: "/Xhr/email/" + URLreadyJSON,
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            $('#feedback_feedback').text(data.message);
            if(!data.error) {
                $("#feedback_popup").popup("open");   // Open confirm popup
                $('#feedback_message').text('');      // Clear original message input
                $('#feedback_email').text('');        // Clear sender email
                setTimeout(function() { $("#feedback_popup").popup("close") }, 2500);
            }
        },
        fail: function(data) {
            console.log("FAIL");
            console.log(data);
        }
    });
}
</code>```

and finally, in my CodeIgniter config file, I have the permitted_uri_chars set to:

```<code>$config['permitted_uri_chars'] = 'a-z 0-9~%.,":_?&=;}{@-';
</code>```

I've gone over all the solutions I could find to this error (and there were a few) and incorporated the suggestions with no success.  I must be missing something and am hoping someone can see what that something is.

答:
Try to change :-

```<code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-\=';
</code>```

TO

```<code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-\=+';
</code>```

Body:
I'm getting this error from CodeIgniter:

"The URI you submitted has disallowed characters. ..."

On this JSON string:

{"from":"feedback@myapp.com","to":"support@myapp.com","cc":"myadmin@ myapp.com, myfellowadmin@myapp.com","subject":"FROM APP: User Feedback","message":"FROM USER: testy.testerson@testme.com:\nHere's a test comment"}

When I try to encode it using:

URLreadyJSON = encodeURIComponent(JSON.stringify(JsonObj));

(JsonObj being the JSON string mentioned above.)

URLreadyJSON resolves to:

https://127.0.0.1/Xhr/email/%7B%22from%22%3A%22feedback%40myapp.com%22%2C%22to%22%3A%22support%40myapp.com%22%2C%22cc%22%3A%22myadmin%40myapp.com%2C%20myfellowadmin%40myapp.com%22%2C%22subject%22%3A%22FROM%20APP%3A%20User%20Feedback%22%2C%22message%22%3A%22FROM%20USER%3A%20testy.testerson%40testme.com%3A%5CnHere's%20a%20test%20comment%22%7D

The relevant code:

function sendFeedback() {
    JsonObj = {
        'from': 'feedback@myapp.com',
        'to': 'support@myapp.com',
        'cc': 'myadmin@myapp.com, myfellowadmin@myapp.com',
        'subject': 'FROM APP: User Feedback',
        'message': 'FROM USER: ' + $('#feedback_email').val() + ":\n" + $('#feedback_message').val()
    }

    URLreadyJSON = encodeURIComponent(JSON.stringify(JsonObj));

    $.ajax({
        url: "/Xhr/email/" + URLreadyJSON,
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            $('#feedback_feedback').text(data.message);
            if(!data.error) {
                $("#feedback_popup").popup("open");   // Open confirm popup
                $('#feedback_message').text('');      // Clear original message input
                $('#feedback_email').text('');        // Clear sender email
                setTimeout(function() { $("#feedback_popup").popup("close") }, 2500);
            }
        },
        fail: function(data) {
            console.log("FAIL");
            console.log(data);
        }
    });
}

and finally, in my CodeIgniter config file, I have the permitted_uri_chars set to:

$config['permitted_uri_chars'] = 'a-z 0-9~%.,":_?&=;}{@-';

I've gone over all the solutions I could find to this error (and there were a few) and incorporated the suggestions with no success.  I must be missing something and am hoping someone can see what that something is.

Body:
Try to change :-

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-\=';

TO

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-\=+';


问:
Sql avg using query
My question today goes like this:

How many customers are above average?
I replied that way but it's wrong

```<code>select avg(height), count(*) as numofppl
from client
group by height
having height > avg(height)
</code>```

Someone can offer a different solution(who work:))

答:
try this query

count(*) count all the customer who height > avg height

```<code>select count(*) as numofppl from client where height > ( select avg(height) from client )
</code>```

Title: Sql avg using query

Body:
My question today goes like this:

How many customers are above average?
I replied that way but it's wrong

select avg(height), count(*) as numofppl
from client
group by height
having height > avg(height)

Someone can offer a different solution(who work:))

Body:
try this query

count(*) count all the customer who height > avg height

select count(*) as numofppl from client where height > ( select avg(height) from client )


问:
PHP CURL sometimes return empty
I want to ask something make me confuse.
I'am using CURL to get html code from this link

```<code>echo set_user_agent_grab("https://www.bandros.co.id/produk/dress-atasan-baju-rajut-wanita-sad-500");
</code>```

And This is my function

```<code>function set_user_agent_grab($link){
    $headers = ["text/html; charset=UTF-8"];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $link);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
    }
</code>```

The problem, sometimes i got return empty, i dont know this is from my server or from the site protection with i dont know, please tell me, thank you.

答:
CURLOPT_VERBOSE should reveal what happened. so just check if curl_exec fail, and if it does, throw a RuntimeException, then, next time it happens, check your php error logs. additionally you can check what curl_errno() and curl_error says.</p>

```<code>function set_user_agent_grab($link) {
    $headers = [
            "text/html; charset=UTF-8"
    ];
    $ch = curl_init ();
    $debugfileh = tmpfile ();
    $debugfile = stream_get_meta_data ( $debugfileh ) ['uri'];
    try {
        curl_setopt ( $ch, CURLOPT_VERBOSE, 1);
        curl_setopt ( $ch, CURLOPT_STDERR, $debugfileh);

        curl_setopt ( $ch, CURLOPT_URL, $link );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $ch, CURLOPT_MAXREDIRS, 10 );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
        curl_setopt ( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_ENCODING, 'gzip' );
        $result = curl_exec ( $ch );
        if (! is_string ( $result )) {
            $errstr = "curl_exec failed: " . curl_errno ( $ch ) . ": " . curl_error ( $ch ) . ". debuginfo: " . file_get_contents ( $debugfile );
            throw new RuntimeException ( $errstr );
        }
        return $result;
    } finally{
        fclose ( $debugfileh );
        curl_close ( $ch );
    }
}
</code>```

Title: PHP CURL sometimes return empty

Body:
I want to ask something make me confuse.
I'am using CURL to get html code from this link

echo set_user_agent_grab("https://www.bandros.co.id/produk/dress-atasan-baju-rajut-wanita-sad-500");

And This is my function

function set_user_agent_grab($link){
    $headers = ["text/html; charset=UTF-8"];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $link);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
    }

The problem, sometimes i got return empty, i dont know this is from my server or from the site protection with i dont know, please tell me, thank you.

Body:
CURLOPT_VERBOSE should reveal what happened. so just check if curl_exec fail, and if it does, throw a RuntimeException, then, next time it happens, check your php error logs. additionally you can check what curl_errno() and curl_error says.

function set_user_agent_grab($link) {
    $headers = [
            "text/html; charset=UTF-8"
    ];
    $ch = curl_init ();
    $debugfileh = tmpfile ();
    $debugfile = stream_get_meta_data ( $debugfileh ) ['uri'];
    try {
        curl_setopt ( $ch, CURLOPT_VERBOSE, 1);
        curl_setopt ( $ch, CURLOPT_STDERR, $debugfileh);

        curl_setopt ( $ch, CURLOPT_URL, $link );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $ch, CURLOPT_MAXREDIRS, 10 );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
        curl_setopt ( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_ENCODING, 'gzip' );
        $result = curl_exec ( $ch );
        if (! is_string ( $result )) {
            $errstr = "curl_exec failed: " . curl_errno ( $ch ) . ": " . curl_error ( $ch ) . ". debuginfo: " . file_get_contents ( $debugfile );
            throw new RuntimeException ( $errstr );
        }
        return $result;
    } finally{
        fclose ( $debugfileh );
        curl_close ( $ch );
    }
}


问:
C++ sort vector using non-static member function
I have a class called Sorter. It has two public items.

int type variable choice

member function called compare with a int type return value that accepts two objects as parameter.

I tried creating an instance of Sorter while passing choice with a value to the constructor,

Then i wanted to use C++ sort function to sort a vector. and to pass the member function compare of the instance i created.

The compare member function uses the variable choice to decide the sorting mechanism.

But i was not able to get the pointer to the member function compare of an instance of Sorter.

Could someone advice me on this?

答:
If you can change the structure of your Sorter class, you could make it a function object by defining operator () like this:

```<code>bool Sorter::operator ()(const MyObject &o1, const MyObject &o2) {
  // return true if o1 < o2
}
</code>```

Then you can just pass an instance of your Sorter class to std::sort.

Body:
If you can change the structure of your Sorter class, you could make it a function object by defining operator () like this:

bool Sorter::operator ()(const MyObject &o1, const MyObject &o2) {
  // return true if o1 < o2
}

Then you can just pass an instance of your Sorter class to std::sort.


问:
changing row backcolor in datagridview
I have Problem with changing rows color in Windows Forms. I did it with Columns and tried the same for Rows but it didn't work. Can someone show me how to do it?

My Code so far:

```<code> public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        abc();
    }

    void abc()
    {
        DataTable hh = new DataTable();
        hh.Columns.Add("1", typeof(string));
        hh.Columns.Add("2", typeof(string));
        hh.Columns.Add("3", typeof(string));

        hh.Rows.Add(new object[] { "a", "b", "c" });
        hh.Rows.Add(new object[] { "a1", "b1", "c1" });
        hh.Rows.Add(new object[] { "a2", "b2", "c2" });

        dataGridView1.DataSource = hh;

        foreach (DataGridViewRow dr in dataGridView1.Rows) // trying to change all rows to orange
            dr.DefaultCellStyle.BackColor = Color.Orange;  // but it doesn't work

        dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Orange; // doesn't work
        dataGridView1.Refresh();
        dataGridView1.Update();

        dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Beige; // this works

    }
}
</code>```

答:
```<code> Private Sub Coloriage()
    Dim fin As Integer = Gridarticles.Rows.Count - 1
    Dim i As Integer
    For i = 0 To fin
        If Gridarticles("stock", i).Value < 0 Then
            Gridarticles.Rows(i).DefaultCellStyle.BackColor = Color.Red
        ElseIf Gridarticles("stock", i).Value = 0 Then
            Gridarticles.Rows(i).DefaultCellStyle.BackColor = Color.Gray
        End If
    Next
End Sub
</code>```

Title: changing row backcolor in datagridview

Body:
I have Problem with changing rows color in Windows Forms. I did it with Columns and tried the same for Rows but it didn't work. Can someone show me how to do it?

My Code so far:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        abc();
    }

    void abc()
    {
        DataTable hh = new DataTable();
        hh.Columns.Add("1", typeof(string));
        hh.Columns.Add("2", typeof(string));
        hh.Columns.Add("3", typeof(string));

        hh.Rows.Add(new object[] { "a", "b", "c" });
        hh.Rows.Add(new object[] { "a1", "b1", "c1" });
        hh.Rows.Add(new object[] { "a2", "b2", "c2" });

        dataGridView1.DataSource = hh;

        foreach (DataGridViewRow dr in dataGridView1.Rows) // trying to change all rows to orange
            dr.DefaultCellStyle.BackColor = Color.Orange;  // but it doesn't work

        dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Orange; // doesn't work
        dataGridView1.Refresh();
        dataGridView1.Update();

        dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Beige; // this works

    }
}


问:
How to add Firepad to a reactjs app
I am trying to add Firepad to a reactjs application. Here is my code

```<code>import React, { Component } from "react";
import firebase from "firebase";
import Firepad from "firepad";
import CodeMirror from 'codemirror';

class CourseNotes extends Component {
  componentDidMount() {
    var firepadRef = firebase.database().ref();
    var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
    var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            defaultText: 'Hello, World!'
          });
  }

  render() {
    return (
      <div>
        <div>testing </div>
        <div id="firepad" />
      </div>
    );
  }
}

export default CourseNotes;
</code>```

I've tried a few things to no success. Other solutions on stack overflow include adding these script tags to the html but that didn't seem to work.

```<code><!-- CodeMirror -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css" />

<!-- Firepad -->
<link rel="stylesheet" href="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.css" />
<script src="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.min.js"></script>
</code>```

Any advice would be much appreciated.

答:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

```<code>import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';
</code>```

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

```<code>new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);
</code>```

Similarly for CodeMirror editor.

Hoping, this would be of some help.

Title: How to add Firepad to a reactjs app

Body:
I am trying to add Firepad to a reactjs application. Here is my code

import React, { Component } from "react";
import firebase from "firebase";
import Firepad from "firepad";
import CodeMirror from 'codemirror';

class CourseNotes extends Component {
  componentDidMount() {
    var firepadRef = firebase.database().ref();
    var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
    var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            defaultText: 'Hello, World!'
          });
  }

  render() {
    return (

testing

    );
  }
}

export default CourseNotes;

I've tried a few things to no success. Other solutions on stack overflow include adding these script tags to the html but that didn't seem to work.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css" />

<link rel="stylesheet" href="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.css" />

Any advice would be much appreciated.

Body:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);

Similarly for CodeMirror editor.

Hoping, this would be of some help.


问:
CUDA functions in DLL, __declspec(dllexport) works but strange results?
I've come across a weird problem with a piece of CUDA code.  It's compiled into a DLL using msvc community 2015 and nvcc in Windows 10.  I'm using CUDA 8.  The application calling the dll is being developed with Qt5.
The application is fairly large and complicated: using Qt, CUDA, VTK, HDF5.  It all seems to work, the app runs and does what it's supposed to, but fails in a reproducible manner that doesn't seem to make any sense.  The example function below seems to reproduce a similar error.

I'm compiling the dll with:

```<code>nvcc -m64 -arch=sm_20 -o  fdm1_cuda.dll -Xcompiler "/LD /D_USRDLL /D_WINDLL" fdm1_cuda.cu
</code>```

This function seems to exhibit the same problem as the main code:

```<code>extern "C" __declspec(dllexport) void fdm1_funnyproblemchecker(){

  cudaError_t errorcode;
  float *a_host;
  float *b_host;
  float *a_device;
  int num, i;

  num=10;

  a_host = (float *)malloc(sizeof(float)*num);
  if( a_host) printf("Result check, allocate host memory a: success\n");
  if(!a_host) printf("Result check, allocate host memory a: failed!\n");
  for(i=0;i<num;i++) a_host[i] = (float)i;
  for(i=0;i<num;i++) printf("%6.3f ", a_host[i]);
  printf("\n");

  b_host = (float *)malloc(sizeof(float)*num);
  if( b_host) printf("Result check, allocate host memory b: success\n");
  if(!b_host) printf("Result check, allocate host memory b: failed!\n");

  errorcode = cudaSuccess;
  cudaMalloc((void **) &a_device, sizeof(float)*num);
  errorcode = cudaGetLastError();
  printf("Result check, allocate device memory: %s\n", cudaGetErrorString(errorcode));

  errorcode = cudaSuccess;
  cudaMemcpy(a_device, a_host, num*sizeof(float), cudaMemcpyHostToDevice);
  errorcode = cudaGetLastError();
  printf("Result check, copy host to device   : %s\n", cudaGetErrorString(errorcode));

  errorcode = cudaSuccess;
  cudaMemcpy(b_host, a_device, num*sizeof(float), cudaMemcpyDeviceToHost);
  errorcode = cudaGetLastError();
  printf("Result check, copy device to host   : %s\n", cudaGetErrorString(errorcode));

  for(i=0;i<num;i++) printf("%6.3f ", b_host[i]);
  printf("\n");

  fflush(stdout);

  cudaFree(a_device);
  free(a_host);
  free(b_host);

}
</code>```

Sometimes the output from this is:

```<code>Result check, allocate host memory a: success
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000
Result check, allocate host memory b: success
Result check, allocate device memory: no error
Result check, copy host to device   : no error
Result check, copy device to host   : no error
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000
</code>```

If I change something which I don't think is related elsewhere in the application (changing the size of a model during runtime), I get this:

```<code>Result check, allocate host memory a: success
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000
Result check, allocate host memory b: success
Result check, allocate device memory: no error
Result check, copy host to device   : an illegal memory access was encountered
Result check, copy device to host   : an illegal memory access was encountered
 0.000  0.000  0.000  0.000  0.000  0.000  0.000 270355481144287188484096.000 74936693461279934656588472647680.000  0.000
</code>```

So, there is a cudaMemcpy failure.
I can't tell if it is a host malloc issue, a cudaMalloc issue, or something related to it running from a dll.
Can anyone see what I'm missing here?

I've had this application running in Linux and Mac, using dynamic libraries, without any major problems.  I'm now trying to get it going under windows.

答:
Problem solved.
It was a kernel elsewher in the code accessing an array[-1] out of bounds.
My error checking with cudaGetLastError was incorrect.  If I do  cudaDeviceSynchronize before each cudaGetLastError it reports errors I was missing.

Thanks.

Body:
I've come across a weird problem with a piece of CUDA code.  It's compiled into a DLL using msvc community 2015 and nvcc in Windows 10.  I'm using CUDA 8.  The application calling the dll is being developed with Qt5.
The application is fairly large and complicated: using Qt, CUDA, VTK, HDF5.  It all seems to work, the app runs and does what it's supposed to, but fails in a reproducible manner that doesn't seem to make any sense.  The example function below seems to reproduce a similar error.

I'm compiling the dll with:

nvcc -m64 -arch=sm_20 -o  fdm1_cuda.dll -Xcompiler "/LD /D_USRDLL /D_WINDLL" fdm1_cuda.cu

This function seems to exhibit the same problem as the main code:

extern "C" __declspec(dllexport) void fdm1_funnyproblemchecker(){

  cudaError_t errorcode;
  float *a_host;
  float *b_host;
  float *a_device;
  int num, i;

  num=10;

  a_host = (float *)malloc(sizeof(float)*num);
  if( a_host) printf("Result check, allocate host memory a: success\n");
  if(!a_host) printf("Result check, allocate host memory a: failed!\n");
  for(i=0;i<num;i++) a_host[i] = (float)i;
  for(i=0;i<num;i++) printf("%6.3f ", a_host[i]);
  printf("\n");

  b_host = (float *)malloc(sizeof(float)*num);
  if( b_host) printf("Result check, allocate host memory b: success\n");
  if(!b_host) printf("Result check, allocate host memory b: failed!\n");

  errorcode = cudaSuccess;
  cudaMalloc((void **) &a_device, sizeof(float)*num);
  errorcode = cudaGetLastError();
  printf("Result check, allocate device memory: %s\n", cudaGetErrorString(errorcode));

  errorcode = cudaSuccess;
  cudaMemcpy(a_device, a_host, num*sizeof(float), cudaMemcpyHostToDevice);
  errorcode = cudaGetLastError();
  printf("Result check, copy host to device   : %s\n", cudaGetErrorString(errorcode));

  errorcode = cudaSuccess;
  cudaMemcpy(b_host, a_device, num*sizeof(float), cudaMemcpyDeviceToHost);
  errorcode = cudaGetLastError();
  printf("Result check, copy device to host   : %s\n", cudaGetErrorString(errorcode));

  for(i=0;i<num;i++) printf("%6.3f ", b_host[i]);
  printf("\n");

  fflush(stdout);

  cudaFree(a_device);
  free(a_host);
  free(b_host);

}

Sometimes the output from this is:

Result check, allocate host memory a: success
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000
Result check, allocate host memory b: success
Result check, allocate device memory: no error
Result check, copy host to device   : no error
Result check, copy device to host   : no error
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000

If I change something which I don't think is related elsewhere in the application (changing the size of a model during runtime), I get this:

Result check, allocate host memory a: success
 0.000  1.000  2.000  3.000  4.000  5.000  6.000  7.000  8.000  9.000
Result check, allocate host memory b: success
Result check, allocate device memory: no error
Result check, copy host to device   : an illegal memory access was encountered
Result check, copy device to host   : an illegal memory access was encountered
 0.000  0.000  0.000  0.000  0.000  0.000  0.000 270355481144287188484096.000 74936693461279934656588472647680.000  0.000

So, there is a cudaMemcpy failure.
I can't tell if it is a host malloc issue, a cudaMalloc issue, or something related to it running from a dll.
Can anyone see what I'm missing here?

I've had this application running in Linux and Mac, using dynamic libraries, without any major problems.  I'm now trying to get it going under windows.


问:
How to render partial index in Rails3
On my dashboard I'm trying to render a partial as a table (index)

My partial: _transaction.html.erb
That partial is actually an index, based on transactions index. It should return all transactions in a table. My partial contains:

```<code>  <% @transactions.each do |transaction| %>
   <tr>
    <td><%= transaction.transaction_type %></td>
    <td><%= transaction.date %></td>
   </tr>
  <% end %>
</code>```

The error I receive:

"You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each"

答:
That would seem to indicate that your TransactionsController#index action is not returning anything for @transactions. The most obvious cause is that whatever logic you are using to find records is broken, returning 0 results, or not setting @transactions correctly.

In views like that, you want to do an error check for the situation where you have no results (or an error of some sort).

Your index.html view:

```<code><% if !@transactions || @transactions.length == 0 %>
    <p>'No transactions found.'</p>
<% else %>
    <table>
        <!-- put your column headers here -->
        <!-- the next line iterates through each transaction and calls a "_transaction" partial to render the content -->
        <%= render @transactions %>
    </table>
<% end %>
</code>```

Your _transaction.html.erb partial:

```<code><tr>
    <td><%= transaction.transaction_type %></td>
    <td><%= transaction.date %></td>
</tr>
</code>```

That will get your view working again. The next step is to figure out why your controller action is not returning results. Start by opening a rails console and trying to retrieve records:

```<code>>> Transaction.all
</code>```

If that returns any results, then you have data. If not, create a record either via a web interface you've developed or via the rails console:

```<code>>> t = Transaction.new()
>> t.transaction_type = 1 #or whatever is appropriate for your application
>> t.date = Date.today
>> t.valid? #if true, your record will save. If not, you need to fix the fields so they validate
>> t.save
</code>```

Once you have a record, test your view again. If it still fails, you probably have an error in your controller logic. As to what that error could be, you'll need to post it for us to help you with that. :)

Title: How to render partial index in Rails3

Body:
On my dashboard I'm trying to render a partial as a table (index)

My partial: _transaction.html.erb
That partial is actually an index, based on transactions index. It should return all transactions in a table. My partial contains:

  <% @transactions.each do |transaction| %>

    <%= transaction.transaction_type %>
    <%= transaction.date %>

  <% end %>

The error I receive:

"You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each"

Body:
That would seem to indicate that your TransactionsController#index action is not returning anything for @transactions. The most obvious cause is that whatever logic you are using to find records is broken, returning 0 results, or not setting @transactions correctly.

In views like that, you want to do an error check for the situation where you have no results (or an error of some sort).

Your index.html view:

<% if !@transactions || @transactions.length == 0 %>
    <p>'No transactions found.'</p>
<% else %>
    <table>
        <!-- put your column headers here -->
        <!-- the next line iterates through each transaction and calls a "_transaction" partial to render the content -->
        <%= render @transactions %>
    </table>
<% end %>

Your _transaction.html.erb partial:

<tr>
    <td><%= transaction.transaction_type %></td>
    <td><%= transaction.date %></td>
</tr>

That will get your view working again. The next step is to figure out why your controller action is not returning results. Start by opening a rails console and trying to retrieve records:

>> Transaction.all

If that returns any results, then you have data. If not, create a record either via a web interface you've developed or via the rails console:

>> t = Transaction.new()
>> t.transaction_type = 1 #or whatever is appropriate for your application
>> t.date = Date.today
>> t.valid? #if true, your record will save. If not, you need to fix the fields so they validate
>> t.save

Once you have a record, test your view again. If it still fails, you probably have an error in your controller logic. As to what that error could be, you'll need to post it for us to help you with that. :)


问:
Failure sending mail: {"The remote name could not be resolved: 'smtp.live.com'"}
I am getting the "The remote name could not be resolved: 'smtp.live.com'" exception continuously from the past 2 hours while trying to send a simple mail.
Here is my code:

```<code>            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("someemail@outlook.com", "Some Name");
            mailMessage.To.Add(new MailAddress("someemail@domain.com"));
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = "<b>This is a check email</b>";
            mailMessage.Subject = "Test subject";

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Port = 587; //also tried 25 and 465
            smtpClient.Host = "smtp.live.com"; //also tried smtp-mail.outlook.com
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false; //also tried removing the credentials and setting this to true
            smtpClient.Credentials = new NetworkCredential("someemail@outlook.com", "its password");

            smtpClient.Send(mailMessage);

            Console.WriteLine("Success");
</code>```

Just out of curiosity, i have tried adding the smtp.gmail.com to the host and entering my gmail credentials as well, but that didn't work either. Here's the trace:

```<code>System.Net.Mail.SmtpException was caught
  Message=Failure sending mail.
  Source=System
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\italha\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 95
  InnerException: System.Net.WebException
       Message=The remote name could not be resolved: 'smtp.live.com'
       Source=System
       StackTrace:
            at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
            at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
            at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
            at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
            at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException:
</code>```

Here is what nslookup shows me for smtp.live.com:

My internet connection uses a proxy address and a port 8080, is that the problem? Please give solution for my specific problem, i have already tried all the general solutions available on internet as of yet.

答:
Looks like there is an issue with your network settings or the firewall is blocking the mailing server. The code seems fine.

Try to ping the hostname with trace and see if that works

Body:
I am getting the "The remote name could not be resolved: 'smtp.live.com'" exception continuously from the past 2 hours while trying to send a simple mail.
Here is my code:

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("someemail@outlook.com", "Some Name");
            mailMessage.To.Add(new MailAddress("someemail@domain.com"));
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = "This is a check email";
            mailMessage.Subject = "Test subject";

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Port = 587; //also tried 25 and 465
            smtpClient.Host = "smtp.live.com"; //also tried smtp-mail.outlook.com
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false; //also tried removing the credentials and setting this to true
            smtpClient.Credentials = new NetworkCredential("someemail@outlook.com", "its password");

            smtpClient.Send(mailMessage);

            Console.WriteLine("Success");

Just out of curiosity, i have tried adding the smtp.gmail.com to the host and entering my gmail credentials as well, but that didn't work either. Here's the trace:

System.Net.Mail.SmtpException was caught
  Message=Failure sending mail.
  Source=System
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\italha\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 95
  InnerException: System.Net.WebException
       Message=The remote name could not be resolved: 'smtp.live.com'
       Source=System
       StackTrace:
            at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
            at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
            at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
            at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
            at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException:

Here is what nslookup shows me for smtp.live.com:

My internet connection uses a proxy address and a port 8080, is that the problem? Please give solution for my specific problem, i have already tried all the general solutions available on internet as of yet.


问:
Office Web Viewer does not work properly in cordova app
I'm building a cordova app with ionic and angular js. I need to integrate the online office viewer provided by Microsoft to view word, excel documents within the app it selt. The api requires you to load the content inside an iframe. When I tried to do this, it gets navigated to a in app browser. I tried implementing tha same using ng-include without any success. Any idea on how to implement this?

I'm using angular 1, Ionic 1, cordova 5.2.

The API I'm referring to view is Office Web Viewer.

Here is the sample code that I tried.

Angular code

```<code>app.config(['$sceDelegateProvider', function ($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://view.officeapps.live.com/op/**'
  ]);
}]);

app.directive('testContent', function () {
  return {
    restrict: 'E', //bind to element tag name
    replace: true, //replace the entire markup with the template
    templateUrl: 'templates/test-content.html',
    controller: ['$scope', function ($scope) {
      $scope.GetUrl = function () { return 'https://view.officeapps.live.com/op/view.aspx?src=https://bonafidedevstorage.blob.core.windows.net/chamika-temp-blobs-1/Documents/ffe7c1fb-35bd-43ad-9e7e-68166697347b.docx'; }
    }]
  };
})
</code>```

Template

```<code><div>
    <p>{{GetUrl()}}</p>
    <ng-include src="GetUrl()" autoscroll></ng-include>
</div>
</code>```

答: Finally managed to resolve this issue with the help of a Colleague, They have given a separate url for these scenarios, Use "https://view.officeapps.live.com/op/embed.aspx".</p>

Body:
I'm building a cordova app with ionic and angular js. I need to integrate the online office viewer provided by Microsoft to view word, excel documents within the app it selt. The api requires you to load the content inside an iframe. When I tried to do this, it gets navigated to a in app browser. I tried implementing tha same using ng-include without any success. Any idea on how to implement this?

I'm using angular 1, Ionic 1, cordova 5.2.

The API I'm referring to view is Office Web Viewer.

Here is the sample code that I tried.

Angular code

app.config(['$sceDelegateProvider', function ($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://view.officeapps.live.com/op/**'
  ]);
}]);

app.directive('testContent', function () {
  return {
    restrict: 'E', //bind to element tag name
    replace: true, //replace the entire markup with the template
    templateUrl: 'templates/test-content.html',
    controller: ['$scope', function ($scope) {
      $scope.GetUrl = function () { return 'https://view.officeapps.live.com/op/view.aspx?src=https://bonafidedevstorage.blob.core.windows.net/chamika-temp-blobs-1/Documents/ffe7c1fb-35bd-43ad-9e7e-68166697347b.docx'; }
    }]
  };
})

Template

{{GetUrl()}}

    <ng-include src="GetUrl()" autoscroll></ng-include>


答:
Seems that you should register the event on document ready like:

```<code>$( document ).ready(function() {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
    });
});
</code>```

Or you can just fire after register it at the fist time, but I'm not sure if it makes sense and:

```<code>function flipTriangle() {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
    });
    $('.triangle1').trigger( "click" );
}
</code>```

It will click twice after the fist time if you don't put a condition to fire only at the first time.

Title: jquery only firing on second click

Body:
i have a dropdown box that when i click it the arrow rotates.how ever the arrow only rotates on the second click.what am i doing wrong?

     // drop down elements

css

.triangle1 {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;
}

.triangle-up {
    transform: rotate(180deg);
}

code:

function flipTriangle() {
                $('.triangle1').on('click', function () {
                    $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
                });
            }

function UserdropDownDetails() {
            flipTriangle(); i need this to fire the first time its clicked
            document.getElementById("myDropdown").classList.toggle("show"); //this shows my drop down,which works fine.

        }

what am i doing wrong?

Body:
Seems that you should register the event on document ready like:

$( document ).ready(function() {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
    });
});

Or you can just fire after register it at the fist time, but I'm not sure if it makes sense and:

function flipTriangle() {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
    });
    $('.triangle1').trigger( "click" );
}

It will click twice after the fist time if you don't put a condition to fire only at the first time.


答:
You group by height. So you get one row for height 100, one for height 200, etc. Now you ask what the avarage per group is, but all records of group height 100 have height = 100, so the avarage is 100 of course. having height > avg(height) is simply having height > height in your query, because of group by height.

What you want to compare with however is not the avarage per height, but the total avarage: no GROUP BY hence:

```<code>select count(*)
from client
where height > (select avg(height) from client);
</code>```

If you want to display the avarage height along, join it:

```<code>select x.avg_height, count(*)
from client c
cross join (select avg(height) as avg_height from client) x
where c.height > x.avg_height;
</code>```

(Depending on the DBMS you may have to use an aggregate function on x.avg_height, e.g. select max(x.avg_height).)

Title: Sql avg using query

Body:
You group by height. So you get one row for height 100, one for height 200, etc. Now you ask what the avarage per group is, but all records of group height 100 have height = 100, so the avarage is 100 of course. having height > avg(height) is simply having height > height in your query, because of group by height.

What you want to compare with however is not the avarage per height, but the total avarage: no GROUP BY hence:

select count(*)
from client
where height > (select avg(height) from client);

If you want to display the avarage height along, join it:

select x.avg_height, count(*)
from client c
cross join (select avg(height) as avg_height from client) x
where c.height > x.avg_height;

(Depending on the DBMS you may have to use an aggregate function on x.avg_height, e.g. select max(x.avg_height).)


问:
Devise action filter for actions that require authentication
I'm using devise for authentication, however I cant see and action filter for specifying actions that require the user to login, is this included in the devise gem? if not how could I create one, I kind of have an idea but since I'm new to rails I'd rather see a solution from a more experienced programmer first.</p>

答:
See the Devise Readme.</p>

```<code>class PostsController < ApplicationController
  respond_to :html

  # Tell Devise that the #destroy action is
  #   special, and that the user must be
  #   authenticated in order to access the
  #   #desroy action.
  # Note that the name of the method here,
  #   #authenticate_user!, depends on the
  #   particular class/table that you have
  #   set up to be managed with Devise.
  before_filter :authenticate_user!,
    :only => [:destroy]

  before_filter :find_post!,
    :only => [:destroy]

  def destroy
    @post.destroy
    respond_with @post
  end

  private

  def find_post!
    @post = Post.find(params[:id])
  end
end
</code>```

Body:
See the Devise Readme.

class PostsController < ApplicationController
  respond_to :html

  # Tell Devise that the #destroy action is
  #   special, and that the user must be
  #   authenticated in order to access the
  #   #desroy action.
  # Note that the name of the method here,
  #   #authenticate_user!, depends on the
  #   particular class/table that you have
  #   set up to be managed with Devise.
  before_filter :authenticate_user!,
    :only => [:destroy]

  before_filter :find_post!,
    :only => [:destroy]

  def destroy
    @post.destroy
    respond_with @post
  end

  private

  def find_post!
    @post = Post.find(params[:id])
  end
end


问:
The Django make ORM query
```<code>class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')
</code>```

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

```<code>users = User.objects.all
</code>```

Does anyone know how to solve this issue? Thx

答:
you can do this by 2 way(have some diffrents):

1.get :

```<code>users = User.objects.get(username = "jack" and email= "jack@gmail.com")
</code>```

note:in this example we have username and password field

2.filter :

```<code>users = User.objects.filter(username = "jack")
</code>```

The differences :

in the filter use:

you can use .exists() or .count() or .first() or .last() (and some other querys)

for exmaple:

```<code>posts_count = Post.objects.filter(owner="jack").count()
</code>```

it will show you the count of post have owner name jack

but in get you can't use .exists() or .count() or .first() or .last() (and some other querys)

Title: The Django make ORM query

Body:
class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

users = User.objects.all

Does anyone know how to solve this issue? Thx

Body:
you can do this by 2 way(have some diffrents):

1.get :

users = User.objects.get(username = "jack" and email= "jack@gmail.com")

note:in this example we have username and password field

2.filter :

users = User.objects.filter(username = "jack")

The differences :

in the filter use:

you can use .exists() or .count() or .first() or .last() (and some other querys)

for exmaple:

posts_count = Post.objects.filter(owner="jack").count()

it will show you the count of post have owner name jack

but in get you can't use .exists() or .count() or .first() or .last() (and some other querys)