问:
Weird Behavior when using between? method for dates
Open up a Rails console and enter this:

```<code>2.weeks.ago.between? 2.weeks.ago, 1.week.ago
</code>```

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

```<code> Date.yesterday.between? Date.yesterday, Date.tomorrow
</code>```

答: I just tried this and got false every time. What is the intent behind this question? I ask b/c I do date comparisons like this at the DB level.</p>

OwnerDisplayName: Jaryl

ContentLicense: CC BY-SA 2.5

Body:
Open up a Rails console and enter this:

2.weeks.ago.between? 2.weeks.ago, 1.week.ago

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

 Date.yesterday.between? Date.yesterday, Date.tomorrow

LastEditorDisplayName: Jaryl

OwnerDisplayName: Bill


来源: stackexchange

问:
Replace nth char with sed
i wanna change or delete every 3rd and 4th chars of a string with sed.

For example the text:

abcdefghijklmnopqrstuvxz

Should be transformed to:

abefijmnqruv

Thanks in advance.

答:
```<code>echo abcdefghijklmnopqrstuvxz | sed 's/\(..\)../\1/g'
</code>```

Title: Replace nth char with sed


问:
Hash value of String that would be stable across iOS releases?
In documentation String.hash for iOS it says:

You should not rely on this property having the same hash value across
  releases of OS X.

(strange why they speak of OS X in iOS documentation)

Well, I need a hasshing function that will not change with iOS releases. It can be simple I do not need anything like SHA. Is there some library for that?

There is another question about this here but the accepted (and only) answer there simply states that we should respect the note in documentation.

答:
Here is a non-crypto hash, for Swift 3:

```<code> func strHash(_ str: String) -> UInt64 {
    var result = UInt64 (5381)
    let buf = [UInt8](str.utf8)
    for b in buf {
        result = 127 * (result & 0x00ffffffffffffff) + UInt64(b)
    }
    return result
 }
</code>```

It was derived somewhat from a C++11 constexpr

```<code>    constexpr uint64_t str2int(char const *input) {
    return *input                      // test for null terminator
    ? (static_cast<uint64_t>(*input) + // add char to end
       127 * ((str2int(input + 1)      // prime 127 shifts left almost 7 bits
               & 0x00ffffffffffffff))) // mask right 56 bits
    : 5381;                            // start with prime number 5381
}
</code>```

Unfortunately, the two don't yield the same hash. To do that you'd need to reverse the iterator order in strHash:

```<code>for b in buf.reversed() {...}
</code>```

But that will run 13x slower, somewhat comparable to the djb2hash String extension that I got from https://useyourloaf.com/blog/swift-hashable/

Here are some benchmarks, for a million iterations:

```<code>hashValue execution time: 0.147760987281799
strHash execution time:   1.45974600315094
strHashReversed time:    18.7755110263824
djb2hash execution time: 16.0091370344162
sdbmhash crashed
</code>```

For C++, the str2Int is roughly as fast as Swift 3's hashValue:

```<code>str2int execution time: 0.136421
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is a non-crypto hash, for Swift 3:

 func strHash(_ str: String) -> UInt64 {
    var result = UInt64 (5381)
    let buf = [UInt8](str.utf8)
    for b in buf {
        result = 127 * (result & 0x00ffffffffffffff) + UInt64(b)
    }
    return result
 }

It was derived somewhat from a C++11 constexpr

    constexpr uint64_t str2int(char const *input) {
    return *input                      // test for null terminator
    ? (static_cast<uint64_t>(*input) + // add char to end
       127 * ((str2int(input + 1)      // prime 127 shifts left almost 7 bits
               & 0x00ffffffffffffff))) // mask right 56 bits
    : 5381;                            // start with prime number 5381
}

Unfortunately, the two don't yield the same hash. To do that you'd need to reverse the iterator order in strHash:

for b in buf.reversed() {...}

But that will run 13x slower, somewhat comparable to the djb2hash String extension that I got from https://useyourloaf.com/blog/swift-hashable/

Here are some benchmarks, for a million iterations:

hashValue execution time: 0.147760987281799
strHash execution time:   1.45974600315094
strHashReversed time:    18.7755110263824
djb2hash execution time: 16.0091370344162
sdbmhash crashed

For C++, the str2Int is roughly as fast as Swift 3's hashValue:

str2int execution time: 0.136421


问:
How to navegation to bottom using srollbar?
Please check jsfiddle.

When opening modal, navigate scrollbar bottom, where you have the word "stop here !!!"

Any idea ?

答:
fixed it
u can use

```<code>href='#elementID'
</code>```

to go or scroll to that

check out https://jsfiddle.net/ZcLSE/1349/

Body:
fixed it
u can use

href='#elementID'

to go or scroll to that

check out https://jsfiddle.net/ZcLSE/1349/


问:
synchronization database RESTful API
My aim is to built a trusted synchronization between both local DB and server DB with NO conflictions or deadlock.

I suppose that a user may request his transaction using DML (insert, update and delete) from his local DB  where there is NO access to the Interent and when he wants he asks for sync and send all the transaction with the data i need to the server via RESTful API.

My problem when tow sync operations has performed in a different time and different user which may cause a conflict (ex. the first user update a row and the second user tries to update the same row but another column while they were both offline before sync operations).

In the local DB i track every transaction on another table for every type of transaction (inserted_table , updated_table and deleted_table) every one of them contain table_id,row_id and time.

My question when i send these information to the server for the first user when he asks for sync and then after while the second user makes sync too how i can know the information for the first sync process for the first user(like time of the transaction in the local for the first user) to make rollback if i need and how to mange the conflict resolution?

答:
The whole synchronization logic is up to you to decide how it should work!

One solution to your problem is to add columns STATUS(varchar) and LASTMODIFICATION(datetime). When syncing the databases, you can choose the most recent by comparing the LASTMODIFICATION field and overwrite the data with the newest update.

Title: synchronization database RESTful API


问:
Vertically and Horizontally center a auto height div inside an auto height div
I'm trying to center text inside of an auto height div. Similar to this example, at the section that says Skate Gallery Here

Here is my HTML and CSS

#home-checker-1 {
  width: 100%;
  height: auto;
  background-color: #9ccd64;
  position: relative;
}

#home-checker-1 img {
  width: 100%;
  height: auto;
}

#home-checker-1 .checker-box-wrapper {
  display: table;
  width: 100%;
  height: 100%;
}
#home-checker-1 .checker-inner {
  display: table-cell;
  vertical-align: middle;
}
#home-checker-1 .checker-text-container {
  width: 360px;
  height: auto;
  color: #fff;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="home-checker-1">
    <div class="row">
        <div class="col-md-6 no-padding">
            <img src="image.jpg">
        </div>
        <div class="col-md-6 no-padding">
            <div class="checker-box-wrapper">
                <div class="checker-inner">
                    <div class="checker-text-container">
                        <h3>Say Something Here</h3>
                        <p>Ius fugit tacimates persecuti ei, in wisi errem comprehensam has. Usu in error pericula delicatissimi,
                            eu cum homero numquam. Nostrud lobortis no mei, no sed vivendo fabellas. Nam te utinam causae, cu pro
                            tempor phaedrum dissentiunt, mei solet possim ei. Rebum evertitur definitiones.</p>
                        Find Job Opportunity
                    </div>
                </div>
            </div>
        </div>
    </div>
</section></code>```

I want the img to take up 50% of the
 horizontally (I'm using bootstrap grid to achieve this .col-md-6). I want it to keep the img aspect ratio. So, the wider the screen the wider and taller the img thus taller the
. This will make the section on the right bigger as well. I can keep the text on the right centered by using margin:0 auto; but I do not know how to keep the text centered vertically. I can't set a defined height for the .checker-text-container because the amount of text within it is dynamic which means the height is dynamic and must be auto.

How can this be done?

答:
Try this.</p>

```<code>#home-checker-1 .checker-text-container {
  width: 360px;
  height: auto;
  color: #fff;
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%,-50%);
}
</code>```

Body:
I'm trying to center text inside of an auto height div. Similar to this example, at the section that says Skate Gallery Here

Here is my HTML and CSS

#home-checker-1 {
  width: 100%;
  height: auto;
  background-color: #9ccd64;
  position: relative;
}

#home-checker-1 img {
  width: 100%;
  height: auto;
}

#home-checker-1 .checker-box-wrapper {
  display: table;
  width: 100%;
  height: 100%;
}
#home-checker-1 .checker-inner {
  display: table-cell;
  vertical-align: middle;
}
#home-checker-1 .checker-text-container {
  width: 360px;
  height: auto;
  color: #fff;
  margin: 0 auto;
}

Say Something Here

Ius fugit tacimates persecuti ei, in wisi errem comprehensam has. Usu in error pericula delicatissimi,
                            eu cum homero numquam. Nostrud lobortis no mei, no sed vivendo fabellas. Nam te utinam causae, cu pro
                            tempor phaedrum dissentiunt, mei solet possim ei. Rebum evertitur definitiones.

                        Find Job Opportunity

I want the img to take up 50% of the
 horizontally (I'm using bootstrap grid to achieve this .col-md-6). I want it to keep the img aspect ratio. So, the wider the screen the wider and taller the img thus taller the
. This will make the section on the right bigger as well. I can keep the text on the right centered by using margin:0 auto; but I do not know how to keep the text centered vertically. I can't set a defined height for the .checker-text-container because the amount of text within it is dynamic which means the height is dynamic and must be auto.

How can this be done?

Body:
Try this.

#home-checker-1 .checker-text-container {
  width: 360px;
  height: auto;
  color: #fff;
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%,-50%);
}


问:
Execute a java class file that uses class from a jar file
I have a java source file named File_2.java that starts with import Jama.*;  and it contains the main method.

