问:
Select rows where string does not repeat
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...
</code>```

My query looks like this:

```<code>SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id
</code>```

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...
</code>```

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

答:
If you really only want the count you can do this:

```<code>SELECT COUNT(DISTINCT table1.string)
FROM table1 INNER JOIN table2 ON table1.id = table2.table1_id
</code>```

Some of the other answers are clearly better if you want do do something with the distinct values other than just count them.

Body:
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...

My query looks like this:

SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

Body:
If you really only want the count you can do this:

SELECT COUNT(DISTINCT table1.string)
FROM table1 INNER JOIN table2 ON table1.id = table2.table1_id

Some of the other answers are clearly better if you want do do something with the distinct values other than just count them.


来源: stackexchange

问:
Using time inside of Watson Dialog
We have a need to make decisions within Watson Dialog based on the current time of day. Is there a good/best practice way of doing that? I thought of periodically writing the current time into a Dialog profile variable but am hoping there is a better way.</p>

答:
Just for any other readers, this is for the now deprecated Watson Dialog Service, NOT the dialog piece inside the Conversation service (which was inspired by the old dialog, but is different...)

anyway,
I think youre right unfortunately. because the profile variables and user messages are separate methods here, you need to make sure the profile is up to date before you respond. Another option would be in your dialog node give multiple responses in some format your app knows what to do with ie

```<code><morning> good morning!</morning> <afternoon> good afternoon!</afternoon>
</code>```

and then your app will see that response, and based on the time give the right message at runtime. This obviously requires more complex app code, but reduces the number of trips to the service.

ContentLicense: CC BY-SA 3.0

Title: Using time inside of Watson Dialog

Body:
Just for any other readers, this is for the now deprecated Watson Dialog Service, NOT the dialog piece inside the Conversation service (which was inspired by the old dialog, but is different...)

anyway,
I think youre right unfortunately. because the profile variables and user messages are separate methods here, you need to make sure the profile is up to date before you respond. Another option would be in your dialog node give multiple responses in some format your app knows what to do with ie

<morning> good morning!</morning> <afternoon> good afternoon!</afternoon>

and then your app will see that response, and based on the time give the right message at runtime. This obviously requires more complex app code, but reduces the number of trips to the service.


问:
Rolling Join multiple columns independently to eliminate NAs
I am trying to do a rolling join in data.table that brings in multiple columns, but rolls over both entire missing rows, and individual NAs in particular columns, even when the row is present. By way of example, I have two tables, A, and B:

```<code>library(data.table)
A <- data.table(v1 = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                v2 = c(6,6,6,4,4,6,4,4,4,6,4,4,4),
                t = c(10,20,30,60,60,10,40,50,60,20,40,50,60),
                key = c("v1", "v2", "t"))

B <- data.table(v1 = c(1,1,1,1,2,2,2,2,3,3,3,3),
                v2 = c(4,4,6,6,4,4,6,6,4,4,6,6),
                t = c(10,70,20,70,10,70,20,70,10,70,20,70),
                valA = c('a','a',NA,'a',NA,'a','b','a', 'b','b',NA,'b'),
                valB = c(NA,'q','q','q','p','p',NA,'p',NA,'q',NA,'q'),
                key = c("v1", "v2", "t"))

B
##     v1 v2  t valA valB
##  1:  1  4 10    a   NA
##  2:  1  4 70    a    q
##  3:  1  6 20   NA    q
##  4:  1  6 70    a    q
##  5:  2  4 10   NA    p
##  6:  2  4 70    a    p
##  7:  2  6 20    b   NA
##  8:  2  6 70    a    p
##  9:  3  4 10    b   NA
## 10:  3  4 70    b    q
## 11:  3  6 20   NA   NA
## 12:  3  6 70    b    q
</code>```

If I do a rolling join (in this case a backwards join), it rolls over all the points when a row cannot be found in B, but still includes points when the row exists but the data to be merged are NA:

```<code>B[A, , roll=-Inf]

##     v1 v2  t valA valB
##  1:  1  4 60    a    q
##  2:  1  4 60    a    q
##  3:  1  6 10   NA    q
##  4:  1  6 20   NA    q
##  5:  1  6 30    a    q
##  6:  2  4 40    a    p
##  7:  2  4 50    a    p
##  8:  2  4 60    a    p
##  9:  2  6 10    b   NA
## 10:  3  4 40    b    q
## 11:  3  4 50    b    q
## 12:  3  4 60    b    q
## 13:  3  6 20   NA   NA
</code>```

I would like to rolling join in such a way that it rolls over these NAs as well. For a single column, I can subset B to remove the NAs, then roll with A:

```<code>C <- B[!is.na(valA), .(v1, v2, t, valA)][A, roll=-Inf]

C
##     v1 v2  t valA
##  1:  1  4 60    a
##  2:  1  4 60    a
##  3:  1  6 10    a
##  4:  1  6 20    a
##  5:  1  6 30    a
##  6:  2  4 40    a
##  7:  2  4 50    a
##  8:  2  4 60    a
##  9:  2  6 10    b
## 10:  3  4 40    b
## 11:  3  4 50    b
## 12:  3  4 60    b
## 13:  3  6 20    b
</code>```

But for multiple columns, I have to do this sequentially, storing the value for each added column and then repeat.

```<code>B[!is.na(valB), .(v1, v2, t, valB)][C, roll=-Inf]

##     v1 v2  t valB valA
##  1:  1  4 60    q    a
##  2:  1  4 60    q    a
##  3:  1  6 10    q    a
##  4:  1  6 20    q    a
##  5:  1  6 30    q    a
##  6:  2  4 40    p    a
##  7:  2  4 50    p    a
##  8:  2  4 60    p    a
##  9:  2  6 10    p    b
## 10:  3  4 40    q    b
## 11:  3  4 50    q    b
## 12:  3  4 60    q    b
## 13:  3  6 20    q    b
</code>```

The end result above is the desired output, but for multiple columns it quickly becomes unwieldy. Is there a better solution?

答:
Joins are about matching up rows. If you want to match rows multiple ways, you'll need multiple joins.

I'd use a loop, but add columns to A (rather than creating new tables C, D, ... following each join):

```<code>k     = key(A)
bcols = setdiff(names(B), k)

for (col in bcols) A[, (col) :=
  B[!.(as(NA, typeof(B[[col]]))), on=col][.SD, roll=-Inf, ..col]
][]

A

    v1 v2  t valA valB
 1:  1  4 60    a    q
 2:  1  4 60    a    q
 3:  1  6 10    a    q
 4:  1  6 20    a    q
 5:  1  6 30    a    q
 6:  2  4 40    a    p
 7:  2  4 50    a    p
 8:  2  4 60    a    p
 9:  2  6 10    b    p
10:  3  4 40    b    q
11:  3  4 50    b    q
12:  3  4 60    b    q
13:  3  6 20    b    q
</code>```

B[!.(NA_character_), on="valA"] is an anti-join that drops rows with NAs in valA. The code above attempts to generalize this (since the NA needs to match the type of the column).

Body:
I am trying to do a rolling join in data.table that brings in multiple columns, but rolls over both entire missing rows, and individual NAs in particular columns, even when the row is present. By way of example, I have two tables, A, and B:

library(data.table)
A <- data.table(v1 = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                v2 = c(6,6,6,4,4,6,4,4,4,6,4,4,4),
                t = c(10,20,30,60,60,10,40,50,60,20,40,50,60),
                key = c("v1", "v2", "t"))

B <- data.table(v1 = c(1,1,1,1,2,2,2,2,3,3,3,3),
                v2 = c(4,4,6,6,4,4,6,6,4,4,6,6),
                t = c(10,70,20,70,10,70,20,70,10,70,20,70),
                valA = c('a','a',NA,'a',NA,'a','b','a', 'b','b',NA,'b'),
                valB = c(NA,'q','q','q','p','p',NA,'p',NA,'q',NA,'q'),
                key = c("v1", "v2", "t"))

B
##     v1 v2  t valA valB
##  1:  1  4 10    a   NA
##  2:  1  4 70    a    q
##  3:  1  6 20   NA    q
##  4:  1  6 70    a    q
##  5:  2  4 10   NA    p
##  6:  2  4 70    a    p
##  7:  2  6 20    b   NA
##  8:  2  6 70    a    p
##  9:  3  4 10    b   NA
## 10:  3  4 70    b    q
## 11:  3  6 20   NA   NA
## 12:  3  6 70    b    q

If I do a rolling join (in this case a backwards join), it rolls over all the points when a row cannot be found in B, but still includes points when the row exists but the data to be merged are NA:

B[A, , roll=-Inf]

