问:
How to connect login details in android from laravel project?
how to use login in android by getting the login details in database from Laravel project?</p>

答:
You can create an API (for example).

From your Android app, you make a request to your laravel project.


来源: stackexchange

问:
Android Studio Lower Sound than Original Soundtrack
I simply want to play an audio with mediaPlayer of Android Studio, but the sound which I hear is too lower than original sound track (Genymotion's emulator sound is at max volume)

Any idea?

```<code>ImageButton img_scream1 = (ImageButton) findViewById(R.id.imageButton_scare_1);
    img_scream1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaControl = MediaPlayer.create(java_sounds_scary.this,R.raw.scream1_sound);
            mediaControl.start();
        }
    });
</code>```

答:
`int maxVolume = 50;

`Then to set setVolume to any value in this range (0-49) you do this:

```<code>float log1=(float)(Math.log(maxVolume-currVolume)/Math.log(maxVolume));
yourMediaPlayer.setVolume(1-log1);
</code>```

Nice and easy! And DON'T use AudioManager to set volume! It will cause many side effects such as disabling silent mode, which will make your users mad!

ContentLicense: CC BY-SA 3.0

Body:
I simply want to play an audio with mediaPlayer of Android Studio, but the sound which I hear is too lower than original sound track (Genymotion's emulator sound is at max volume)

Any idea?

ImageButton img_scream1 = (ImageButton) findViewById(R.id.imageButton_scare_1);
    img_scream1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaControl = MediaPlayer.create(java_sounds_scary.this,R.raw.scream1_sound);
            mediaControl.start();
        }
    });

Body:
`int maxVolume = 50;

`Then to set setVolume to any value in this range (0-49) you do this:

float log1=(float)(Math.log(maxVolume-currVolume)/Math.log(maxVolume));
yourMediaPlayer.setVolume(1-log1);

Nice and easy! And DON'T use AudioManager to set volume! It will cause many side effects such as disabling silent mode, which will make your users mad!


问:
After changing PHP version, Joomla cannot connect to MySQL
I have Joomla 3.3.3 in a server where PHP 5.3.29 is installed.

I requested the hosting team (Hostgator) to install PHP 5.5.28 side by side.

When they told me the task was finished, I added these lines to the top of .htaccess file:

```<code># PHP 5.5
AddHandler application/x-httpd-php55 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php55/lib
</IfModule>
</code>```

After that, I tried to load the page and this error was shown, in both front end an in administration pages:

```<code>Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.
</code>```

If I remove the added lines in .htaccess, site works again.

What may be hapenning here?

答:
Typically, the most common reason for this problem (in your scenario) is when the mysql[i] package is not compatible with the version of PHP installed. Usually, the host takes care of the problem (I would bug them about it).

You can check the installation of mysqli on a Centos environment here: http://php.net/manual/en/mysqli.installation.php

Body:
I have Joomla 3.3.3 in a server where PHP 5.3.29 is installed.

I requested the hosting team (Hostgator) to install PHP 5.5.28 side by side.

When they told me the task was finished, I added these lines to the top of .htaccess file:

# PHP 5.5
AddHandler application/x-httpd-php55 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php55/lib
</IfModule>

After that, I tried to load the page and this error was shown, in both front end an in administration pages:

Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.

If I remove the added lines in .htaccess, site works again.

What may be hapenning here?


问:
Robot FrameworK: Unable to run robot scripts in ie, same script ran perfectly alright previous day, this is recurring now
Unable to run Robot Framework scripts:

Zoom size set to 100% but still this issue, same script ran yesterday perfectly fine. All of a sudden its failing to launch, now this issue is faced multiple times.

答:
You should first troubleshoot IEDriverServer, by launching it and then access with IE to http://localhost: or http://127.0.0.1:. You should see:

```<code>This is the initial start page for the WebDriver server.
</code>```

The port you tried, 52920 could be blocked.

Body:
You should first troubleshoot IEDriverServer, by launching it and then access with IE to http://localhost: or http://127.0.0.1:. You should see:

This is the initial start page for the WebDriver server.

The port you tried, 52920 could be blocked.


问:
Javascript ES6 Get JSON from URL (no jQuery)
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

```<code>var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});
</code>```

or without jQuery something like this:

```<code>function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</code>```

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

答:
What you want is the Fetch API, but the Fetch API is not a part of ES6 - it just happens to use Promises, which were standardised in ES6.

To get JSON from a URL with the Fetch API:

```<code>window.fetch('/path/to.json')
    .then(function(response){
        return response.json();
    }).then(function(json){
        return doSomethingWith(json);
    });
</code>```

If you need to support browsers which don’t have the Fetch API, Github has open sourced a polyfill.

Body:
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});

or without jQuery something like this:

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

Body:
What you want is the Fetch API, but the Fetch API is not a part of ES6 - it just happens to use Promises, which were standardised in ES6.

To get JSON from a URL with the Fetch API:

window.fetch('/path/to.json')
    .then(function(response){
        return response.json();
    }).then(function(json){
        return doSomethingWith(json);
    });

If you need to support browsers which don’t have the Fetch API, Github has open sourced a polyfill.


问:
Should I use libc::c_char or std::os::raw::c_char?
I am writing a FFI wrapper for Rust. I have seen usages of both libc::c_char and std::os::raw::c_char. My knowledge of C is very minimal and I wonder if there is any difference. What should I use if I would like to expose a string to Python via cffi?

答:
In addition to @Shepmaster's answer, I'd like to highlight the fact that libc does not depend on std.

Therefore, if you can't use std, you'll have to use libc.
This situation can be seen here.

Currently libc by default links to the standard library, but if you would instead like to use libc in a #![no_std] situation or crate you can request this via:

```<code>[dependencies]
libc = { version = "0.2", default-features = false }
</code>```

Body:
In addition to @Shepmaster's answer, I'd like to highlight the fact that libc does not depend on std.

Therefore, if you can't use std, you'll have to use libc.
This situation can be seen here.

Currently libc by default links to the standard library, but if you would instead like to use libc in a #![no_std] situation or crate you can request this via:

[dependencies]
libc = { version = "0.2", default-features = false }


问:
EASession, EAAccessoryDelegate and "ERROR - opening session failed"
I am working with External Accessory framework. I am encountering problems reestablishing EASession after app goes into background and then returns to foreground. If I terminate my app and relaunch, then Bluetooth connection is reestablished as one would expect. I suspect that there is some part of the teardown that I am missing - or which is not exposed (??).

[EAAccessoryManager sharedAccessoryManager] connectedAccessories]] is returning my connected accessory, and I am able to query it to get name, modelNumber, etc. However, the following line sets _session to nil.

```<code>_session = [[EASession alloc] initWithAccessory:_accessory forProtocol:_protocolString];
</code>```

Is there any way to diagnosis the reason for failed EASession initialization?

Is there some mantra for clearing out old EASession?

This question is related to this one - but I am not asking for advice on which path to follow. I am asking why this path has this large pitfall and how to navigate around it.

答:
As far as I can tell, there is no clearing out of old EASession instances. I can hypothesize, but I don't really know why this is. I suspect that the established EASession does not release its association with its accessory - and that this prevent subsequent EASession instances from being successfully associated with the same accessory.

I opted to leave EASession in tact when app resigns active. This seems to be working. In testing, I have connected to Bluetooth accessory, launched my app, accessed accessory, sent my app into background, disconnected/reconnected BT accessory, brought app to foreground and been able to access accessory again. This is as much as I could hope for.

One caveat: with iOS 4.0 it is possible to have more than one accessory. For example, a video cable and a Bluetooth device are both accessories.

ContentLicense: CC BY-SA 2.5

Body:
I am working with External Accessory framework. I am encountering problems reestablishing EASession after app goes into background and then returns to foreground. If I terminate my app and relaunch, then Bluetooth connection is reestablished as one would expect. I suspect that there is some part of the teardown that I am missing - or which is not exposed (??).

[EAAccessoryManager sharedAccessoryManager] connectedAccessories]] is returning my connected accessory, and I am able to query it to get name, modelNumber, etc. However, the following line sets _session to nil.

_session = [[EASession alloc] initWithAccessory:_accessory forProtocol:_protocolString];

Is there any way to diagnosis the reason for failed EASession initialization?

Is there some mantra for clearing out old EASession?

This question is related to this one - but I am not asking for advice on which path to follow. I am asking why this path has this large pitfall and how to navigate around it.


问:
Autolayout constraint mismatch In UITableViewCell
Create simple application for dynamic cell height.

I have Custom UITableViewCell and in that I have some controls. I have fixed the constraint of all the controls. Tableview not displaying any error after constraint set. Tableview runtime cell height is ok, but when I check the console log it gives me error as given below.