The current directory contains java source file File_2.java and the Jama-1.0.3.jar file

I can compile the source File_2.java using

```<code>javac -classpath Jama-1.0.3.jar File_2.java
</code>```

This generates a File_2.class file in the current directory which is not getting executed. I have tried the following

```<code>$ java File_2
Exception in thread "main" java.lang.NoClassDefFoundError: Jama/Matrix
at File_2.main(File_2.java:32)
</code>```

and

```<code>$ java -classpath Jama-1.0.3.jar File_2
Error: Could not find or load main class File_2
</code>```

Thus my question is how do I execute the File_2.class file ? Kindly help.

答:
You have to add your current directory to in order to find your class file.

You must run java -classpath Jama-1.0.3.jar:. File_2.

Body:
I have a java source file named File_2.java that starts with import Jama.*;  and it contains the main method.

The current directory contains java source file File_2.java and the Jama-1.0.3.jar file

I can compile the source File_2.java using

javac -classpath Jama-1.0.3.jar File_2.java

This generates a File_2.class file in the current directory which is not getting executed. I have tried the following

$ java File_2
Exception in thread "main" java.lang.NoClassDefFoundError: Jama/Matrix
at File_2.main(File_2.java:32)

and

$ java -classpath Jama-1.0.3.jar File_2
Error: Could not find or load main class File_2

Thus my question is how do I execute the File_2.class file ? Kindly help.


问:
An active access token must be used to query information about the current user in laravel
I am trying to login with facebook using angularjs with laravel. But I am stuck with this error:

