问:
How to authorize webapp with ebay?
I am making a django app that can hold info about items i have on ebay.
So, each user would have multiple ebay accounts.
For example:
user1 would have access to ebay1, ebay2, ebay3 account.
How can I get appid, certid, devid and token for each account?
The best would be to click 'add ebay account' and in new window with ebay sign in page and authorize by inserting username/password.

I had a look to:

https://github.com/timotheus/ebaysdk-python

https://developer.ebay.com/devzone/xml/docs/reference/ebay/FetchToken.html

but it is not clear to me.
Can anyone provide me some step-by-step or any guidelines?

Thanks in advance

答:
```<code>InvalidHeader at /ebay_accounts/begin_create Header value 3 must be of type str or bytes, not <class 'int'>
</code>```

you have to append the str to your data you send so str("whatever")

Title: How to authorize webapp with ebay?

Body:
InvalidHeader at /ebay_accounts/begin_create Header value 3 must be of type str or bytes, not <class 'int'>

you have to append the str to your data you send so str("whatever")


来源: stackexchange

问:
Vim ignore case by default, vimrc
I would like to be able to use '/' and 'f' in vim and ignore case by default. I know that this works if I enter the command :set ic, but I don't want to have to enter this command each time I open vim. I tried adding set ic to and :set ic in my ~/.vimrc but this did not work.

Also, I am using cygwin and zsh, if that's relevant.

Any help?

答: Whoops. Turns it's only not working in vimtutor. I guess .vimrc doesn't affect vimtutor?</p>

ContentLicense: CC BY-SA 3.0

Title: Vim ignore case by default, vimrc


问:
Reason module system
https://facebook.github.io/reason/modules.html#modules-basic-modules

```<code>I don’t see any import or require in my file; how does module resolution work?

Reason/OCaml doesn’t require you to write any import; modules being referred to in the file are automatically searched in the project. Specifically, a module Hello asks the compiler to look for the file hello.re or hello.ml (and their corresponding interface file, hello.rei or hello.mli, if available).
A module name is the file name, capitalized. It has to be unique per project; this abstracts away the file system and allows you to move files around without changing code.
</code>```

I tried reason modules system but can't understand how it works.

1) What the differents between open and include?

2) I have file foo.re with defined module Foo. I have file bar.re and want to call function from module Foo.

Should I open or include module Foo at bar.re?  Or just direct access - Foo.someFunction?

3) Module interfaces should be implemented only ay *.rei files? And module interface file should be with same name but with rei ext?

答:
1) open is like import, it adds the exported definitions in the opened module to the local namespace. include adds them to the module as if you copied the definitions from the included module to the includee. ìnclude will therefore also export the definitions (unless there's an interface file/signature that restricts what's exported of course)

2) you should prefer the most local use of a module that is convenient, in order to not unnecessarily pollute the namespace. So typically you'll want to use direct access, and only if a module has been specifically designed to be opened at file level should you do so. There are however forms of open that are more local than file level. You can open a module in just the scope of a function, or even scoped to a single expression in the form of Foo.(someFunction 4 |> otherFunction 2)

3) Toplevel (file) modules must be implemented in the form of an rei file with the same name as the re file. You can however define module types as "interfaces" for submodules.

OCaml's module system is quite extensive and flexible. I recommend reading the module chapter of Real World Ocaml to get a better grasp of it: https://realworldocaml.org/v1/en/html/files-modules-and-programs.html

Title: Reason module system

Body:
https://facebook.github.io/reason/modules.html#modules-basic-modules

I don’t see any import or require in my file; how does module resolution work?

Reason/OCaml doesn’t require you to write any import; modules being referred to in the file are automatically searched in the project. Specifically, a module Hello asks the compiler to look for the file hello.re or hello.ml (and their corresponding interface file, hello.rei or hello.mli, if available).
A module name is the file name, capitalized. It has to be unique per project; this abstracts away the file system and allows you to move files around without changing code.

I tried reason modules system but can't understand how it works.

1) What the differents between open and include?

2) I have file foo.re with defined module Foo. I have file bar.re and want to call function from module Foo.

Should I open or include module Foo at bar.re?  Or just direct access - Foo.someFunction?

3) Module interfaces should be implemented only ay *.rei files? And module interface file should be with same name but with rei ext?


问:
Spring Web Flux cannot resolve path to static content
I am using Spring Boot 2.0.0 M1 with WebFlux to build my sample web application. After succeeding with REST endpoints I've decided to add some views to my application. I've decided to use Thymeleaf 3.x version. I know that Spring serves static content from 4 default location:

/META-INF/resources/

/resources/

/static/

/public/

I've decided to go with second example so my css file is in /resources/static/css/. However after loading my page .css file was not found.
This is a screenshot from my IDE:

I am not providing my own configuration for static directory I just want to use default one. What might be important is the fact that templates are loading just fine from the /resources/templates/ directory.

Css file is loaded like this:

```<code><link data-th-href="@{css/bootstrap.min.css}" rel="stylesheet">
</code>```

App is not using normal Controller class instead I've provided function as a Bean to define my router:

```<code>@Bean
RouterFunction<?> router(final GeneratorHandler generatorHandler) {
    return route(GET("/generate"), handler::render);
}
</code>```

Any ideas what's wrong here?

答:
I've found the right solution. In your RouterFunction you need to use:

```<code>return resources("/**", new ClassPathResource("/static/"))
</code>```

This will set your static directory to:

```<code>:classpath/static
</code>```

Body:
I am using Spring Boot 2.0.0 M1 with WebFlux to build my sample web application. After succeeding with REST endpoints I've decided to add some views to my application. I've decided to use Thymeleaf 3.x version. I know that Spring serves static content from 4 default location:

/META-INF/resources/

/resources/

/static/

/public/

I've decided to go with second example so my css file is in /resources/static/css/. However after loading my page .css file was not found.
This is a screenshot from my IDE:

I am not providing my own configuration for static directory I just want to use default one. What might be important is the fact that templates are loading just fine from the /resources/templates/ directory.

Css file is loaded like this:

<link data-th-href="@{css/bootstrap.min.css}" rel="stylesheet">

App is not using normal Controller class instead I've provided function as a Bean to define my router:

@Bean
RouterFunction<?> router(final GeneratorHandler generatorHandler) {
    return route(GET("/generate"), handler::render);
}

Any ideas what's wrong here?

Body:
I've found the right solution. In your RouterFunction you need to use:

return resources("/**", new ClassPathResource("/static/"))

This will set your static directory to:

:classpath/static


问:
Creating base in mem sql
When I create data base in MEMSQL with the name "evento" for example, it create two others bases automatically, "evento_0" and "evento_1", and if I exclude, the querys in data base "evento" throws error.</p>

答:
What exactly is your question?

When you create a database evento, you will see databases evento_0 etc - they are the partition databases - but users should not see or query those databases, as they exist on the leaves only.

Title: Creating base in mem sql


问:
How to check conditions without multiple if statements?
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

```<code>private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}
</code>```

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

```<code>        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }
</code>```

Is there a way to make this code less DRY? Input is appreciated.

答:
The first part can be condensed as follows:

```<code>canvas.SetBackgroundResource( level == 5? Resource.Drawable.LevelUpOneBackground :
                              level = 10? Resource.Drawable.LevelUpTwoBackground :
                                          Resource.Drawable.LevelUpThreeBackground );
</code>```

Or, better yet, create a dictionary, mapping level numbers to backgrounds, so then you can have this:

```<code>gameAreaCanvas.SetBackgroundResource( resourcesFromLevels[level] );
</code>```

Simplifying the second part is a bit more involved.

In cases like this, one possible solution is inheritance.

You make a new abstract class Level to represent a level of your game, and you create a subclass of that class for each specific level.  So, you would have class Level1: Level, class Level2: Level, and so on.  The base class has a Setup() method which which works by invoking overridables on itself, and each overridable has a default implementation, but descendants of Level can provide their own implementation.

Also, not everything has to be handled by overridables.  The Level class can accept some constructor parameters, like the level name, and then each descendant can supply the right level name to the base class.  So, it would look like this:

```<code>class Level
{
    readonly string levelName;

    Level( String levelName )
    {
        this.levelName = levelName;
    }

    void Setup()
    {
        levelDisplay.Text = levelName;
        SetupTimer();
    }

    virtual void SetupTimer()
    {
         //Default implementation
    }
}

class Level1: Level
{
    Level1() : Level( "LEVEL 1" )
    {
    }

    override void SetupTimer()
    {
        //Level1 implementation
    }
}
</code>```

Body:
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }

Is there a way to make this code less DRY? Input is appreciated.

Body:
The first part can be condensed as follows:

canvas.SetBackgroundResource( level == 5? Resource.Drawable.LevelUpOneBackground :
                              level = 10? Resource.Drawable.LevelUpTwoBackground :
                                          Resource.Drawable.LevelUpThreeBackground );

Or, better yet, create a dictionary, mapping level numbers to backgrounds, so then you can have this:

gameAreaCanvas.SetBackgroundResource( resourcesFromLevels[level] );

Simplifying the second part is a bit more involved.

In cases like this, one possible solution is inheritance.

You make a new abstract class Level to represent a level of your game, and you create a subclass of that class for each specific level.  So, you would have class Level1: Level, class Level2: Level, and so on.  The base class has a Setup() method which which works by invoking overridables on itself, and each overridable has a default implementation, but descendants of Level can provide their own implementation.