```<code>Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2017-06-08 17:54:22.184177+0530 Test[46461:306448] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>",
    "<NSLayoutConstraint:0x600000286810 V:|-(14)-[UILabel:0x7fe86bd1c4e0'Label']   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286860 V:[UILabel:0x7fe86bd1c4e0'Label']-(15)-|   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286cc0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fe86bd1c220.height == 49   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>
</code>```

Bellow is my TableView and its constraint.

Bellow is my TableView Code

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSString * strAction = arrActionList[indexPath.row];
    if ([strAction isEqualToString:@"More"]) {
        cell.lblActionHeight.constant = 50;
    }
    else{
        cell.lblActionHeight.constant = 20;
    }
    cell.lblAction.text = strAction;
    [cell.contentView layoutIfNeeded];
    return cell;
}
</code>```

Thanks in advance.

答:
If you dont want to give height constraint,you should give top,bottom,leading,trailing.

If you need height constraint, then you should give (leading,trailing,top,height) or (leading,trailing,centerY,height)

Make sure you return the proper height in the heightForRow method.

You need to specify estimated row height if you want to use UITableViewAutomaticDimension

In your case, estimatedRow height is the exact row height in the IB.

Body:
Create simple application for dynamic cell height.

I have Custom UITableViewCell and in that I have some controls. I have fixed the constraint of all the controls. Tableview not displaying any error after constraint set. Tableview runtime cell height is ok, but when I check the console log it gives me error as given below.

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2017-06-08 17:54:22.184177+0530 Test[46461:306448] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>",
    "<NSLayoutConstraint:0x600000286810 V:|-(14)-[UILabel:0x7fe86bd1c4e0'Label']   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286860 V:[UILabel:0x7fe86bd1c4e0'Label']-(15)-|   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286cc0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fe86bd1c220.height == 49   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>

Bellow is my TableView and its constraint.

Bellow is my TableView Code

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSString * strAction = arrActionList[indexPath.row];
    if ([strAction isEqualToString:@"More"]) {
        cell.lblActionHeight.constant = 50;
    }
    else{
        cell.lblActionHeight.constant = 20;
    }
    cell.lblAction.text = strAction;
    [cell.contentView layoutIfNeeded];
    return cell;
}

Thanks in advance.


问:
Delete variables based on their duplicate consecutive values in pandas
Suppose I have a dataframe in python with index, variable and value columns. I would like to delete the rows in which the variable has the same value as a previous instant. In other words, I would like to get another dataframe with variables whose values are changing. Example,

Original dataframe:

```<code>Index  var  val
0      x1   10
1      x2   11
2      x1   10
3      x3   12
4      x1   13
5      x3   14
6      x2   12
7      x1   14
</code>```

Output table:

```<code>Index  var  val
0      x1   10
1      x2   11
2      x3   12
3      x1   13
4      x3   14
5      x2   12
6      x1   14
</code>```

What would be the most efficient way to do this?, imagine if I have a lot of variables (1000).

Cheers.

答:
I found a step by step way which creates a few True False 'helper' columns, after sorting and then finally reindexes it and returns just the desired columns.</p>

```<code>df = df.sort_values(['var', 'val'])
df['original_index'] = df.index
df = df.reset_index()
df['varHasChanged'] = df['var'] != df['var'].shift(+1)
df['valhasChanged'] = df['val'] != df['val'].shift(+1)
df = df[~((df.varHasChanged == False) & (df.valhasChanged == False))]
df = df.sort_values(['Index'])
df = df.set_index(['Index'])
df = df[['var', 'val']]
df
</code>```

Body:
Suppose I have a dataframe in python with index, variable and value columns. I would like to delete the rows in which the variable has the same value as a previous instant. In other words, I would like to get another dataframe with variables whose values are changing. Example,

Original dataframe:

Index  var  val
0      x1   10
1      x2   11
2      x1   10
3      x3   12
4      x1   13
5      x3   14
6      x2   12
7      x1   14

Output table:

Index  var  val
0      x1   10
1      x2   11
2      x3   12
3      x1   13
4      x3   14
5      x2   12
6      x1   14

What would be the most efficient way to do this?, imagine if I have a lot of variables (1000).

Cheers.

Body:
I found a step by step way which creates a few True False 'helper' columns, after sorting and then finally reindexes it and returns just the desired columns.

df = df.sort_values(['var', 'val'])
df['original_index'] = df.index
df = df.reset_index()
df['varHasChanged'] = df['var'] != df['var'].shift(+1)
df['valhasChanged'] = df['val'] != df['val'].shift(+1)
df = df[~((df.varHasChanged == False) & (df.valhasChanged == False))]
df = df.sort_values(['Index'])
df = df.set_index(['Index'])
df = df[['var', 'val']]
df


问:
stuck at "Getting org.scala-sbt sbt 0.13.6 ..." when running sbt in terminal
Similar problem with How to use sbt behind authenticated proxy?. I tried with the given answer and problem still there.

When I run sbt in terminal, it shows and stucks at :

```<code>Getting org.scala-sbt sbt 0.13.6 ...
</code>```

additional information:

```<code> sbt --version
 sbt launcher version 0.13.6
</code>```

How could I fix it?

答:
It's quite a late answer, but I encountered the same problem working behind a proxy. If this is your case, you should run export JAVA_OPTS="$JAVA_OPTS
-Dhttp.proxyHost=<your-proxy> -Dhttp.proxyPort=<your-proxy-port>" before running sbt.

If you are still unsure if it's going ahead with the downloading, you should try launching sbt with the verbose option sbt -v, as suggested by @evan912. If you had a problem with the proxy, after setting it you should see some [info] downloading logging on your console.

Body:
Similar problem with How to use sbt behind authenticated proxy?. I tried with the given answer and problem still there.

When I run sbt in terminal, it shows and stucks at :

Getting org.scala-sbt sbt 0.13.6 ...

additional information:

 sbt --version
 sbt launcher version 0.13.6

How could I fix it?


问:
AngularJS Unknown Provider Error Message
I have an angular app that will not load and is returning the error message:

Error: [$injector:unpr] Unknown provider: navigatorProvider <-
  navigator <- LayoutController

This is ever since I introduced a service I have this registered on the controller, but it still not working. The controller referenced is:

```<code>(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "navigator"];

    function LayoutController($scope, navigator){
        var layout = this;

        // Layout
        layout.loadTemplate = function() {
            return navigator.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }

})();
</code>```

This is the service:

```<code>(function() {

    var navigator = angular.module('navigator', []);
    navigator.factory('loadTemplate', function () {
        var loadTemplate = this;

        // Page Directory
        navigator.login = "templates/login.html";
        navigator.dashboard = "templates/dashboard.html";
        navigator.job = "templates/job.html";

        // Template switcher
        navigator.loadTemplate = function () {
            return navigator.login;
        }

        return loadTemplate;
    });

}());
</code>```

And the app page just in case I've missed something there:

```<code>(function () {
    'use strict';

    angular.module('HtJobPortal', []);
})();
</code>```

答:
You are add the dependencies when defining the HtJobPortal module

```<code>//define dependencies
angular.module('HtJobPortal', ['navigator']);
</code>```

In the controller, you need to inject the factory in controller

```<code>(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "loadTemplate"];

    function LayoutController($scope, loadTemplate){
        var layout = this;
        // Layout
        layout.loadTemplate = function() {
            return loadTemplate.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }
})();
</code>```

And define factory as

```<code>(function () {
    angular.module('navigator', []).factory('loadTemplate', function () {
        // Page Directory
        var login = "templates/login.html";
        var dashboard = "templates/dashboard.html";
        var job = "templates/job.html";

        return {
            // Template switcher
            loadTemplate: function () {
                return login;
            }
        };
    });
})();
</code>```

Body:
I have an angular app that will not load and is returning the error message:

Error: [$injector:unpr] Unknown provider: navigatorProvider <-
  navigator <- LayoutController

This is ever since I introduced a service I have this registered on the controller, but it still not working. The controller referenced is:

(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "navigator"];

    function LayoutController($scope, navigator){
        var layout = this;

        // Layout
        layout.loadTemplate = function() {
            return navigator.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }

})();

This is the service:

(function() {

    var navigator = angular.module('navigator', []);
    navigator.factory('loadTemplate', function () {
        var loadTemplate = this;

        // Page Directory
        navigator.login = "templates/login.html";
        navigator.dashboard = "templates/dashboard.html";
        navigator.job = "templates/job.html";

        // Template switcher
        navigator.loadTemplate = function () {
            return navigator.login;
        }

        return loadTemplate;
    });

}());

And the app page just in case I've missed something there:

(function () {
    'use strict';

    angular.module('HtJobPortal', []);
})();

Body:
You are add the dependencies when defining the HtJobPortal module

//define dependencies
angular.module('HtJobPortal', ['navigator']);

In the controller, you need to inject the factory in controller

(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "loadTemplate"];

    function LayoutController($scope, loadTemplate){
        var layout = this;
        // Layout
        layout.loadTemplate = function() {
            return loadTemplate.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }
})();

And define factory as

(function () {
    angular.module('navigator', []).factory('loadTemplate', function () {
        // Page Directory
        var login = "templates/login.html";
        var dashboard = "templates/dashboard.html";
        var job = "templates/job.html";

        return {
            // Template switcher
            loadTemplate: function () {
                return login;
            }
        };
    });
})();


问:
Incremental Google OAuth with Asp.Net Owin Oauth
I'm looking for a solution to doing incremental authorization against Google's api's with Asp.Net's Owin OAuth Libraries.

I know how to set scope for specific api's, but I would like to do it incrementally and can only see how to set it on globally.

Doc on Google Oauth Incremental Auth...
https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth

Current VB Code...

```<code>Public Sub ConfigureAuth(app As IAppBuilder)

    Dim googleCreds = New GoogleOAuth2AuthenticationOptions() With {
                .ClientId = "xxxx",
                .ClientSecret = "xxx"
    }

    googleCreds.Scope.Add("https://www.googleapis.com/auth/analytics.readonly")
    app.UseGoogleAuthentication(googleCreds)

    ' Would like to add another way to specify GoogleDrive, YouTube, Google+ scopes
    ' Example code that doesn't work that would add a 2nd Google Oauth Listener
    googleCreds.Scope.Clear()
    googleCreds.Scope.Add("https://www.googleapis.com/auth/drive.file")
    googleCreds.AuthenticationType = "GoogleDrive"
    app.UseGoogleAuthentication(googleCreds)