{"error":{"message":"An active access token must be used to query
  information about the current user.","type":"OAuthExce (truncated...)

Here is my Controller:

```<code> public function facebookLogin(Request $request){
        $client = new GuzzleHttp\Client();

        $params = [
            'code' => $request->input('code'),
            'client_id' => $request->input('clientId'),
            'redirect_uri' => $request->input('redirectUri'),
            'client_secret' => Config::get('app.facebook_secret'),
            'grant_type'=>'client_credentials'
        ];

        // Step 1. Exchange authorization code for access token.
        $accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [
            'query' => $params
        ]);

        $accessToken = json_decode($accessTokenResponse->getBody(), true);

        // Step 2. Retrieve profile information about the current user.
        $fields = 'id,email,first_name,last_name,link,name,picture';
        /**** problem counted with this request ************/
        $profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
            'query' => [
                'access_token' => $accessToken['access_token'],
                'fields' => $fields
            ]
        ]);

        $profile = json_decode($profileResponse->getBody(), true);

        $user = User::where('email', '=', $profile['email'])->first();

        if($user) {
            Auth::loginUsingId($user->id);
            $user_info = Auth::user();
            $profile_seen = $user_info->profile_seen;
            User::where('id', '=', $user_info->id)->update(array('profile_seen' => 1));
            return Response::json(['login' => Auth::check(),'profile_seen' => $profile_seen ]);

        }else{

            $user = User::create(array(
                                        'username'   => $profile['name'],
                                        'email'      => $profile['email'],
                                        'first_name' => $profile['first_name'],
                                        'last_name'  => $profile['last_name'],
                                        'facebook_id'=> $profile['id']
                                       ));

            Auth::loginUsingId($user->id,1);
            $user_info = Auth::user();
            $profile_seen = $user_info->profile_seen;
            User::where('id', '=', $user_info->id)->update(array('profile_seen' => 1));
            return Response::json(['login' => Auth::check(),'profile_seen' => $profile_seen ]);
        }

    }
</code>```

答: I have encountered this problem. You need to run the composer update. Then run the command composer dump-autoload. This problem has been fixed in version Socialite v2.0.21.

Body:
I am trying to login with facebook using angularjs with laravel. But I am stuck with this error:

{"error":{"message":"An active access token must be used to query
  information about the current user.","type":"OAuthExce (truncated...)

Here is my Controller:

 public function facebookLogin(Request $request){
        $client = new GuzzleHttp\Client();

        $params = [
            'code' => $request->input('code'),
            'client_id' => $request->input('clientId'),
            'redirect_uri' => $request->input('redirectUri'),
            'client_secret' => Config::get('app.facebook_secret'),
            'grant_type'=>'client_credentials'
        ];

        // Step 1. Exchange authorization code for access token.
        $accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [
            'query' => $params
        ]);

        $accessToken = json_decode($accessTokenResponse->getBody(), true);

        // Step 2. Retrieve profile information about the current user.
        $fields = 'id,email,first_name,last_name,link,name,picture';
        /**** problem counted with this request ************/
        $profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
            'query' => [
                'access_token' => $accessToken['access_token'],
                'fields' => $fields
            ]
        ]);

        $profile = json_decode($profileResponse->getBody(), true);

        $user = User::where('email', '=', $profile['email'])->first();

        if($user) {
            Auth::loginUsingId($user->id);
            $user_info = Auth::user();
            $profile_seen = $user_info->profile_seen;
            User::where('id', '=', $user_info->id)->update(array('profile_seen' => 1));
            return Response::json(['login' => Auth::check(),'profile_seen' => $profile_seen ]);

        }else{

            $user = User::create(array(
                                        'username'   => $profile['name'],
                                        'email'      => $profile['email'],
                                        'first_name' => $profile['first_name'],
                                        'last_name'  => $profile['last_name'],
                                        'facebook_id'=> $profile['id']
                                       ));

            Auth::loginUsingId($user->id,1);
            $user_info = Auth::user();
            $profile_seen = $user_info->profile_seen;
            User::where('id', '=', $user_info->id)->update(array('profile_seen' => 1));
            return Response::json(['login' => Auth::check(),'profile_seen' => $profile_seen ]);
        }

    }


问:
How to save an object in a file using nodejs
My code is this:

```<code>fs.writeFile("file.bin", this, 'binary', function(err){
  if(err) console.log(err);
  else console.log("file saved");
});
</code>```

This is inside a function with a bunch of attributes.
If I do console.log(this), it shows the object but when I save it, the file has only this:

```<code>[object Object]
</code>```

Since I didn't get the answer I wanted, I want to clarify a bit what I want.
I want my object to be stored as an object but not as a json file or txt file. If I have a mp3 stream for example, I want this stream to be stored as a mp3 file not a json file. Someone knows how to do this?

答:
You can't save it as an object to a file, but you can save it as a textual representation of an object. You need to turn the object into a string using JSON.stringify. Like this:

```<code>var myObj = {a:123,b:456};
JSON.stringify(myObj);
</code>```

or in your case:

```<code>JSON.stringify(this);
</code>```

Then when you need to access it, you can turn it back into an object with JSON.parse()

References

JSON.stringify

JSON.parse

Body:
My code is this:

fs.writeFile("file.bin", this, 'binary', function(err){
  if(err) console.log(err);
  else console.log("file saved");
});

This is inside a function with a bunch of attributes.
If I do console.log(this), it shows the object but when I save it, the file has only this:

[object Object]

Since I didn't get the answer I wanted, I want to clarify a bit what I want.
I want my object to be stored as an object but not as a json file or txt file. If I have a mp3 stream for example, I want this stream to be stored as a mp3 file not a json file. Someone knows how to do this?

Body:
You can't save it as an object to a file, but you can save it as a textual representation of an object. You need to turn the object into a string using JSON.stringify. Like this:

var myObj = {a:123,b:456};
JSON.stringify(myObj);

or in your case:

JSON.stringify(this);

Then when you need to access it, you can turn it back into an object with JSON.parse()

References

JSON.stringify

JSON.parse


问:
Tsql:Incorrect syntax near the keyword 'IF'
I get an error message: Incorrect syntax near the keyword 'IF'. I need the CTE in the later IF statement. Can anyone know how to resolve it? Thanks!
The code is below: </p>

```<code>ALTER FUNCTION A
    (
        @CLT_NBR int,
        @YES OR NO varchar(10)

    )
    RETURNS datetime
    AS
    BEGIN
        DECLARE @EFFECT_DT date;

        WITH EFFECT_DT
        AS
        (
            SELECT CLT_NBR,
                EFFECT_DT,
                RN
            FROM S
        )

        IF @YES_OR_NO='YES'
        BEGIN
            SELECT @EFFECT_DT=EFFECT_DT
            FROM EFFECT_DT
            WHERE RN=2
            RETURN (@EFFECT_DT)
        END
        ELSE IF @YES_OR_NO='NO'
        BEGIN
            SELECT @EFFECT_DT=EFFECT_DT
            FROM EFFECT_DT
            WHERE RN=3
            RETURN (@EFFECT_DT)
        END

    END
    GO
</code>```

答:
You need to declare your common table expression in the context where it will be used.

```<code>IF @YES_OR_NO='YES'
BEGIN;
  ;WITH EFFECT_DT AS (
    ...
  )
    SELECT @EFFECT_DT=EFFECT_DT
    FROM EFFECT_DT
    RETURN (@EFFECT_DT)
END;
</code>```

For your updated question, correcting the scalar udf:

```<code>alter function A (@CLT_NBR int, @YES_OR_NO varchar(10)) returns datetime as
begin;
  declare @EFFECT_DT date;
  with EFFECT_DT as (
  select
      CLT_NBR
    , EFFECT_DT
    , RN
  from S
  )
  select @EFFECT_DT = EFFECT_DT
  from EFFECT_DT
  where (RN = 2 and @YES_OR_NO = 'YES')
     or (RN = 3 and @YES_OR_NO = 'NO')
  return (@EFFECT_DT);
end;
go
</code>```

Body:
I get an error message: Incorrect syntax near the keyword 'IF'. I need the CTE in the later IF statement. Can anyone know how to resolve it? Thanks!
The code is below:

ALTER FUNCTION A
    (
        @CLT_NBR int,
        @YES OR NO varchar(10)

    )
    RETURNS datetime
    AS
    BEGIN
        DECLARE @EFFECT_DT date;

        WITH EFFECT_DT
        AS
        (
            SELECT CLT_NBR,
                EFFECT_DT,
                RN
            FROM S
        )

        IF @YES_OR_NO='YES'
        BEGIN
            SELECT @EFFECT_DT=EFFECT_DT
            FROM EFFECT_DT
            WHERE RN=2
            RETURN (@EFFECT_DT)
        END
        ELSE IF @YES_OR_NO='NO'
        BEGIN
            SELECT @EFFECT_DT=EFFECT_DT
            FROM EFFECT_DT
            WHERE RN=3
            RETURN (@EFFECT_DT)
        END

    END
    GO

Body:
You need to declare your common table expression in the context where it will be used.

IF @YES_OR_NO='YES'
BEGIN;
  ;WITH EFFECT_DT AS (
    ...
  )
    SELECT @EFFECT_DT=EFFECT_DT
    FROM EFFECT_DT
    RETURN (@EFFECT_DT)
END;

For your updated question, correcting the scalar udf:

alter function A (@CLT_NBR int, @YES_OR_NO varchar(10)) returns datetime as
begin;
  declare @EFFECT_DT date;
  with EFFECT_DT as (
  select
      CLT_NBR
    , EFFECT_DT
    , RN
  from S
  )
  select @EFFECT_DT = EFFECT_DT
  from EFFECT_DT
  where (RN = 2 and @YES_OR_NO = 'YES')
     or (RN = 3 and @YES_OR_NO = 'NO')
  return (@EFFECT_DT);
end;
go


问:
My site is displaying some errors SQL related
I am not an developer and have limited knowledge. My site is displaying the following errors at the top...Its a wordpress site.

Can you guys help without being too technical. I have shielded server name for security purposes

Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in /home/.....and line 118

Warning: mysql_query(): A link to the server could not be established in /home./(servername)/public_html/wp-content/themes/clip/header.php on line 118

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/(servername) /public_html/wp-content/themes/clip/header.php on line 14

答: You don't have access to the sql database with your account. Maybe give away how you connect to the database to see what's going on? And there are a lot of ressources about this specific problem, I think you didn't look that much into it.</p>

ContentLicense: CC BY-SA 4.0


问:
How do I create a desaturated version of a Display P3 color?
I have a color UIColor(displayP3Red: 1, green: 0, blue: 0.8, alpha: 1). I want to create a desaturated version of this — with the same hue and brightness, but less saturation, like half the saturation of the original. How do I do this?

答:
It should be straightforward given you can compute the Normalised Primary Matrix (NPM) of DCI-P3: the middle row of the NPM represents the Luminance factors. I will illustrate this using Colour, it assumes that you are using linear values:

import numpy as np
import colour

# Computing the sRGB Luminance Equation, you should be familiar with the
# resulting Luminance factors.
print(colour.RGB_luminance_equation(
    colour.sRGB_COLOURSPACE.primaries,
    colour.sRGB_COLOURSPACE.whitepoint))
# Y = 0.212639005872(R) + 0.715168678768(G) + 0.0721923153607(B)

# Computing the DCI-P3 Luminance Equation.
print(colour.RGB_luminance_equation(
    colour.DCI_P3_COLOURSPACE.primaries,
    colour.DCI_P3_COLOURSPACE.whitepoint))
# Y = 0.209491677913(R) + 0.721595254161(G) + 0.0689130679262(B)

# Computing Luminance of given RGB colour, this is assuming it is representing linear values.
DCI_P3_LUMINANCE_FACTORS = np.array([0.209491677913, 0.721595254161, 0.0689130679262])
RGB = np.array([1.0, 0.0, 0.8])
Y = np.dot(RGB, DCI_P3_LUMINANCE_FACTORS)
print(Y)
# 0.264622132254
```

With Y representing the Luminance of your given colour, if you wanted to desaturate at 50% you could do something like that:

lerp(RGB, [Y, Y, Y], 0.5)

Body:
It should be straightforward given you can compute the Normalised Primary Matrix (NPM) of DCI-P3: the middle row of the NPM represents the Luminance factors. I will illustrate this using Colour, it assumes that you are using linear values:

import numpy as np
import colour

# Computing the sRGB Luminance Equation, you should be familiar with the
# resulting Luminance factors.
print(colour.RGB_luminance_equation(
    colour.sRGB_COLOURSPACE.primaries,
    colour.sRGB_COLOURSPACE.whitepoint))
# Y = 0.212639005872(R) + 0.715168678768(G) + 0.0721923153607(B)

# Computing the DCI-P3 Luminance Equation.
print(colour.RGB_luminance_equation(
    colour.DCI_P3_COLOURSPACE.primaries,
    colour.DCI_P3_COLOURSPACE.whitepoint))
# Y = 0.209491677913(R) + 0.721595254161(G) + 0.0689130679262(B)

# Computing Luminance of given RGB colour, this is assuming it is representing linear values.
DCI_P3_LUMINANCE_FACTORS = np.array([0.209491677913, 0.721595254161, 0.0689130679262])
RGB = np.array([1.0, 0.0, 0.8])
Y = np.dot(RGB, DCI_P3_LUMINANCE_FACTORS)
print(Y)
# 0.264622132254

With Y representing the Luminance of your given colour, if you wanted to desaturate at 50% you could do something like that:

lerp(RGB, [Y, Y, Y], 0.5)


问:
How to get a list of name arguments in Django's urlpatterns
Suppose I have two apps, App1 and App2. I want to get the list of names of each url in urlpatterns.

App1 urls.py:

```<code>urlpatterns = (
    url(regex=r'^$', view=views.index_view, name='index_url'),
    url(regex=r'^about/$', view=views.about_view, name='about_url'),
    url(regex=r'^contact/$', view=views.contact_view, name='contact_url'),
)
</code>```

In App2, I want to get the following list:

```<code>['index_url', 'about_url', 'contact_url']
</code>```

I can get individual names:

```<code>>>> import App1.urls
>>> App1.urls.urlpatterns[1].name
'index_url'
</code>```

Technically, I can go over a loop to collect each name in a list. But is there a direct way to get them, like: App1.urls.urlpatterns.names?

答:
Posting the comment as an answer:

Use

```<code>names=[u.name for u in urls.urlpatterns if hasattr(u,'name')]
</code>```

to populate the array of names.

It seems like there is no direct accessor.

Body:
Suppose I have two apps, App1 and App2. I want to get the list of names of each url in urlpatterns.

App1 urls.py:

urlpatterns = (
    url(regex=r'^$', view=views.index_view, name='index_url'),
    url(regex=r'^about/$', view=views.about_view, name='about_url'),
    url(regex=r'^contact/$', view=views.contact_view, name='contact_url'),
)

In App2, I want to get the following list:

['index_url', 'about_url', 'contact_url']

I can get individual names:

>>> import App1.urls
>>> App1.urls.urlpatterns[1].name
'index_url'

Technically, I can go over a loop to collect each name in a list. But is there a direct way to get them, like: App1.urls.urlpatterns.names?

Body:
Posting the comment as an answer:

Use

names=[u.name for u in urls.urlpatterns if hasattr(u,'name')]

to populate the array of names.

It seems like there is no direct accessor.


问:
Python Speed Optimization
I am creating a program (to test a theory), and to get the data I need, I need a program to run as fast as possible.

Here's the problem - I have made it as fast as I could manage and it is still to slow. It is using a very small amount of my computer's RAM and CPU capacity. I am running the program with PyCharm 2017 Community Edition.

The code is below; How would I further optimize or change this to make it run faster?

Main:

```<code>from functions import *
from graphics import *
import time

Alpha = True

x = timestamp()

while Alpha:
    master = GraphWin(title="Image", width=512, height=512)

    build_image(master)

    getter(master, x)

    x = timestamp()

    time.sleep(3)

    master.close()
</code>```

Module "Functions":

```<code>from graphics import *
import random
from PIL import ImageGrab

def build_image(window):
    for i in range(513):
        for j in range(513):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

def getter(widget, counter):
    x = widget.winfo_rootx()+widget.winfo_x()
    y = widget.winfo_rooty()+widget.winfo_y()
    x1 = x+widget.winfo_width()
    y1 = y+widget.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("{}.png".format(str(counter)))

def timestamp():
    timelist = time.gmtime()
    filename = ("Image" + "_" + str(timelist[0]) + "_" + str(timelist[1]) + "_" + str(timelist[2]) + "_" +
                str(timelist[3]) + "_" + str(timelist[4]) + "_" + str(timelist[5]) + "_UTC")
    return filename
</code>```

Note: Module "Graphics" is a module that allows for easy manipulation of Tkinter.

答:
Since you do a lot of independent tasks, you could benefit from parallelism. Something like:</p>

```<code>from concurrent.futures import ThreadPoolExecutor

def build_image(window, start, end, step):
    for i in range(start, end, step):
        for j in range(end):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

max_workers = 8
with ThreadPoolExecutor(max_workers=max_workers) as executor:
    for id in range(max_workers):
        executor.submit(build_image, window, id, 513, max_workers)
</code>```

Title: Python Speed Optimization

Body:
I am creating a program (to test a theory), and to get the data I need, I need a program to run as fast as possible.

Here's the problem - I have made it as fast as I could manage and it is still to slow. It is using a very small amount of my computer's RAM and CPU capacity. I am running the program with PyCharm 2017 Community Edition.

The code is below; How would I further optimize or change this to make it run faster?

Main:

from functions import *
from graphics import *
import time

Alpha = True

x = timestamp()

while Alpha:
    master = GraphWin(title="Image", width=512, height=512)

    build_image(master)

    getter(master, x)

    x = timestamp()

    time.sleep(3)

    master.close()

Module "Functions":

from graphics import *
import random
from PIL import ImageGrab

def build_image(window):
    for i in range(513):
        for j in range(513):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

def getter(widget, counter):
    x = widget.winfo_rootx()+widget.winfo_x()
    y = widget.winfo_rooty()+widget.winfo_y()
    x1 = x+widget.winfo_width()
    y1 = y+widget.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("{}.png".format(str(counter)))

def timestamp():
    timelist = time.gmtime()
    filename = ("Image" + "_" + str(timelist[0]) + "_" + str(timelist[1]) + "_" + str(timelist[2]) + "_" +
                str(timelist[3]) + "_" + str(timelist[4]) + "_" + str(timelist[5]) + "_UTC")
    return filename

Note: Module "Graphics" is a module that allows for easy manipulation of Tkinter.

Body:
Since you do a lot of independent tasks, you could benefit from parallelism. Something like:

from concurrent.futures import ThreadPoolExecutor

def build_image(window, start, end, step):
    for i in range(start, end, step):
        for j in range(end):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

max_workers = 8
with ThreadPoolExecutor(max_workers=max_workers) as executor:
    for id in range(max_workers):
        executor.submit(build_image, window, id, 513, max_workers)


答:
this may be a bit faster if you use numpy.  loops inside loops will kill your speed.</p>

```<code>from PIL import Image
import numpy as np

def drawImage():
    return Image.fromarray(np.random.randint(255, size=(600, 600, 3)).astype(np.uint8))
</code>```

Title: Python Speed Optimization

Body:
this may be a bit faster if you use numpy.  loops inside loops will kill your speed.

from PIL import Image
import numpy as np

def drawImage():
    return Image.fromarray(np.random.randint(255, size=(600, 600, 3)).astype(np.uint8))


问:
Query server address to find out what mail software is installed
Let's say there's a mail server accessible on the internet, example:  mail3.domain.com

Is it possible to query that address and find out what mail software they are using? Like lotus notes, Exchange, or a linux mailserver software, etc..

答:
You can run a command like:

```<code>telnet mail.domain.com 25
</code>```

In the response you'll see something like:

```<code>Trying 122.33.44.555...
Connected to mail.domain.com
Escape character is '^]'.
220-mail.domain.com ESMTP Exim 4.87 #1 Fri, 31 Mar 2017 20:53:59 +0000
220-We do not authorize the use of this system to transport unsolicited,
220 and/or bulk e-mail.
</code>```

From that you can learn something about the software being run on the server.

Body:
You can run a command like:

telnet mail.domain.com 25

In the response you'll see something like:

Trying 122.33.44.555...
Connected to mail.domain.com
Escape character is '^]'.
220-mail.domain.com ESMTP Exim 4.87 #1 Fri, 31 Mar 2017 20:53:59 +0000
220-We do not authorize the use of this system to transport unsolicited,
220 and/or bulk e-mail.

From that you can learn something about the software being run on the server.


答:
WITH is part of the SELECT statement.  IF is a separate statement, so they are in the wrong order:

```<code>IF @YES_OR_NO='YES'
BEGIN
    WITH EFFECT_DT AS (
        ...
    )
    SELECT @EFFECT_DT=EFFECT_DT
    FROM EFFECT_DT
    RETURN (@EFFECT_DT)
END;
</code>```

If you want a "CTE" that spans multiple statements, then use a table variable or temporary table.  WITH is for only one statement.

Title: Tsql:Incorrect syntax near the keyword 'IF'

Body:
WITH is part of the SELECT statement.  IF is a separate statement, so they are in the wrong order:

IF @YES_OR_NO='YES'
BEGIN
    WITH EFFECT_DT AS (
        ...
    )
    SELECT @EFFECT_DT=EFFECT_DT
    FROM EFFECT_DT
    RETURN (@EFFECT_DT)
END;

If you want a "CTE" that spans multiple statements, then use a table variable or temporary table.  WITH is for only one statement.


问:
Why my tensor still have the rank 2 after a reshape to 3D
This is my script. `

```<code>def phi(x, b, w, B):
    z1 = tf.matmul(x,w)
    z2 = tf.cos(z1+b)
    w1 =tf.reshape(w,(1,2,1000))
    #z= tf.reshape(z2,(100,1,1000))
    z=tf.expand_dims(z2, 1)
    print(z)
    print(w1)
    phix = tf.matmul(z, tf.transpose(w1))
    phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
    #print(phix)
    phix = np.reshape(phix,(200,1000))

    return phix,B

def model(phix, B, param) :
    #return tf.matmul(tf.matmul(phix, tf.transpose(param)), B)
    one = tf.matmul(phix, param)
    return one
x2 = tf.constant(Xtr)  # variable
#xtest = tf.placeholder(tf.float32, shape=[1925, 2])  # variable

#W2 = tf.Variable(tf.zeros([784, 10]),trainable=False ,name="W2")
W2 = tf.constant(np.random.normal( loc = .0 , scale = 1./20. ,size =[2, 1000] ),name="W2")
#b2 = tf.Variable(tf.zeros([10]),trainable=False , name="b2" )
b2 = tf.Variable(tf.random_uniform(shape=[1000],dtype=tf.float64),trainable=False , name="b2")
y = tf.placeholder(tf.float64, [100, 2])
#ytest = tf.placeholder(tf.float64, [1925, 2])
B = W2

param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention
phix, B = phi (x2,b2,W2,B)
lamda = 1.e-43
y_ = model(phix, B,param)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

step = 0.002

opt = tf.train.AdamOptimizer(step).minimize(cost)
correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

d = {}
evolution_train = []
evolution_cost = []
iteration = range(10000)
init = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init)
    for k in [10000] :
        for i in range(k):
            batch_ys = ytr
            #batch_xs = Xtr

            #X_train, X_test, y_train, y_test = train_test_split(batch_xs, batch_ys, test_size=0.33, random_state=42)
            p = sess.run(cost, feed_dict = { y : batch_ys })

            train_accuracy = accuracy.eval(feed_dict={y: batch_ys})
            evolution_cost.append(p)
            evolution_train.append(train_accuracy)
            #print(p)
            if i%100 == 0:
                print("step " +str(i)+ " cost " +str(p)+ " train_accuracy " +str(train_accuracy)+ " --- %s seconds --- " % (time.time() - start_time))

        d["cost for " +str(k) + " iteration"] = p
</code>```

`
I reshape well z but when I do  phix = tf.matmul(z, tf.transpose(w1)) the following message appears : ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank

this is the error :

```<code>    ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    546       try:
--> 547         self.assert_same_rank(other)
    548         new_dims = []

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in assert_same_rank(self, other)
    592         raise ValueError(
--> 593             "Shapes %s and %s must have the same rank" % (self, other))
    594

ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    622     try:
--> 623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    553         raise ValueError("Shapes %s and %s are not compatible" %
--> 554                          (self, other))
    555

ValueError: Shapes (100, 1, 1000) and (?, ?) are not compatible

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-75-1f84fec5a618> in <module>()
     33 param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
     34 norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention
---> 35 phix, B = phi (x2,b2,W2,B)
     36 lamda = 1.e-43
     37 y_ = model(phix, B,param)

<ipython-input-75-1f84fec5a618> in phi(x, b, w, B)
      7     print(z)
      8     print(w1)
----> 9     phix = tf.matmul(z, tf.transpose(w1))
     10     phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
     11     #print(phix)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, a_is_sparse, b_is_sparse, name)
   1034                                    transpose_a=transpose_a,
   1035                                    transpose_b=transpose_b,
-> 1036                                    name=name)
   1037
   1038 sparse_matmul = gen_math_ops._sparse_mat_mul

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
    909   """
    910   return _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
--> 911                               transpose_b=transpose_b, name=name)
    912
    913

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    653         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    654                          input_types=input_types, attrs=attr_protos,
--> 655                          op_def=op_def)
    656         outputs = op.outputs
    657         return _Restructure(ops.convert_n_to_tensor(outputs), output_structure)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device)
   2154                     original_op=self._default_original_op, op_def=op_def)
   2155     if compute_shapes:
-> 2156       set_shapes_for_outputs(ret)
   2157     self._add_op(ret)
   2158     self._record_op_seen_by_control_dependencies(ret)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in set_shapes_for_outputs(op)
   1610       raise RuntimeError("No shape function registered for standard op: %s"
   1611                          % op.type)
-> 1612   shapes = shape_func(op)
   1613   if len(op.outputs) != len(shapes):
   1614     raise RuntimeError(

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/common_shapes.py in matmul_shape(op)
     79 def matmul_shape(op):
     80   """Shape function for a MatMul op."""
---> 81   a_shape = op.inputs[0].get_shape().with_rank(2)
     82   transpose_a = op.get_attr("transpose_a")
     83   b_shape = op.inputs[1].get_shape().with_rank(2)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:
--> 625       raise ValueError("Shape %s must have rank %d" % (self, rank))
    626
    627   def with_rank_at_least(self, rank):

ValueError: Shape (100, 1, 1000) must have rank 2
</code>```

答:
You did phix = np.reshape(phix,(200,1000)) using numpy to do the reshape. I think you meant to do phix = tf.reshape(phix,(200,1000)) so tensorflow does it right?

Numpy doesn't get used at computation time, only tensorflow operations get used.

Body:
This is my script. `

def phi(x, b, w, B):
    z1 = tf.matmul(x,w)
    z2 = tf.cos(z1+b)
    w1 =tf.reshape(w,(1,2,1000))
    #z= tf.reshape(z2,(100,1,1000))
    z=tf.expand_dims(z2, 1)
    print(z)
    print(w1)
    phix = tf.matmul(z, tf.transpose(w1))
    phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
    #print(phix)
    phix = np.reshape(phix,(200,1000))

    return phix,B

def model(phix, B, param) :
    #return tf.matmul(tf.matmul(phix, tf.transpose(param)), B)
    one = tf.matmul(phix, param)
    return one
x2 = tf.constant(Xtr)  # variable
#xtest = tf.placeholder(tf.float32, shape=[1925, 2])  # variable

#W2 = tf.Variable(tf.zeros([784, 10]),trainable=False ,name="W2")
W2 = tf.constant(np.random.normal( loc = .0 , scale = 1./20. ,size =[2, 1000] ),name="W2")
#b2 = tf.Variable(tf.zeros([10]),trainable=False , name="b2" )
b2 = tf.Variable(tf.random_uniform(shape=[1000],dtype=tf.float64),trainable=False , name="b2")
y = tf.placeholder(tf.float64, [100, 2])
#ytest = tf.placeholder(tf.float64, [1925, 2])
B = W2

param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention
phix, B = phi (x2,b2,W2,B)
lamda = 1.e-43
y_ = model(phix, B,param)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

step = 0.002

opt = tf.train.AdamOptimizer(step).minimize(cost)
correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

d = {}
evolution_train = []
evolution_cost = []
iteration = range(10000)
init = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init)
    for k in [10000] :
        for i in range(k):
            batch_ys = ytr
            #batch_xs = Xtr

            #X_train, X_test, y_train, y_test = train_test_split(batch_xs, batch_ys, test_size=0.33, random_state=42)
            p = sess.run(cost, feed_dict = { y : batch_ys })

            train_accuracy = accuracy.eval(feed_dict={y: batch_ys})
            evolution_cost.append(p)
            evolution_train.append(train_accuracy)
            #print(p)
            if i%100 == 0:
                print("step " +str(i)+ " cost " +str(p)+ " train_accuracy " +str(train_accuracy)+ " --- %s seconds --- " % (time.time() - start_time))

        d["cost for " +str(k) + " iteration"] = p

`
I reshape well z but when I do  phix = tf.matmul(z, tf.transpose(w1)) the following message appears : ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank

this is the error :

    ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    546       try:
--> 547         self.assert_same_rank(other)
    548         new_dims = []

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in assert_same_rank(self, other)
    592         raise ValueError(
--> 593             "Shapes %s and %s must have the same rank" % (self, other))
    594

ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    622     try:
--> 623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    553         raise ValueError("Shapes %s and %s are not compatible" %
--> 554                          (self, other))
    555

ValueError: Shapes (100, 1, 1000) and (?, ?) are not compatible

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-75-1f84fec5a618> in <module>()
     33 param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
     34 norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention
---> 35 phix, B = phi (x2,b2,W2,B)
     36 lamda = 1.e-43
     37 y_ = model(phix, B,param)

<ipython-input-75-1f84fec5a618> in phi(x, b, w, B)
      7     print(z)
      8     print(w1)
----> 9     phix = tf.matmul(z, tf.transpose(w1))
     10     phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
     11     #print(phix)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, a_is_sparse, b_is_sparse, name)
   1034                                    transpose_a=transpose_a,
   1035                                    transpose_b=transpose_b,
-> 1036                                    name=name)
   1037
   1038 sparse_matmul = gen_math_ops._sparse_mat_mul

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
    909   """
    910   return _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