##     v1 v2  t valA valB
##  1:  1  4 60    a    q
##  2:  1  4 60    a    q
##  3:  1  6 10   NA    q
##  4:  1  6 20   NA    q
##  5:  1  6 30    a    q
##  6:  2  4 40    a    p
##  7:  2  4 50    a    p
##  8:  2  4 60    a    p
##  9:  2  6 10    b   NA
## 10:  3  4 40    b    q
## 11:  3  4 50    b    q
## 12:  3  4 60    b    q
## 13:  3  6 20   NA   NA

I would like to rolling join in such a way that it rolls over these NAs as well. For a single column, I can subset B to remove the NAs, then roll with A:

C <- B[!is.na(valA), .(v1, v2, t, valA)][A, roll=-Inf]

C
##     v1 v2  t valA
##  1:  1  4 60    a
##  2:  1  4 60    a
##  3:  1  6 10    a
##  4:  1  6 20    a
##  5:  1  6 30    a
##  6:  2  4 40    a
##  7:  2  4 50    a
##  8:  2  4 60    a
##  9:  2  6 10    b
## 10:  3  4 40    b
## 11:  3  4 50    b
## 12:  3  4 60    b
## 13:  3  6 20    b

But for multiple columns, I have to do this sequentially, storing the value for each added column and then repeat.

B[!is.na(valB), .(v1, v2, t, valB)][C, roll=-Inf]

##     v1 v2  t valB valA
##  1:  1  4 60    q    a
##  2:  1  4 60    q    a
##  3:  1  6 10    q    a
##  4:  1  6 20    q    a
##  5:  1  6 30    q    a
##  6:  2  4 40    p    a
##  7:  2  4 50    p    a
##  8:  2  4 60    p    a
##  9:  2  6 10    p    b
## 10:  3  4 40    q    b
## 11:  3  4 50    q    b
## 12:  3  4 60    q    b
## 13:  3  6 20    q    b

The end result above is the desired output, but for multiple columns it quickly becomes unwieldy. Is there a better solution?

Body:
Joins are about matching up rows. If you want to match rows multiple ways, you'll need multiple joins.

I'd use a loop, but add columns to A (rather than creating new tables C, D, ... following each join):

k     = key(A)
bcols = setdiff(names(B), k)

for (col in bcols) A[, (col) :=
  B[!.(as(NA, typeof(B[[col]]))), on=col][.SD, roll=-Inf, ..col]
][]

A

    v1 v2  t valA valB
 1:  1  4 60    a    q
 2:  1  4 60    a    q
 3:  1  6 10    a    q
 4:  1  6 20    a    q
 5:  1  6 30    a    q
 6:  2  4 40    a    p
 7:  2  4 50    a    p
 8:  2  4 60    a    p
 9:  2  6 10    b    p
10:  3  4 40    b    q
11:  3  4 50    b    q
12:  3  4 60    b    q
13:  3  6 20    b    q

B[!.(NA_character_), on="valA"] is an anti-join that drops rows with NAs in valA. The code above attempts to generalize this (since the NA needs to match the type of the column).


问:
AngularJs Spring MVC $http.post Error 415 (Unsupported Media Type)
Trying to send data from angularjs to Spring MVC but keeps getting 415 error