End Class
</code>```

答:
In OWIN version 3.1 incremental authentication works as expected. (It may well work in earlier versions, I've not tested that).

There were two tricks that were necessary to get this working:

OWIN expects a 401

If you try and call:

```<code>var ctx = HttpContext.Current.Request.GetOwinContext();
var properties = new AuthenticationProperties
{
    RedirectUri = "/your/redirect",
};

ctx.Authentication.Challenge(properties, "Google");
</code>```

While logged in to your application, the call to Google from the Middleware will not happen.

This can be confusing, since it just works, when using the exact same code during login.

The reason is that the Middleware only works when the current HTTP response is 401, so after the call above you need something like:

```<code>Page.Response.StatusCode = 401;
Page.Response.End();
</code>```

Specification of scopes is picky

In my original code to try and call with a new scope, I had something like this:

```<code>var ctx = HttpContext.Current.Request.GetOwinContext();
var properties = new AuthenticationProperties
{
    RedirectUri = redirect,
};

properties.Dictionary["scope"] ="https://www.googleapis.com/auth/calendar.readonly";
</code>```

This was calling Google as expected and Goggle was correctly challenging based on the requested scopes, but then the response back to my server was breaking (never did find out where).

What I found I needed to do was to resend all my base scopes as well:

```<code>var scopes = new List<string>
{
    "https://www.googleapis.com/auth/plus.me",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
};

if (additionalScopes != null)
{
    scopes = scopes.Union(additionalScopes).ToList();
}

properties.Dictionary["scope"] = string.Join(" ", scopes);
</code>```

Body:
I'm looking for a solution to doing incremental authorization against Google's api's with Asp.Net's Owin OAuth Libraries.

I know how to set scope for specific api's, but I would like to do it incrementally and can only see how to set it on globally.

Doc on Google Oauth Incremental Auth...
https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth

Current VB Code...

Public Sub ConfigureAuth(app As IAppBuilder)

    Dim googleCreds = New GoogleOAuth2AuthenticationOptions() With {
                .ClientId = "xxxx",
                .ClientSecret = "xxx"
    }

    googleCreds.Scope.Add("https://www.googleapis.com/auth/analytics.readonly")
    app.UseGoogleAuthentication(googleCreds)

    ' Would like to add another way to specify GoogleDrive, YouTube, Google+ scopes
    ' Example code that doesn't work that would add a 2nd Google Oauth Listener
    googleCreds.Scope.Clear()
    googleCreds.Scope.Add("https://www.googleapis.com/auth/drive.file")
    googleCreds.AuthenticationType = "GoogleDrive"
    app.UseGoogleAuthentication(googleCreds)

End Class

Body:
In OWIN version 3.1 incremental authentication works as expected. (It may well work in earlier versions, I've not tested that).

There were two tricks that were necessary to get this working:

OWIN expects a 401

If you try and call:

var ctx = HttpContext.Current.Request.GetOwinContext();
var properties = new AuthenticationProperties
{
    RedirectUri = "/your/redirect",
};

ctx.Authentication.Challenge(properties, "Google");

While logged in to your application, the call to Google from the Middleware will not happen.

This can be confusing, since it just works, when using the exact same code during login.

The reason is that the Middleware only works when the current HTTP response is 401, so after the call above you need something like:

Page.Response.StatusCode = 401;
Page.Response.End();

Specification of scopes is picky

In my original code to try and call with a new scope, I had something like this:

var ctx = HttpContext.Current.Request.GetOwinContext();
var properties = new AuthenticationProperties
{
    RedirectUri = redirect,
};

properties.Dictionary["scope"] ="https://www.googleapis.com/auth/calendar.readonly";

This was calling Google as expected and Goggle was correctly challenging based on the requested scopes, but then the response back to my server was breaking (never did find out where).

What I found I needed to do was to resend all my base scopes as well:

var scopes = new List<string>
{
    "https://www.googleapis.com/auth/plus.me",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
};

if (additionalScopes != null)
{
    scopes = scopes.Union(additionalScopes).ToList();
}

properties.Dictionary["scope"] = string.Join(" ", scopes);


问:
Bootstrap modal appearing under background
I have used the code for my modal straight from the Bootstrap example, and have included only the bootstrap.js (and not bootstrap-modal.js). However, my modal is appearing underneath the grey fade (backdrop) and is non editable.

Here's what it looks like:

See this fiddle for one way  to reproduce this problem. The basic structure of that code is like this:

Lorem ipsum dolor sit amet.

        This container contains the modal code.

Modal

```

<pre class="lang-css prettyprint-override"><code>body {
    padding-top: 50px;
}

.my-module {
    position: fixed;
    top: 0;
    left: 0;
}
</code>```

Any ideas why this is or what I can do to fix this?

答:
I had some problem like this on Iphone and Ipad using Sharepoint 2013
Modal bootstrap keep z-index problems with backdrop.

I just use this on JS :

$('#myModal').on('shown.bs.modal', function() {
   //To relate the z-index make sure backdrop and modal are siblings
   $(this).before($('.modal-backdrop'));
   //Now set z-index of modal greater than backdrop
   $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
}); ```

Body:
I have used the code for my modal straight from the Bootstrap example, and have included only the bootstrap.js (and not bootstrap-modal.js). However, my modal is appearing underneath the grey fade (backdrop) and is non editable.

Here's what it looks like:

See this fiddle for one way  to reproduce this problem. The basic structure of that code is like this:

Lorem ipsum dolor sit amet.

        This container contains the modal code.

Modal

body {
    padding-top: 50px;
}

.my-module {
    position: fixed;
    top: 0;
    left: 0;
}

Any ideas why this is or what I can do to fix this?


问:
C#, Using Main variables in methods without passing parameters?
How can I use a variable/const, declared in Main, inside another method?
Without passing it like: static string my_method(string my_variable_to_pass)
Just using static void my_method()

What I want is to call any other method into Main and it has to use the variable declared in Main.

I do not want to use public static class either because it does not seem the proper way.
Is there another way?

Here is an example of what I want. This code does not work because "cats does not exist in the current contend" inside test_method().
But how could I make it work without adding too complicated code?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        string cats;

        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}
</code>```

答:
I think a number of the answers here are missing a valid point - the program has to be static, your functionality probably shouldnt be!</p>

```<code>public class CatStuff
{
    private int cats;
    public CatStuff(int howManyCats)
    {
        this.cats = howManyCats;
    }

    public void TestMethod()
    {
        Console.WriteLine("{0} cats", this.cats);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cats1 = new CatStuff(1000);
        cats1.TestMethod();

         var cats2 = new CatStuff(6);
        cats2.TestMethod();
    }
}
</code>```

Body:
How can I use a variable/const, declared in Main, inside another method?
Without passing it like: static string my_method(string my_variable_to_pass)
Just using static void my_method()

What I want is to call any other method into Main and it has to use the variable declared in Main.

I do not want to use public static class either because it does not seem the proper way.
Is there another way?

Here is an example of what I want. This code does not work because "cats does not exist in the current contend" inside test_method().
But how could I make it work without adding too complicated code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        string cats;

        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}

Body:
I think a number of the answers here are missing a valid point - the program has to be static, your functionality probably shouldnt be!

public class CatStuff
{
    private int cats;
    public CatStuff(int howManyCats)
    {
        this.cats = howManyCats;
    }

    public void TestMethod()
    {
        Console.WriteLine("{0} cats", this.cats);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cats1 = new CatStuff(1000);
        cats1.TestMethod();

         var cats2 = new CatStuff(6);
        cats2.TestMethod();
    }
}


问:
how to put quotes properly in Ansible tasks
i am using following code in ansible tasks

```<code>- name: Check the status of application server {{ server }}
  command: /opt/serverStatus.sh {{ server }}
  register: url