--> 911                               transpose_b=transpose_b, name=name)
    912
    913

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    653         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    654                          input_types=input_types, attrs=attr_protos,
--> 655                          op_def=op_def)
    656         outputs = op.outputs
    657         return _Restructure(ops.convert_n_to_tensor(outputs), output_structure)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device)
   2154                     original_op=self._default_original_op, op_def=op_def)
   2155     if compute_shapes:
-> 2156       set_shapes_for_outputs(ret)
   2157     self._add_op(ret)
   2158     self._record_op_seen_by_control_dependencies(ret)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in set_shapes_for_outputs(op)
   1610       raise RuntimeError("No shape function registered for standard op: %s"
   1611                          % op.type)
-> 1612   shapes = shape_func(op)
   1613   if len(op.outputs) != len(shapes):
   1614     raise RuntimeError(

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/common_shapes.py in matmul_shape(op)
     79 def matmul_shape(op):
     80   """Shape function for a MatMul op."""
---> 81   a_shape = op.inputs[0].get_shape().with_rank(2)
     82   transpose_a = op.get_attr("transpose_a")
     83   b_shape = op.inputs[1].get_shape().with_rank(2)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:
--> 625       raise ValueError("Shape %s must have rank %d" % (self, rank))
    626
    627   def with_rank_at_least(self, rank):

ValueError: Shape (100, 1, 1000) must have rank 2


问:
Capturing mouseMove event in ember.js
I'm trying to implement a slider view in ember.js; for that I would need to capture the mouseMove event even if it leaves the view that first received it. In pure js I would do something like this:

```<code>element.addEventListener 'mousemove', ..., true   // true means 'capture event'
</code>```

This also has the nice side effect of having the event being fired on the capturing element even if the mouse leaves the browser window, mimicking the way UI controls behave in native applications.

I don't seem to be able to find a way to do that in ember.js but I'm sure I'm overlooking something. If not, then what is the recommended way of doing something like that?

答:
An update for people viewing an old question. Now components contain a mouseMove and other event handlers built in, as well as the ability ability to add custom ones.

https://guides.emberjs.com/v2.12.0/components/handling-events/

```<code>import Ember from 'ember';

export default Ember.Component.extend({
    mouseMove() {
        //do stuff
    }
});
</code>```

Title: Capturing mouseMove event in ember.js

Body:
I'm trying to implement a slider view in ember.js; for that I would need to capture the mouseMove event even if it leaves the view that first received it. In pure js I would do something like this:

element.addEventListener 'mousemove', ..., true   // true means 'capture event'

This also has the nice side effect of having the event being fired on the capturing element even if the mouse leaves the browser window, mimicking the way UI controls behave in native applications.

I don't seem to be able to find a way to do that in ember.js but I'm sure I'm overlooking something. If not, then what is the recommended way of doing something like that?

Body:
An update for people viewing an old question. Now components contain a mouseMove and other event handlers built in, as well as the ability ability to add custom ones.

https://guides.emberjs.com/v2.12.0/components/handling-events/

import Ember from 'ember';

export default Ember.Component.extend({
    mouseMove() {
        //do stuff
    }
});


问:
SSDT Equivalent for Oracle Database
In SSDT there is a mechanism for managing DDL changes, for instance a new column or a change to a data type. Instead of putting an 'Alter Table' statement into the database project, instead we edit that original 'Create Table' statement which focuses on the final state that includes the new column. It detects the difference between older and new script and creates necessary 'Alter Table' script to use for deployment.

Is there any equivalent strategy to achieve the same in Oracle Database as I am using J2EE technologies and Eclipse IDE.

答:
No it is not I am afraid, SSDT is a free tool developed by Microsoft to help SQL Server deployments. I would think it extremely unlikely that Microsoft would ever allow let alone help deployments to Oracle - it is a new Microsoft sure but some things will never change!

The best alternative is to use JetBrains datagrip  as an IDE and flyway as a deployment tool:

https://flywaydb.org/documentation/database/oracle

https://www.jetbrains.com/datagrip/

In my opinion Microsoft has created the best development environment of ANY RDBMS and throw in the redgate suite of tools and it makes the tooling a real differentiator.

Ed

Title: SSDT Equivalent for Oracle Database


问:
connect to SQL hosted on a local machine from my laptop (using an IP)
I set up an SQL server on my Windows 7 PC.

I have a laptop, from which I want to connect to the SQL server (using visual studio 2010).
I need to fill in a "server name" when creating a database connection.

I tried "My.IP.Address/SQLEXPRESS,custom-port", but that doesn't work. All examples talk about using server names which are formatted like so "TOM-PC/SQLEXPRESS", but I have an important requirement:

I want to be able to connect from anywhere (not only when in the same local network), therefore I'm trying to use the IP address (the port isn't simply 1433 since my ISP blocks it).