```<code>app.controller('RegisterFormSubmitCtrl', ['$scope', '$http', '$location', function($scope, $http) {

$scope.submit = function() {

    var registerData = {
        "email" : $scope.email,
        "firstName" : $scope.firstName,
        "lastName" : $scope.lastName,
        "DoB": $scope.DoB = new Date(),
        "password" : $scope.password
    };

    console.log(registerData);

    $http({
        method: 'POST',
        url: "http://localhost:8080/home",
        data: registerData,
        headers: {
            'Content-type': 'application/json, charset=UTF-8'
        }
    }).then(function successCallback(response) {
    }, function errorCallback(response) {

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

Spring MVC controller

```<code> @Consumes("text/html")
    @RequestMapping(value = "/home", method = RequestMethod.POST)
    public ResponseEntity<Void> afterRegister(@RequestBody RegisterUserRequest request){
        System.out.print("Register user: " + request.getFirstName());
        if(userManager.emailRegistered(request.getEmail())){
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }
        // checking with google datastore
        else if(userManager.addUser(request.getEmail(), request.getPassword(), request.getFirstName(), request.getLastName(),
                request.getDoB(), "User")) {
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }
</code>```

RegisterUserRequest class

```<code>@Accessors(chain = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RegisterUserRequest {
    @NotNull
    private String email;
    private String firstName;
    private String lastName;
    private Date DoB;
    @NotNull
    private String password;
}
</code>```

error:

```<code>Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)
</code>```

I've tried removing @RequestBody notation to get rid of the error, but then the controller only receives null from request.
Also tried adding produces='application/json' in mapping, still got error 415

In dependencies I added the below to read json:

```<code><dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>
</code>```

答: Your controller afterRegister() method is now accepting text/html content i.e., @Consumes("text/html"), so change it to @Consumes("application/json")

Body:
Trying to send data from angularjs to Spring MVC but keeps getting 415 error

app.controller('RegisterFormSubmitCtrl', ['$scope', '$http', '$location', function($scope, $http) {

$scope.submit = function() {

    var registerData = {
        "email" : $scope.email,
        "firstName" : $scope.firstName,
        "lastName" : $scope.lastName,
        "DoB": $scope.DoB = new Date(),
        "password" : $scope.password
    };

    console.log(registerData);

    $http({
        method: 'POST',
        url: "http://localhost:8080/home",
        data: registerData,
        headers: {
            'Content-type': 'application/json, charset=UTF-8'
        }
    }).then(function successCallback(response) {
    }, function errorCallback(response) {

    });
}; }]);

Spring MVC controller

 @Consumes("text/html")
    @RequestMapping(value = "/home", method = RequestMethod.POST)
    public ResponseEntity<Void> afterRegister(@RequestBody RegisterUserRequest request){
        System.out.print("Register user: " + request.getFirstName());
        if(userManager.emailRegistered(request.getEmail())){
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }
        // checking with google datastore
        else if(userManager.addUser(request.getEmail(), request.getPassword(), request.getFirstName(), request.getLastName(),
                request.getDoB(), "User")) {
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

RegisterUserRequest class

@Accessors(chain = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RegisterUserRequest {
    @NotNull
    private String email;
    private String firstName;
    private String lastName;
    private Date DoB;
    @NotNull
    private String password;
}

error:

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)

I've tried removing @RequestBody notation to get rid of the error, but then the controller only receives null from request.
Also tried adding produces='application/json' in mapping, still got error 415

In dependencies I added the below to read json:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>


问:
Android: RelativeLayout problem with xml
I am trying to put some triangles & squares on Android screen in certain way as shown in following figure. I am putting them separately because all shapes are clickable.

I used RelativeLayout (other layouts I tried, but they aren't working). Following is xml code for the same:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
    android:id="@+id/LeftTopTriangle"
    android:src="@drawable/a_triangle_towards_right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="true"
    android:layout_alignTop="true"
    android:clickable="true" />
<ImageView
    android:id="@+id/TopLeftTriangle"
    android:src="@drawable/a_triangle_towards_bottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="true"
    android:layout_alignTop="true"
    android:clickable="true" />
<ImageView
    android:id="@+id/LeftBottomTriangle"
    android:src="@drawable/a_triangle_towards_right"
    android:layout_below="@id/LeftTopTriangle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true" />
</code>```

Here I am trying only 3 triangles, 2 on the left-top corner and one on the left-bottom corner. Now whatever, I trial-error, somehow the bottom triangle never shows up.
I end up as following:

Any one have idea, how to achieve it ?
[P.S.: Strangely in the xml file, I am getting the same figure even removing following lines from both the ImageViews
        android:layout_alignLeft="true"
        android:layout_alignTop="true"
]

答:
I have found one easier way to achieve this.
I have drawn all the images separately in the same dimension width x height.
e.g. If the overall image size is 400 x 300 then, I would draw all the triangles and diamonds individually at given points in the same 400 x 300 frame.

->following is triangle on top-left

-> following is triangle on left-top

-> following is diamond in left

Also note that, everyone's background has been removed (by PAINT.net) so that they can overlap on each other (otherwise final image will be only visible).
Now all images will be simply declared in FrameLayout with scaleType="fitXY".
Done !!

ContentLicense: CC BY-SA 2.5

Body:
I am trying to put some triangles & squares on Android screen in certain way as shown in following figure. I am putting them separately because all shapes are clickable.

I used RelativeLayout (other layouts I tried, but they aren't working). Following is xml code for the same:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
    android:id="@+id/LeftTopTriangle"
    android:src="@drawable/a_triangle_towards_right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="true"
    android:layout_alignTop="true"
    android:clickable="true" />
<ImageView
    android:id="@+id/TopLeftTriangle"
    android:src="@drawable/a_triangle_towards_bottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="true"
    android:layout_alignTop="true"
    android:clickable="true" />
<ImageView
    android:id="@+id/LeftBottomTriangle"
    android:src="@drawable/a_triangle_towards_right"
    android:layout_below="@id/LeftTopTriangle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true" />

Here I am trying only 3 triangles, 2 on the left-top corner and one on the left-bottom corner. Now whatever, I trial-error, somehow the bottom triangle never shows up.
I end up as following:

Any one have idea, how to achieve it ?
[P.S.: Strangely in the xml file, I am getting the same figure even removing following lines from both the ImageViews
        android:layout_alignLeft="true"
        android:layout_alignTop="true"
]


问:
WatchKit Extension[4608:145616] Unable to find image named "hello" on Watch
Problem:

Trying to set the WKInterfaceLabel text using xCode 6.2 but it returns this error:

```<code>WatchKit Extension[4608:145616] Unable to find image named "hello" on Watch
</code>```

Code:

```<code>@IBOutlet var lblPassword: WKInterfaceLabel!

lblPassword.setText("hello")
</code>```

答: i've had the exact same problem. solution: i've exedently connected the group parenting the WKInterfaceLabel. Try setting YOURSUPPOSEDLABLE.setTextColor(.brown), if the Background of it changes, you have connected the group.</p>

Body:
Problem:

Trying to set the WKInterfaceLabel text using xCode 6.2 but it returns this error:

WatchKit Extension[4608:145616] Unable to find image named "hello" on Watch

Code:

@IBOutlet var lblPassword: WKInterfaceLabel!

lblPassword.setText("hello")


问:
Laravel 5.4 Script loading issue
I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected.
I use Mix and Blade :

```<code>// webpack.mix.js
let { mix } = require('laravel-mix').mix;

    // copy fonts and patterns
mix .copy('resources/assets/vendor/bootstrap/fonts', 'public/fonts')
    .copy('resources/assets/vendor/font-awesome/fonts', 'public/fonts')
    .copy('resources/assets/patterns', 'public/css/patterns')

    // compile scss and concatenate css files
    .sass('resources/assets/sass/app.scss', 'public/css')
    .styles([
        'resources/assets/vendor/bootstrap/css/bootstrap.css',
        'resources/assets/vendor/animate/animate.css'
        // ...
    ], 'public/css/vendor.css')

    // concatenate js files
    .js([
        'resources/assets/vendor/jquery/jquery-3.1.1.min.js',
        'resources/assets/vendor/bootstrap/js/bootstrap.js',
        'resources/assets/js/app.js'
        // ...
    ], 'public/js/app.js')
    .options({ processCssUrls: false }); // fix for path issue : https://github.com/almasaeed2010/AdminLTE/issues/1360
</code>```

After npm run dev compliation looks good :

```<code>DONE  Compiled successfully in 6497ms                                                     4:20:57 PM

                                   Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.ttf   45.4 kB          [emitted]
                              /js/app.js    1.2 MB       0  [emitted]  [big]  /js/app
                       mix-manifest.json  66 bytes          [emitted]
  fonts/glyphicons-halflings-regular.eot   20.1 kB          [emitted]
fonts/glyphicons-halflings-regular.woff2     18 kB          [emitted]
  fonts/glyphicons-halflings-regular.svg    109 kB          [emitted]
 fonts/glyphicons-halflings-regular.woff   23.4 kB          [emitted]
                            /css/app.css    178 kB       0  [emitted]         /js/app
           fonts/fontawesome-webfont.ttf    166 kB          [emitted]
           fonts/fontawesome-webfont.svg    444 kB          [emitted]  [big]
           fonts/fontawesome-webfont.eot    166 kB          [emitted]
          fonts/fontawesome-webfont.woff     98 kB          [emitted]
         fonts/fontawesome-webfont.woff2   77.2 kB          [emitted]
                   fonts/FontAwesome.otf    135 kB          [emitted]
         css/patterns/header-profile.png   5.88 kB          [emitted]
</code>```

CSS works fine, bootstrap.js also works and when I check inside /js/app.js it seems like everything is inside.

An here is my tempate :

```<code>{{-- app.blade.php--}}
<!DOCTYPE html>
<html lang="{{ config('app.locale', 'en') }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
    <link rel="stylesheet" href="{!! asset('css/app.css') !!}" />
</head>
<body>
    <!-- Main view  -->
    @yield('content')

    <script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>

    @section('scripts')
    @show
</body>
</html>
</code>```

My troubles began when I want to add a script inside the script section from a child.

```<code>@extends('layouts.app')

@section('scripts')
    <script type="text/javascript">
        $(document).ready(function () {
            alert('test');
        });
    </script>
@endsection
</code>```

I got Uncaught ReferenceError: $ is not defined like if jquery wasn't loaded.

I have no clue why, any idea ?

[note]

It works if I replace inside app.blade.php :

```<code><script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>
</code>```

with :

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

答:
I finally figure who was guilty : Mix (or the way I used Mix)

I wrongly believed that mix.js and mix.scripts was the same function. But mix.scripts only combine and minify files while mix.js also do compiling ECMAScript 2015 and module bundling. I don't really know why but it was a problem in my case.

```<code>mix.js(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js');
</code>```

replaced by :

```<code>mix.scripts(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js/all.js');
</code>```

See more : Laravel doc

Title: Laravel 5.4 Script loading issue

Body:
I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected.
I use Mix and Blade :

// webpack.mix.js
let { mix } = require('laravel-mix').mix;

    // copy fonts and patterns
mix .copy('resources/assets/vendor/bootstrap/fonts', 'public/fonts')
    .copy('resources/assets/vendor/font-awesome/fonts', 'public/fonts')
    .copy('resources/assets/patterns', 'public/css/patterns')

    // compile scss and concatenate css files
    .sass('resources/assets/sass/app.scss', 'public/css')
    .styles([
        'resources/assets/vendor/bootstrap/css/bootstrap.css',
        'resources/assets/vendor/animate/animate.css'
        // ...
    ], 'public/css/vendor.css')

    // concatenate js files
    .js([
        'resources/assets/vendor/jquery/jquery-3.1.1.min.js',
        'resources/assets/vendor/bootstrap/js/bootstrap.js',
        'resources/assets/js/app.js'
        // ...
    ], 'public/js/app.js')
    .options({ processCssUrls: false }); // fix for path issue : https://github.com/almasaeed2010/AdminLTE/issues/1360

After npm run dev compliation looks good :

DONE  Compiled successfully in 6497ms                                                     4:20:57 PM

                                   Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.ttf   45.4 kB          [emitted]
                              /js/app.js    1.2 MB       0  [emitted]  [big]  /js/app
                       mix-manifest.json  66 bytes          [emitted]
  fonts/glyphicons-halflings-regular.eot   20.1 kB          [emitted]
fonts/glyphicons-halflings-regular.woff2     18 kB          [emitted]
  fonts/glyphicons-halflings-regular.svg    109 kB          [emitted]
 fonts/glyphicons-halflings-regular.woff   23.4 kB          [emitted]
                            /css/app.css    178 kB       0  [emitted]         /js/app
           fonts/fontawesome-webfont.ttf    166 kB          [emitted]
           fonts/fontawesome-webfont.svg    444 kB          [emitted]  [big]
           fonts/fontawesome-webfont.eot    166 kB          [emitted]
          fonts/fontawesome-webfont.woff     98 kB          [emitted]
         fonts/fontawesome-webfont.woff2   77.2 kB          [emitted]
                   fonts/FontAwesome.otf    135 kB          [emitted]
         css/patterns/header-profile.png   5.88 kB          [emitted]

CSS works fine, bootstrap.js also works and when I check inside /js/app.js it seems like everything is inside.

An here is my tempate :

{{-- app.blade.php--}}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
    <link rel="stylesheet" href="{!! asset('css/app.css') !!}" />

    @yield('content')

    @section('scripts')
    @show

My troubles began when I want to add a script inside the script section from a child.

@extends('layouts.app')

@section('scripts')

@endsection

I got Uncaught ReferenceError: $ is not defined like if jquery wasn't loaded.

I have no clue why, any idea ?

[note]

It works if I replace inside app.blade.php :

with :

Body:
I finally figure who was guilty : Mix (or the way I used Mix)

I wrongly believed that mix.js and mix.scripts was the same function. But mix.scripts only combine and minify files while mix.js also do compiling ECMAScript 2015 and module bundling. I don't really know why but it was a problem in my case.

mix.js(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js');

replaced by :

mix.scripts(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js/all.js');

See more : Laravel doc


问:
Discord.js check roles
How can you check roles from a certain server/guild?

Scenario:
I have two discord servers, one old with 3k+ people, the other new: only selected people can join, my bot is on both.
I have been handing out invites through PM, but I want to make the invite link public
But only certain people can join new server, only the people that have "OG" role, if they don't have that role in server 1, they will get kicked/banned from server two whenever they try to join

so far I have this:

```<code>bot.on("guildMemberAdd", member => {
  let guild = member.guild;
  let user = member.user;
  // log [join] from each server
  console.log(user.username + " (" + user.id + ") joined " + guild.name + " (" + guild.id + ")");

});
</code>```

答:
As long as you have the Guild object of the server you want to check the role of in your client's list of Guilds, this isn't too difficult to do. All you need to do is figure out the id string of the Guild you want to check permissions in. Then, you need to get the user's GuildMember from the other Guild and check its roles. If they aren't in the other Guild or they don't have the role, kick/ban them.

```<code>bot.on("guildMemberAdd", member => {
  let guild = member.guild;
  let user = member.user;
  let oldGuild = bot.guilds.filter(x.id => x === /* put the id string here */);
  let oldGuildMember = oldGuild.member(user);
  if (oldGuildMember == undefined || !oldGuildMember.roles.has('OG')) {
    member.kick().then((kicked) => {
      if (kicked) {
        console.log('Kicked ' + user.name);
      } else {
        console.log('Failed to kick user.');
      }
    });
  }
});
</code>```

Title: Discord.js check roles

Body:
How can you check roles from a certain server/guild?

Scenario:
I have two discord servers, one old with 3k+ people, the other new: only selected people can join, my bot is on both.
I have been handing out invites through PM, but I want to make the invite link public
But only certain people can join new server, only the people that have "OG" role, if they don't have that role in server 1, they will get kicked/banned from server two whenever they try to join

so far I have this:

bot.on("guildMemberAdd", member => {
  let guild = member.guild;
  let user = member.user;
  // log [join] from each server
  console.log(user.username + " (" + user.id + ") joined " + guild.name + " (" + guild.id + ")");

});

Body:
As long as you have the Guild object of the server you want to check the role of in your client's list of Guilds, this isn't too difficult to do. All you need to do is figure out the id string of the Guild you want to check permissions in. Then, you need to get the user's GuildMember from the other Guild and check its roles. If they aren't in the other Guild or they don't have the role, kick/ban them.

bot.on("guildMemberAdd", member => {
  let guild = member.guild;
  let user = member.user;
  let oldGuild = bot.guilds.filter(x.id => x === /* put the id string here */);
  let oldGuildMember = oldGuild.member(user);
  if (oldGuildMember == undefined || !oldGuildMember.roles.has('OG')) {
    member.kick().then((kicked) => {
      if (kicked) {
        console.log('Kicked ' + user.name);
      } else {
        console.log('Failed to kick user.');
      }
    });
  }
});


问:
Python String to dateTime conversion
I have a string like

```<code>a = "datetime.datetime(2009,04,01)"
</code>```

I would like to convert this to a datetime object in python. How should I proceed?

答:
You can use eval

```<code>eval('datetime.datetime(2009, 1, 1)')
</code>```

You'll have to make sure datetime is imported first

```<code>>>> import datetime
>>> d = datetime.datetime(2009, 1, 1)
>>> repr(d)
'datetime.datetime(2009, 1, 1, 0, 0)`
>>> eval(repr(d))
datetime.datetime(2009, 1, 1, 0, 0)
</code>```

Title: Python String to dateTime conversion

Body:
I have a string like

a = "datetime.datetime(2009,04,01)"

I would like to convert this to a datetime object in python. How should I proceed?

Body:
You can use eval

eval('datetime.datetime(2009, 1, 1)')

You'll have to make sure datetime is imported first

>>> import datetime
>>> d = datetime.datetime(2009, 1, 1)
>>> repr(d)
'datetime.datetime(2009, 1, 1, 0, 0)`
>>> eval(repr(d))
datetime.datetime(2009, 1, 1, 0, 0)


问:
My c++ programm keeps crashing ist my code bad?
Can somebody pls check if my code is bad? My command prompt crashes when I execute it.

I narrowed the problem down to this section:

```<code>    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");
</code>```

If I comment out 2 out of the 3 functions it seems to work. +
I don't know if my code is bad or of there is a problem with my command prompt.

The rest of the code:

```<code>#include <iostream>

using namespace std;

    string pwpasst (string username, string password, string un, string pw){
        if (username == un && password == pw)
        {
            return "You are logged in!";
        }
    };

int main()
{
    string username;
    string password;

    cout << "Enter your username: ";
    cin >> username;

    cout << "Enter your password: ";
    cin >> password;

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

    if (result != "You are logged in!"){
        cout << "Wrong password or username!";
    }   else { cout << result;}
}
</code>```

答: You are missing a return statement if if (username == un && password == pw) is false, and by your function definition, a string value needs to be returned by the function at the end. That invokes undefined behavior, which causes your program to terminate with a runtime error.

Body:
Can somebody pls check if my code is bad? My command prompt crashes when I execute it.

I narrowed the problem down to this section:

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

If I comment out 2 out of the 3 functions it seems to work. +
I don't know if my code is bad or of there is a problem with my command prompt.

The rest of the code:

#include <iostream>

using namespace std;

    string pwpasst (string username, string password, string un, string pw){
        if (username == un && password == pw)
        {
            return "You are logged in!";
        }
    };

int main()
{
    string username;
    string password;

    cout << "Enter your username: ";
    cin >> username;

    cout << "Enter your password: ";
    cin >> password;

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

    if (result != "You are logged in!"){
        cout << "Wrong password or username!";
    }   else { cout << result;}
}


问:
Angular 2 + NodeJS + Mongoose - post data from angular 2 to rest api nodejs backend. Node api logs: OPTION /url, POST headers doesnt work
I have issue with posting data from angular2 frontend api to backend client - nodeJS + mongoose.
On Angular2 client I make console.log using data, which I'am sending, and service display correct values.

On NodeJS backend I try also to console.log posted data, but I got undefined. Please look at code below, and try to figure out what I make wrong. I tried to this also with Promise<> and Observable<>, with same effect.

PS. GET data from NodeJS api via Angular 2 is working well.

PS2. Important fact, Problem exist, because angular2 doesnt make a headers in post or put. Every time, when I make POST Req, NODE Server logs OPTION /login. What that's mean?

Angular2:

```<code>signIn(data: Object): Observable<User> {
    let bodyString = JSON.stringify(data);

    let headers = new Headers({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    });
    let options = new RequestOptions({ headers: headers });

    console.log("data: ", data, "\nbodyString: ", bodyString, "\nHeaders: ", headers, "\nOptions: ");

    return this.http
        .post( this.signInUrl, bodyString, {headers: headers})
        .map( (res:Response) => res.json() )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

}
</code>```

NodeJS:

```<code>[...]
// configure app
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var mongoose    = require('mongoose');

var Test        = require('./model/test');
var User        = require('./model/user.schema');

mongoose.connect('mongodb://localhost:27017/lounge');

app.set('secret', config.secret);

app.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});
app.post('/login', function (req, res) {
        console.log("Recived login request!", req.body);
    });
[...]
</code>```

答:
I think problem is at nodejs and angular cominication. Because they work on different port they can not comminicate. So you should add this code to nodejs as middleware and also ı recommend you to search "cors express" and "cors npm package". I hope this solve your problem.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});```

Body:
I have issue with posting data from angular2 frontend api to backend client - nodeJS + mongoose.
On Angular2 client I make console.log using data, which I'am sending, and service display correct values.

On NodeJS backend I try also to console.log posted data, but I got undefined. Please look at code below, and try to figure out what I make wrong. I tried to this also with Promise<> and Observable<>, with same effect.

PS. GET data from NodeJS api via Angular 2 is working well.

PS2. Important fact, Problem exist, because angular2 doesnt make a headers in post or put. Every time, when I make POST Req, NODE Server logs OPTION /login. What that's mean?

Angular2:

signIn(data: Object): Observable<User> {
    let bodyString = JSON.stringify(data);

    let headers = new Headers({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    });
    let options = new RequestOptions({ headers: headers });

    console.log("data: ", data, "\nbodyString: ", bodyString, "\nHeaders: ", headers, "\nOptions: ");

    return this.http
        .post( this.signInUrl, bodyString, {headers: headers})
        .map( (res:Response) => res.json() )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

}

NodeJS:

[...]
// configure app
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var mongoose    = require('mongoose');

var Test        = require('./model/test');
var User        = require('./model/user.schema');

mongoose.connect('mongodb://localhost:27017/lounge');

app.set('secret', config.secret);

app.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});
app.post('/login', function (req, res) {
        console.log("Recived login request!", req.body);
    });
[...]


问:
What is the best ORM framework and why?
What is the best ORM Object Relational Mapping framework or architecture in your opinion, And why??</p>

答:
Hibernate.

There is a community support behind it. It s widely used. Easy to learn and use.

Title: What is the best ORM framework and why?


问:
Property trigger bound to flag enum
I have DependencyProperty State of Flags enum type. I want to change some element border color due to changing of the State property. For some reasons I can not operate with the element directly but only by setting its Style.

How can I change following code to make it possible not to check exact value of State but check whether it contains desired flag?

```<code><Style.Triggers>
            <Trigger Property="State" Value="None">
                <Setter Property="StateBorderBrush" Value="Transparent"/>
            </Trigger>
            <Trigger Property="State" Value="Covered">
                <Setter Property="StateBorderBrush" Value="Blue"/>
            </Trigger>
            <Trigger Property="State" Value="Selected">
                <Setter Property="StateBorderBrush" Value="Red"/>
            </Trigger>
            <Trigger Property="State" Value="contains flag 'Controlled'">
                <Setter Property="StateBorderBrush" Value="Orange"/>
            </Trigger>
        </Style.Triggers>
</code>```

答:
This is how you test for an enum in a trigger:</p>

```<code>    <ControlTemplate.Triggers>
        <Trigger Property="ViewState"
                 Value="{x:Static constants:LicenseViewState.License}">
            <Setter Property="Visibility"
                    Value="Collapsed"
                    TargetName="ProductComboBoxField">
            </Setter>
        </Trigger>
    </ControlTemplate.Triggers>
</code>```

Title: Property trigger bound to flag enum

Body:
This is how you test for an enum in a trigger:

    <ControlTemplate.Triggers>
        <Trigger Property="ViewState"
                 Value="{x:Static constants:LicenseViewState.License}">
            <Setter Property="Visibility"
                    Value="Collapsed"
                    TargetName="ProductComboBoxField">
            </Setter>
        </Trigger>
    </ControlTemplate.Triggers>


问:
Pushing Object to array does not reflect at ng-repeat
I am updating an array by pushing the Json object returned by MVC controller to an array in Angular JS controller.

Following is the code sports-controller.js

```<code>portsApp.controller("SportsController", ["$scope","$http",function ($scope,$http) {
    $scope.data = { id: "rehmat" };
    $scope.sports = [];
    $scope.selectedSport ={};
    $scope.sportsObj = {};

    $scope.SportsModel = {};

    $scope.sport = {};

    $scope.remoteUrlRequestFn = function (str) {
        return { term: str };
    };

    function genericSuccess(res) {
        return res.data; // yes, really.
    }
    $scope.selectedSport = function (selected) {
        $scope.sport =
            {
            title: selected.originalObject.name,
            parent_id: selected.originalObject.parent,
            sports_id: selected.originalObject.sports_id,
            user_id: selected.originalObject.uid

        }
        $http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
        });

    }

    $scope.UpdateSport = function (id) {
        if(id > 0)
        {
            $http.post("/usersports/update_sports", { user_sport_id: id }).then(function (data,status,headers,config){

                if(data.Success)
                {
                   alert(data.Message)
                }else
                {
                    alert(data.Message)
                }

            })
        }
    }

}
])
</code>```

VIEW :

```<code><div class="container sports-c" ng-app="SportsApp" >
    <!--ADD SPORTS TEXT-->
    <div class="col-lg-12" ng-controller="SportsController">
        {{sports}}
        <div class="add-sports-text  ">

            <h1 style="text-align:center;" class="animated jello">ADD SPORTS</h1>
            <hr style="width:30%">
            <p>
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            </p>
        </div>
        <div class="form-group" style="text-align:center;">
            <label for="search" style="text-align:center;"> SEARCH</label>
            <angucomplete-alt id="sports_input_box"
                              placeholder="Search Sports"
                              pause="400"
                              selected-object="selectedSport"
                              remote-url="/ajax/getSports"
                              remote-url-request-formatter="remoteUrlRequestFn"
                              remote-url-data-field="items"
                              title-field="name"
                              minlength="2"
                              input-class="form-control input-custom" />

            @*<input type="Search" placeholder="SEARCH" class="form-control input-custom" id="sports_input_box">*@
        </div>
    </div>
    <div class="col-lg-12">
        <div class="table-responsive">
           {{sports.length}}
             <table class="table  table-bordered " id="sports-table">
                 <tr>
                        <td>ID</td>
                        <td>SPORTS NAME</td>
                        <td>SELECT SKILL LEVEL</td>

                        <td>ACTION</td>
                    </tr>
                <tbody>
                    <tr ng-repeat="item in sports">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td style="position: relative;top: 10px;">
                            <select class="example" name="" ng-change="updatePlayerSkill(item.id)" ng-bind="SportsModel.skill_level">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                            </select>
                        </td>
                        <td class="icons-tab">
                            <a href=""><i class="fa fa-check-square-o" aria-hidden="true" ng-click="UpdateSport(item.id)"></i></a>
                            <a href=""><i class="fa fa-trash-o" aria-hidden="true" ng-click="RemoveSport(item.id)"></i></a>
                        </td>
                    </tr>
                    <tr ng-show="sports.length === 0"><td colspan="5">No Sports Added</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