Also, not everything has to be handled by overridables.  The Level class can accept some constructor parameters, like the level name, and then each descendant can supply the right level name to the base class.  So, it would look like this:

class Level
{
    readonly string levelName;

    Level( String levelName )
    {
        this.levelName = levelName;
    }

    void Setup()
    {
        levelDisplay.Text = levelName;
        SetupTimer();
    }

    virtual void SetupTimer()
    {
         //Default implementation
    }
}

class Level1: Level
{
    Level1() : Level( "LEVEL 1" )
    {
    }

    override void SetupTimer()
    {
        //Level1 implementation
    }
}


问:
Get package name and version of Parent Application from it's dependency
I am developing an android-library project which is then can be added as a module dependency to android-UI project. May I know, is there a way to get a package name and version of Parent project from the module dependency?</p>

答: Given a Context, call getPackageName() on the Context to find out the package name of the app. Given the Context and the package name, you can call getPackageManager().getPackageInfo() on the Context to get a PackageInfo object for the app, which contains versionCode and versionName.


问:
Use a defined class in main in other files
I declared a class I've written in my main file, because I need it there the most. There you see my defined class Sock sock=new Sock();

```<code>#include "stdafx.h"
#include <iomanip>
#define TEST "test"

using namespace std;
using namespace cv;

 Sock *sock = new Sock();

int main()
{
    Mat image;
    Mat mbuffer;
    VideoCapture capture;

    uint8_t bytes[11];
</code>```

So now I need this class in another function, witch is in another file to keep the main file clean and easy to read. But I cannot set it public and sock isn't recognized. I just can write a function below my declaration of the class. Is there a way to use a declared class in every file?

答:
In the other files, declare sock as follows:

```<code>extern class Sock *sock;
</code>```

Keyword extern tells the compiler that the variable is defined elsewhere.

Body:
I declared a class I've written in my main file, because I need it there the most. There you see my defined class Sock sock=new Sock();

#include "stdafx.h"
#include <iomanip>
#define TEST "test"

using namespace std;
using namespace cv;

 Sock *sock = new Sock();

int main()
{
    Mat image;
    Mat mbuffer;
    VideoCapture capture;

    uint8_t bytes[11];

So now I need this class in another function, witch is in another file to keep the main file clean and easy to read. But I cannot set it public and sock isn't recognized. I just can write a function below my declaration of the class. Is there a way to use a declared class in every file?

Body:
In the other files, declare sock as follows:

extern class Sock *sock;

Keyword extern tells the compiler that the variable is defined elsewhere.


答:
I would make your "levels" more object-oriented:

```<code>public LevelObject
{
    public BackgroundResource BackgroundResource { get; set; }
    public string Text { get; set; }
    public double TimeInterval { get; set; }
    public double ElapsedInterval { get; set; }

    // constructors, methods, etc...
}
</code>```

This way, you can initialize collection of "levels", like a List<LevelObject>, then based on your current level, set whatever properties as necessary:

```<code>int level = // current level
List<LevelObject> levelObjectList =
    new List<LevelObject>
    {
        new LevelObject("LEVEL 1", 2000, Level1),
        new LevelObject("LEVEL 2", 2000, Level2),
        // etc...
    }
LevelObject levelObject = levelObjectList[level];
</code>```

Examples:

```<code>private void SetBackgrounds(LevelObject levelObject)
{
    if (levelObject.BackgroundResource != null)
    {
        gameAreaCanvas.SetBackgroundResource(levelObject.BackgroundResource);
    }
}
</code>```

```<code>levelDisplay.Text = levelObject.Text;
timer = new Timer();
timer.Interval = levelObject.TimeInterval;
timer.Enabled = true;
timer.Elapsed += levelObject.ElapsedInterval;
timer.Start();
</code>```

Title: How to check conditions without multiple if statements?

Body:
I would make your "levels" more object-oriented:

public LevelObject
{
    public BackgroundResource BackgroundResource { get; set; }
    public string Text { get; set; }
    public double TimeInterval { get; set; }
    public double ElapsedInterval { get; set; }

    // constructors, methods, etc...
}

This way, you can initialize collection of "levels", like a List<LevelObject>, then based on your current level, set whatever properties as necessary:

int level = // current level
List<LevelObject> levelObjectList =
    new List<LevelObject>
    {
        new LevelObject("LEVEL 1", 2000, Level1),
        new LevelObject("LEVEL 2", 2000, Level2),
        // etc...
    }
LevelObject levelObject = levelObjectList[level];

Examples:

private void SetBackgrounds(LevelObject levelObject)
{
    if (levelObject.BackgroundResource != null)
    {
        gameAreaCanvas.SetBackgroundResource(levelObject.BackgroundResource);
    }
}

levelDisplay.Text = levelObject.Text;
timer = new Timer();
timer.Interval = levelObject.TimeInterval;
timer.Enabled = true;
timer.Elapsed += levelObject.ElapsedInterval;
timer.Start();


问:
psycopg2 programming error while creating table
In a Python2.7 script, the following gave me an error, I can't figure out why:

```<code>import psycopg2
conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()
curs.execute("CREATE TABLE newtable;")
</code>```

The error looks like:

```<code>Traceback (most recent call last):

  File "<ipython-input-17-f4ba0186c40c>", line 1, in <module>
    curs.execute("CREATE TABLE newtable;")

ProgrammingError: syntax error at or near ";"
LINE 1: CREATE TABLE newtable;
</code>```

Any SELECT statement works perfectly well on the other hand. For example:

```<code>curs.execute("SELECT * FROM table1 LIMIT 0;")
</code>```

works like a charm.

答:
CREATE TABLE newtable; is not the correct syntax to create a new table. You need to define some columns.

```<code>CREATE TABLE newtable (
    foo INTEGER,
    bar TEXT
);
</code>```

See the CREATE TABLE docs for more info.

Body:
In a Python2.7 script, the following gave me an error, I can't figure out why:

import psycopg2
conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()
curs.execute("CREATE TABLE newtable;")

The error looks like:

Traceback (most recent call last):

  File "<ipython-input-17-f4ba0186c40c>", line 1, in <module>
    curs.execute("CREATE TABLE newtable;")

ProgrammingError: syntax error at or near ";"
LINE 1: CREATE TABLE newtable;

Any SELECT statement works perfectly well on the other hand. For example:

curs.execute("SELECT * FROM table1 LIMIT 0;")

works like a charm.

Body:
CREATE TABLE newtable; is not the correct syntax to create a new table. You need to define some columns.

CREATE TABLE newtable (
    foo INTEGER,
    bar TEXT
);

See the CREATE TABLE docs for more info.


问:
Elasticsearch Bool query with Regexp filter
I have been trying to figure out the best way to use actual regex patterns within an Elasticsearch 5.4 query. After searching about the standard analyzer and tokenizing each string field, I started using the not analyzed field placed in my mappings (standard .raw property). I have tried two variants of the same query, neither has been successful.

Query String filter:

```<code>GET /test-*/_search
{
"query": {
  "bool": {
    "must": [
      {
          "query_string":{
            "query": "URL.raw:/^(http|https)\\:\/\/.+(wp-content|wp-admin)/"
          }
      }
    ]
  }
},
"sort": {
  "@timestamp": {
    "order": "desc"
  }
 }
}
</code>```

REGEXP FILTER:

```<code>GET /test-*/_search
{
 "query": {
  "bool": {
    "must": [
      {
        "regexp": {
          "URL.raw":{
            "value": "/^(http|https)\\:\/\/.+(wp-content|wp-admin)/"
          }
        }
      }
    ]
  }
 },
 "sort": {
  "@timestamp": {
    "order": "desc"
  }
 }
}
</code>```

Both seem to yield no results or parse exceptions

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "parse_exception",
        "reason": "parse_exception: Encountered \" \"^\" \"^ \"\" at line 1, column 8.\nWas expecting one of:\n    <BAREOPER> ...\n    \"(\" ...\n    \"*\" ...\n    <QUOTED> ...\n    <TERM> ...\n    <PREFIXTERM> ...\n    <WILDTERM> ...\n    <REGEXPTERM> ...\n    \"[\" ...\n    \"{\" ...\n    <NUMBER> ...\n    "
      },