The custom port is open, and reachable in tests.

I've been Googling this all day long, but can't find a solution. Please help!

Thank you,

Tom

答:
To access from a remote location, you need to setup port forwarding on your router. If you have a static external facing IP address, then you can use that for your server address (123.123.123.123\SQLEXPRESS), otherwise you will need to setup a dynamic DNS service like DynDNS.com that will give your router a hostname.

DynDNS Free allows you to create a
  hostname that points to your home or
  office IP address, providing an
  easy-to-remember URL for quick access.
  We also provide an update mechanism
  which makes the hostname work with
  your dynamic IP address. We continue
  to offer this service free to the
  Internet community as we have done so
  for nearly 10 years.


问:
Generating Twillio video token with my php server
I'm trying to set up my own php accessToken server to grant new token for different user on my ios swift app.

I've set it up already, and can get the token key, however when the videoQuickStart app uses the token key get from my server, it will not connect to room, and even if I try to use the "token.php" from here : https://github.com/TwilioDevEd/video-quickstart-php/blob/master/token.php it still not working.

It seems like my key is not validated?

Can anyone helps?

Here's my implement of server, which is almost identical to the original one.

```<code>< ? php
include('/Applications/XAMPP/xamppfiles/htdocs/dashboard/vendor/autoload.php');

use Twilio\Jwt\AccessToken;

use Twilio\Jwt\Grants\VideoGrant;

// Required for all Twilio access tokens

$TWILIO_ACCOUNT_SID = 'XXXXX';

$TWILIO_CONFIGURATION_SID = 'XXXX';

$TWILIO_API_KEY = 'XXXX';

$TWILIO_API_SECRET = 'XXXXX';

// An identifier for your app - can be anything you'd like

$identity = $_GET['name'];

// Create access token, which we will serialize and send to the client

$token = new AccessToken(
$TWILIO_ACCOUNT_SID,
$TWILIO_API_KEY,
$TWILIO_API_SECRET,
3600,
$identity
);

$grant = new VideoGrant();

$grant->setConfigurationProfileSid($TWILIO_CONFIGURATION_SID);

$token->addGrant($grant);

// render token to string

echo json_encode(array(
'identity' => $identity,
'token' => $token->toJWT(),
));
?>
</code>```