What is a possible solution for this since I am updating the array by pushing the elements and its not reflecting?

I am using Angular Js 1.6, any help would be really appreciated.

please check the image

答:
Try to surround the code that is pushing the element in the array with a $timeout (Don't forget to inject the $timeout in your controller). This will trigger the diggest cycle and update the bindings, as can be seen here.

`

```<code>$http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
       $timeout(function(){
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
       });
    });
</code>```

`

Body:
I am updating an array by pushing the Json object returned by MVC controller to an array in Angular JS controller.

Following is the code sports-controller.js

portsApp.controller("SportsController", ["$scope","$http",function ($scope,$http) {
    $scope.data = { id: "rehmat" };
    $scope.sports = [];
    $scope.selectedSport ={};
    $scope.sportsObj = {};

    $scope.SportsModel = {};

    $scope.sport = {};

    $scope.remoteUrlRequestFn = function (str) {
        return { term: str };
    };

    function genericSuccess(res) {
        return res.data; // yes, really.
    }
    $scope.selectedSport = function (selected) {
        $scope.sport =
            {
            title: selected.originalObject.name,
            parent_id: selected.originalObject.parent,
            sports_id: selected.originalObject.sports_id,
            user_id: selected.originalObject.uid

        }
        $http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
        });

    }

    $scope.UpdateSport = function (id) {
        if(id > 0)
        {
            $http.post("/usersports/update_sports", { user_sport_id: id }).then(function (data,status,headers,config){

                if(data.Success)
                {
                   alert(data.Message)
                }else
                {
                    alert(data.Message)
                }

            })
        }
    }

}
])