</code>```

Does lucene require special escaping or blacklisted chars? Any help or pointers would be much appreciated. Thanks!

答:
Lucene regexps are anchored by default and ^ / $ are not special there.

You do not need / regex delimiters and you do not need to escape / due to that.

Use the following pattern:

```<code>"value": "https?://.*wp-(content|admin).*"
</code>```

Note that I modified the groups a bit to make the pattern more linear and efficient.

Details:

https?:// - string starts with https:// or http://

.* - then has any 0+ chars

wp- - a wp- substring

(content|admin) - either content or admin substring

.* - then has any 0+ chars.

Body:
I have been trying to figure out the best way to use actual regex patterns within an Elasticsearch 5.4 query. After searching about the standard analyzer and tokenizing each string field, I started using the not analyzed field placed in my mappings (standard .raw property). I have tried two variants of the same query, neither has been successful.

Query String filter:

GET /test-*/_search
{
"query": {
  "bool": {
    "must": [
      {
          "query_string":{
            "query": "URL.raw:/^(http|https)\\:\/\/.+(wp-content|wp-admin)/"
          }
      }
    ]
  }
},
"sort": {
  "@timestamp": {
    "order": "desc"
  }
 }
}

REGEXP FILTER:

GET /test-*/_search
{
 "query": {
  "bool": {
    "must": [
      {
        "regexp": {
          "URL.raw":{
            "value": "/^(http|https)\\:\/\/.+(wp-content|wp-admin)/"
          }
        }
      }
    ]
  }
 },
 "sort": {
  "@timestamp": {
    "order": "desc"
  }
 }
}

Both seem to yield no results or parse exceptions

{
  "error": {
    "root_cause": [
      {
        "type": "parse_exception",
        "reason": "parse_exception: Encountered \" \"^\" \"^ \"\" at line 1, column 8.\nWas expecting one of:\n    <BAREOPER> ...\n    \"(\" ...\n    \"*\" ...\n    <QUOTED> ...\n    <TERM> ...\n    <PREFIXTERM> ...\n    <WILDTERM> ...\n    <REGEXPTERM> ...\n    \"[\" ...\n    \"{\" ...\n    <NUMBER> ...\n    "
      },

Does lucene require special escaping or blacklisted chars? Any help or pointers would be much appreciated. Thanks!

Body:
Lucene regexps are anchored by default and ^ / $ are not special there.

You do not need / regex delimiters and you do not need to escape / due to that.

Use the following pattern:

"value": "https?://.*wp-(content|admin).*"

Note that I modified the groups a bit to make the pattern more linear and efficient.

Details:

https?:// - string starts with https:// or http://

.* - then has any 0+ chars

wp- - a wp- substring

(content|admin) - either content or admin substring

.* - then has any 0+ chars.


问:
C# Sort by boolean equality to static string, followed by sort on integer number ascending
I have a List<Data> myList where

```<code>public class Data
{
    public string Classifier;
    public int Code;
}
</code>```

and I want to sort it

By whether or not a data's Classifier is equal to some static string, we'll just call it @"Alpha" for now (non-equals first, equals second)

By Code, ascending.

So the input data

```<code>    {
      "Beta", 6
      "Alpha", 4
      "Lambda", 2
      "Beta", 1
      "Alpha", 5
    }
</code>```

would result in

```<code>    {
      "Beta", 1
      "Lambda", 2
      "Beta", 6
      "Alpha", 4
      "Alpha", 5
    }
</code>```

Specifically, I want the alpha's to settle to the bottom of the list in ascending numerical order.

I'm not sure how to implement a .Sort Comparison<Data> instance to support this, and .OrderBy doesn't seem to fit the problem.  Any thoughts?

答:
My preferred solution is Ian Ray's solution of using OrderBy-ThenBy to sort a list out-of-place.

What if you needed to sort it in-place?

Build the solution out of smaller parts, each of which is clearly correct.

```<code>Comparison<int> intComparison =
  (x, y) => x == y ? 0 : (x < y ? -1 : 1);

Comparison<bool> boolComparison =
  intComparison(x ? 1 : 0, y ? 1 : 0);

Comparison<string> alphaComparison =
  (x, y) => boolComparison(x == "Alpha", y == "Alpha");

Comparison<Data> dataComparison =
  (x, y) => {
    int a = alphaComparison(x.Classifier, y.Classifier);
    return (a != 0) ? a : intComparison(x.Code, y.Code);
  };
</code>```

Now you have an implementation of Comparison<Data> you can pass to Sort.

Body:
I have a List<Data> myList where

public class Data
{
    public string Classifier;
    public int Code;
}

and I want to sort it

By whether or not a data's Classifier is equal to some static string, we'll just call it @"Alpha" for now (non-equals first, equals second)

By Code, ascending.

So the input data

    {
      "Beta", 6
      "Alpha", 4
      "Lambda", 2
      "Beta", 1
      "Alpha", 5
    }

would result in

    {
      "Beta", 1
      "Lambda", 2
      "Beta", 6
      "Alpha", 4
      "Alpha", 5
    }

Specifically, I want the alpha's to settle to the bottom of the list in ascending numerical order.

I'm not sure how to implement a .Sort Comparison<Data> instance to support this, and .OrderBy doesn't seem to fit the problem.  Any thoughts?

Body:
My preferred solution is Ian Ray's solution of using OrderBy-ThenBy to sort a list out-of-place.

What if you needed to sort it in-place?

Build the solution out of smaller parts, each of which is clearly correct.

Comparison<int> intComparison =
  (x, y) => x == y ? 0 : (x < y ? -1 : 1);

Comparison<bool> boolComparison =
  intComparison(x ? 1 : 0, y ? 1 : 0);

Comparison<string> alphaComparison =
  (x, y) => boolComparison(x == "Alpha", y == "Alpha");

Comparison<Data> dataComparison =
  (x, y) => {
    int a = alphaComparison(x.Classifier, y.Classifier);
    return (a != 0) ? a : intComparison(x.Code, y.Code);
  };

Now you have an implementation of Comparison<Data> you can pass to Sort.


问:
Convert hours, mins, secs String to hours
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

```<code>1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins
</code>```

whereas my output will be:

```<code>1.505
2.167
0.75
</code>```

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

答:
An alternative way would be to parse it as a Duration, but you will need to change the format a bit first. Something like:

```<code>String adjusted = input.replaceAll("\\s+(hour|hr)[s]\\s+", "H");
//Do the same for minutes and seconds
//So adjusted looks like 1H30M20S
Duration d = Duration.parse("PT" + adjusted);

double result = d.toMillis() / 3_600_000d;
</code>```

Body:
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins

whereas my output will be:

1.505
2.167
0.75

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

Body:
An alternative way would be to parse it as a Duration, but you will need to change the format a bit first. Something like:

String adjusted = input.replaceAll("\\s+(hour|hr)[s]\\s+", "H");
//Do the same for minutes and seconds
//So adjusted looks like 1H30M20S
Duration d = Duration.parse("PT" + adjusted);

double result = d.toMillis() / 3_600_000d;


问:
ReactJS: Uncaught TypeError: this.props.updateCommentText is not a function
I am a newbie and just followed a React tutorial on YouTube but I failed to click save button as well as edit button because of the same error (in the save and edit function) as the question title. I tried to ask the YouTube author, but still no respond. </p>

<p>This is the source code: </p>

```<code>var Comment = React.createClass({
  getInitialState: function(){
    return {editing: false};
  },
  edit: function(){
    this.setState({editing: true});
  },
  remove: function(){
    this.props.deleteFromBoard(this.props.index);
  },
  save: function(){
    this.props.updateCommentText(this.refs.newText.value, this.props.index);
    this.setState({editing: false});
  },

  renderNormal: function(){
    return(
      <div className = "commentContainer">
        <div className = "commentText">{this.props.children}</div>
        <button onClick = {this.edit} className = "btn btn-primary">Edit</button>
        <button onClick = {this.remove} className = "btn btn-danger">Remove</button>
      </div>
    );
  },

  renderForm: function(){
    return(
      <div className = "commentContainer">
        <textarea ref = "newText" defaultValue = {this.props.children}></textarea>
        <button onClick = {this.save} className = "btn btn-success">Save</button>
      </div>
    );
  },

  render: function(){
    if(this.state.editing){
      return this.renderForm();
    }
    else{
      return this.renderNormal();
    }
  }
});

var Board = React.createClass({
  getInitialState: function(){
    return{
      comments: [
        "Hello",
        "Hola"
      ]
    }
  },

  removeComment: function(i){
    var arr = this.state.comments;
    arr.splice(i, 1);
    this.setState({comments: arr});
  },

  updateComment: function(newText, i){
    var arr = this.state.comments;
    arr[i] = newText;
    this.setState({comments: arr});
  },

  eachComment: function(text, i){
            return (
              <Comment key = {i} index = {i} updateCommentText = {this.updateComment} deleteFromBoard = {this.removeComment}>
                {text}
              </Comment>
            );
  },

  render: function(){
    return(
      <div className = "board">
        {
          this.state.comments.map(function(text, i){
            return (
              <Comment key = {i}>{text}</Comment>
            );
          })
        }
      </div>
    );
  }
});

ReactDOM.render(
  <Board />
  ,document.getElementById("target"));
</code>```

答:
You need to call eachComment in your render method loop.

```<code>render: function(){
    return(
      <div className = "board">
        {
          this.state.comments.map( this.eachComment.bind(this) ); //you may or not need the .bind() here
        }
      </div>
    );
  }