- debug: msg="{{ url.stdout }}"

- name: start the application server
  command: /opt/startServer.sh {{ server }}
  when: msg | match("It appears to be stopped.")
</code>```

getting following error :

fatal: server: FAILED! => {"failed": true, "msg": "The conditional check 'msg | match(\"It appears to be stopped.\")' failed. The error was: Unexpected templating type error occurred on ({% if msg | match(\"It appears to be stopped.\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/abc/xyz/roles/was/tasks/main.yml': line 28, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: start the application server\n  ^ here\n"}

please help where i am doing wrong. any quotes missing ?

答:
This happens because msg is undefined. You want to use:

```<code>- name: start the application server
  command: /opt/startServer.sh {{ server }}
  when: url.stdout | match("It appears to be stopped.")
</code>```

Body:
i am using following code in ansible tasks

- name: Check the status of application server {{ server }}
  command: /opt/serverStatus.sh {{ server }}
  register: url

- debug: msg="{{ url.stdout }}"

- name: start the application server
  command: /opt/startServer.sh {{ server }}
  when: msg | match("It appears to be stopped.")

getting following error :

fatal: server: FAILED! => {"failed": true, "msg": "The conditional check 'msg | match(\"It appears to be stopped.\")' failed. The error was: Unexpected templating type error occurred on ({% if msg | match(\"It appears to be stopped.\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/abc/xyz/roles/was/tasks/main.yml': line 28, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: start the application server\n  ^ here\n"}

please help where i am doing wrong. any quotes missing ?

Body:
This happens because msg is undefined. You want to use:

- name: start the application server
  command: /opt/startServer.sh {{ server }}
  when: url.stdout | match("It appears to be stopped.")


问:
GWT bookmarket or GWT as an external library
I simply want to load a GWT(Google Web Toolkit) app by adding a script tag to the DOM, however because the GWT linker uses document.write() I'm unable to find any good way of doing so. I've found some hacks for doing so on various blog posts but they all seem to fail with the latest version of GWT. Any reasonably non-invasive approach for doing this come to mind?

Clarification:

Normal way to start up a GWT app, in your host html page:

```<code><script type="text/javascript" language="javascript" src="myapp.nocache.js"></script>
</code>```

This, of course, starts up as soon as the page loads. I want to do it at a later time:

```<code>function startapp() {
    var head = document.getElementsByTagName('head');
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', 'myapp.nocache.js');
    head[0].appendChild(s);
}
</code>```

答:
Whenever a browser loads a javascript file, its also execute every line of it inorder to build the symbol tables etc.

In your case, the app loads in the browser and after the dom is loaded, your GWT module js gets loaded. At this point, the browser will try to execute every line of the GWT module javascript, possibly causing your earlier loaded DOM to go for a toss.

What exactly is your use case? If your requirement is conditionally loading the GWT module then your could try something like this:
Include this in your head:

```<code><script src="gwtmoduleloader.js"></script>
</code>```

Here, gwtmoduleloader.js is infact a servlet that will hold logic to figure out if the gwt module is to be loaded.

If the GWT module is to be loaded, the sevlet can print a

```<code>document.write('<script src="myapp.nocache.js"></script>')
</code>```

or else return silently.

When browser evaluates the contents of gwtmoduleloader.js, it may find a document.write for another script (in your case the gwt module), which it will load and evaluate. This is thus a conditional load and can be achieved before the body begins loading.

Is this what you were looking for?

ContentLicense: CC BY-SA 4.0

Body:
I simply want to load a GWT(Google Web Toolkit) app by adding a script tag to the DOM, however because the GWT linker uses document.write() I'm unable to find any good way of doing so. I've found some hacks for doing so on various blog posts but they all seem to fail with the latest version of GWT. Any reasonably non-invasive approach for doing this come to mind?

Clarification:

Normal way to start up a GWT app, in your host html page:

This, of course, starts up as soon as the page loads. I want to do it at a later time:

function startapp() {
    var head = document.getElementsByTagName('head');
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', 'myapp.nocache.js');
    head[0].appendChild(s);
}

Body:
Whenever a browser loads a javascript file, its also execute every line of it inorder to build the symbol tables etc.

In your case, the app loads in the browser and after the dom is loaded, your GWT module js gets loaded. At this point, the browser will try to execute every line of the GWT module javascript, possibly causing your earlier loaded DOM to go for a toss.

What exactly is your use case? If your requirement is conditionally loading the GWT module then your could try something like this:
Include this in your head:

<script src="gwtmoduleloader.js"></script>

Here, gwtmoduleloader.js is infact a servlet that will hold logic to figure out if the gwt module is to be loaded.

If the GWT module is to be loaded, the sevlet can print a

document.write('<script src="myapp.nocache.js"></script>')

or else return silently.

When browser evaluates the contents of gwtmoduleloader.js, it may find a document.write for another script (in your case the gwt module), which it will load and evaluate. This is thus a conditional load and can be achieved before the body begins loading.

Is this what you were looking for?


问:
How to skip wrapping to Try if the argument is already a Try-instance?
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

```<code>def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
</code>```

but that does not compile due to type erasure with the compilation error

```<code>Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^
</code>```

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

```<code>object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}
</code>```

But that does not compile due to ambiguity with the following compiler error:

```<code>Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^
</code>```

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

```<code>class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }
</code>```

This allows me to write tests like the following one:

```<code>"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }
</code>```

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

答:
I would go with specialised implicits here:

```<code>object Helpers {
  implicit class TryConverter[T](obj: => T) {
    def asTry: Try[T] = Try(obj)
  }

  implicit class TryIdentity[T](obj: => Try[T]) {
    def asTry: Try[T] = obj
  }
}
</code>```

Now the compiler can do its type magic for you.

```<code>import Helpers._
</code>```

And then call .asTry anywhere you need to. You should not intermediate this with something that returns Any though, why lose type specialisation  voluntarily?

Body:
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg

but that does not compile due to type erasure with the compilation error

Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}

But that does not compile due to ambiguity with the following compiler error:

Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }

This allows me to write tests like the following one:

"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

Body:
I would go with specialised implicits here:

object Helpers {
  implicit class TryConverter[T](obj: => T) {
    def asTry: Try[T] = Try(obj)
  }

  implicit class TryIdentity[T](obj: => Try[T]) {
    def asTry: Try[T] = obj
  }
}

Now the compiler can do its type magic for you.

import Helpers._

And then call .asTry anywhere you need to. You should not intermediate this with something that returns Any though, why lose type specialisation  voluntarily?


问:
How to query on multiple date using TABLE_QUERY() in Big Query
I want to query on these tables using table_query(). How can I query on all the tables with date range from 2017-03-22 to 2017-03-24.

Format of my BQ tables is (auctions_other_YYYYMMDDHHM)

BQ tables are listed below:

1.auctions_other_20170322104

  2.auctions_other_20170322105

  3.auctions_other_20170323206

  4.auctions_other_20170323207

  5.auctions_other_20170324108

  6.auctions_other_20170324209

I am using query:

```<code>SELECT  * FROM
TABLE_QUERY(chocolate_raw, "table_id contains 'auctions_others_' and
table_id contains '20170322104' and  table_id contains '20170324209'
")
WHERE
  id='f3667fd6-8329-4124-a4a2-737e637a5e7d'
</code>```

Getting Error:

FROM clause with table wildcards matches no table

答:
First of all use standard SQL (it's easier/neater). Because you have the hour and minute suffixed, it makes it a little trickier, but something like this should work:</p>

```<code>#standardSQL
SELECT
  *
FROM
  `<dataset>.auctions_other_*`
WHERE
  _TABLE_SUFFIX LIKE '20170322%'
  OR _TABLE_SUFFIX LIKE '20170323%'
  OR _TABLE_SUFFIX LIKE '20170324%'
</code>```

Body:
I want to query on these tables using table_query(). How can I query on all the tables with date range from 2017-03-22 to 2017-03-24.

Format of my BQ tables is (auctions_other_YYYYMMDDHHM)

BQ tables are listed below:

1.auctions_other_20170322104

  2.auctions_other_20170322105

  3.auctions_other_20170323206

  4.auctions_other_20170323207

  5.auctions_other_20170324108

  6.auctions_other_20170324209

I am using query:

SELECT  * FROM
TABLE_QUERY(chocolate_raw, "table_id contains 'auctions_others_' and
table_id contains '20170322104' and  table_id contains '20170324209'
")
WHERE
  id='f3667fd6-8329-4124-a4a2-737e637a5e7d'

Getting Error:

FROM clause with table wildcards matches no table

Body:
First of all use standard SQL (it's easier/neater). Because you have the hour and minute suffixed, it makes it a little trickier, but something like this should work:

#standardSQL
SELECT
  *
FROM
  `<dataset>.auctions_other_*`
WHERE
  _TABLE_SUFFIX LIKE '20170322%'
  OR _TABLE_SUFFIX LIKE '20170323%'
  OR _TABLE_SUFFIX LIKE '20170324%'


问:
Error with place holder on jsx
I have a simple react HTML input component and as it used on different sections/pages, I added some props for styling it and its placeholder. The problem is that sometimes I got an error on the compilation(we are using nextjs).
This the code:

```<code>{placeHolderColor && (<style jsx>{`input::placeholder{color:${placeHolderColor}}`}</style>)}
</code>```

Basically, I'm using an inline If with Logical && Operator inside the render function to check if the prop placeHolderColor exists, and if exist add the style tag.

The error I'm getting:

Warning: Unknown prop jsx on  tag. Remove this prop from the element.

The error only occurs when you reload the page. If you made a change and the hot code reloading run, there is no error. Not sure if the problem is the var inside the literal, the '::placeholder' pseudo-element or what. The code works anyway, and if the placeHolderColor var is defined the style is applied.

答:
When I tested your code I got the same error(also on page load). After that I talked to a styled jsx dev with nickname @g (on github @giuseppeg) on ZEIT's #next slack channel https://zeit.chat/ and he confirmed that the conditional use of

I've got this error:

Module build failed: SyntaxError: Expected placeHolderColor to not come from the closest scope.
  Styled JSX encourages the use of constants instead of props or dynamic values which are better set via inline styles or className toggling. See https://github.com/zeit/styled-jsx#dynamic-styles.

According to recommendations from https://github.com/zeit/styled-jsx#dynamic-styles, you basically should not add dynamic values into template literals inside

);
```

and render it like <InputWithColouredPlaceholder placeholderColourClass="reddy" />

It gets more complicated in case of large range of possible colours though. In this case I would recommend to ask for suggestions in #next channel on ZEIT's slack https://zeit.chat/.

UPDATE
Using constants and constant expressions in template literals should work in styled-jsx 1.0.4 (but nextjs currently depends on 1.0.3, and separate installation of styled-jsx will not help, so wait for update of nextjs to support styled jsx 1.0.4). It means that any constants that are not passed trough props and not created inside component should work (for example you can have a js file with constants for colours and import them into your input component). But it does not fit your case because you need a dynamic way.

Title: Error with place holder on jsx

Body:
I have a simple react HTML input component and as it used on different sections/pages, I added some props for styling it and its placeholder. The problem is that sometimes I got an error on the compilation(we are using nextjs).
This the code:

{placeHolderColor && ()}

Basically, I'm using an inline If with Logical && Operator inside the render function to check if the prop placeHolderColor exists, and if exist add the style tag.

The error I'm getting:

Warning: Unknown prop jsx on  tag. Remove this prop from the element.

The error only occurs when you reload the page. If you made a change and the hot code reloading run, there is no error. Not sure if the problem is the var inside the literal, the '::placeholder' pseudo-element or what. The code works anyway, and if the placeHolderColor var is defined the style is applied.

Body:
When I tested your code I got the same error(also on page load). After that I talked to a styled jsx dev with nickname @g (on github @giuseppeg) on ZEIT's #next slack channel https://zeit.chat/ and he confirmed that the conditional use of <style jsx> tag is not supported. Here is his explanation https://github.com/zeit/styled-jsx/issues/233.

Also, after removing conditional and just inserting your tag like this:

<style jsx>{'input::placeholder{color:${placeHolderColor}}'}</style>

I've got this error:

Module build failed: SyntaxError: Expected placeHolderColor to not come from the closest scope.
  Styled JSX encourages the use of constants instead of props or dynamic values which are better set via inline styles or className toggling. See https://github.com/zeit/styled-jsx#dynamic-styles.

According to recommendations from https://github.com/zeit/styled-jsx#dynamic-styles, you basically should not add dynamic values into template literals inside <style jsx> tag (though you can put there constants and constant expressions starting from version 1.0.4 (see UPDATE at the bottom of the answer for details)). The reason behind the prohibition of using props/dynamic values, according to @giuseppeg comment in the slack thread https://zeit-community.slack.com/archives/C2U01UYEA/p1496928897076534, is following: "at the moment styled-jsx compiles and produces static code and therefore the hashes that make the final CSS unique won't change when the value of a variable like color changes"

So, as you see from documentation, it is recommended to use dynamic values via inline styles or className toggling. Unfortunately, styling pseudo-elements (placeholder etc.) in not possible via inline styles in React, so if you have finite number of possible colours then create a class for each colour case and use it like this:

const InputWithColouredPlaceholder = props => (
  <div>
    <input
      placeholder="text"
      className={
        'placeholderColourClass' in props && props.placeholderColourClass
      }
    />
    <style jsx>{`
       .reddy::placeholder {
         color: red;
       }
       .greeny::placeholder {
         color: green;
       }
     `}</style>
  </div>
);

and render it like <InputWithColouredPlaceholder placeholderColourClass="reddy" />

It gets more complicated in case of large range of possible colours though. In this case I would recommend to ask for suggestions in #next channel on ZEIT's slack https://zeit.chat/.

UPDATE
Using constants and constant expressions in template literals should work in styled-jsx 1.0.4 (but nextjs currently depends on 1.0.3, and separate installation of styled-jsx will not help, so wait for update of nextjs to support styled jsx 1.0.4). It means that any constants that are not passed trough props and not created inside component should work (for example you can have a js file with constants for colours and import them into your input component). But it does not fit your case because you need a dynamic way.


问:
Simple Javascript Regex Question
Google is failing me because ?= is not searchable.  What does

```<code>(?=[aeiouy])
</code>```

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.

答: ?= is the positive lookahead syntax, it matches anything followed by a vowel here.

Title: Simple Javascript Regex Question

Body:
Google is failing me because ?= is not searchable.  What does

(?=[aeiouy])

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.


问:
Where to store values calculated from props in React
What is the best place to store the result of an expensive calculation from the React props which I use in render() but do not want to execute at each render() ?

```<code>constructor(props) {
    super(props)
    const result = this.doExpensiveCalculation(props)
}

componentWillReceiveProps(nextProps) {
    // if nextProps differ from props
    const result = this.doExpensiveCalculation(nextProps)
}

doExpensiveCalculation(props) {
   // Some expensive stuff
}

render(){
    // Use doExpensiveCalculation(this.props) here
}
</code>```

The options are this and state but both I see rather unsatisfying. Is there a ready solution which uses memoisation?

On the other hand, should I worry about optimizing this ? I read that React can rerender component even if the props have not changed but does this happen often ?

答:
You can handle the re-rendering in the lifecycle method of shouldComponentUpdate. Default value is always return true. By returning false there React will not re-render the component.

See the docs for more. Besides that, React only updates if a state change occurs since props are read-only.

Your options are to store it as you suggested or have a class with a static field to keep it there.

Body:
What is the best place to store the result of an expensive calculation from the React props which I use in render() but do not want to execute at each render() ?

constructor(props) {
    super(props)
    const result = this.doExpensiveCalculation(props)
}

componentWillReceiveProps(nextProps) {
    // if nextProps differ from props
    const result = this.doExpensiveCalculation(nextProps)
}

doExpensiveCalculation(props) {
   // Some expensive stuff
}

render(){
    // Use doExpensiveCalculation(this.props) here
}

The options are this and state but both I see rather unsatisfying. Is there a ready solution which uses memoisation?

On the other hand, should I worry about optimizing this ? I read that React can rerender component even if the props have not changed but does this happen often ?


问:
Include/require file from Flysystem
My PHP application dynamically generates some script files that are later run by using require or include.

I'm now in the process of migrating my production server to Amazon Web Services, to get scaling and load balancing. This means that the generated script files should no longer be stored in the local file system, but rather in an S3 bucket.

Therefore I would like to use Flysystem, so I don't have to think about whether the files are stored locally (development) or in an S3 bucket (production).

But how do I require or include a file from Flysystem? Do I have to get the file content and then eval it?

答:
Local storage:

```<code>use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;

$adapter = new Local(__DIR__.'/path/to/root');
$localFilesystem = new Filesystem($adapter);
</code>```

S3 Storage:

```<code>use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;

$client = S3Client::factory([
    'credentials' => [
        'key'    => 'your-key',
        'secret' => 'your-secret',
    ],
    'region' => 'your-region',
    'version' => 'latest|version',
]);

$adapter = new AwsS3Adapter($client, 'your-bucket-name', 'optional/path/prefix');
$s3Filesystem = new Filesystem($adapter);
</code>```

Then, open your file with one, and write to the other:

```<code>$contents = $localFilesystem->read('path/to/file.txt');
$s3Filesystem->write('path/to/file.txt', $contents);
</code>```

You shouldn't need to require, include, or eval anything! Hope this helps!

Title: Include/require file from Flysystem

Body:
Local storage:

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;

$adapter = new Local(__DIR__.'/path/to/root');
$localFilesystem = new Filesystem($adapter);

S3 Storage:

use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;

$client = S3Client::factory([
    'credentials' => [
        'key'    => 'your-key',
        'secret' => 'your-secret',
    ],
    'region' => 'your-region',
    'version' => 'latest|version',
]);

$adapter = new AwsS3Adapter($client, 'your-bucket-name', 'optional/path/prefix');
$s3Filesystem = new Filesystem($adapter);

Then, open your file with one, and write to the other:

$contents = $localFilesystem->read('path/to/file.txt');
$s3Filesystem->write('path/to/file.txt', $contents);

You shouldn't need to require, include, or eval anything! Hope this helps!


问:
Binomial test in Python vs R
I am trying to re-implement a binomial test initialy developed in R with Python. However, I am not sure if I am using the right functionality.

In R, I get:

```<code>> binom.test (2, 8, 11/2364, alternative = "greater")
0.25
</code>```

With Python & SciPy, I use

```<code>from scipy.stats import binom
binom.sf(2, 8, float(11)/float(2364))
5.5441613055814931e-06
</code>```

In fact I have to do binom.sf(2, 8, float(11)/float(2364)) to make sure the third parameter is not 0 because of int division.

Why do the values differ? Do I have to specify the moments for Scipy / binom.sf?
Should I use some other library?

答:
Here's what I get in R:

```<code>> binom.test(2, 8, 11/2364, alternative = "greater")

    Exact binomial test

data:  2 and 8
number of successes = 2, number of trials = 8, p-value = 0.0005951
alternative hypothesis: true probability of success is greater than 0.00465313
95 percent confidence interval:
 0.04638926 1.00000000
sample estimates:
probability of success
                  0.25

>
</code>```

Note that the p-value is 0.0005951.

Compare that to the result of scipy.stats.binom_test (which returns just the p-value):

```<code>In [25]: from scipy.stats import binom_test

In [26]: binom_test(2, 8, 11/2364, alternative='greater')
Out[26]: 0.00059505960517880572
</code>```

So that agrees with R.

To use the survival function of scipy.stats.binom, you have to adjust the first argument (as noted in a comment by Marius):

```<code>In [27]: from scipy.stats import binom

In [28]: binom.sf(1, 8, 11/2364)
Out[28]: 0.00059505960517880572
</code>```

(I am using Python 3, so 11/2364 equals 0.004653130287648054.  If you are using Python 2, be sure to write that fraction as 11.0/2364 or float(11)/2364.)

Title: Binomial test in Python vs R

Body:
I am trying to re-implement a binomial test initialy developed in R with Python. However, I am not sure if I am using the right functionality.

In R, I get:

> binom.test (2, 8, 11/2364, alternative = "greater")
0.25

With Python & SciPy, I use

from scipy.stats import binom
binom.sf(2, 8, float(11)/float(2364))
5.5441613055814931e-06

In fact I have to do binom.sf(2, 8, float(11)/float(2364)) to make sure the third parameter is not 0 because of int division.

Why do the values differ? Do I have to specify the moments for Scipy / binom.sf?
Should I use some other library?

Body:
Here's what I get in R:

> binom.test(2, 8, 11/2364, alternative = "greater")

    Exact binomial test

data:  2 and 8
number of successes = 2, number of trials = 8, p-value = 0.0005951
alternative hypothesis: true probability of success is greater than 0.00465313
95 percent confidence interval:
 0.04638926 1.00000000
sample estimates:
probability of success
                  0.25

>

Note that the p-value is 0.0005951.

Compare that to the result of scipy.stats.binom_test (which returns just the p-value):

In [25]: from scipy.stats import binom_test

In [26]: binom_test(2, 8, 11/2364, alternative='greater')
Out[26]: 0.00059505960517880572

So that agrees with R.

To use the survival function of scipy.stats.binom, you have to adjust the first argument (as noted in a comment by Marius):

In [27]: from scipy.stats import binom

In [28]: binom.sf(1, 8, 11/2364)
Out[28]: 0.00059505960517880572

(I am using Python 3, so 11/2364 equals 0.004653130287648054.  If you are using Python 2, be sure to write that fraction as 11.0/2364 or float(11)/2364.)


问:
"The process can not access the file '...' because it is being used by another process" when recreating temporary file for upload with FtpWebRequest
I am uploading a file on FTP. At first it works fine, but as soon as I click the upload button second time it throws an error

The process can not access the file '...' because it is being used by another process

The code is below

```<code>using (StreamWriter sw = new StreamWriter(filename, false)) //THIS LINE THROWS ERROR
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
        sw.Close();
        sw.Dispose();
    }
    else
    {
        sw.Close();
        sw.Dispose();
    }
}
</code>```

I am saving file in csv, can anyone please help me!! Why i am getting this error in second time?

Following is the code to upload on FTP

```<code>public void UploadToFTP()
{
     string fileName = "ReportName";
     string propfilename = Server.MapPath("~") + fileName + ".csv";

     string FtpUserid = null;
     string FtpPwd = null;
     string sourcePath = string.Empty;
     string destPath = string.Empty;
     string fName = string.Empty;
     FtpUserid = "abc";
     FtpPwd = "abc";

     fName = fileName + ".csv";

     destPath = ConfigurationManager.AppSettings["destipath"].ToString();
     destPath = destPath.Insert(destPath.LastIndexOf("/") + 1, fName);

     FtpWebRequest requestFileExists = (FtpWebRequest)WebRequest.Create(destPath);

     //GET DATA IN CSV
     UploadFTPCode(FtpUserid, FtpPwd, sourcePath, destPath, false);
 }

private void UploadFTPCode(string FtpUserid, string FtpPwd, string sourcePath, string destPath)
{
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destPath);
     request.Method = WebRequestMethods.Ftp.UploadFile;
     request.Credentials = new NetworkCredential(FtpUserid, FtpPwd);
     request.Proxy = null;
     request.UseBinary = false;
     request.UsePassive = true;
     request.KeepAlive = false;
     request.Timeout = 500000;

     // Copy the contents of the file to the request stream.
     StreamReader sourceStream = new StreamReader(sourcePath);
     byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
     sourceStream.Dispose();
     sourceStream.Close();
     request.ContentLength = fileContents.Length;

     Stream requestStream = request.GetRequestStream();
     requestStream.Write(fileContents, 0, fileContents.Length);
     requestStream.Flush();
     requestStream.Close();
     requestStream.Dispose();
     sourceStream.Close();
 }
</code>```

答:
There's nothing wrong with your code (apart from being inefficient, redundant and unsafe) - If I run it twice in a loop, all works right.

Though I do not see a point of creating a supposedly temporary file, just for the upload. Write the data directly to the upload/request stream.

```<code>FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.Proxy = null;
request.UseBinary = false;
request.UsePassive = true;
request.KeepAlive = false;
request.Timeout = 500000;

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter sw = new StreamWriter(requestStream))
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
    }
}
</code>```

Also note that your CSV creating code does not look right either (you do not terminate the lines). It should be like:

```<code>sw.WriteLine("Column1,Column2");

foreach (DataRow dr in dt.Rows)
{
    sw.WriteLine(dr["Column1"].ToString() + "," + dr["Column2"].ToString());
}
</code>```

Body:
I am uploading a file on FTP. At first it works fine, but as soon as I click the upload button second time it throws an error

The process can not access the file '...' because it is being used by another process

The code is below

using (StreamWriter sw = new StreamWriter(filename, false)) //THIS LINE THROWS ERROR
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
        sw.Close();
        sw.Dispose();
    }
    else
    {
        sw.Close();
        sw.Dispose();
    }
}