VIEW :

        {{sports}}

ADD SPORTS

                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

             SEARCH
            <angucomplete-alt id="sports_input_box"
                              placeholder="Search Sports"
                              pause="400"
                              selected-object="selectedSport"
                              remote-url="/ajax/getSports"
                              remote-url-request-formatter="remoteUrlRequestFn"
                              remote-url-data-field="items"
                              title-field="name"
                              minlength="2"
                              input-class="form-control input-custom" />

            @*<input type="Search" placeholder="SEARCH" class="form-control input-custom" id="sports_input_box">*@

           {{sports.length}}

                        ID
                        SPORTS NAME
                        SELECT SKILL LEVEL

                        ACTION

                        {{item.id}}
                        {{item.name}}

                            <select class="example" name="" ng-change="updatePlayerSkill(item.id)" ng-bind="SportsModel.skill_level">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                            </select>

No Sports Added

What is a possible solution for this since I am updating the array by pushing the elements and its not reflecting?

I am using Angular Js 1.6, any help would be really appreciated.

please check the image

Body:
Try to surround the code that is pushing the element in the array with a $timeout (Don't forget to inject the $timeout in your controller). This will trigger the diggest cycle and update the bindings, as can be seen here.

`

$http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
       $timeout(function(){
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
       });
    });

`


问:
Two objects having same hashcode means they are referring to same object ..right?
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?</p>

```<code> object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }
</code>```

答:
If two references refer to the same instance, selecting hashCode will invoke that method on the instance.

It's not relevant that two variables are used, and it's not relevant whether the referent is a Singleton.

```<code>scala> val x = new AnyRef
x: Object = java.lang.Object@21fdfefc

scala> val y = x
y: Object = java.lang.Object@21fdfefc

scala> x.hashCode == y.hashCode
res0: Boolean = true
</code>```

Body:
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?

 object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }

Body:
If two references refer to the same instance, selecting hashCode will invoke that method on the instance.

It's not relevant that two variables are used, and it's not relevant whether the referent is a Singleton.

scala> val x = new AnyRef
x: Object = java.lang.Object@21fdfefc

scala> val y = x
y: Object = java.lang.Object@21fdfefc

scala> x.hashCode == y.hashCode
res0: Boolean = true


问:
Connect Java to a MySQL database
How do you connect to a MySQL database in Java?

When I try, I get

```<code>java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
</code>```

Or

```<code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
</code>```

Or

```<code>java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
</code>```

答:
MySQL JDBC Connection with useSSL. </p>