</code>```

Body:
I am a newbie and just followed a React tutorial on YouTube but I failed to click save button as well as edit button because of the same error (in the save and edit function) as the question title. I tried to ask the YouTube author, but still no respond.

This is the source code:

var Comment = React.createClass({
  getInitialState: function(){
    return {editing: false};
  },
  edit: function(){
    this.setState({editing: true});
  },
  remove: function(){
    this.props.deleteFromBoard(this.props.index);
  },
  save: function(){
    this.props.updateCommentText(this.refs.newText.value, this.props.index);
    this.setState({editing: false});
  },

  renderNormal: function(){
    return(

{this.props.children}

        <button onClick = {this.edit} className = "btn btn-primary">Edit</button>
        <button onClick = {this.remove} className = "btn btn-danger">Remove</button>

    );
  },

  renderForm: function(){
    return(

        <textarea ref = "newText" defaultValue = {this.props.children}></textarea>
        <button onClick = {this.save} className = "btn btn-success">Save</button>

    );
  },

  render: function(){
    if(this.state.editing){
      return this.renderForm();
    }
    else{
      return this.renderNormal();
    }
  }
});

var Board = React.createClass({
  getInitialState: function(){
    return{
      comments: [
        "Hello",
        "Hola"
      ]
    }
  },

  removeComment: function(i){
    var arr = this.state.comments;
    arr.splice(i, 1);
    this.setState({comments: arr});
  },

  updateComment: function(newText, i){
    var arr = this.state.comments;
    arr[i] = newText;
    this.setState({comments: arr});
  },

  eachComment: function(text, i){
            return (
              <Comment key = {i} index = {i} updateCommentText = {this.updateComment} deleteFromBoard = {this.removeComment}>
                {text}
              </Comment>
            );
  },

  render: function(){
    return(

        {
          this.state.comments.map(function(text, i){
            return (
              <Comment key = {i}>{text}</Comment>
            );
          })
        }

    );
  }
});

ReactDOM.render(
  <Board />
  ,document.getElementById("target"));

Body:
You need to call eachComment in your render method loop.

render: function(){
    return(
      <div className = "board">
        {
          this.state.comments.map( this.eachComment.bind(this) ); //you may or not need the .bind() here
        }
      </div>
    );
  }


问:
How to convert NSObject to NSDictionary or how to access NSObject key Swift3
I`m new on this I hope you can help me.

I recibe a variable in a function, this variable is a key value object and I have the next code to set this var.

```<code>let params = command.arguments[0] as? NSObject
</code>```

If I print this variable the result is:

```<code>Optional(<__NSArrayM 0x17024fea0>(
{
    coordinate = "xxxxxxx,xxxxx";
    identifier = cordstrab;
    latitude = "xxxxxxxx";
    longitude = "xxxxxxx";
    note = Trabajo;
    radius = 5;
    type = onEntry;
}
)
)
</code>```

I want to be able to acces to the data, I'm trying with

```<code>let lat = (params?.value(forKey: "latitude") as! String)
</code>```

I don´t know what is wrong or how can I get the the values of this object.

答:
Your response says it is an array of dictionaries. you need to do

```<code>  params?[0].value(forKey...)
</code>```

But before that you need to cast it as

chnage it to

```<code>  command.arguments[0] as? NSArray
</code>```

As vadian suggests , try not to use NSArray. Use more like a swift array!

Body:
I`m new on this I hope you can help me.

I recibe a variable in a function, this variable is a key value object and I have the next code to set this var.

let params = command.arguments[0] as? NSObject

If I print this variable the result is:

Optional(<__NSArrayM 0x17024fea0>(
{
    coordinate = "xxxxxxx,xxxxx";
    identifier = cordstrab;
    latitude = "xxxxxxxx";
    longitude = "xxxxxxx";
    note = Trabajo;
    radius = 5;
    type = onEntry;
}
)
)

I want to be able to acces to the data, I'm trying with

let lat = (params?.value(forKey: "latitude") as! String)

I don´t know what is wrong or how can I get the the values of this object.

Body:
Your response says it is an array of dictionaries. you need to do

  params?[0].value(forKey...)

But before that you need to cast it as

chnage it to

  command.arguments[0] as? NSArray

As vadian suggests , try not to use NSArray. Use more like a swift array!


问:
How to put the time spent that a person takes on my page? What should go in html? Should it go in component? In angular 2
I try to put the time spent that a person takes on my page through a service, but I have not had success I would appreciate much of your help

What should go in html?

Should it go in component?

This is my code so far

This is service

import {
  Injectable
} from '@angular/core';

@Injectable()
export class TiempoService {

  horas: number = 0;
  minutos: number = 0;
  segundos: number = 0;

  constructor() {}

  tiempoTranscurrido() {
    setInterval(
      () => {
        this.segundos++;
        if (this.segundos == 60) {
          this.minutos++;
          this.segundos = 0;
          if (this.minutos == 60) {
            this.minutos = 0;
            this.horas++;
          }
        }
      }, 1000);
  }
}```
</div>
</div>
</p>

<p>This is component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  Component,
  OnInit,
  Input
} from '@angular/core';

import {
  TiempoService
} from "../../servicios/tiempo.service";

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  private id: number;
  constructor(private tiempoService: TiempoService) {}

  ngOnInit() {

  }

  tiempoTranscurrido() {
    this.tiempoService.tiempoTranscurrido()

  }

}</code>```

This is html

        Tiempo transcurrido

{{horas}}:{{minutos}}:{{segundos}}

```

答:
You can leverage date pipe from angular

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
      <p>Current time is: {{currentTime | date:'mediumTime'}}</p>
      <p>Time spent on the page: {{timeOnThePage | date:'HH:mm:ss'}}</p>
      <p>I need "start" property in the component because of this
         behaviour {{ 00 | date:'h:m:s'}}</p>
      <p> Zero in date pipe becomes 1:00:00</p>
    </div>
  `,
})
export class App implements OnInit{
  start: number = 82800000;
  timeOnThePage: number;
  currentTime: number = 0;
  now: Date;

  ngOnInit() {
    this.now = new Date().getTime();
    Rx.Observable.interval(1000).subscribe(seconds => {
      this.currentTime = this.now + seconds * 1000;
      this.timeOnThePage = this.start + seconds * 1000;
    })
  }
}
</code>```

Please, have a look on the plunker demo

Body:
I try to put the time spent that a person takes on my page through a service, but I have not had success I would appreciate much of your help

What should go in html?

Should it go in component?

This is my code so far

This is service

import {
  Injectable
} from '@angular/core';

@Injectable()
export class TiempoService {

  horas: number = 0;
  minutos: number = 0;
  segundos: number = 0;

  constructor() {}

  tiempoTranscurrido() {
    setInterval(
      () => {
        this.segundos++;
        if (this.segundos == 60) {
          this.minutos++;
          this.segundos = 0;
          if (this.minutos == 60) {
            this.minutos = 0;
            this.horas++;
          }
        }
      }, 1000);
  }
}

This is component

import {
  Component,
  OnInit,
  Input
} from '@angular/core';

import {
  TiempoService
} from "../../servicios/tiempo.service";

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  private id: number;
  constructor(private tiempoService: TiempoService) {}

  ngOnInit() {

  }

  tiempoTranscurrido() {
    this.tiempoService.tiempoTranscurrido()

  }

}

This is html

        Tiempo transcurrido

{{horas}}:{{minutos}}:{{segundos}}

Body:
You can leverage date pipe from angular

@Component({
  selector: 'my-app',
  template: `
    <div>
      <p>Current time is: {{currentTime | date:'mediumTime'}}</p>
      <p>Time spent on the page: {{timeOnThePage | date:'HH:mm:ss'}}</p>
      <p>I need "start" property in the component because of this
         behaviour {{ 00 | date:'h:m:s'}}</p>
      <p> Zero in date pipe becomes 1:00:00</p>
    </div>
  `,
})
export class App implements OnInit{
  start: number = 82800000;
  timeOnThePage: number;
  currentTime: number = 0;
  now: Date;

  ngOnInit() {
    this.now = new Date().getTime();
    Rx.Observable.interval(1000).subscribe(seconds => {
      this.currentTime = this.now + seconds * 1000;
      this.timeOnThePage = this.start + seconds * 1000;
    })
  }
}

Please, have a look on the plunker demo


问:
I can't put String on the first position of a string array
Please I have a proble, this is my code so far

```<code>    System.out.println("Please give alue for the table");
    int value = scanner.nextInt();

    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.nextLine();
    }
}
</code>```

And my output is that

```<code>Please give alue for the table
3
Please insert string for the position:1
Please insert string for the position:2
</code>```

Why i can't insert String to the position 1 and my program goes me in position 2 and after??
Please I need help, I can't unsterstand.
Thanks for your time.

答:
you can use BufferedReader and InputStreamReader :) </p>

```<code>System.out.println("Please give alue for the table");
    BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in));
    int value = Integer.parseInt(scanner.readLine());
    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.readLine();

    }
</code>```

Body:
Please I have a proble, this is my code so far

    System.out.println("Please give alue for the table");
    int value = scanner.nextInt();

    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.nextLine();
    }
}

And my output is that

Please give alue for the table
3
Please insert string for the position:1
Please insert string for the position:2

Why i can't insert String to the position 1 and my program goes me in position 2 and after??
Please I need help, I can't unsterstand.
Thanks for your time.

Body:
you can use BufferedReader and InputStreamReader :)

System.out.println("Please give alue for the table");
    BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in));
    int value = Integer.parseInt(scanner.readLine());
    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.readLine();

    }


问:
make app without of multitasking support
my application should not support multitasking , is there any to force app without multitasking support ? </p>

答: Set the UIApplicationExitsOnSuspend key in your Info.plist file.</p>

ContentLicense: CC BY-SA 2.5


问:
Portable Class Library and code analysis ca055/ca0052
I read the following both articticles about the using of portable class library(PCL) in application design:

http://www.dotnetcurry.com/showarticle.aspx?ID=843
and
http://blogs.msdn.com/b/dsplaisted/archive/2012/08/27/how-to-make-portable-class-libraries-work-for-you.aspx

I created an PCL and a unit test project to test the PCL. I build everything with my visual studio 2012 and it works great, i was also able to start my application using this PCL.

I use a TFS for source controll and nightly tests.
If i try to build the the unit test project or my apllication via TFS i retrieve two errors:

CA0055 : * Could not load file: 'C:...\MyPCL.dll'.
 CA0052 : No targets were selected.

The PCL use .Net Framework 4.5 and .Net for Windows Store apps as targets and all projects which are no PCL are configured to use .Net Framework 4.5. I does not use any other reference as the default ".Net Protable Subset" reference.

If i check the build server there is a compiled and working version of my PCL.
If i disable the code analysis while building there are no errors and all unit test works fine.

But it is no solution for me to disbale the code analysis. So has anybody an idea why it crashed and how to get it working with code analyse?

答: I ran into the same problem after renaming the project. Check the AssemblyInfo.cs file, make sure the assemblyTitle is correct. Better to have it same as the project name, and is not conflicting with any other projects</p>


问:
Featch Installed SQL instance names on multiple servers
I writing this to get the list of installed instance on a remote sql server but it was failing  with below error I am going achieve this as follows

Read the list of servers names from my central db server

create a function that takes servers from step1 retrieved.

Code

```<code># -- Get the patch servers from central server  function
get-patchservers {
    # -- Where is your central patching database located?
    $sql_inst   = Read-Host "SQL instance hosting Patching DB; default: Severname\SQL201201"
    # -- Default patching control server to "ServerName\SQL201201"
    if($sql_inst -eq "") {$sql_inst="Severname\SQL201201"}
    # -- What's the name of your central patching database?
    $sql_db     = Read-Host "Name of Patching DB; default:patchdb"
    # -- Default datatabase for patching db
    if($sql_db -eq "") {$sql_db="patchdb" }
    # -- T-SQL to feacth server name from cerntral db
    $Tsql = "SELECT svr_name  FROM server"
    $ServerList = Invoke-Sqlcmd -Query $Tsql -ServerInstance $sql_inst -Database $sql_db    #return $ServerList

    foreach($Server in $ServerList) {
        ECHO $Server
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Server)
        $regKey= $reg.OpenSubKey("SOFTWARE\\Microsoft\\MicrosoftSQL Server\\Instance Names\\SQL" )
        $instances = $regkey.GetValueNames()
        $instances
    }
}
</code>```

答: I found what is causing here.  It looks problem with header returned by invoke-sqlcmd command </p>

Body:
I writing this to get the list of installed instance on a remote sql server but it was failing  with below error I am going achieve this as follows

Read the list of servers names from my central db server

create a function that takes servers from step1 retrieved.

Code

# -- Get the patch servers from central server  function
get-patchservers {
    # -- Where is your central patching database located?
    $sql_inst   = Read-Host "SQL instance hosting Patching DB; default: Severname\SQL201201"
    # -- Default patching control server to "ServerName\SQL201201"
    if($sql_inst -eq "") {$sql_inst="Severname\SQL201201"}
    # -- What's the name of your central patching database?
    $sql_db     = Read-Host "Name of Patching DB; default:patchdb"
    # -- Default datatabase for patching db
    if($sql_db -eq "") {$sql_db="patchdb" }
    # -- T-SQL to feacth server name from cerntral db
    $Tsql = "SELECT svr_name  FROM server"
    $ServerList = Invoke-Sqlcmd -Query $Tsql -ServerInstance $sql_inst -Database $sql_db    #return $ServerList

    foreach($Server in $ServerList) {
        ECHO $Server
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Server)
        $regKey= $reg.OpenSubKey("SOFTWARE\\Microsoft\\MicrosoftSQL Server\\Instance Names\\SQL" )
        $instances = $regkey.GetValueNames()
        $instances
    }
}


问:
How to convert float to binary without using unsafe code?
Is there a way to convert a floating point number (f32 or f64) to a data type that I can access bitwise, like u32/u64? That is, something corresponding to:

```<code>fn as_bits(i: f64) -> u64 {
    unsafe { mem::transmute(i) }
}
</code>```

but without the unsafe. This code is safe per the rules, even though it may not return the same values on all platforms, specifically for NaNs. The reverse safe interface would also be nice.

答:
Rust 1.20 introduced f64::to_bits and f32::to_bits:

```<code>fn main() {
    println!("{}", (4.2f64).to_bits())
}
</code>```

Before then, you need to use the unsafe function transmute. They produce the same result:

```<code>use std::mem;

fn main() {
    let float = 4.2f64;

    let via_method = float.to_bits();
    let via_transmute: u64 = unsafe { mem::transmute(float) };

    assert_eq!(via_method, via_transmute);
}
</code>```

Body:
Is there a way to convert a floating point number (f32 or f64) to a data type that I can access bitwise, like u32/u64? That is, something corresponding to:

fn as_bits(i: f64) -> u64 {
    unsafe { mem::transmute(i) }
}

but without the unsafe. This code is safe per the rules, even though it may not return the same values on all platforms, specifically for NaNs. The reverse safe interface would also be nice.

Body:
Rust 1.20 introduced f64::to_bits and f32::to_bits:

fn main() {
    println!("{}", (4.2f64).to_bits())
}

Before then, you need to use the unsafe function transmute. They produce the same result:

use std::mem;

fn main() {
    let float = 4.2f64;

    let via_method = float.to_bits();
    let via_transmute: u64 = unsafe { mem::transmute(float) };

    assert_eq!(via_method, via_transmute);
}


问:
lumen customize validation response
I am trying to create a custom response if validation fails in lumen. But getting the default response. Expecting a response something like

```<code>    [
       'code'    => 406,
       'message' => "forbidden",
       'errors'  => {
                      "phone": [
                             "The phone must be 11 digits."
                               ]
                    },
    ]
</code>```

but getting default response like this

```<code>{
  "phone": [
    "The phone must be 11 digits."
  ]
}
</code>```

Here is what I have tried.

```<code>public function validatePhoneNumber(Request $request)
    {
        try {
            $this->validate($request, ['phone' => 'required|digits:11']);
        } catch (ValidationException $e) {
            return response()->json([
                'code'    => 406,
                'message' => "forbidden",
                'errors'  => $e->getMessage(),
            ]);
        }
        return [
            'code'          => 200,
            'message'       => 'Phone number ok',
            'data'          => $request->phone
        ];
    }
</code>```

答:
You can use the function buildFailedValidationResponse in you controller

```<code>protected function buildFailedValidationResponse(Request $request, array $errors) {
    return ["code"=> 406 , "message" => "forbidden" , "errors" =>$errors];
}
</code>```

Title: lumen customize validation response

Body:
I am trying to create a custom response if validation fails in lumen. But getting the default response. Expecting a response something like

    [
       'code'    => 406,
       'message' => "forbidden",
       'errors'  => {
                      "phone": [
                             "The phone must be 11 digits."
                               ]
                    },
    ]

but getting default response like this

{
  "phone": [
    "The phone must be 11 digits."
  ]
}

Here is what I have tried.

public function validatePhoneNumber(Request $request)
    {
        try {
            $this->validate($request, ['phone' => 'required|digits:11']);
        } catch (ValidationException $e) {
            return response()->json([
                'code'    => 406,
                'message' => "forbidden",
                'errors'  => $e->getMessage(),
            ]);
        }
        return [
            'code'          => 200,
            'message'       => 'Phone number ok',
            'data'          => $request->phone
        ];
    }

Body:
You can use the function buildFailedValidationResponse in you controller

protected function buildFailedValidationResponse(Request $request, array $errors) {
    return ["code"=> 406 , "message" => "forbidden" , "errors" =>$errors];
}


问:
Why should preprocessing be done on CPU rather than GPU?
The performance guide advises to do the preprocessing on CPU rather that on GPU. The listed reasons are

This prevent the data from going from CPU to GPU to CPU to GPU back again.

This frees the GPU of these tasks to focus on training.

I am not sure to understand either arguments.

Why would preprocessing send the result back to the CPU, esp. if all nodes are on GPU? Why preprocessing operations and not any other operation on the graph, why are they/should they be special?

Even though I understand the rationale behind putting the CPU to work rather than keeping it idle, compared to the huge convolutions and other gradient backpropagation a training step has to do, I would have assumed that random cropping, flip and other standard preprocessing steps on the input images should be nowhere near in term of computation needs, and should be executed in a fraction of the time. Even if we think of preprocessing as mostly moving things around (crop, flips), I think GPU memory should be faster for that. Yet doing preprocessing on the CPU can yield a 6+-fold increase in throughput according to the same guide.

I am assuming of course that preprocessing does not result in a drastic decrease in size of the data (e.g. supersampling or cropping to a much smaller size), in which case the gain in transfer time to the device is obvious. I suppose these are rather extreme cases and do not constitute the basis for the above recommendation.

Can somebody make sense out of this?

答:
It is based on the same logic on how CPU and GPU works. GPU is good at doing repetitive parallelised tasks very well, whereas CPU is good at other computations, which require more processing capabilities.

For example, consider a program, which accepts inputs of two integers from the user and runs a for-loop for 1 Million times to sum the two numbers.

How we can achieve this with the combination of CPU and GPU processing?

We do the initial data (two user input integers) intercept part from the user on CPU and then send the two numbers to GPU and the for-loop to sum the numbers runs on the GPU because that is the repetitive, parallelizable yet simple computation part, which GPU is better at. [Although this example wasn't really exactly related to tensorflow but this concept is the heart of all CPU and GPU processing. Regarding your query: Processing abilities like random cropping, flip and other standard preprocessing steps on the input images might not be computational intensive but GPU doesn't excel in such kind of interrupt related computation either.]

Another thing we need to keep in mind that the latency between CPU and GPU also plays a key role here. Copying and transferring data to and fro CPU and GPU is expensive if compared to the transfer of data between different cache levels inside CPU.

As Dey, 2014 [1] have mentioned:

When a parallelized program is computed on the GPGPU, first the data
  is copied from the memory to the GPU and after computation the data is
  written back to the memory from the GPU using the PCI-e bus (Refer to
  Fig. 1.8). Thus for every computation, data has to be copied to and
  fro device-host-memory. Although the computation is very fast in
  GPGPU, but because of the gap between the device-host-memory due to
  communication via PCI-e, the bottleneck in the performance is
  generated.

For this reason it is advisable that:

You do the preprocessing on CPU, where the CPU does the initial
  computation, prepares and sends the rest of the repetitive
  parallelised tasks to the GPU for further processing.

I once developed a buffer mechanism to increase the data processing between CPU and GPU, and henceforth reduce the negative effects of latency between CPU and GPU. Have a look at this thesis to gain a better understanding of this issue:

EFFICIENT DATA INPUT/OUTPUT (I/O) FOR FINITE DIFFERENCE TIME DOMAIN (FDTD) COMPUTATION ON GRAPHICS PROCESSING UNIT (GPU)

Now, to answer your question:

Why would preprocessing send the result back to the CPU, esp. if all nodes are on GPU?

As quoted from the performance guide of Tensorflow [2],

When preprocessing occurs on the GPU the flow of data is CPU -> GPU
  (preprocessing) -> CPU -> GPU (training). The data is bounced back and
  forth between the CPU and GPU.

If you remember the dataflow diagram between the CPU-Memory-GPU mentioned above, the reason for doing the preprocessing on CPU improves performance because:

After computation of nodes on GPU, data is sent back on the memory
and CPU fetches that memory for further processing. GPU does not have
enough memory on-board (on GPU itself) to keep all the data on it for computational prupose. So
back-and-forth of data is inevitable. To optimise this data flow, you
do preprocessing on CPU, then the data (for training purposes), which is prepared for parallelizable tasks, is sent to the memory and GPU
fetches that preprocessed data and work on it.

In the performance guide itself it also mentions that by doing this, and having an efficient input pipeline, you won't starve either CPU or GPU or both, which itself proves the aforementioned logic. Again, in the same performance doc, you will also see the mentioning of

If your training loop runs faster when using SSDs vs HDDs for storing
  your input data, you could could be I/O bottlenecked.If this is the
  case, you should pre-process your input data, creating a few large
  TFRecord files.

This again tries to mention the same CPU-Memory-GPU performance bottleneck, which is mentioned above.

Hope this helps and in case you need more clarification (on CPU-GPU performance), do not hesitate to drop a message!

References:

[1] Somdip Dey, EFFICIENT DATA INPUT/OUTPUT (I/O) FOR FINITE DIFFERENCE TIME DOMAIN (FDTD) COMPUTATION ON GRAPHICS PROCESSING UNIT (GPU), 2014

[2] Tensorflow Performance Guide: https://www.tensorflow.org/performance/performance_guide


问:
EvoSuit generate test for specific class with maven
Is it possible to configure in maven plugin,for which classes (like include/exclude by name pattern) JUNIT tests should be generated?

As i don't need tests for every class.

I managed to do it with command line but I need to do it in maven.

答:
It isn't possible to do that, but you can use the -Dcuts and -DcutsFile command line arguments to generate test classes for 1..N classes.

Writing a small class that generates the class names for a given package structure is pretty trivial.  You can then use the results to create a comma-delimited string that can be pasted into the file you associate with the -DcutsFile argument, e.g.:

mvn evosuite:generate evosuite:export -DcutsFile=c:\temp\cutsFile.txt

Where the contents of cutsFile.txt are:

com.foo.A, com.foo.B

Another way to generate the list of testable classes is to run the EvoSuite jar from the command line with the -listClasses and -target parameters and pipe the output to a file (Windows example below):

java -jar c:\evosuite\evosuite-master-1.0.5.jar -listClasses -target target/classes > c:temp\testableClasses.txt

From there you can just pick and choose the classes you'd want to add to the CUTs file or add them to the command line using the -Dcuts command line argument.


问:
Ruby on Rails: Modal Not Popping Up, Stays Embedded
I am attempting to get a basic modal working for my rails project and when I click the link the modal stays embedded, it doesn't pop out. To show what I'm talking about I added a picture. After the "New Post" is clicked, that is what appears.

My question is how do I get it to pop out? Is there something with javascript or bootstrap I am missing?

Picture Link

Below are my files.

routes.rb

```<code>get "new_invitation" => "posts#new_invitation", as: :new_invitation
</code>```

gemfile

```<code>gem 'bootstrap-sass'
gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'jquery-rails'
gem 'sass-rails', '~> 5.0'
</code>```

app/assets/javascripts/application.js

```<code>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets
//= require bootstrap/modal
</code>```

posts_controller.rb

```<code>def new_invitation
    respond_to do |format|
        format.html
        format.js
    end
end
</code>```

app/views/posts/_new_invitation.html.erb

```<code><div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
  <h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
   **here comes whatever you want to show!**
</div>
<div class="modal-footer">
  <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  <button class="btn btn-primary">Save changes</button>
</div>
</code>```

app/views/posts/new_invitation.js.erb

```<code>$("#modal-window").html("<%= escape_javascript(render 'posts/new_invitation') %>");
$('#modal-window').modal('show');
</code>```

app/views/home/home_page/html.erb

```<code> <%= link_to '"New Post"', new_invitation_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}  %>
    <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
</code>```

Looking at other questions I saw that some suggested to add the bootstrap.js file downloaded from here to the assets/javascripts folder. I did this and it did not change anything for me.

Rendered HTML

                <hgroup id="logo" class="row">

                </hgroup>

                                    Home

                                    Feeds »

Posts

Requests

                                    Post Formats »

Standard Post

Image Gallery Post

Video Post

Audio Post

Quote Post

Link Post

                                    Account »

Manage

Sign Out

                        <select class="alt-nav"><option selected="selected" value="">Go to...</option><option value="/">Home</option><option value="">Feeds »</option><option value="/posts-feed">Posts</option><option value="/requests-feed">Requests</option><option value="">Post Formats »</option><option value="single.html">Standard Post</option><option value="single-gallery.html">Image Gallery Post</option><option value="single-video.html">Video Post</option><option value="single-audio.html">Audio Post</option><option value="single-quote.html">Quote Post</option><option value="single-link.html">Link Post</option><option value="">Account »</option><option value="/users/edit">Manage</option><option value="/users/sign_out">Sign Out</option></select>

                            <form action="/" class="searchform" method="get" role="search">
                                Search<input size="27" title="Search" class="s" name="s" type="text">
                                <input class="searchsubmit btn" value="GO" type="submit">
                            </form>

Home Page

    "New Post"

  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

   **here comes whatever you want to show!**

  <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  <button class="btn btn-primary">Save changes</button>

        Distance(miles)
        <form action="/" accept-charset="UTF-8" method="get"><input name="utf8" value="✓" type="hidden">
            <select name="distance" id="distance"><option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option></select>
            <input name="nil" value="Enter" class="btn" data-disable-with="Enter" type="submit">
</form>

            <form style="display:inline-block;" class="button_to" method="get" action="/new_post"><input user_id="1" value="Create Post" type="submit"></form>
            <form style="display:inline-block;" class="button_to" method="get" action="/new-request"><input user_id="1" value="Create Request" type="submit"></form>

        <meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="HgOsQnrX29DHy6/DRu2bsvkX28uAEeGC96MBsN/wsZLb+22A0ooExo4JiTMfE0TJOIPiDWaeX+TIYDcB0h+zDA==">

        <link rel="stylesheet" media="all" href="/assets/ad.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/authentication.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/blue_teal.self-4c3ac755b1249ca5ab1cc1381a9c51cc5e93f972b3b8887a9e9084b48a120622.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/brown.self-b1fe0945887a9ffb4a8e17d6af716f8f5efe35a6dabc9975ce07c501bd7a89be.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/default.self-7035985272857bf2c8d61047b810d2c689e9fcfd3d9477632d7098aae2c516cd.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/green_orange.self-71b8bd155d9854213a540485cc90589d05eca69c963679f5bd5cafa616c55772.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/grey_clean.self-b034cc3d7197f1310351adbde518f7e5c81ca69fc6d85bd4f9acc1e08bdfcf65.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/teal_pink.self-76df5149952b4d4e2bf4a53e3cd3a691b96166d46728f1d861b2ed993d47a5d5.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/company.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/donation.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/flexslider.self-9288181b186ec4642a579dd115dba62d226697fd0ae14cb10bff22bd2d256119.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/foundation.self-9c5de18f7dbca474e85180686bb86da0245aee0477a8d118639e4e354b60f75c.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/home.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/ie.self-8c0d4d38a1533a06b7070edebefbbeb41f34621bc05fbac1c50a73be0ea96152.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/mediaqueries.self-07ca3bbc837ff0e3001058a23313ece36b67f81e2a1099eda77ec92665b920b5.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/post.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/request.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/response.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/style.self-70c8e9e6a72de0172235aaee820b03e41c9c2cdddf627169a378804b143904f4.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/user.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-af04b226fd7202dfc532ce7aedb95a0128277937e90d3b3a3d35e1cce9e16886.css?body=1" data-turbolinks-track="reload">
        <link rel="stylesheet" media="screen" href="/assets/foundation.self-9c5de18f7dbca474e85180686bb86da0245aee0477a8d118639e4e354b60f75c.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/flexslider.self-9288181b186ec4642a579dd115dba62d226697fd0ae14cb10bff22bd2d256119.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/style.self-70c8e9e6a72de0172235aaee820b03e41c9c2cdddf627169a378804b143904f4.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/mediaqueries.self-07ca3bbc837ff0e3001058a23313ece36b67f81e2a1099eda77ec92665b920b5.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/colors/default.self-7035985272857bf2c8d61047b810d2c689e9fcfd3d9477632d7098aae2c516cd.css?body=1">

Project

This is a test footer with a bunch of useless information that will be relevant once something interesting gets added here.

```

答:
It looks to me, based on the docs, that the markup should look like this:

```<code><div class="modal fade" id="modal-window" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
      </div>
      <div class="modal-body">
        **here comes whatever you want to show!**
      </div>
      <div class="modal-footer">
        <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

You might be missing:

```<code>  <div class="modal-dialog" role="document">
    <div class="modal-content">
      ...
    </div>
  </div>
</code>```

I don't know if that'll make the difference, but it might be worth a shot.

Also, it seems like you're supposed to trigger the modal using data attributes or javascript. It looks like you're doing both.

Here's your data attributes:

```<code><%= link_to '"New Post"', new_invitation_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}  %>
</code>```

And here's your javascript:

```<code>$('#modal-window').modal('show')
</code>```

Also, it seems like you're inserting _new_invitation.html.erb into:

```<code><div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
</code>```

Which would give you a redundant
 like this:

```<code><div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
       **here comes whatever you want to show!**
    </div>
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
      <button class="btn btn-primary">Save changes</button>
    </div>
  </div>
</div>
</code>```

So, what about trying something like:

```<code><%= link_to '"New Post"', new_invitation_path,  :remote => true  %>
<div id="modal-container"></div>
</code>```

And:

```<code>$("#modal-container").html("<%= escape_javascript(render 'posts/new_invitation') %>");
</code>```

Finally, you might try initializing the modal without options:

```<code>$('#modal-window').modal()
</code>```

I think options are meant to be a hash-y js object, something more like:

```<code>$('#modal-window').modal({show: 'true'})
</code>```

But, I'm not sure about that, so you might give the option-less thing a try.

I hope maybe something in there is useful.

UPDATE

I added this to one of the pages of my current project:

```<code>%button{data: {target: "#modal-window", toggle: "modal", type: "button"}}

#modal-window.modal.fade{role: 'dialog', 'aria-labelledby': 'myModalLabel', 'aria-hidden': true}
  .modal-dialog{role: 'document'}
    .modal-content
      .modal-header
        %button.close{type: 'button', data: {dismiss: 'modal'}, 'aria-hidden': true} Close
        %h3#myModalLabel Modal header
      .modal-body
        **here comes whatever you want to show!**
      .modal-footer
        %button.btn{data: {dismiss: 'modal'}, 'aria-hidden': true} Close
        %button.btn.btn-primary Save changes
</code>```

(Sorry, I use HAML, not ERB). The resulting HTML looked like this:

```<code><button data-target="#modal-window" data-toggle="modal" data-type="button"></button>

<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="modal-window" role="dialog" style="display: none;">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button aria-hidden="" class="close" data-dismiss="modal" type="button">Close</button>
        <h3 id="myModalLabel">Modal header</h3>
      </div>
      <div class="modal-body">
        **here comes whatever you want to show!**
      </div>
      <div class="modal-footer">
        <button aria-hidden="" class="btn" data-dismiss="modal">Close</button>
        <button class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

And the modal worked just fine. FWIW.

Body:
I am attempting to get a basic modal working for my rails project and when I click the link the modal stays embedded, it doesn't pop out. To show what I'm talking about I added a picture. After the "New Post" is clicked, that is what appears.

My question is how do I get it to pop out? Is there something with javascript or bootstrap I am missing?

Picture Link

Below are my files.

routes.rb

get "new_invitation" => "posts#new_invitation", as: :new_invitation

gemfile

gem 'bootstrap-sass'
gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'jquery-rails'
gem 'sass-rails', '~> 5.0'

app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets
//= require bootstrap/modal

posts_controller.rb

def new_invitation
    respond_to do |format|
        format.html
        format.js
    end
end

app/views/posts/_new_invitation.html.erb

  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

   **here comes whatever you want to show!**

  <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  <button class="btn btn-primary">Save changes</button>

app/views/posts/new_invitation.js.erb

$("#modal-window").html("<%= escape_javascript(render 'posts/new_invitation') %>");
$('#modal-window').modal('show');

app/views/home/home_page/html.erb

 <%= link_to '"New Post"', new_invitation_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}  %>

Looking at other questions I saw that some suggested to add the bootstrap.js file downloaded from here to the assets/javascripts folder. I did this and it did not change anything for me.

Rendered HTML

                <hgroup id="logo" class="row">

                </hgroup>

                                    Home

                                    Feeds »

Posts

Requests

                                    Post Formats »

Standard Post

Image Gallery Post

Video Post

Audio Post

Quote Post

Link Post

                                    Account »

Manage

<a Sign Out

                        <select class="alt-nav"><option selected="selected" value="">Go to...</option><option value="/">Home</option><option value="">Feeds »</option><option value="/posts-feed">Posts</option><option value="/requests-feed">Requests</option><option value="">Post Formats »</option><option value="single.html">Standard Post</option><option value="single-gallery.html">Image Gallery Post</option><option value="single-video.html">Video Post</option><option value="single-audio.html">Audio Post</option><option value="single-quote.html">Quote Post</option><option value="single-link.html">Link Post</option><option value="">Account »</option><option value="/users/edit">Manage</option><option value="/users/sign_out">Sign Out</option></select>

                            <form action="/" class="searchform" method="get" role="search">
                                Search<input size="27" title="Search" class="s" name="s" type="text">
                                <input class="searchsubmit btn" value="GO" type="submit">
                            </form>

Home Page

    "New Post"

  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

   **here comes whatever you want to show!**

  <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  <button class="btn btn-primary">Save changes</button>

        Distance(miles)
        <form action="/" accept-charset="UTF-8" method="get"><input name="utf8" value="✓" type="hidden">
            <select name="distance" id="distance"><option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option></select>
            <input name="nil" value="Enter" class="btn" data-disable-with="Enter" type="submit">
</form>

            <form style="display:inline-block;" class="button_to" method="get" action="/new_post"><input user_id="1" value="Create Post" type="submit"></form>
            <form style="display:inline-block;" class="button_to" method="get" action="/new-request"><input user_id="1" value="Create Request" type="submit"></form>

        <meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="HgOsQnrX29DHy6/DRu2bsvkX28uAEeGC96MBsN/wsZLb+22A0ooExo4JiTMfE0TJOIPiDWaeX+TIYDcB0h+zDA==">

        <link rel="stylesheet" media="all" href="/assets/ad.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/authentication.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/blue_teal.self-4c3ac755b1249ca5ab1cc1381a9c51cc5e93f972b3b8887a9e9084b48a120622.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/brown.self-b1fe0945887a9ffb4a8e17d6af716f8f5efe35a6dabc9975ce07c501bd7a89be.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/default.self-7035985272857bf2c8d61047b810d2c689e9fcfd3d9477632d7098aae2c516cd.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/green_orange.self-71b8bd155d9854213a540485cc90589d05eca69c963679f5bd5cafa616c55772.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/grey_clean.self-b034cc3d7197f1310351adbde518f7e5c81ca69fc6d85bd4f9acc1e08bdfcf65.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/colors/teal_pink.self-76df5149952b4d4e2bf4a53e3cd3a691b96166d46728f1d861b2ed993d47a5d5.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/company.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/donation.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/flexslider.self-9288181b186ec4642a579dd115dba62d226697fd0ae14cb10bff22bd2d256119.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/foundation.self-9c5de18f7dbca474e85180686bb86da0245aee0477a8d118639e4e354b60f75c.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/home.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/ie.self-8c0d4d38a1533a06b7070edebefbbeb41f34621bc05fbac1c50a73be0ea96152.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/mediaqueries.self-07ca3bbc837ff0e3001058a23313ece36b67f81e2a1099eda77ec92665b920b5.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/post.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/request.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/response.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/style.self-70c8e9e6a72de0172235aaee820b03e41c9c2cdddf627169a378804b143904f4.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/user.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-af04b226fd7202dfc532ce7aedb95a0128277937e90d3b3a3d35e1cce9e16886.css?body=1" data-turbolinks-track="reload">
        <link rel="stylesheet" media="screen" href="/assets/foundation.self-9c5de18f7dbca474e85180686bb86da0245aee0477a8d118639e4e354b60f75c.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/flexslider.self-9288181b186ec4642a579dd115dba62d226697fd0ae14cb10bff22bd2d256119.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/style.self-70c8e9e6a72de0172235aaee820b03e41c9c2cdddf627169a378804b143904f4.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/mediaqueries.self-07ca3bbc837ff0e3001058a23313ece36b67f81e2a1099eda77ec92665b920b5.css?body=1">
        <link rel="stylesheet" media="screen" href="/assets/colors/default.self-7035985272857bf2c8d61047b810d2c689e9fcfd3d9477632d7098aae2c516cd.css?body=1">

Project

This is a test footer with a bunch of useless information that will be relevant once something interesting gets added here.

Body:
It looks to me, based on the docs, that the markup should look like this:

<div class="modal fade" id="modal-window" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
      </div>
      <div class="modal-body">
        **here comes whatever you want to show!**
      </div>
      <div class="modal-footer">
        <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

You might be missing:

  <div class="modal-dialog" role="document">
    <div class="modal-content">
      ...
    </div>
  </div>

I don't know if that'll make the difference, but it might be worth a shot.

Also, it seems like you're supposed to trigger the modal using data attributes or javascript. It looks like you're doing both.

Here's your data attributes:

<%= link_to '"New Post"', new_invitation_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window'}  %>

And here's your javascript:

$('#modal-window').modal('show')

Also, it seems like you're inserting _new_invitation.html.erb into:

<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>

Which would give you a redundant <div id="modal-window" ...> like this:

<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
       **here comes whatever you want to show!**
    </div>
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
      <button class="btn btn-primary">Save changes</button>
    </div>
  </div>
</div>

So, what about trying something like:

<%= link_to '"New Post"', new_invitation_path,  :remote => true  %>
<div id="modal-container"></div>

And:

$("#modal-container").html("<%= escape_javascript(render 'posts/new_invitation') %>");

Finally, you might try initializing the modal without options:

$('#modal-window').modal()

I think options are meant to be a hash-y js object, something more like:

$('#modal-window').modal({show: 'true'})

But, I'm not sure about that, so you might give the option-less thing a try.

I hope maybe something in there is useful.

UPDATE

I added this to one of the pages of my current project:

%button{data: {target: "#modal-window", toggle: "modal", type: "button"}}

#modal-window.modal.fade{role: 'dialog', 'aria-labelledby': 'myModalLabel', 'aria-hidden': true}
  .modal-dialog{role: 'document'}
    .modal-content
      .modal-header
        %button.close{type: 'button', data: {dismiss: 'modal'}, 'aria-hidden': true} Close
        %h3#myModalLabel Modal header
      .modal-body
        **here comes whatever you want to show!**
      .modal-footer
        %button.btn{data: {dismiss: 'modal'}, 'aria-hidden': true} Close
        %button.btn.btn-primary Save changes

(Sorry, I use HAML, not ERB). The resulting HTML looked like this:

<button data-target="#modal-window" data-toggle="modal" data-type="button"></button>

<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="modal-window" role="dialog" style="display: none;">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button aria-hidden="" class="close" data-dismiss="modal" type="button">Close</button>
        <h3 id="myModalLabel">Modal header</h3>
      </div>
      <div class="modal-body">
        **here comes whatever you want to show!**
      </div>
      <div class="modal-footer">
        <button aria-hidden="" class="btn" data-dismiss="modal">Close</button>
        <button class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

And the modal worked just fine. FWIW.


问:
Get connection string in .NET Core application
I'm trying to get connection string dynamically from appsettings.json file. I see that I can do that via Configuration property of startup class. I've marked Configuration field as static field and access it across the app.

I'm wondering if there is a better way to get connection string value from .NET Core app.

答:
```<code>private readonly IHostingEnvironment _hostEnvironment;
    public IConfiguration Configuration;
    public IActionResult Index()
    {
        return View();
    }

    public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config)
    {
        _hostEnvironment = hostEnvironment;
        Configuration = config;
    }
</code>```

and in class that you want connection string

```<code> var connectionString = Configuration.GetConnectionString("SQLCashConnection");
</code>```

Body:
private readonly IHostingEnvironment _hostEnvironment;
    public IConfiguration Configuration;
    public IActionResult Index()
    {
        return View();
    }

    public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config)
    {
        _hostEnvironment = hostEnvironment;
        Configuration = config;
    }

and in class that you want connection string

 var connectionString = Configuration.GetConnectionString("SQLCashConnection");


问:
How to select option in select list using jquery
i have a form that has select element

```<code><select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>
</code>```

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

答:
In your click() handler, you could write something like:

```<code>$("#adddisplaypage").val("index");
</code>```

That should select "index", for example.

Body:
i have a form that has select element

<select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

Body:
In your click() handler, you could write something like:

$("#adddisplaypage").val("index");

That should select "index", for example.


问:
How to switch from a ViewController back to the second tab of a TabBarController
My app has a TabBarController in which on the second Tab has a button in which pressed takes the user to a new ViewController. I would like to know if its possible to move from the ViewController presented after the button is clicked back to the second tab of the TabBarController. Right now my app is able to go back to the TabBarController but it just presents the view from the first tab rather than the second. Currently I just have the segues setup from the main.storyboard in order to go back to the TabBarController. </p>

答:
Just set the selected index:</p>

```<code>tabBarController?.selectedIndex = 1
</code>```

Body:
Just set the selected index:

tabBarController?.selectedIndex = 1


问:
Can Qlik Sense be uninstalled silently without the original exe?
I'm installing Qlik Sense 3.2 as a prerequisite to another application. I'm using InstallShield 2016 to perform this task. Since InstallShield handles putting the files for prerequisites in some temp location I can't guarantee the location for the Qlik setup file in the event the user wants to uninstall later.

I know how to silently uninstall if the setup file is available.

Is there a way to silently uninstall Qlik without knowing the original Qlik_Sense_setup.exe file location?

答:
I'm not familiar with Qlik, but if it is installed with its own MSI and you know the ProductCode for it you can uninstall it using msiexec.exe

msiexec /x {ProductCode}

If you don't know the ProductCode you can open the cached MSI for it and find it there.


问:
Trying to import keras but got an error
Trying to import Keras 2.0.4 with Tensorflow 1.0.1 on Windows10 as backend, but I got the following message:

AttributeError: module 'pandas' has no attribute 'computation'

I've recently upgraded my pandas into version 0.20.1, is it the reason why I failed to import keras?

There is a lot more information available on the error message. if you want to know about it, just let me know

答:
It was caused by updating to latest version of pandas (0.20.2). Updating dask package to the latest version (0.14.3) can resolve this issue.</p>

```<code>$ conda update dask
</code>```

Title: Trying to import keras but got an error

Body:
It was caused by updating to latest version of pandas (0.20.2). Updating dask package to the latest version (0.14.3) can resolve this issue.

$ conda update dask


问:
.replaceWith messes up the script
For learning reasons, I build my own link shortener and yeah...
After 5 Seconds this code

```<code><div class="skip-container">
    <p class="five">SKIP IN 5 SECONDS</p>
</div>
</code>```

should be replaced with

```<code><div class="skip-button">
    <a href="PHP CODE" class="js-skip-button">SKIP THIS AD</a>
    <div class="skip-arrow"></div>
</div>
</code>```

to do that I tried

```<code>$( document ).ready(function test() {
    setTimeout(function test() {
        $("p.five").replaceWith('<div class="skip-button">
        <a href="PHP CODE" class="js-skip-button">SKIP THIS AD</a>
        <div class="skip-arrow"></div>  </div> ');
    }, 5000);
});
</code>```

It changed the script, but it looks broken and not like how it should... I read something about it keeps it in DOM and such stuff, but I am new in all that and yeah... https://viid.su/bBwgN is the problem page!

答:
You either need to concatenate the string down, or escape the new lines:</p>

```<code>$(function() {
    setTimeout(function() {
    $("p.five").replaceWith('<div class="skip-button">\
                                 <a href="PHP CODE" class="js-skip-button">SKIP THIS AD</a>\
                                 <div class="skip-arrow"></div>\
                             </div> ');
    }, 5000);
});
</code>```

Title: .replaceWith messes up the script

Body:
For learning reasons, I build my own link shortener and yeah...
After 5 Seconds this code

SKIP IN 5 SECONDS

should be replaced with

    SKIP THIS AD

to do that I tried

$( document ).ready(function test() {
    setTimeout(function test() {
        $("p.five").replaceWith('

        SKIP THIS AD

 ');
    }, 5000);
});

It changed the script, but it looks broken and not like how it should... I read something about it keeps it in DOM and such stuff, but I am new in all that and yeah... https://viid.su/bBwgN is the problem page!

Body:
You either need to concatenate the string down, or escape the new lines:

$(function() {
    setTimeout(function() {
    $("p.five").replaceWith('<div class="skip-button">\
                                 <a href="PHP CODE" class="js-skip-button">SKIP THIS AD</a>\
                                 <div class="skip-arrow"></div>\
                             </div> ');
    }, 5000);
});