I am saving file in csv, can anyone please help me!! Why i am getting this error in second time?

Following is the code to upload on FTP

public void UploadToFTP()
{
     string fileName = "ReportName";
     string propfilename = Server.MapPath("~") + fileName + ".csv";

     string FtpUserid = null;
     string FtpPwd = null;
     string sourcePath = string.Empty;
     string destPath = string.Empty;
     string fName = string.Empty;
     FtpUserid = "abc";
     FtpPwd = "abc";

     fName = fileName + ".csv";

     destPath = ConfigurationManager.AppSettings["destipath"].ToString();
     destPath = destPath.Insert(destPath.LastIndexOf("/") + 1, fName);

     FtpWebRequest requestFileExists = (FtpWebRequest)WebRequest.Create(destPath);

     //GET DATA IN CSV
     UploadFTPCode(FtpUserid, FtpPwd, sourcePath, destPath, false);
 }

private void UploadFTPCode(string FtpUserid, string FtpPwd, string sourcePath, string destPath)
{
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destPath);
     request.Method = WebRequestMethods.Ftp.UploadFile;
     request.Credentials = new NetworkCredential(FtpUserid, FtpPwd);
     request.Proxy = null;
     request.UseBinary = false;
     request.UsePassive = true;
     request.KeepAlive = false;
     request.Timeout = 500000;

     // Copy the contents of the file to the request stream.
     StreamReader sourceStream = new StreamReader(sourcePath);
     byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
     sourceStream.Dispose();
     sourceStream.Close();
     request.ContentLength = fileContents.Length;

     Stream requestStream = request.GetRequestStream();
     requestStream.Write(fileContents, 0, fileContents.Length);
     requestStream.Flush();
     requestStream.Close();
     requestStream.Dispose();
     sourceStream.Close();
 }