```<code>private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private String connectToDb() throws Exception {
   String jdbcDriver = "com.mysql.jdbc.Driver";
   String dbUrl = "jdbc:mysql://" + db_server  +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
    String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
    ResultSet resultSet = statement.executeQuery(query);
    resultSet.next();
    return resultSet.getString(1);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Connect Java to a MySQL database

Body:
How do you connect to a MySQL database in Java?

When I try, I get

java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)

Or

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Or

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

Body:
MySQL JDBC Connection with useSSL.

private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private String connectToDb() throws Exception {
   String jdbcDriver = "com.mysql.jdbc.Driver";
   String dbUrl = "jdbc:mysql://" + db_server  +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
    String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
    ResultSet resultSet = statement.executeQuery(query);
    resultSet.next();
    return resultSet.getString(1);
}


问:
Accessing a Dictionary.Keys Key through a numeric index
I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

```<code>int LastCount = mydict[mydict.keys[mydict.keys.Count]];
</code>```

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

答:
I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.

You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).

Body:
I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

int LastCount = mydict[mydict.keys[mydict.keys.Count]];

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?


问:
Algorithm to randomly generate an aesthetically-pleasing color palette
I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc.

I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors.

Any ideas would be great.

答:
It's going to be hard to get what you want algorithmically - people have been studying color theory for a long time, and they don't even know all the rules.

However, there are some rules which you can use to cull bad color combinations (ie, there are rules for clashing colors, and choosing complementary colors).

I'd recommend you visit your library's art section and check out books on color theory to gain a better understanding of what is a good color before you try to make one - it appears you might not even know why certain combinations work and others don't.

-Adam

OwnerDisplayName: Brian Gianforcaro

OwnerDisplayName: Adam Davis


问:
JSON Syntax: Transmitting an array
A valid JSON Syntax is something of the kind:

```<code>{
  "username": "admin",
  "password": "123"
}
</code>```

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

```<code>[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]
</code>```

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

答:
Yes, your example is valid JSON - that is exactly how you want to use an array.

Edit : Here is a good link on JSON and its usage.

OwnerDisplayName: Dreas Grech

Title: JSON Syntax: Transmitting an array

Body:
A valid JSON Syntax is something of the kind:

{
  "username": "admin",
  "password": "123"
}

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

OwnerDisplayName: Andrew Hare


问:
Make the document un tracked changeable in Word 2013
On word-2013, I am unable to understand that what happened to my word document. The line I want to delete or change is going to cut with a red color and remains in the document as showing the picture below.

I want to get rid from it. Any solution to get rid it off?

答:
On the Review Tab in the Ribbon you have enabled the Track Changes option and set the Markup option most likely to "All Markup".

If you want to keep track of changes leave this enabled but set your Markup option to either "No Markup" or "Simple Markup". Otherwise just disable Track Changes.

Your question is not a developer question, you are most likely better served when you ask questions like this on SuperUser.com

To serve developers looking for a solution in code, turning Markup off in VBA can be done like this:

```<code>With ActiveWindow.View.RevisionsFilter
    .Markup = wdRevisionsMarkupNone
    .View = wdRevisionsViewFinal
End With
</code>```

Body:
On the Review Tab in the Ribbon you have enabled the Track Changes option and set the Markup option most likely to "All Markup".

If you want to keep track of changes leave this enabled but set your Markup option to either "No Markup" or "Simple Markup". Otherwise just disable Track Changes.

Your question is not a developer question, you are most likely better served when you ask questions like this on SuperUser.com

To serve developers looking for a solution in code, turning Markup off in VBA can be done like this:

With ActiveWindow.View.RevisionsFilter
    .Markup = wdRevisionsMarkupNone
    .View = wdRevisionsViewFinal
End With


问:
Passing a variable into another page and running the variable
Is it possible to pass a variable from one page to the next page and running that variable at the same time?

What I am trying to do is have a search bar that allows the user to search and upon enter opening up a new page that has a datatable. I want to pass what they type into search bar into the search bar of the datatable and have the results shown.

```<code><!-- START Search form-->
            <form role="search" action="searchalltransactions.cfm" class="navbar-form">
               <div class="form-group has-feedback">
                  <input type="text" placeholder="Type and hit enter ..." class="form-control">
                  <div data-search-dismiss="" class="fa fa-times form-control-feedback"></div>
               </div>
               <button type="submit" class="hidden btn btn-default">Submit</button>
            </form>
            <!-- END Search form-->
</code>```

Is something like this possible? I am not familiar with this and just trying to learn how to do this if its even possible.

How can I pass this into the (search that datatables creates) on the next page searchalltransactions.cfm

Search that jquery datatables creates

```<code> <input class="form-control input-sm" placeholder="" aria-controls="processing1" type="search">
</code>```

答:
While I am not familiar with datatables, or much of what you are doing, I do think I can help. You can use localStorage with javascript to store the variable.

```<code>localStorage.setItem("userSearch", value);
</code>```

In this code "userSearch will be the name of the variable, and value is the value of the search. this will be stored similar to cookies, only that localStorage doesn't have an expiration date.

Then when you want to use the value you would run

```<code>var search = localStorage.search;
</code>```

You will need to compensate for any data type other than string by parsing localStorage.search

I hope that this at least leads you in the right direction, and that if this is not a feasible solution, I hope you find one.

Body:
Is it possible to pass a variable from one page to the next page and running that variable at the same time?

What I am trying to do is have a search bar that allows the user to search and upon enter opening up a new page that has a datatable. I want to pass what they type into search bar into the search bar of the datatable and have the results shown.

            <form role="search" action="searchalltransactions.cfm" class="navbar-form">

                  <input type="text" placeholder="Type and hit enter ..." class="form-control">

               <button type="submit" class="hidden btn btn-default">Submit</button>
            </form>

Is something like this possible? I am not familiar with this and just trying to learn how to do this if its even possible.

How can I pass this into the (search that datatables creates) on the next page searchalltransactions.cfm

Search that jquery datatables creates

 <input class="form-control input-sm" placeholder="" aria-controls="processing1" type="search">

Body:
While I am not familiar with datatables, or much of what you are doing, I do think I can help. You can use localStorage with javascript to store the variable.

localStorage.setItem("userSearch", value);

In this code "userSearch will be the name of the variable, and value is the value of the search. this will be stored similar to cookies, only that localStorage doesn't have an expiration date.

Then when you want to use the value you would run

var search = localStorage.search;

You will need to compensate for any data type other than string by parsing localStorage.search

I hope that this at least leads you in the right direction, and that if this is not a feasible solution, I hope you find one.


问:
iOS dispatch_after is firing immediately
I am trying to fire an event after 6 seconds using dispatch_after.

I'm firing a regular dispatch_after snippet (right built into Xcode itself).

```<code>dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration + 0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [do something];
});
</code>```

duration is 6 seconds. However, [do something] executes instantly (I've got a breakpoint on it). I am on main thread/main queue. What am I doing wrong?

答:
It was a simple operator precedence error. My intention was to pass in a duration parameter but (in case 0 is passed) also add a small amount. 0.01 there.

I've mistakenly written duration + 0.01 * NSEC_PER_SEC trying to mean (duration + 0.01) * NSEC_PER_SEC, but because of operator precedence it was interpreted as duration + (0.01 * NSEC_PER_SEC). I've added the parantheses and it started working correctly.

Body:
I am trying to fire an event after 6 seconds using dispatch_after.

I'm firing a regular dispatch_after snippet (right built into Xcode itself).

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration + 0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [do something];
});

duration is 6 seconds. However, [do something] executes instantly (I've got a breakpoint on it). I am on main thread/main queue. What am I doing wrong?


问:
How can i make the text in the label move like in (marquee) if the label width not fit the text width in C# windows form application?
Is there a way to make the label text move as in marquee but in windows form application , thanks.
Thanks.   </p>

答:
It isn't exactly clear where you might want to move the text to, if it doesn't fit the layout then there are no real options.  In general, window layouts are contrained width-wise but have some room for growth vertically.  Enforce this by setting the Label's MaximumSize property to, say, (100,0) so it cannot grow in the width and overlap some other control.  That will make it start wrapping text and use more vertical space.

If that's a problem as well then set AutoSize = False and AutoEllipsis = True.  The user can now tell that the text got truncated.  And automatically gets a tooltip when she hovers the label.


答:
From the comments -
i can pass it through the url and have it say searchalltransactions.cfm?search=33 but how can i get the 33 to show in the jquery datatables search

Change this:

```<code><input class="form-control input-sm"
placeholder="" aria-controls="processing1" type="search">
</code>```

to this:

```<code><cfoutput>
<input class="form-control input-sm"
placeholder="" aria-controls="processing1" type="search"
value="#url.search#">
</cfoutput>
</code>```

Title: Passing a variable into another page and running the variable

Body:
From the comments -
i can pass it through the url and have it say searchalltransactions.cfm?search=33 but how can i get the 33 to show in the jquery datatables search

Change this:

<input class="form-control input-sm"
placeholder="" aria-controls="processing1" type="search">

to this:

<cfoutput>
<input class="form-control input-sm"
placeholder="" aria-controls="processing1" type="search"
value="#url.search#">
</cfoutput>


问:
Making Input[number] field dependent for another input[number] field by JQuery
Every input field should be dependent for Total Quiz Marks(input field). I just want to set an attribute: max which should be less than or equal to total quiz marks.
I'm attaching a snapshot & I'm sure it will be clear.

& I'm also attaching my html code:

```<code><form action="../controllers/classroom.php" method="POST">
    <input type="number" class="form-control" id="totalMark" name="totalMark" placeholder="Enter quiz mark" required>
    <div class="row">
    <?php
        $count=0;
        $query4="SELECT * FROM enrollments WHERE classId='{$classId}'";
        $res4=mysqli_query($connection, $query4);

        while($row=mysqli_fetch_array($res4)){
            $count++;
    ?>
            <div class="col-md-2">#<?php echo $count; ?></div>
            <div class="col-md-6"><?php echo ucwords(getUser($row['userId'])['name']); ?></div>
            <div class="col-md-4"><input type="number" class="form-control" name="user[<?php echo $row['id']; ?>]" placeholder="Enter marks" required>
            </div>
    <?php } ?>
    </div>
    <button type="submit" name="quiz-marks" class="btn btn-primary">Submit</button>