答:
It's fixed.

It turns out I misplaced TWILIO_ACCOUNT_SID and TWILIO_CONFIGURATION_SID.

Thanks guys

Body:
I'm trying to set up my own php accessToken server to grant new token for different user on my ios swift app.

I've set it up already, and can get the token key, however when the videoQuickStart app uses the token key get from my server, it will not connect to room, and even if I try to use the "token.php" from here : https://github.com/TwilioDevEd/video-quickstart-php/blob/master/token.php it still not working.

It seems like my key is not validated?

Can anyone helps?

Here's my implement of server, which is almost identical to the original one.

< ? php
include('/Applications/XAMPP/xamppfiles/htdocs/dashboard/vendor/autoload.php');

use Twilio\Jwt\AccessToken;

use Twilio\Jwt\Grants\VideoGrant;

// Required for all Twilio access tokens

$TWILIO_ACCOUNT_SID = 'XXXXX';

$TWILIO_CONFIGURATION_SID = 'XXXX';

$TWILIO_API_KEY = 'XXXX';

$TWILIO_API_SECRET = 'XXXXX';

// An identifier for your app - can be anything you'd like

$identity = $_GET['name'];

// Create access token, which we will serialize and send to the client

$token = new AccessToken(
$TWILIO_ACCOUNT_SID,
$TWILIO_API_KEY,
$TWILIO_API_SECRET,
3600,
$identity
);

$grant = new VideoGrant();

$grant->setConfigurationProfileSid($TWILIO_CONFIGURATION_SID);

$token->addGrant($grant);

// render token to string

echo json_encode(array(
'identity' => $identity,
'token' => $token->toJWT(),
));
?>


问:
Migrating CXF web service app to WebSphere 8.5.5
I am in the process of migrating an application which is deployed on WAS 6.1. It's CXF based web services compatible with Java 1.5 (developed on JDK 1.4). It needs to be migrated/deployed on WAS 8.5.5.9.

Will I be needing any kind of code changes or configuration changes will be enough?

答:
The biggest hurdle will probably be the fact that WAS now includes its own web services libraries (that wasn't added to 6.1 until a feature pack), so you'll need to do a bit of configuration to use a third-party web services implementation.  The official doc is here: https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.nd.doc/ae/twbs_thirdparty.html

The most important things:

1) Set a property to disable WebSphere's JAX-WS engine