Body:
There's nothing wrong with your code (apart from being inefficient, redundant and unsafe) - If I run it twice in a loop, all works right.

Though I do not see a point of creating a supposedly temporary file, just for the upload. Write the data directly to the upload/request stream.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.Proxy = null;
request.UseBinary = false;
request.UsePassive = true;
request.KeepAlive = false;
request.Timeout = 500000;

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter sw = new StreamWriter(requestStream))
{
    if (dt.Rows.Count > 0)
    {
        sw.Write("Column1,Column2");
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            sw.Write(dr["Column1"].ToString());
            sw.Write(",");
            sw.Write(dr["Column2"].ToString());
            sw.Write(",");
        }
    }
}

Also note that your CSV creating code does not look right either (you do not terminate the lines). It should be like:

sw.WriteLine("Column1,Column2");

foreach (DataRow dr in dt.Rows)
{
    sw.WriteLine(dr["Column1"].ToString() + "," + dr["Column2"].ToString());
}


答:
It matches any place where the next character is an a, e, i, o, u or y, but it doesn't match that character - see http://www.rubular.com/r/Tjq3ocLMVJ

Specifically, (?=...) is called a "lookahead" and it verifies that the following chunk is present

Title: Simple Javascript Regex Question


问:
How to load html with iframe?
I have:

index.html

and

test.html

and I could load my test.html with jquery load(); function to in index.html

but then my index.html style is broken that is why I want to load my test.html into index.html as iframe..

index.html

load test.html here with iframe

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">
I'm a test div and I want to be in index.html in `item` class
</div></code>```

答:
to load html file into an iframe</p>

```<code><html>
<body>

  <iframe src="test.html">
    <p>Your browser does not support iframes.</p>
  </iframe>

</body>
</html>
</code>```

Title: How to load html with iframe?

Body:
I have:

index.html

and

test.html

and I could load my test.html with jquery load(); function to in index.html

but then my index.html style is broken that is why I want to load my test.html into index.html as iframe..

index.html

load test.html here with iframe

I'm a test div and I want to be in index.html in `item` class

Body:
to load html file into an iframe

<html>
<body>

  <iframe src="test.html">
    <p>Your browser does not support iframes.</p>
  </iframe>

</body>
</html>


问:
Button with handler and bound tag attributes
I want to define in a jsviews template a button that have both click handler and data bound property.

Assuming I have this data:

```<code>var data = {
    Enable : true,
    DisplayName : "foo",
    SomeData : 42
};
</code>```

This helpers :

```<code>var handlers = {
    fooClicked : function(data, evt) {
        console.log(arguments);
    }
};
</code>```

How to add a button in my template to plumb the event handler and the properties of the button ?

I tried :

<button data-link="{on ~onAvailabilityClick SomeData disabled:^{!Enable}}">
     {^{>DisplayName}}
</button>

<button data-link="{on ~onAvailabilityClick SomeData} disabled:^{!Enable}">
     {^{>DisplayName}}
</button>

{^{on ~onAvailabilityClick SomeData}}<button data-link="disabled:^{!Enable}">
     {^{>DisplayName}}
</button>{{/on}}

But none of these works (either template syntax error or incomplete button, like having no text, or no handler).

I'm using jsViews 0.98.4.

PS: I don't know if it matters, but actually, my template is fed within a for loop, for an deep object structure.

答:
I finally made it :</p>

```<code><button data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData}">
     {^{>DisplayName}}
</button>
</code>```

Body:
I want to define in a jsviews template a button that have both click handler and data bound property.

Assuming I have this data:

var data = {
    Enable : true,
    DisplayName : "foo",
    SomeData : 42
};

This helpers :

var handlers = {
    fooClicked : function(data, evt) {
        console.log(arguments);
    }
};

How to add a button in my template to plumb the event handler and the properties of the button ?

I tried :

<button data-link="{on ~onAvailabilityClick SomeData disabled:^{!Enable}}">
     {^{>DisplayName}}
</button>

<button data-link="{on ~onAvailabilityClick SomeData} disabled:^{!Enable}">
     {^{>DisplayName}}
</button>

{^{on ~onAvailabilityClick SomeData}}<button data-link="disabled:^{!Enable}">
     {^{>DisplayName}}
</button>{{/on}}

But none of these works (either template syntax error or incomplete button, like having no text, or no handler).

I'm using jsViews 0.98.4.

PS: I don't know if it matters, but actually, my template is fed within a for loop, for an deep object structure.

Body:
I finally made it :

<button data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData}">
     {^{>DisplayName}}
</button>


问:
C++ "File format not recognized"?
I'm trying to run the code located here:
http://r3dux.org/2010/11/single-call-opengl-texture-loader-in-devil/

And it requires me to use DevIL, so I installed it to my c:\usr\ folder using the Win32 installer. I'm positive my environment is setup to read from the proper \lib folder as well. My linker looks like this:

```<code>-lglfw
-gluw32
-lopengl32
-lglu32
-ldevil
</code>```

Everything else loads fine, but when it gets to "ldevil", the compiler (Dev-C++) throws the error: File format not recognized.

答: Most likely the devil library wasn't build with the same compiler/OS/options/architecture as the one you're trying to build your application for. You'll need to build it from source or obtain the correct version.</p>

Title: C++ "File format not recognized"?

Body:
I'm trying to run the code located here:
http://r3dux.org/2010/11/single-call-opengl-texture-loader-in-devil/

And it requires me to use DevIL, so I installed it to my c:\usr\ folder using the Win32 installer. I'm positive my environment is setup to read from the proper \lib folder as well. My linker looks like this:

-lglfw
-gluw32
-lopengl32
-lglu32
-ldevil

Everything else loads fine, but when it gets to "ldevil", the compiler (Dev-C++) throws the error: File format not recognized.


问:
See when packages were installed / updated using pip
I know how to see installed Python packages using pip, just use pip freeze. But is there any way to see the date and time when package is installed or updated with pip?

答:
Unfortunately, python packaging makes this a bit complicated since there is no consistent place that lists where the package files or module directories are placed.

Here's the best I've come up with:

```<code>#!/usr/bin/env python
# Prints when python packages were installed
from __future__ import print_function
from datetime import datetime
import os
import pip

if __name__ == "__main__":
    packages = []
    for package in pip.get_installed_distributions():
        package_name_version = str(package)
        try:
            module_dir = next(package._get_metadata('top_level.txt'))
            package_location = os.path.join(package.location, module_dir)
            os.stat(package_location)
        except (StopIteration, OSError):
            try:
                package_location = os.path.join(package.location, package.key)
                os.stat(package_location)
            except:
                package_location = package.location
        modification_time = os.path.getctime(package_location)
        modification_time = datetime.fromtimestamp(modification_time)
        packages.append([
            modification_time,
            package_name_version
        ])
    for modification_time, package_name_version in sorted(packages):
        print("{0} - {1}".format(modification_time,
                                 package_name_version))
</code>```

Body:
Unfortunately, python packaging makes this a bit complicated since there is no consistent place that lists where the package files or module directories are placed.

Here's the best I've come up with:

#!/usr/bin/env python
# Prints when python packages were installed
from __future__ import print_function
from datetime import datetime
import os
import pip

if __name__ == "__main__":
    packages = []
    for package in pip.get_installed_distributions():
        package_name_version = str(package)
        try:
            module_dir = next(package._get_metadata('top_level.txt'))
            package_location = os.path.join(package.location, module_dir)
            os.stat(package_location)
        except (StopIteration, OSError):
            try:
                package_location = os.path.join(package.location, package.key)
                os.stat(package_location)
            except:
                package_location = package.location
        modification_time = os.path.getctime(package_location)
        modification_time = datetime.fromtimestamp(modification_time)
        packages.append([
            modification_time,
            package_name_version
        ])
    for modification_time, package_name_version in sorted(packages):
        print("{0} - {1}".format(modification_time,
                                 package_name_version))


问:
Sorting date m/y format in a data frame in R
I am trying to sort date column which is in the format M/Y. I tried using several ways given in other posts but none helped. Please suggest.
For 2012 it shows correctly with all the months given with 2012 but then it changes the pattern. Thank you.

Here is how it looks like currently

答:
That should work:</p>

```<code>#let's add a column to your data.frame with a proper date
df$date_of_first_day <- as.Date(paste0("1/",monyear),format = "%d/%m/%y")
# then sort the data.frame
df <- df[order(df$date_of_first_day,decreasing = FALSE),]
# then get rid of this column
df$date_of_first_day <- NULL
</code>```

Body:
That should work:

#let's add a column to your data.frame with a proper date
df$date_of_first_day <- as.Date(paste0("1/",monyear),format = "%d/%m/%y")
# then sort the data.frame
df <- df[order(df$date_of_first_day,decreasing = FALSE),]
# then get rid of this column
df$date_of_first_day <- NULL


问:
k means clustering on matrix
I am trying to cluster a Multidimensional Functional Object with the "kmeans" algorithms. What does it mean: So I don't have anymore a vector per each row or Individual, even more a 3x3 observation matrix per each Individual.For example: Individual = 1 has the following observations:

(x1, x2, x3),(y1,y2,y3),(z1,z2,z3).

The same structure of observations is also given for the other Individuals. So do you know how I can cluster with "kmeans" including all 3 observation vectors -and not only one observation vector how it is normal used for "kmeans" clustering?
Would you do it for each observation vector, f.e. (x1, x2, x3), separately and then combine the Information somehow together? I want to do this with the kmeans() Function in R.

Many thanks for your answers!

答: Just give the argument to kmeans() with all the three columns it'll calculate the distances in 3 dimension, if that is what you are looking for.

Title: k means clustering on matrix


问:
embed R leaflet map in wordpress
I have just created a simple interactive map using leaflet package in R. Something like this

```<code>leaflet() %>% addTiles()
</code>```

Now I would like to embed it in my wordpress website.

I clicked on the export button of RStudio Viewer and chosen "Save as web page...", then stored the .html in my local computer.

I tried to embed this map in a post in my WP website by clicking on "Add a media" in the editor of the page and the choosing the .html previously stored. But I get the error:

"1 file could not be uploaded because the file type is not supported."

I tried to open the html file in an editor and copy and paste the (very long, full of coordinates) html code into the html tab of WP page editor. The editor convert this code into

```<code><div id="htmlwidget_container">
<div id="htmlwidget-2390" class="leaflet html-widget" style="width: 100%; height: 400px;"></div> </div>
</code>```

and I don't see any map in the visual tab.
I really don't know how to proceed. Any help will be appreciated. As you have noticed I am completely new to WP and web applications.

Thanks a lot,
jacopo

答:
U can try to save the widget to a .html file and import this .html file to your media library.

```<code>library(htmlwidgets)
library(DT)
a <- datatable(iris)
saveWidget(a, "datatable-iris-example.html")
</code>```

Next, import the .html file to your media library. Then, add the shortcode to your post. Here's how to encode it in the page when editing the blog post:

```<code><iframe seamless src="http://www.phillipburger.net/wordpress/wp-
content/uploads/2015/05/datatable-iris-example.html" width="100%"
height="500"></iframe>
</code>```

All credits go to Phillip Burger and his post.

Anyone got a better method?

Title: embed R leaflet map in wordpress

Body:
I have just created a simple interactive map using leaflet package in R. Something like this

leaflet() %>% addTiles()

Now I would like to embed it in my wordpress website.

I clicked on the export button of RStudio Viewer and chosen "Save as web page...", then stored the .html in my local computer.

I tried to embed this map in a post in my WP website by clicking on "Add a media" in the editor of the page and the choosing the .html previously stored. But I get the error:

"1 file could not be uploaded because the file type is not supported."

I tried to open the html file in an editor and copy and paste the (very long, full of coordinates) html code into the html tab of WP page editor. The editor convert this code into

and I don't see any map in the visual tab.
I really don't know how to proceed. Any help will be appreciated. As you have noticed I am completely new to WP and web applications.

Thanks a lot,
jacopo

Body:
U can try to save the widget to a .html file and import this .html file to your media library.

library(htmlwidgets)
library(DT)
a <- datatable(iris)
saveWidget(a, "datatable-iris-example.html")

Next, import the .html file to your media library. Then, add the shortcode to your post. Here's how to encode it in the page when editing the blog post:

<iframe seamless src="http://www.phillipburger.net/wordpress/wp-
content/uploads/2015/05/datatable-iris-example.html" width="100%"
height="500"></iframe>

All credits go to Phillip Burger and his post.

Anyone got a better method?


问:
Extract multidimensional array values
I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.

I need to be able to extract the values and place them in strings, for example,

$uuid =

and so on.

I can't seem to find a similar query and have tried so many variations. Many thanks in advance.

```<code>Array
(
[action] => edit
[data] => Array
    (
        [row_204] => Array
            (
                [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
                [userID] => 7
                [maxPoints] => 7
                [awardedPoints] => 6
                [Date] => 2017-06-08
            )

    )

)
</code>```

答:
If you know there is always only one row_* item in that array, you can just pull the first item (i.e., the only one in your case) off the front of the list with array_shift():

```<code>$data = array_shift($array['data']);
print_r($data);
</code>```

Will give you:

```<code>Array (
    [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
    [userID] => 7
    [maxPoints] => 7
    [awardedPoints] => 6
    [Date] => 2017-06-08
)
</code>```

Then you can just deference the keys you want:

```<code>$uuid = $data['UUID'];
</code>```

Title: Extract multidimensional array values

Body:
I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.

I need to be able to extract the values and place them in strings, for example,

$uuid =

and so on.

I can't seem to find a similar query and have tried so many variations. Many thanks in advance.

Array
(
[action] => edit
[data] => Array
    (
        [row_204] => Array
            (
                [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
                [userID] => 7
                [maxPoints] => 7
                [awardedPoints] => 6
                [Date] => 2017-06-08
            )

    )

)

Body:
If you know there is always only one row_* item in that array, you can just pull the first item (i.e., the only one in your case) off the front of the list with array_shift():

$data = array_shift($array['data']);
print_r($data);

Will give you:

Array (
    [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
    [userID] => 7
    [maxPoints] => 7
    [awardedPoints] => 6
    [Date] => 2017-06-08
)

Then you can just deference the keys you want:

$uuid = $data['UUID'];


问:
How to open editor tab context menu using keyboard?
Mouse right clicking on the editor tab opens tab context menu (see: context menu of a tab).

How to open this context menu using keyboard?

答:
It's not possible to access it via the keyboard.

A workaround would be to use the Quick Lists feature where you can create your own lists of actions and assign this list to the keyboard shortcut.


问:
Ionic md-tabs squeezing tabs
I have created this app with ionic and angular material design. My issue is when I use md-tabs with more than 4 tabs. It's squeezing when I switch between views and back to md-tabs... it's common on android, ios it's just usually.

```<code><md-tabs md-stretch-tabs="auto" md-align-tabs="top" md-center-tabs="yes"
         md-dynamic-height="" md-border-bottom=""
         md-selected="data.selectedIndex">
</code>```

Normal

With squeeze

Solution

```<code>md-tab-item.md-tab.md-ink-ripple {
    min-width: 111px;
}
</code>```

答: Have you tried setting a min-width css property for the generated tab elements?

Title: Ionic md-tabs squeezing tabs

Body:
I have created this app with ionic and angular material design. My issue is when I use md-tabs with more than 4 tabs. It's squeezing when I switch between views and back to md-tabs... it's common on android, ios it's just usually.

<md-tabs md-stretch-tabs="auto" md-align-tabs="top" md-center-tabs="yes"
         md-dynamic-height="" md-border-bottom=""
         md-selected="data.selectedIndex">

Normal

With squeeze

Solution

md-tab-item.md-tab.md-ink-ripple {
    min-width: 111px;
}


问:
mysql select only groups having certain length
Lets say, i have a table like this:

table1

```<code>  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c
</code>```

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

```<code>[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]
</code>```

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

答:
try it   </p>

```<code> select sel.id, sel.val
    from
        (Select COUNT(*) over (partition by val order by val) rowcount, a.*
    from table1 a) sel
        where sel.rowcount = 3
</code>```

Body:
Lets say, i have a table like this:

table1

  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

Body:
try it

 select sel.id, sel.val
    from
        (Select COUNT(*) over (partition by val order by val) rowcount, a.*
    from table1 a) sel
        where sel.rowcount = 3