</form>
</code>```

I want to make a live validation. Thanks

答:
The easist way is to listen for the change event on the #totalMark input then change the max property. I've used jQuery for brevity, but I'm sure you could use vanilla javascript if you wanted.

$(function(){
 $('#totalMark').change(function(){
  $('.form-control:not(#totalMark)').prop('max',this.value)
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="number" class="form-control" id="totalMark" name="totalMark" value="20" placeholder="Enter quiz mark" required>
    <input type="number" class="form-control" max="20" required>
    <input type="number" class="form-control" max="20" required>
    <input type="number" class="form-control" max="20" required>
</form></code>```

Body:
Every input field should be dependent for Total Quiz Marks(input field). I just want to set an attribute: max which should be less than or equal to total quiz marks.
I'm attaching a snapshot & I'm sure it will be clear.

& I'm also attaching my html code:

<form action="../controllers/classroom.php" method="POST">
    <input type="number" class="form-control" id="totalMark" name="totalMark" placeholder="Enter quiz mark" required>

    <?php
        $count=0;
        $query4="SELECT * FROM enrollments WHERE classId='{$classId}'";
        $res4=mysqli_query($connection, $query4);

        while($row=mysqli_fetch_array($res4)){
            $count++;
    ?>

#<?php echo $count; ?>

<?php echo ucwords(getUser($row['userId'])['name']); ?>

<input type="number" class="form-control" name="user[<?php echo $row['id']; ?>]" placeholder="Enter marks" required>

    <?php } ?>

    <button type="submit" name="quiz-marks" class="btn btn-primary">Submit</button>
</form>

I want to make a live validation. Thanks

Body:
The easist way is to listen for the change event on the #totalMark input then change the max property. I've used jQuery for brevity, but I'm sure you could use vanilla javascript if you wanted.