2) Make sure that your CXF implementation and JAX-WS API are packaged in a PARENT_LAST class loader (a loader that searches locally before delegating to its parents, to keep you from picking up WebSphere's JAX-WS runtime).  The doc recommends setting your web module class loader to PARENT_LAST, but it'd be even safer to put the CXF/JAX-WS jars into a shared library with the "use an isolated class loader" option, which will cause just those specific jars to be loaded in that manner.


问:
Angular http.get API Request - No 'Access-Control-Allow-Origin' header is present
I'm trying to do a simple get request in Angular to a certain API, but I get the following:

XMLHttpRequest cannot load
  https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_KEY.
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'https://my-site.herokuapp.com' is therefore not
  allowed access.

I have tried many different APIs just to test if maybe it's a setting that needs enabled on my target API or if it's just something in general with any ol' API I try to access. I got this error with all of them, so at this point it's GOTTA be something I'm doing wrong.

Also to note, I'm pushing to heroku so it's up and running on a web server, not local host.

Here's my angular code below:

```<code>$http.get("https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_KEY")
                .then(function(response) {
                    vm.output = response.data;
                });
</code>```

I've opened about a thousand browser tabs searching for info on this, and many say "You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access." or something like that. But I'm trying Google and obviously they should allow cross-site requests, so it's gotta be something I'm doing wrong. Thanks for any help.

答:
The issue you're running into is quite common. You are running up against the Same origin Policy. To better understand the problem you're facing, read through some of that information but at a high level, you cannot call another domain from a different domain within JavaScript. There are workarounds such as JSONP and CORS but I would recommend moving the API call to server side code so you don't run into this.

https://en.wikipedia.org/wiki/Same-origin_policy

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Can anyone explain what JSONP is, in layman terms?

Body:
I'm trying to do a simple get request in Angular to a certain API, but I get the following:

XMLHttpRequest cannot load
  https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_KEY.
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'https://my-site.herokuapp.com' is therefore not
  allowed access.

I have tried many different APIs just to test if maybe it's a setting that needs enabled on my target API or if it's just something in general with any ol' API I try to access. I got this error with all of them, so at this point it's GOTTA be something I'm doing wrong.

Also to note, I'm pushing to heroku so it's up and running on a web server, not local host.

Here's my angular code below:

$http.get("https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_KEY")
                .then(function(response) {
                    vm.output = response.data;
                });

I've opened about a thousand browser tabs searching for info on this, and many say "You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access." or something like that. But I'm trying Google and obviously they should allow cross-site requests, so it's gotta be something I'm doing wrong. Thanks for any help.


问:
DB Schema Design - Designing multiple many to many tables
I am trying to design a DB that has multiple many to many junction tables but each many to many is a cascading option based on previous tables.

For Example: Let's begin with four tables with their primary keys.

Style table --> Style ID (PK)

     Fabric table --> FabricID (PK)

     Body table --> BodyID (PK)

     Color table --> ColorID (PK)

A User chooses a Style and then a Fabric, so this is easy to define the many to many.

StyleFabric table --> StyleID, FabricID (Composite PK)

Now this is where I get confused. The User after choosing Style and Fabric can now choose Body. So I created a table called:

StyleFabricBody table --> StyleID, FabricID, BodyID  (Composite PK)

Now Based on Style,Fabric and Body, the user can select a color

StyleFabricBodyColor table --> StyleID, FabricID, BodyID, ColorID (Composite PK)

Hopefully you can see the pattern by now and I have 5 more tables to add.

Is this a correct approach to connect the main tables ?

答:
Something like this should be enough, you don't need more than one table:</p>

```<code>create table dbo.UserChoice
(
    Id int identity(1, 1) primary key nonclustered,

    UserId   int not null,

    StyleId  int not null,
    FabricId int not null,
    BodyId   int not null,
    ColorId  int not null,
    ...,

    constraint FK_UserChoice_UserId   foreign Key (UserId)   references dbo.User   (Id),

    constraint FK_UserChoice_StyleId  foreign Key (StyleId)  references dbo.Style  (Id),
    constraint FK_UserChoice_FabricId foreign Key (FabricId) references dbo.Fabric (Id),
    constraint FK_UserChoice_BodyId   foreign Key (BodyId)   references dbo.Body   (Id),
    constraint FK_UserChoice_ColorId  foreign Key (ColorId)  references dbo.Color  (Id),
    ...
)
</code>```

Body:
Something like this should be enough, you don't need more than one table:

create table dbo.UserChoice
(
    Id int identity(1, 1) primary key nonclustered,

    UserId   int not null,

    StyleId  int not null,
    FabricId int not null,
    BodyId   int not null,
    ColorId  int not null,
    ...,

    constraint FK_UserChoice_UserId   foreign Key (UserId)   references dbo.User   (Id),

    constraint FK_UserChoice_StyleId  foreign Key (StyleId)  references dbo.Style  (Id),
    constraint FK_UserChoice_FabricId foreign Key (FabricId) references dbo.Fabric (Id),
    constraint FK_UserChoice_BodyId   foreign Key (BodyId)   references dbo.Body   (Id),
    constraint FK_UserChoice_ColorId  foreign Key (ColorId)  references dbo.Color  (Id),
    ...
)


问:
FillDataSet is not declared msg
```<code>Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function
</code>```

答:
Presumably, you haven't actually defined the FillDataSet method.

I think you may have meant to use the SqlDataAdapter's Fill method. You can see a complete example of how to do that here: Direct method from SQL command text to DataSet

Title: FillDataSet is not declared msg


问:
How can I unit test Arduino code?
I'd like to be able to unit test my Arduino code. Ideally, I would be able to run any tests without having to upload the code to the Arduino. What tools or libraries can help me with this?

There is an Arduino emulator in development which could be useful, but it doesn't yet seem to be ready for use.

AVR Studio from Atmel contains a chip simulator which could be useful, but I can't see how I would use it in conjunction with the Arduino IDE.

答: James W. Grenning writes great books and this one is about unit testing embedded C code Test Driven Development for Embedded C.

Title: How can I unit test Arduino code?


问:
WebSocket (Sockjs and Stomp) with ServiceWorkers
I'm using Stomp and Sockjs to register a websocket with my Spring Boot self-contained server (3.1.1), which all works fine. However, I have implemented a ServiceWorker to handle offline services, which is all working, except for the socket. The call to ws://localhost/registerSocket yields this error on the frontend:

Firefox can't establish a connection to the server at ws://localhost/registerSocket/351/4vevdv79/websocket.

And this on the backend:

ERROR o.s.w.s.s.s.DefaultHandshakeHandler - Handshake failed due to invalid Upgrade header: null

In my ServiceWorker I've specifically excluded it from intercepting the ws request:

```<code>if (uri.indexOf("/registerSocket") === -1) {
   event.respondWith(getResponse(event));
}
</code>```

Yet, inevitably the ws upgrade fails and it reverts to the old comet style polyfill.

Does anybody know of a way to get websockets working correctly with ServiceWorker?

答:
I've just found out about a bug in Firefox 44 that prevented Web Socket connections from working when a Service Worker was used.

See this bug report.

The bug should be fixed now (since Firefox 44.0.1; it's even in the release notes).

Body:
I'm using Stomp and Sockjs to register a websocket with my Spring Boot self-contained server (3.1.1), which all works fine. However, I have implemented a ServiceWorker to handle offline services, which is all working, except for the socket. The call to ws://localhost/registerSocket yields this error on the frontend:

Firefox can't establish a connection to the server at ws://localhost/registerSocket/351/4vevdv79/websocket.

And this on the backend:

ERROR o.s.w.s.s.s.DefaultHandshakeHandler - Handshake failed due to invalid Upgrade header: null

In my ServiceWorker I've specifically excluded it from intercepting the ws request:

if (uri.indexOf("/registerSocket") === -1) {
   event.respondWith(getResponse(event));
}

Yet, inevitably the ws upgrade fails and it reverts to the old comet style polyfill.

Does anybody know of a way to get websockets working correctly with ServiceWorker?


问:
Failed to decode downloaded font
This is an error I am getting in Chrome and unfortunately searching for it hasn't given me much results. The font itself is appearing correctly. However I still get this error/warning. More specifically, this is the full warning:

"Failed to decode downloaded font:
  http://localhost:8000/app/fonts/Lato/"

My CSS are these:

```<code>@font-face {
    font-family:"Lato";
    src: url("../fonts/Lato/");
}

html, body {
    font-family:'Lato';
}
</code>```

I just do not understand. The font is applied correctly, but the warning is always there. Trying to use Sans-Serif makes the font revert to the normal browser font, so that may be it, but I am not sure, and even after searching I have found nothing. Thanks!

EDIT

There are various font files, all from the same family. I am trying to load them all. The font files are .ttf. I am loading them from a local folder, and there are various font-files, like Lato-Black.ttf, Lato-Bold.ttf, Lato-Italic.ttf etc.

答:
For me, this error was occuring when I referenced a google font using https. When I switched to http, the error went away. (and yes, I tried it multiple times to confirm that was the cause)

So I changed:

```<code>@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,100,500,900);
</code>```

To:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,100,500,900);
</code>```

Title: Failed to decode downloaded font

Body:
This is an error I am getting in Chrome and unfortunately searching for it hasn't given me much results. The font itself is appearing correctly. However I still get this error/warning. More specifically, this is the full warning:

"Failed to decode downloaded font:
  http://localhost:8000/app/fonts/Lato/"

My CSS are these:

@font-face {
    font-family:"Lato";
    src: url("../fonts/Lato/");
}

html, body {
    font-family:'Lato';
}

I just do not understand. The font is applied correctly, but the warning is always there. Trying to use Sans-Serif makes the font revert to the normal browser font, so that may be it, but I am not sure, and even after searching I have found nothing. Thanks!

EDIT

There are various font files, all from the same family. I am trying to load them all. The font files are .ttf. I am loading them from a local folder, and there are various font-files, like Lato-Black.ttf, Lato-Bold.ttf, Lato-Italic.ttf etc.

Body:
For me, this error was occuring when I referenced a google font using https. When I switched to http, the error went away. (and yes, I tried it multiple times to confirm that was the cause)

So I changed:

@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,100,500,900);

To:

@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,100,500,900);


问:
How to write a Task.ContinueWith within an Async computation expression
I'm struggling to figure out how to write a Task.ContinueWith within a Async computation expression.

Ultimately, I want to process a cancel without relying on the Cancel Exception. As a result, I thought I could use Task.ContinueWith.

However, I'm in-over-my-head on trying to write this.

Any suggestions?

```<code>let rec receiveXmlMessage connection (cancellation:CancellationToken) queue =

    async {

        use receiveCommand = new SqlCommand(receiveQuery, connection, CommandTimeout = 0)
        let result = receiveCommand.ExecuteNonQueryAsync(cancellation)

        result.ContinueWith(fun (someResult:Task<int>) -> CancellableResult.Cancelled // IDK... ) |> AsyncResult.fromAsync
    }
</code>```

Error     Type mismatch. Expecting a
      Task> -> 'b     but given a
      Async<'c> -> Async>     The type 'Task>' does not match the type 'Async<'b>'

答:
Sorry, this isn't necessarily an answer but wouldn't fit well as a comment.

Do you need to pass a cancellation token to your workflow?  I think it might be better to use Async.CancellationToken to propagate the workflow's existing token:

```<code>async {
    let! ct = Async.CancellationToken // gets the async workflow's current cancellation token
    use receiveCommand = new SqlCommand(receiveQuery, connection, CommandTimeout = 0)
    let! result = receiveCommand.ExecuteNonQueryAsync(ct) |> Async.AwaitTask
    // do something with the result
}
</code>```

By threading the async workflow's cancellation token through to the computation you care about, you enable cancelling the workflow to do the right thing - it can cancel the top-level workflow when transitioning from one step to another, or it can cancel the query execution if that's what's executing.

Then when you schedule your async via a method like Async.RunSynchronously or Async.Start you can pass in an existing cancellation token if you have one.

However, it's not completely clear to me if this is what you're actually trying to do, since you're using let rec but you haven't indicated any need for recursive logic.

Body:
I'm struggling to figure out how to write a Task.ContinueWith within a Async computation expression.

Ultimately, I want to process a cancel without relying on the Cancel Exception. As a result, I thought I could use Task.ContinueWith.

However, I'm in-over-my-head on trying to write this.

Any suggestions?

let rec receiveXmlMessage connection (cancellation:CancellationToken) queue =

    async {

        use receiveCommand = new SqlCommand(receiveQuery, connection, CommandTimeout = 0)
        let result = receiveCommand.ExecuteNonQueryAsync(cancellation)

        result.ContinueWith(fun (someResult:Task<int>) -> CancellableResult.Cancelled // IDK... ) |> AsyncResult.fromAsync
    }

Error     Type mismatch. Expecting a
      Task> -> 'b     but given a
      Async<'c> -> Async>     The type 'Task>' does not match the type 'Async<'b>'

Body:
Sorry, this isn't necessarily an answer but wouldn't fit well as a comment.

Do you need to pass a cancellation token to your workflow?  I think it might be better to use Async.CancellationToken to propagate the workflow's existing token:

async {
    let! ct = Async.CancellationToken // gets the async workflow's current cancellation token
    use receiveCommand = new SqlCommand(receiveQuery, connection, CommandTimeout = 0)
    let! result = receiveCommand.ExecuteNonQueryAsync(ct) |> Async.AwaitTask
    // do something with the result
}

By threading the async workflow's cancellation token through to the computation you care about, you enable cancelling the workflow to do the right thing - it can cancel the top-level workflow when transitioning from one step to another, or it can cancel the query execution if that's what's executing.

Then when you schedule your async via a method like Async.RunSynchronously or Async.Start you can pass in an existing cancellation token if you have one.

However, it's not completely clear to me if this is what you're actually trying to do, since you're using let rec but you haven't indicated any need for recursive logic.


问:
FCM push notifications with Parse Server
This is complicated but I'll try to be as concise as possible. I am using FCM to send push notifications to Android devices. My backend is parse server. I can successfully send pushes from the FCM console to the device. And when I send pushes from parse to https://mybackend/parse/push, it says {"result": "true" } as the response. I have checked the server logs, and it (predictably) says all http post requests to /parse/push were 200 success.

However when sending from parse (using curl or the parse push console), the pushes do NOT show up in FCM console. There is some issue between parse server and FCM then.

In my index.js, I have:

```<code>push: {
  android: {
    senderId: "XXXXX",
    apiKey: "YYYYYY"
   }
}
</code>```

I have the keys, and done everything according to here: http://parseplatform.org/docs/parse-server/guide/#push-notifications

what else am I missing? Why can't I get this to actually appear on the device? Any help is greatly appreciated, thanks.

答:
Setting up a Parse Server for an Android app, I remember having to double check this to get it right.  The key for me was this: when I logged into Firebase console and selected the app I was working on, and clicked on the gear [or cog or whatever] and then Project Settings, I had to make sure to click on the Cloud Messaging tab and grab the Legacy server key [under project credentials] NOT the web api key that appears on the General tab.  Also the sender ID that you want to use appears on that page.

I'm not sure when they will deprecate the Legacy server key, you might try the Server key instead, but definitely make sure you get the info off of the Cloud Messaging tab.

I don't know why FCM (and APNs) don't send a different message when the key (or cert) is not set up right [that would be more developer-friendly at least] and instead just send a 200 but my guess is that they evaluate the key [or cert] after receiving the intended notification and sending a response.

Body:
This is complicated but I'll try to be as concise as possible. I am using FCM to send push notifications to Android devices. My backend is parse server. I can successfully send pushes from the FCM console to the device. And when I send pushes from parse to https://mybackend/parse/push, it says {"result": "true" } as the response. I have checked the server logs, and it (predictably) says all http post requests to /parse/push were 200 success.

However when sending from parse (using curl or the parse push console), the pushes do NOT show up in FCM console. There is some issue between parse server and FCM then.

In my index.js, I have:

push: {
  android: {
    senderId: "XXXXX",
    apiKey: "YYYYYY"
   }
}

I have the keys, and done everything according to here: http://parseplatform.org/docs/parse-server/guide/#push-notifications

what else am I missing? Why can't I get this to actually appear on the device? Any help is greatly appreciated, thanks.


问:
jQuery - Variable Scope Problem
I have the following javascript:

```<code>      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );
</code>```

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?

答:
The variables aren't set until that callback runs (when the server comes back with the JSON data), so you need to call whatever code uses them from that callback, like this:

```<code>$.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
  var moulding_1_cost = data.moulding.cost;
  var moulding_1_width = data.moulding.width;
  var cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
  $('#item_total').html( cost_of_moulding );
});
</code>```

Or call another function like this:

```<code>$.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
  someFunction(data.moulding.cost, data.moulding.width);
});
function someFunction(mqc, m1w) {
  var cost_of_moulding = ( ( 2 * ( width + ( 2 * m1w) ) + 2 * ( height + ( 2 * m1w) ) ) / 1000 ) * m1c;
  $('#item_total').html( cost_of_moulding );
}
</code>```

In either case what remains true is you need to trigger whatever uses the data once you have the data, all asynchronous operations are like this.

Title: jQuery - Variable Scope Problem

Body:
I have the following javascript:

      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?

Body:
The variables aren't set until that callback runs (when the server comes back with the JSON data), so you need to call whatever code uses them from that callback, like this:

$.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
  var moulding_1_cost = data.moulding.cost;
  var moulding_1_width = data.moulding.width;
  var cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
  $('#item_total').html( cost_of_moulding );
});

Or call another function like this:

$.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
  someFunction(data.moulding.cost, data.moulding.width);
});
function someFunction(mqc, m1w) {
  var cost_of_moulding = ( ( 2 * ( width + ( 2 * m1w) ) + 2 * ( height + ( 2 * m1w) ) ) / 1000 ) * m1c;
  $('#item_total').html( cost_of_moulding );
}

In either case what remains true is you need to trigger whatever uses the data once you have the data, all asynchronous operations are like this.


问:
PHP format multiple entries from textarea regex
I can get the number from a file using Regex and PHP for example:

```<code><?PHP
  $txt='house.1x01.pilot.ws_dvdrip_xvid-fov.mp4';
  if ($c=preg_match_all ("/.*?(\\d+).*?(\\d+)/is", $txt, $matches))
  {
      $int1=$matches[1][0];
      $int2=$matches[2][0];
      print "($int1) ($int2) \n";
  }
?>
</code>```

but what i want to do is for instance, enter multiple file names in a text área and convert this:

```<code>house.1x02.paternity.ws_dvdrip_xvid-fov.mp4
house.1x03.occams_razor.ws_dvdrip_xvid-fov.mp4
house.s04e15.dvdrip.xvid-orpheus.mp4
</code>```

into this

```<code>INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '1', '2', 'house.1x02.paternity.ws_dvdrip_xvid-fov.mp4');

INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '1', '3', 'house.1x03.occams_razor.ws_dvdrip_xvid-fov.mp4');

INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '4', '15', 'house.s04e15.dvdrip.xvid-orpheus.mp4');
</code>```

Format it for SQL, removing the 0 just keeping the 1 2 3, etc. and not 01 02 03 make it easier to copy-paste the query and insert into the database. As there is so many file names, kind of time-consuming doing it one by one.

is there any better way to acquire this?

答:
```<code>"/.*?(\\d+).*?(\\d+)/is"  -- working too hard; instead:

"/(\d+).(\d+)/"
</code>```

Since regexp is not anchored, there is no need for leading .*?

.*? is the same as.*`

I don't think you need the extra backslashes.

The separator between the numbers is strange.  I cannot really be zero-length, else the \d+ would have pick up the second string of digits.

/i is unnecessary since there are no letters.

Avoiding leading zeros seems unnecessary; MySQL will treat the string  '010' as ten, not eight.  (I suspect you were concerned that PHP would treate 010 as eight.)

The /s is probably unnecessary -- will there be multiple "lines"?

Body:
I can get the number from a file using Regex and PHP for example:

<?PHP
  $txt='house.1x01.pilot.ws_dvdrip_xvid-fov.mp4';
  if ($c=preg_match_all ("/.*?(\\d+).*?(\\d+)/is", $txt, $matches))
  {
      $int1=$matches[1][0];
      $int2=$matches[2][0];
      print "($int1) ($int2) \n";
  }
?>

but what i want to do is for instance, enter multiple file names in a text área and convert this:

house.1x02.paternity.ws_dvdrip_xvid-fov.mp4
house.1x03.occams_razor.ws_dvdrip_xvid-fov.mp4
house.s04e15.dvdrip.xvid-orpheus.mp4

into this

INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '1', '2', 'house.1x02.paternity.ws_dvdrip_xvid-fov.mp4');

INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '1', '3', 'house.1x03.occams_razor.ws_dvdrip_xvid-fov.mp4');

INSERT INTO `tvshow` (`id`, `show_id`, `season`, `episode`, `file`) VALUES (NULL, '18', '4', '15', 'house.s04e15.dvdrip.xvid-orpheus.mp4');

Format it for SQL, removing the 0 just keeping the 1 2 3, etc. and not 01 02 03 make it easier to copy-paste the query and insert into the database. As there is so many file names, kind of time-consuming doing it one by one.

is there any better way to acquire this?

Body:
"/.*?(\\d+).*?(\\d+)/is"  -- working too hard; instead:

"/(\d+).(\d+)/"

Since regexp is not anchored, there is no need for leading .*?

.*? is the same as.*`

I don't think you need the extra backslashes.

The separator between the numbers is strange.  I cannot really be zero-length, else the \d+ would have pick up the second string of digits.

/i is unnecessary since there are no letters.

Avoiding leading zeros seems unnecessary; MySQL will treat the string  '010' as ten, not eight.  (I suspect you were concerned that PHP would treate 010 as eight.)

The /s is probably unnecessary -- will there be multiple "lines"?


问:
Google Cloud Functions with ECONNRESET errors until I redeploy
I'm using Google Cloud Functions to:

Watch for a new Firebase entry

Download a file that's referenced in the Firebase entry

Generate a thumbnail based on that file.

Upload the thumbnail to the cloud bucket.

Unfortunately I'm getting ECONNRESET errors repeatedly on step 4, and the only way to fix it seems to be to redeploy the function. Any ideas how to further debug this?

Edit:

It seems like many times when this happens, when I try to deploy the function again, it errors, and I have to run the deploy twice. Is something hanging or something?

答:
Update May 9 2017

According to this thread, the google cloud nodejs API developers have made some changes to the defaults that are used when initializing that should solve these ECONNRESET socket issues.

From @stephen++ on github GoogleCloudPlatform/google-cloud-node issue 2254:

We have disabled the forever agent by default in Cloud Function
  environments. If you un- and re-install @google-cloud/storage, you
  will pick up the new behavior automatically. Thanks for all of the
  helpful debugging, everyone!

Older Post Follows:

The solution for me to similar ECONNRESET issues using storage on the cloud functions platform was to use npm:promise-retry, but set up your own retry strategy because the default of 10 retries is too many.

I reported an ECONNRESET issue with cloud functions to Google Support (which you might star if you are also getting ECONNRESET in this context but not in other contexts) and they replied with a "won't fix" that the behavior is expected.  Google support said the socket that the API client library uses to connect times out after a few minutes, and then when your cloud function tries to use it again you get ECONNRESET. They recommended adding autoRetry:true when initializing the storage API, but that did not help.

The ECONNRESETs happen on the read side too.  In both read and write cases promise-retry helps, and most of the time with only 1 retry needed to reset the bad socket.

So I wrote npm:pipe-to-storage to return a promise to do the retries, check md5, etc., but I haven't tested it with binary data, only text, so I don't know if you could use it with image files.  The calls would look like this:

```<code>const fs = require('fs');
const storage = require('@google-cloud/storage')();
const pipeToStorage = require('pipe-to-storage')(storage);
const source = ()=>(fs.createReadStream("/path/to/your/file/to/upload"));
pipeToStorage(source, bucketName, fileNameInBucket).then(//do next step);
</code>```

See also How do I read the contents of a new cloud storage file of type .json from within a cloud function?

Body:
Update May 9 2017

According to this thread, the google cloud nodejs API developers have made some changes to the defaults that are used when initializing that should solve these ECONNRESET socket issues.

From @stephen++ on github GoogleCloudPlatform/google-cloud-node issue 2254:

We have disabled the forever agent by default in Cloud Function
  environments. If you un- and re-install @google-cloud/storage, you
  will pick up the new behavior automatically. Thanks for all of the
  helpful debugging, everyone!

Older Post Follows:

The solution for me to similar ECONNRESET issues using storage on the cloud functions platform was to use npm:promise-retry, but set up your own retry strategy because the default of 10 retries is too many.

I reported an ECONNRESET issue with cloud functions to Google Support (which you might star if you are also getting ECONNRESET in this context but not in other contexts) and they replied with a "won't fix" that the behavior is expected.  Google support said the socket that the API client library uses to connect times out after a few minutes, and then when your cloud function tries to use it again you get ECONNRESET. They recommended adding autoRetry:true when initializing the storage API, but that did not help.

The ECONNRESETs happen on the read side too.  In both read and write cases promise-retry helps, and most of the time with only 1 retry needed to reset the bad socket.

So I wrote npm:pipe-to-storage to return a promise to do the retries, check md5, etc., but I haven't tested it with binary data, only text, so I don't know if you could use it with image files.  The calls would look like this:

const fs = require('fs');
const storage = require('@google-cloud/storage')();
const pipeToStorage = require('pipe-to-storage')(storage);
const source = ()=>(fs.createReadStream("/path/to/your/file/to/upload"));
pipeToStorage(source, bucketName, fileNameInBucket).then(//do next step);

See also How do I read the contents of a new cloud storage file of type .json from within a cloud function?