$(function(){
 $('#totalMark').change(function(){
  $('.form-control:not(#totalMark)').prop('max',this.value)
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="number" class="form-control" id="totalMark" name="totalMark" value="20" placeholder="Enter quiz mark" required>
    <input type="number" class="form-control" max="20" required>
    <input type="number" class="form-control" max="20" required>
    <input type="number" class="form-control" max="20" required>
</form>


问:
Case Insensitive Entity Keys
I've got a view vwCountyStateJurisdiction with columns:

```<code>State varchar(2) PK
County varchar(20) PK
Jurisdiction varchar(20) PK
JurisdictionName varchar(100)
</code>```

(those keys are not on the view, but rather added to the entity in EF)

In EF, I'm trying to add an association from the Property table, to this view.  I add the referential constraint, map properties from the Property table over to the three key fields in the view, and attempt to query.  The problem is, those string keys are case sensitive when a property tries to load its related view object.  When the case matches, it loads fine, otherwise I get nulls.

Is there ANY way to get this to be case insensitive?

Needless to say changing the database is not an option.

Thanks

答:
You can try the following approach, but note that it is rather work- and time-consuming.

Create DefiningQuery for each entity that has primary key that should be compared in case insensitive way. These queries should return the Upper(keycolumn) instead of keycolumn (the same for the dependent entities).

Please note that this approach remains read only until you create a set of stored procedures for insert, update and delete for each entity you have defined a query for.

Title: Case Insensitive Entity Keys

Body:
I've got a view vwCountyStateJurisdiction with columns:

State varchar(2) PK
County varchar(20) PK
Jurisdiction varchar(20) PK
JurisdictionName varchar(100)

(those keys are not on the view, but rather added to the entity in EF)

In EF, I'm trying to add an association from the Property table, to this view.  I add the referential constraint, map properties from the Property table over to the three key fields in the view, and attempt to query.  The problem is, those string keys are case sensitive when a property tries to load its related view object.  When the case matches, it loads fine, otherwise I get nulls.

Is there ANY way to get this to be case insensitive?

Needless to say changing the database is not an option.

Thanks


问:
Setup sending post request from android to php script
Android Retrofit's servise interface:

```<code>//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " + BuildConfig.CLIENT_PASSWORD)
@FormUrlEncoded
@POST("api/post/report")
Observable<Object> postReport(@Field("message") String message);
</code>```

Android monitor tells:

```<code>--> POST http://<mysite>/api/post/report http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 104
D/OkHttp: message=%D0%B2%D0%BB%D0%BE%D1%81%D0%B8%3A%20%D1%81%D0%BB%D1%87%D0%BB%D1%8C%D1%8F%D0%B1%D1%8B%D0%B6%D1%8B
D/OkHttp: --> END POST (104-byte body)
</code>```

I do not know how to catch the Message from PHP.

$_POST - is empty

```<code>parse_str(file_get_contents("php://input"), $data);
$data = (object)$data;
</code>```

Different variants of ^ are also not working. They returns nullable results, empty objects and ext

答:
You are making a POST request.

```<code>print_r($_POST);
</code>```

Should give you the value sent from retrofit.

Body:
Android Retrofit's servise interface:

//@Headers("Authorization: " + BuildConfig.CLIENT_NAME + " " + BuildConfig.CLIENT_PASSWORD)
@FormUrlEncoded
@POST("api/post/report")
Observable<Object> postReport(@Field("message") String message);

Android monitor tells:

--> POST http://<mysite>/api/post/report http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 104
D/OkHttp: message=%D0%B2%D0%BB%D0%BE%D1%81%D0%B8%3A%20%D1%81%D0%BB%D1%87%D0%BB%D1%8C%D1%8F%D0%B1%D1%8B%D0%B6%D1%8B
D/OkHttp: --> END POST (104-byte body)

I do not know how to catch the Message from PHP.

$_POST - is empty

parse_str(file_get_contents("php://input"), $data);
$data = (object)$data;

Different variants of ^ are also not working. They returns nullable results, empty objects and ext

Body:
You are making a POST request.

print_r($_POST);

Should give you the value sent from retrofit.


问:
jQuery if-else working 50%
The code below is inside a document.ready function. The if-else statement works only half the way... the first part (if) works fine, and I made an alert after powerClicked to show me if it's setting powerClicked to 1, and it is. The else if does absolutely nothing... Anyone seeing my error? I don't know if something might be bugging the jQuery, the entire HTML is being rendered over ReactJS VDOM.

var powerClicked = 0;

    if(powerClicked == 0) {
        $('#Power').click(function() {
            powerClicked = 1;
           $('#Power').animate({
              backgroundColor: 'rgba(255,0,0,1)'
           }, 1500);
            //fading in text
        $('#boxText').delay(2000).fadeIn(500).text('Listening');

        });

    } else if(powerClicked == 1) {
        $('#Power').click(function() {

           $('#Power').animate({
              backgroundColor: 'rgba(255,255,255,1)'
           }, 1500);
           //fading out text
            $('boxText').fadeOut(500);
            powerClicked = 0;
        });
    }```

答: $('boxText') you need to change it to $('#boxText') so that it correctly grabs the element node (assuming it has an id of "boxText"

Title: jQuery if-else working 50%


问:
Anaconda menu failed
I tried downloading/installing Versions 3.4, then 3.6 of Anaconda on Windows 10. Each time. I got an error message that the Anaconda menu filed to load.
I did a re-try, then even tried to IGNORE, but then I got another message that the directories had failed to load. Are these versions meant for Windows 10? </p>

<p>Thanks - Steve </p>

答:
This has come up quite a bit. It should be fixed in Anaconda4.3.1. It often happens when installing to all user areas and if you have spaces or unicode characters in the username. It is best to install to your user directory. Even though it gives an error Anaconda is still installed, it just didn't make the Start Menu items. You can install them yourself:</p>

```<code>conda install -f console_shortcut ipython ipython-qtconsole anaconda-navigator spyder jupyter
</code>```

Title: Anaconda menu failed

Body:
I tried downloading/installing Versions 3.4, then 3.6 of Anaconda on Windows 10. Each time. I got an error message that the Anaconda menu filed to load.
I did a re-try, then even tried to IGNORE, but then I got another message that the directories had failed to load. Are these versions meant for Windows 10?

Thanks - Steve

Body:
This has come up quite a bit. It should be fixed in Anaconda4.3.1. It often happens when installing to all user areas and if you have spaces or unicode characters in the username. It is best to install to your user directory. Even though it gives an error Anaconda is still installed, it just didn't make the Start Menu items. You can install them yourself:

conda install -f console_shortcut ipython ipython-qtconsole anaconda-navigator spyder jupyter


问:
How to use multiple queries on Entity Framework backed datagridview?
I have a form with a datagridview. The datagridview datasource is set to an Entity Framework data context.

```<code>_dc = New WarehouseEntities1
_dc.Configuration.ProxyCreationEnabled = False
_dc.USER_MANAGEMENT_INFO.Load()
dgvSUMA.DataSource = _dc.USER_MANAGEMENT_INFO.Local.ToBindingList()
</code>```

This works fine. I have a number of search boxes that filter the data and these work fine as well.

```<code>If txtUserNameSrch.Text <> "" Then
    Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.Where(Function(c) c.USER_NAME.Contains(pQrytxt)).ToList()
    dgvSUMA.DataSource = pOC
End If

If Not chkbxIncludeDropped.Checked Then
    Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.Where(Function(c) c.USER_STATUS.Contains("ACTIVE")).ToList()
    dgvSUMA.DataSource = pOC

End If
</code>```

Again this works fine except that only one filter is applied at a time. I want to combine the Where queries if they are both set and so far I'm failing. I don't want to combine them in if statements as I have 15 different search controls. Instead I want to apply the filters to the results of the previous filter and then set the datagridview datasource at the end.

This post is similar to what I want to do but in c#

答:
If you are OK with executing the query up front, then filtering the results, you can do this. Move the declaration of pOC out of each If, so it can be filtered in each place.

```<code>Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.ToList() ' database is queried

If txtUserNameSrch.Text <> "" Then
    pOC = pOC.Where(Function(c) c.USER_NAME.Contains(pQrytxt)).ToList() ' filtered
End If

If Not chkbxIncludeDropped.Checked Then
    pOC = pOC.Where(Function(c) c.USER_STATUS.Contains("ACTIVE")).ToList() ' filtered
End If

dgvSUMA.DataSource = pOC
</code>```

Body:
I have a form with a datagridview. The datagridview datasource is set to an Entity Framework data context.

_dc = New WarehouseEntities1
_dc.Configuration.ProxyCreationEnabled = False
_dc.USER_MANAGEMENT_INFO.Load()
dgvSUMA.DataSource = _dc.USER_MANAGEMENT_INFO.Local.ToBindingList()

This works fine. I have a number of search boxes that filter the data and these work fine as well.

If txtUserNameSrch.Text <> "" Then
    Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.Where(Function(c) c.USER_NAME.Contains(pQrytxt)).ToList()
    dgvSUMA.DataSource = pOC
End If

If Not chkbxIncludeDropped.Checked Then
    Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.Where(Function(c) c.USER_STATUS.Contains("ACTIVE")).ToList()
    dgvSUMA.DataSource = pOC

End If

Again this works fine except that only one filter is applied at a time. I want to combine the Where queries if they are both set and so far I'm failing. I don't want to combine them in if statements as I have 15 different search controls. Instead I want to apply the filters to the results of the previous filter and then set the datagridview datasource at the end.

This post is similar to what I want to do but in c#

Body:
If you are OK with executing the query up front, then filtering the results, you can do this. Move the declaration of pOC out of each If, so it can be filtered in each place.

Dim pOC = _dc.USER_MANAGEMENT_INFO.Local.ToList() ' database is queried

If txtUserNameSrch.Text <> "" Then
    pOC = pOC.Where(Function(c) c.USER_NAME.Contains(pQrytxt)).ToList() ' filtered
End If

If Not chkbxIncludeDropped.Checked Then
    pOC = pOC.Where(Function(c) c.USER_STATUS.Contains("ACTIVE")).ToList() ' filtered
End If

dgvSUMA.DataSource = pOC


问:
Obtaining the Build ID in a Java Application
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime? </p>

<p>Building from within Eclipse, all I need is the ID, I can then pass it up to the title.  </p>

答:
If you are using Ant, you can easily set up your "jar" or "package" target so that it generates a file including the current timestamp and include this in your jar output.

If using Maven, there are a few ways to achieve something similar, such as dropping down to Ant using the antrun plugin.

Body:
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime?

Building from within Eclipse, all I need is the ID, I can then pass it up to the title.


问:
Send email with Qt
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

```<code>    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}
</code>```

how to make it able to send english and non english text
thank you

答:
fixed by setting
"Content-Type: text/plain;
and
setting codec in
QTextStream t ;
t.setcodec("UTF-8"");</p>

Title: Send email with Qt

Body:
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}

how to make it able to send english and non english text
thank you


问:
Cannot create AD Application with Service Principal
```<code>C:\> $app = New-AzureRmADApplication -DisplayName "exampleapp" -HomePage "https://www.contoso.org/exampleapp" -IdentifierUris "https://www.contoso.org/exampleapp" -Password "Qwertyu123$"
New-AzureRmADApplication : Resource not found for the segment 'me'.
</code>```

I can issue the same command using the owner account. The thing is this application has almost all possible permissions with Azure (including owner)

edit - command used to launch Azure session:

```<code>Add-AzureRmAccount -TenantId $env:tenant_id -ServicePrincipal `
   -Credential ([pscredential]::new($env:app_id,(ConvertTo-SecureString -String $env:app_key -AsPlainText -Force)))
</code>```

Obviously I'm missing some permission(s), which one(s)?

Body: {   "odata.error": {
      "code": "Authorization_RequestDenied",
      "message": {
        "lang": "en",
        "value": "Insufficient privileges to complete the operation."
      },
      "requestId": "9c3bf711-c9ad-4883-a5cf-fa7926ccdf63",
      "date": "2017-03-06T10:14:29"   } }

答: So I guess that would be some kind of transient failure cloud is famous for, nothing did I change yet this is now working.</p>

Body:
C:\> $app = New-AzureRmADApplication -DisplayName "exampleapp" -HomePage "https://www.contoso.org/exampleapp" -IdentifierUris "https://www.contoso.org/exampleapp" -Password "Qwertyu123$"
New-AzureRmADApplication : Resource not found for the segment 'me'.

I can issue the same command using the owner account. The thing is this application has almost all possible permissions with Azure (including owner)

edit - command used to launch Azure session:

Add-AzureRmAccount -TenantId $env:tenant_id -ServicePrincipal `
   -Credential ([pscredential]::new($env:app_id,(ConvertTo-SecureString -String $env:app_key -AsPlainText -Force)))

Obviously I'm missing some permission(s), which one(s)?

Body: {   "odata.error": {
      "code": "Authorization_RequestDenied",
      "message": {
        "lang": "en",
        "value": "Insufficient privileges to complete the operation."
      },
      "requestId": "9c3bf711-c9ad-4883-a5cf-fa7926ccdf63",
      "date": "2017-03-06T10:14:29"   } }


问:
Python String to dateTime conversion
I have a string like

```<code>a = "datetime.datetime(2009,04,01)"
</code>```

I would like to convert this to a datetime object in python. How should I proceed?

答:
The code in the previous answer would work, but using eval is considered risky, because an unexpected input could have disastrous consequences. (Here's more info on why eval can be dangerous.)

A better option here is to use Python's strptime method:

```<code>from datetime import datetime

datetime_string = "datetime.datetime(2017, 3, 31)"
format = "datetime.datetime(%Y, %m, %d)"
datetime_object = datetime.strptime(datetime_string, format)
</code>```

There are lots of different formats you can use for parsing datetimes from strings. You may want to check out the docs: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Title: Python String to dateTime conversion

Body:
I have a string like

a = "datetime.datetime(2009,04,01)"

I would like to convert this to a datetime object in python. How should I proceed?

Body:
The code in the previous answer would work, but using eval is considered risky, because an unexpected input could have disastrous consequences. (Here's more info on why eval can be dangerous.)

A better option here is to use Python's strptime method:

from datetime import datetime

datetime_string = "datetime.datetime(2017, 3, 31)"
format = "datetime.datetime(%Y, %m, %d)"
datetime_object = datetime.strptime(datetime_string, format)

There are lots of different formats you can use for parsing datetimes from strings. You may want to check out the docs: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior