问:
cannot Install Angular2 app using Cli

i followed link; https://github.com/angular/angular-cli/wiki

npm version:5.0.1

node version:6.11.0

i run command

```<code>   npm install -g @angular/cli
</code>```

solution i tried

```<code>npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
</code>```

but it doesn't work for me .

does it is npm bug or angular2.

please suggest.

error

```<code>unexpected end of input at 1:13267
</code>```

i also tried with ;https://angular.io/docs/ts/latest/guide/setup.html.

npm install not working

答:
You can try to uninstall wrong packages by:

```<code>npm uninstall -g angular-cli          # Remove global package
npm uninstall --save-dev angular-cli  # Remove from package.json

npm uninstall -g @angular/cli         # Remove global package
npm uninstall --save-dev @angular/cli # Remove from package.json

rm -rf node_modules dist # Use rmdir on Windows
npm cache clean
</code>```

And now:

```<code> npm install npm@latest -g                   #update npm
 npm install -g @angular/cli@latest          # Global package
 npm install --save-dev @angular/cli@latest  # Local package
 npm install                                 # Restore removed dependencies
</code>```

More information can be found here: https://github.com/angular/angular-cli/wiki/stories-1.0-update

Title: cannot Install Angular2 app using Cli

Body:
i followed link; https://github.com/angular/angular-cli/wiki

npm version:5.0.1

node version:6.11.0

i run command

   npm install -g @angular/cli

solution i tried

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

but it doesn't work for me .

does it is npm bug or angular2.

please suggest.

error

unexpected end of input at 1:13267

i also tried with ;https://angular.io/docs/ts/latest/guide/setup.html.

npm install not working

Body:
You can try to uninstall wrong packages by:

npm uninstall -g angular-cli          # Remove global package
npm uninstall --save-dev angular-cli  # Remove from package.json

npm uninstall -g @angular/cli         # Remove global package
npm uninstall --save-dev @angular/cli # Remove from package.json

rm -rf node_modules dist # Use rmdir on Windows
npm cache clean

And now:

 npm install npm@latest -g                   #update npm
 npm install -g @angular/cli@latest          # Global package
 npm install --save-dev @angular/cli@latest  # Local package
 npm install                                 # Restore removed dependencies

More information can be found here: https://github.com/angular/angular-cli/wiki/stories-1.0-update


来源: stackexchange

问:
What is the difference between the Ping and WebClient classes in C#
I was looking for ways to check and report the status of a webservice, and came across both these classes. Is there any benefit in using one of these over the other?</p>

答:
Ping sends ICMP echo requests to the target machine. Many machines will not respond to these requests because firewalls. So this is an unreliable means of checking if a machine is running, let alone running the service you're interested in connecting to.

The best way to check if a service is running is to try and use it (without any kind of pre-check) in the way that the service provider intends you to use it. If it doesn't work, then you can safely say that the service is down.

ContentLicense: CC BY-SA 3.0


问:
windows registry values coming back as long integers
I'm working my way through Violent Python and have encountered a problem with the first program in chapter 3.

The idea is to print the name of each network in HKEY_LOCAL_MACHINE../unmanaged as well as their assigned DefaultGateWayMac.

I've already checked various questions here on SO as I was initially having trouble setting up the script (Violen Python is getting quite old..).

the problem I'm facing is that when I attempt to print the Mac Address I'm getting a bunch of integers. My initial thought was that some of the combinations could be ASCII values, but even trying to convert them wouldn't create a correct MAC-address.

I've checked in my machine's registry keys for mac-addresses and most of them seem fine (some of them are empty). But as mentioned above, none of them seem to print fine.

This is my script:

```<code>from winreg import *

def val2addr(val):
    if val:
        address = ""
        for ch in val:
            if(not int(ch)):
                address += "%02x " % ord(ch)
                address = address.strip(' ').replace(' ', ':')[0: 17]
            else:
                address += str(ch)
        return address
    return "[!] No MAC [!]"

def print_networks():
    net = u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"+\
          "\\NetworkList\\Signatures\\Unmanaged"
    print(str(HKEY_LOCAL_MACHINE) + net)
    key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, (KEY_WOW64_64KEY + KEY_READ))
    print('\n[*] Networks You have Joined:\n')

    for network in range(100):
        try:
            guid = EnumKey(key, network)
            netkey = OpenKey(key, str(guid))
            mac = QueryValueEx(netkey, 'DefaultGatewayMac')[0]
            mac = val2addr(mac)
            network_name = QueryValueEx(netkey, 'Description')[0]
            print("[+] Network Name: " + network_name + "[+] Mac: " + mac)
            CloseKey(netkey)
        except Exception as e:
            print(e)
            break

def main():
    print_networks()

if __name__ == '__main__':
    main()
</code>```

As you can see I've made some changes (in particular to val2addr):

```<code>def val2addr(val):
    addr = ''
    for ch in val:
        addr += '%02x '% ord(ch)
        addr = addr.strip(' ').replace(' ', ':')[0:17]
    return addr
</code>```

Here is some sample output that my program prints:

[*] Networks You have Joined:

[+] Network Name: DIRECT-HUJABERO059243[+] Mac: [!] No MAC [!]
[+] Network Name: Network  2[+] Mac: 72906311290171
[+] Network Name: Network  3[+] Mac: 1447774159240
[+] Network Name: Network[+] Mac: 200205114121180123
[+] Network Name: BTHub3-JZM3[+] Mac: 20451187180235148
[WinError 259] No more data is available
```

答:
Try using this version of val2addr:

```<code>def val2addr(val):
    return ':'.join('{:02X}'.format(b) for b in val)
</code>```

Body:
I'm working my way through Violent Python and have encountered a problem with the first program in chapter 3.

The idea is to print the name of each network in HKEY_LOCAL_MACHINE../unmanaged as well as their assigned DefaultGateWayMac.

I've already checked various questions here on SO as I was initially having trouble setting up the script (Violen Python is getting quite old..).

the problem I'm facing is that when I attempt to print the Mac Address I'm getting a bunch of integers. My initial thought was that some of the combinations could be ASCII values, but even trying to convert them wouldn't create a correct MAC-address.

I've checked in my machine's registry keys for mac-addresses and most of them seem fine (some of them are empty). But as mentioned above, none of them seem to print fine.

This is my script:

from winreg import *

def val2addr(val):
    if val:
        address = ""
        for ch in val:
            if(not int(ch)):
                address += "%02x " % ord(ch)
                address = address.strip(' ').replace(' ', ':')[0: 17]
            else:
                address += str(ch)
        return address
    return "[!] No MAC [!]"

def print_networks():
    net = u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"+\
          "\\NetworkList\\Signatures\\Unmanaged"
    print(str(HKEY_LOCAL_MACHINE) + net)
    key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, (KEY_WOW64_64KEY + KEY_READ))
    print('\n[*] Networks You have Joined:\n')

    for network in range(100):
        try:
            guid = EnumKey(key, network)
            netkey = OpenKey(key, str(guid))
            mac = QueryValueEx(netkey, 'DefaultGatewayMac')[0]
            mac = val2addr(mac)
            network_name = QueryValueEx(netkey, 'Description')[0]
            print("[+] Network Name: " + network_name + "[+] Mac: " + mac)
            CloseKey(netkey)
        except Exception as e:
            print(e)
            break

def main():
    print_networks()

if __name__ == '__main__':
    main()

As you can see I've made some changes (in particular to val2addr):

def val2addr(val):
    addr = ''
    for ch in val:
        addr += '%02x '% ord(ch)
        addr = addr.strip(' ').replace(' ', ':')[0:17]
    return addr

Here is some sample output that my program prints:

[*] Networks You have Joined:

[+] Network Name: DIRECT-HUJABERO059243[+] Mac: [!] No MAC [!]
[+] Network Name: Network  2[+] Mac: 72906311290171
[+] Network Name: Network  3[+] Mac: 1447774159240
[+] Network Name: Network[+] Mac: 200205114121180123
[+] Network Name: BTHub3-JZM3[+] Mac: 20451187180235148
[WinError 259] No more data is available

Body:
Try using this version of val2addr:

def val2addr(val):
    return ':'.join('{:02X}'.format(b) for b in val)


问:
CodingBat Logic-1 > caughtSpeeding
Hi I'm new to Java and I need a little help.The problem is from coding bat:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

```<code> public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday = true){
       if (speed >=61 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday = false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }
</code>```

I'm getting caughtSpeeding(65, true) should be 0 when my code runs to = 1 and caughtSpeeding(85, false) should be 2 when my code runs to = 1 again.

Thanks

答:
Fixed it:</p>

```<code>public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday == true){
       if (speed <=65){
         int2 = 0;
       }
       if (speed >=66 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday == false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }
</code>```

Title: CodingBat Logic-1 > caughtSpeeding

Body:
Hi I'm new to Java and I need a little help.The problem is from coding bat:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

 public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday = true){
       if (speed >=61 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday = false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }

I'm getting caughtSpeeding(65, true) should be 0 when my code runs to = 1 and caughtSpeeding(85, false) should be 2 when my code runs to = 1 again.

Thanks

Body:
Fixed it:

public int caughtSpeeding(int speed, boolean isBirthday) {
      Integer int2 = 0;
      if (speed <= 60){
        int2 = 0;
      }
      if (isBirthday == true){
       if (speed <=65){
         int2 = 0;
       }
       if (speed >=66 && speed <= 85){
        int2 = 1;
       }
       if (speed >= 86){
         int2 = 2;
       }
      }
      if (isBirthday == false){
        if (speed >=61 && speed <=80){
          int2 = 1;
        }
        if (speed >= 81){
          int2 = 2;
        }
      }
      return int2;
    }


问:
How to get FCMToken in Firebase on ios?
As mentioned in Firebase documentation we can retrieve FCMToken as follows.

```<code>NSString *fcmToken = [FIRMessaging messaging].FCMToken;
NSLog(@"FCM registration token: %@", fcmToken);
</code>```

However above returns compile time error Property 'FCMToken' not found on object of type 'FIRMessaging *'.

How to get FCMToken?

答:
Try using :

NSString *fcmToken = [[FIRInstanceID instanceID] token];

For more information on this, please follow: stackoverflow post

Title: How to get FCMToken in Firebase on ios?

Body:
As mentioned in Firebase documentation we can retrieve FCMToken as follows.

NSString *fcmToken = [FIRMessaging messaging].FCMToken;
NSLog(@"FCM registration token: %@", fcmToken);

However above returns compile time error Property 'FCMToken' not found on object of type 'FIRMessaging *'.

How to get FCMToken?


问:
Embedding python interpreter in the TM4c1294XL
I have a python file that I want to run on the board. Hence I want to embed the python interpreter (written in C) in the board. I managed to write separate C project that runs the Python file. It compiles and runs as I want to. Here's the makefile for same:-

```<code>CC=gcc
CFLAGS=-I python3.5 -I config -I . -c -w
LDFLAGS= -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions

all: classifier trainer test link

test:
    $(CC) $(CFLAGS) test.c

trainer: Trainer.c
    $(CC) $(CFLAGS) Trainer.c
    $(CC) Trainer.o $(LDFLAGS) -o Trainer

.ONESHELL:
classifier: Classifier.c
    $(CC) $(CFLAGS) Classifier.c
    # $(CC) Classifier.o $(LLFLAGS) -o Classifier

link:
    $(CC) test.o Classifier.o $(LDFLAGS) -o test

clean:
    rm -f Trainer.o Trainer Classifier.o Classifier
</code>```

http://dpaste.com/3BCY2RE is my entire directory of project "hello" (It is not the one from the examples).

I included "Classifier.h" in my "hello.c" and I am getting the following errors: http://dpaste.com/3KKCF84

Compiler include options (No preincludes):

```<code>"${CG_TOOL_ROOT}/include"
"${workspace_loc:/${ProjName}/TerrainPredict}"
"${workspace_loc:/${ProjName}/TerrainPredict/config}"
"${workspace_loc:/${ProjName}/TerrainPredict/python3.5}"
"${SW_ROOT}/examples/boards/ek-tm4c1294xl"
"${SW_ROOT}"
</code>```

Linker file search paths:

```<code>"libc.a"
"${workspace_loc:/${ProjName}/TerrainPredict/libterrainclf.a}"
"${SW_ROOT}/driverlib/ccs/Debug/driverlib.lib"
</code>```

and:

```<code>"${CG_TOOL_ROOT}/lib"
"${workspace_loc:/hello/TerrainPredict/libterrainclf.a}"
"${CG_TOOL_ROOT}/include"
</code>```

Am I wrong with some of my configurations? Or is this some problem with python interpreter? Any help is greatly appreciated

EDIT:-
As @KevinDTimm suggested, the problem is that there is no pyconfig.h for my environment. This file is required by python to define important variables like source of system clock. I tried removing safety checks in existing pyconfig.h. The first error I am getting is in pytime.h as :

```<code>"_PyTime_t need signed 64-bit integer type"
</code>```

Which was further because of the following code block:

```<code>#ifdef PY_INT64_T
/* _PyTime_t: Python timestamp with subsecond precision. It can be used to
   store a duration, and so indirectly a date (related to another date, like
   UNIX epoch). */
typedef PY_INT64_T _PyTime_t;
#define _PyTime_MIN PY_LLONG_MIN
#define _PyTime_MAX PY_LLONG_MAX
#else
#  error "_PyTime_t need signed 64-bit integer type"
#endif
</code>```

It appears to me that it needs a variable that stores time. I need help in assigning that variable.

答:
From the linked problem

The multiarch error message is a bit misleading. It's not failing because there's a multiarch problem, it's failing because there's a multi-OS problem. /usr/include/python*/pyconfig.h is trying to figure out where to find the real pyconfig.h from, and since it doesn't know, it's bailing out.

You essentially need a pyconfig.h generated for the target environment. I don't know what produced pyconfig.h, perhaps building cython from source? pyconfig.h looks like something generated by gnu autoconf, so there should not be any big problems in generating it.

Body:
I have a python file that I want to run on the board. Hence I want to embed the python interpreter (written in C) in the board. I managed to write separate C project that runs the Python file. It compiles and runs as I want to. Here's the makefile for same:-

CC=gcc
CFLAGS=-I python3.5 -I config -I . -c -w
LDFLAGS= -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions

all: classifier trainer test link

test:
    $(CC) $(CFLAGS) test.c

trainer: Trainer.c
    $(CC) $(CFLAGS) Trainer.c
    $(CC) Trainer.o $(LDFLAGS) -o Trainer

.ONESHELL:
classifier: Classifier.c
    $(CC) $(CFLAGS) Classifier.c
    # $(CC) Classifier.o $(LLFLAGS) -o Classifier

link:
    $(CC) test.o Classifier.o $(LDFLAGS) -o test

clean:
    rm -f Trainer.o Trainer Classifier.o Classifier

http://dpaste.com/3BCY2RE is my entire directory of project "hello" (It is not the one from the examples).

I included "Classifier.h" in my "hello.c" and I am getting the following errors: http://dpaste.com/3KKCF84

Compiler include options (No preincludes):

"${CG_TOOL_ROOT}/include"
"${workspace_loc:/${ProjName}/TerrainPredict}"
"${workspace_loc:/${ProjName}/TerrainPredict/config}"
"${workspace_loc:/${ProjName}/TerrainPredict/python3.5}"
"${SW_ROOT}/examples/boards/ek-tm4c1294xl"
"${SW_ROOT}"

Linker file search paths:

"libc.a"
"${workspace_loc:/${ProjName}/TerrainPredict/libterrainclf.a}"
"${SW_ROOT}/driverlib/ccs/Debug/driverlib.lib"

and:

"${CG_TOOL_ROOT}/lib"
"${workspace_loc:/hello/TerrainPredict/libterrainclf.a}"
"${CG_TOOL_ROOT}/include"

Am I wrong with some of my configurations? Or is this some problem with python interpreter? Any help is greatly appreciated

EDIT:-
As @KevinDTimm suggested, the problem is that there is no pyconfig.h for my environment. This file is required by python to define important variables like source of system clock. I tried removing safety checks in existing pyconfig.h. The first error I am getting is in pytime.h as :

"_PyTime_t need signed 64-bit integer type"

Which was further because of the following code block:

#ifdef PY_INT64_T
/* _PyTime_t: Python timestamp with subsecond precision. It can be used to
   store a duration, and so indirectly a date (related to another date, like
   UNIX epoch). */
typedef PY_INT64_T _PyTime_t;
#define _PyTime_MIN PY_LLONG_MIN
#define _PyTime_MAX PY_LLONG_MAX
#else
#  error "_PyTime_t need signed 64-bit integer type"
#endif

It appears to me that it needs a variable that stores time. I need help in assigning that variable.


问:
Calculating average speed from lon/lat and timestamp using distance (geosphere) and difftime
I am trying to figure out the haversine distance between two consecutive instances (rows) using the distm function from geosphere. Ultimately, i would like to calculate the average speed using the distance in meters divided by the time difference in seconds.

This is how I've calculated the time difference in seconds

```<code>df$Timediff_secs <-
  with(df,
       difftime(Timestamp, ave(Timestamp, ID, FUN=lag), units='secs'))
</code>```

A similar question has been asked before and the answer does work but I need to index by ID so that each new ID starts with NA. I would like to create a new column called df$Distance.

This needs to be edited so that it indexes by ID and so that the first row is NA (since there's no difference in distance to be calculated)

```<code>library(geosphere)
metersPerMile <- 1609.34
pts <- df1[c("lon", "lat")]

## Pass in two derived data.frames that are lagged by one point
segDists <- distVincentyEllipsoid(p1 = pts[-nrow(df),],
                                  p2 = pts[-1,])
sum(segDists)/metersPerMile
# [1] 1013.919
</code>```

Here is some sample data I copied from the link

```<code>> df
          Timestamp      ID      lat       lon
2012-11-12 02:08:41      1  76.57169 -110.8070
2012-11-12 02:09:41      1  76.44325 -110.7525
2012-11-12 02:10:41      1  76.90897 -110.8613
2012-11-12 03:18:41      2  76.11152 -110.2037
2012-11-12 03:19:41      2  76.29013 -110.3838
2012-11-12 03:20:41      2  76.15544 -110.4506
</code>```

Feels like I've tried everything, any help is much appreciated!

答:
If you are inclined to do with data.table here is how:

```<code>df[, Timestamp := parse_datetime(Timestamp)]
df[, distance := distVincentyEllipsoid(p1 = cbind(lon, lat),
                                       p2 = cbind(shift(lon), shift(lat))),
   by = ID]
output <- df[, .(time_diff = as.numeric(Timestamp[.N] - Timestamp[1], unit = "secs") ,
                 tot_distance = sum(distance, na.rm = TRUE)), by = ID]
output[, avg_speed := tot_distance /time_diff]
##    ID time_diff tot_distance avg_speed
## 1:  1       120     66473.26  553.9438
## 2:  2       120     35646.55  297.0546
</code>```

Body:
I am trying to figure out the haversine distance between two consecutive instances (rows) using the distm function from geosphere. Ultimately, i would like to calculate the average speed using the distance in meters divided by the time difference in seconds.

This is how I've calculated the time difference in seconds

df$Timediff_secs <-
  with(df,
       difftime(Timestamp, ave(Timestamp, ID, FUN=lag), units='secs'))

A similar question has been asked before and the answer does work but I need to index by ID so that each new ID starts with NA. I would like to create a new column called df$Distance.

This needs to be edited so that it indexes by ID and so that the first row is NA (since there's no difference in distance to be calculated)

library(geosphere)
metersPerMile <- 1609.34
pts <- df1[c("lon", "lat")]

## Pass in two derived data.frames that are lagged by one point
segDists <- distVincentyEllipsoid(p1 = pts[-nrow(df),],
                                  p2 = pts[-1,])
sum(segDists)/metersPerMile
# [1] 1013.919

Here is some sample data I copied from the link

> df
          Timestamp      ID      lat       lon
2012-11-12 02:08:41      1  76.57169 -110.8070
2012-11-12 02:09:41      1  76.44325 -110.7525
2012-11-12 02:10:41      1  76.90897 -110.8613
2012-11-12 03:18:41      2  76.11152 -110.2037
2012-11-12 03:19:41      2  76.29013 -110.3838
2012-11-12 03:20:41      2  76.15544 -110.4506

Feels like I've tried everything, any help is much appreciated!

Body:
If you are inclined to do with data.table here is how:

df[, Timestamp := parse_datetime(Timestamp)]
df[, distance := distVincentyEllipsoid(p1 = cbind(lon, lat),
                                       p2 = cbind(shift(lon), shift(lat))),
   by = ID]
output <- df[, .(time_diff = as.numeric(Timestamp[.N] - Timestamp[1], unit = "secs") ,
                 tot_distance = sum(distance, na.rm = TRUE)), by = ID]
output[, avg_speed := tot_distance /time_diff]
##    ID time_diff tot_distance avg_speed
## 1:  1       120     66473.26  553.9438
## 2:  2       120     35646.55  297.0546


问:
The term "Add-Migration" is not recognized
I'm using this MSDN Tutorial to run in VS2015 the command PM> Add-Migration MyFirstMigration -context BloggingContext that ran yesterday successfully but today it's giving the following error that is also pointed out by other users here. I even deleted the Migrations folder from solution explorer and the corresponding db from SQL Express 2014 on Win 8.1 but same error. Even if I run Add-Migration MyFirstMigration I get same error:

```<code>Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Add-Migration MyFirstMigration -context BloggingContext
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

Note: I'm using latest version of ASP.NET Core 1.0 and VS2015 - Update 3 released on June 27, 2016.

UPDATE

The following commands work fine from the project directory in the windows explorer when using command window:

```<code>> dotnet ef migrations add MyFirstMigration --context BloggingContext
> dotnet ef database update --context BloggingContext
</code>```

UPDATE 2a

Following is the project.json file:

```<code>{
  "userSecretsId": "aspnet-ASPCore_RTM_CodeFirst_test-bef835d9-9831-41a8-bc3a-cd2f1477a880",

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": {
      "version": "1.0.0",
      "type": "build"
    },
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    }
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
</code>```

答:
These are the steps I followed and it solved the problem

1)Upgraded my Power shell from version 2 to 3

2)Closed the PM Console

3)Restarted Visual Studio

4)Ran the below command in PM Console
 dotnet restore

5)Add-Migration InitialMigration

It worked !!!

Body:
I'm using this MSDN Tutorial to run in VS2015 the command PM> Add-Migration MyFirstMigration -context BloggingContext that ran yesterday successfully but today it's giving the following error that is also pointed out by other users here. I even deleted the Migrations folder from solution explorer and the corresponding db from SQL Express 2014 on Win 8.1 but same error. Even if I run Add-Migration MyFirstMigration I get same error:

Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Add-Migration MyFirstMigration -context BloggingContext
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Note: I'm using latest version of ASP.NET Core 1.0 and VS2015 - Update 3 released on June 27, 2016.

UPDATE

The following commands work fine from the project directory in the windows explorer when using command window:

> dotnet ef migrations add MyFirstMigration --context BloggingContext
> dotnet ef database update --context BloggingContext

UPDATE 2a

Following is the project.json file:

{
  "userSecretsId": "aspnet-ASPCore_RTM_CodeFirst_test-bef835d9-9831-41a8-bc3a-cd2f1477a880",

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": {
      "version": "1.0.0",
      "type": "build"
    },
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    }
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}


问:
How to use Unix command line utils to filter fields from a json record?
I have a text file with many json records in a similar format to the following:

```<code>{"foo":"1","bar":"2","baz":"1","fu":"1"}
{"foo":"3","bar":"2","baz":"4","fu":"2","barf":"1"}
{"foo":"2","bar":"4","baz":"5","fu":"3"}
{"foo":"5","blerg":"1","bar":"6","baz":"6","fu":"7"}
</code>```

How can I use standard unix command line utils to filter out more than one non adjacent field?

Ex. say I want to select only bar and fu, I would want my output to look like:

```<code>"bar":"2" "fu":"1"
</code>```

...or something along those lines. Thanks!

答: Fur future comers, I think json-specific parsers like json command-line tool would be the cleanest solution. The bottom of the readme page there has a few references to alternatives as well</p>

Body:
I have a text file with many json records in a similar format to the following:

{"foo":"1","bar":"2","baz":"1","fu":"1"}
{"foo":"3","bar":"2","baz":"4","fu":"2","barf":"1"}
{"foo":"2","bar":"4","baz":"5","fu":"3"}
{"foo":"5","blerg":"1","bar":"6","baz":"6","fu":"7"}

How can I use standard unix command line utils to filter out more than one non adjacent field?

Ex. say I want to select only bar and fu, I would want my output to look like:

"bar":"2" "fu":"1"

...or something along those lines. Thanks!


问:
Android Studio using , insted of . after formatting string
Im trying to make a calculator, but after i've formatted the text im getting the output in XX,XX insted of XX.XX which makes the program crash when reusing the number.

My code is:

```<code>                tempX = Double.parseDouble(xText.getText().toString());
                //tempY = Double.parseDouble(yText.getText().toString());
                tempA = Double.parseDouble(aText.getText().toString());
                tempB = Double.parseDouble(bText.getText().toString());

                tempY = tempA * tempX + tempB;
                yText.setText(String.format("%.2f", tempY));
</code>```

答:
Just use </p>

```<code>String.format(Locale.US, "%.2f", tempY);
</code>```

Body:
Im trying to make a calculator, but after i've formatted the text im getting the output in XX,XX insted of XX.XX which makes the program crash when reusing the number.

My code is:

                tempX = Double.parseDouble(xText.getText().toString());
                //tempY = Double.parseDouble(yText.getText().toString());
                tempA = Double.parseDouble(aText.getText().toString());
                tempB = Double.parseDouble(bText.getText().toString());

                tempY = tempA * tempX + tempB;
                yText.setText(String.format("%.2f", tempY));

Body:
Just use

String.format(Locale.US, "%.2f", tempY);


问:
How do I clear Command bindings registered by CommandManager?
I have this control (WPF) that uses a CommandBinding and it gets registered like this:

```<code>CommandBinding binding = new CommandBinding(ApplicationCommands.Delete, OnDeleteExecuted, CanExecuteDelete);
CommandManager.RegisterClassCommandBinding(typeof(MyObject), binding);
</code>```

So, when I unload the control, I want to clear this binding. How would I go about that?

Thanks!

答:
If the scope of the Commands is a concrete UIElement, you should better use:

Register a CommandBinding: myUIelement.CommandBindings.Add(myCommand);

Unregister a CommandBinding: myUIelement.CommandBindings.Remove(myCommand);

Unregister all CommandBindings: myUIelement.CommandBindings.Clear();

I hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
I have this control (WPF) that uses a CommandBinding and it gets registered like this:

CommandBinding binding = new CommandBinding(ApplicationCommands.Delete, OnDeleteExecuted, CanExecuteDelete);
CommandManager.RegisterClassCommandBinding(typeof(MyObject), binding);

So, when I unload the control, I want to clear this binding. How would I go about that?

Thanks!


问:
Error when testing a component which uses templateUrl
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});
</code>```

dummy.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}
</code>```

Error after running the test:

```<code>07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98
</code>```

答:
Would you mind trying something?

Import fakeAsync and tick from @angular/core/testing.
Move the .then() body inside the test case, and use fakeAsync() there and let me know how it goes.

```<code>beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [DummyComponent]
    })
    .compileComponents();
}));

it('should work', fakeAsync(() => {
    fixture = TestBed.createComponent(DummyComponent);
    dummyComponentInstance = fixture.componentInstance;
    tick();

    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
}));
</code>```

Hope this works for you!

Body:
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});

dummy.component.ts

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

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}

Error after running the test:

07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98

Body:
Would you mind trying something?

Import fakeAsync and tick from @angular/core/testing.
Move the .then() body inside the test case, and use fakeAsync() there and let me know how it goes.

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [DummyComponent]
    })
    .compileComponents();
}));

it('should work', fakeAsync(() => {
    fixture = TestBed.createComponent(DummyComponent);
    dummyComponentInstance = fixture.componentInstance;
    tick();

    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
}));

Hope this works for you!


问:
Convert decorator to custom widget in DOJO?
I would like to know if it possible to convert my decorator function in a custom widget (based on dijit/form/Select) in order to apply a monkey patch.

Or do you know an alternative solution ?

require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {
  var decorator = function(select) {
    select.on('change', function(value) {
      alert(value);
    });

    select.dropDown._onUpArrow = function() {
      this.focusPrev()
    }.bind(select.dropDown);

    select.dropDown._onDownArrow = function() {
      this.focusNext()
    }.bind(select.dropDown);

    select.dropDown.focusNext = function() {
      var focusNext = function() {
        var next = this._getNextFocusableChild(this.focusedChild, 1);
        this.focusChild(next);
        if (next.option.group) {
          focusNext();
        }
      }.bind(this);
      focusNext();
    }.bind(select.dropDown);

    select.dropDown.focusPrev = function() {
      var focusPrev = function() {
        var prev = this._getNextFocusableChild(this.focusedChild, -1);
        this.focusChild(prev);
        if (prev.option.group) {
          focusPrev();
        }
      }.bind(this);
      focusPrev();
    }.bind(select.dropDown);

    select.dropDown.onItemHover = function(item) {
      if (item.option.group) {
        item._set('hovering', false);
        return;
      }

      if (this.activated) {
        this.set('selected', item);
        if (item.popup && !item.disabled && !this.hover_timer) {
          this.hover_timer = this.defer(function() {
            this._openItemPopup(item);
          }, this.popupDelay);
        }
      } else if (this.passivePopupDelay < Infinity) {
        if (this.passive_hover_timer) {
          this.passive_hover_timer.remove();
        }
        this.passive_hover_timer = this.defer(function() {
          this.onItemClick(item, {
            type: 'click'
          });
        }, this.passivePopupDelay);
      }

      this._hoveredChild = item;

      item._set('hovering', true);
    }.bind(select.dropDown);

    select.dropDown._onItemFocus = function(item) {
      if (item.option.group) {
        return;
      }
      if (this._hoveredChild && this._hoveredChild != item) {
        this.onItemUnhover(this._hoveredChild);
      }
      this.set('selected', item);
    }.bind(select.dropDown);
  };

  var select = new Select({
    name: 'select2',
    options: [{
        label: 'Colors I love',
        value: 'G 1',
        group: true,
        disabled: true
      },
      {
        label: 'Red',
        value: '1'
      },
      {
        label: 'Green',
        value: '2',
        selected: true
      },
      {
        label: 'Yello',
        value: '3'
      },
      {
        label: 'Purple',
        value: '4'
      },
      {
        label: 'Food I love</',
        value: 'G 2',
        group: true,
        disabled: true
      },
      {
        label: 'Red tomatoes',
        value: '1'
      },
      {
        label: 'Green apples',
        value: '3'
      }
    ]
  }, 'select');

  decorator(select);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js">
</script>

<body class="claro">
  <div id="select"></div>
</body></code>```

Code taken from this answer ;

答:
If you want to create a custom form select js widget in your project , without that decorator ,

For reusability Create JS file (by example app/path/MyCustomSelect.js ) , ( make sure you configuring your dojo to locate the created file
 see here in documentation  ) , after importing the resource (AMD using define )create you widget and inherit the select using the declare class ,

at this stage , you have to ovveride the postCreate ( widget base lifcycle method , this is executed after instantiation and before rendring ) and then add you decorator code (by replacing select by the current scope this ) ,

Why using postcreate , beacause the widget is instantiated and all other referenced ressouce are created , so you can access the this.dropDown property , which is impossible in the constructor method , see the above link for better understand of widget lifecycle phases .

After your use the widget in your app , using require("location_to_your_jsile") , and use its refernce in the callback ,

So the MyCustomSelect.js file should looks like :

```<code>define([
  "dojo/_base/declare",
  'dijit/form/Select',
], function(declare, Select) {

  return declare(Select, {
    postCreate: function() {
      //make sur call this , like call super() ; inherited code will be executed
      this.inherited(arguments);

      console.log(this.dropDown);
      this.dropDown._onUpArrow = function() {
        this.focusPrev()
      }.bind(this.dropDown);

      this.dropDown._onDownArrow = function() {
        this.focusNext()
      }.bind(this.dropDown);

      this.dropDown.focusNext = function() {
        var focusNext = function() {
            var next = this._getNextFocusableChild(this.focusedChild, 1);
            this.focusChild(next);
            if (next.option.group) {
              focusNext();
            }
        }.bind(this);
        focusNext();
      }.bind(this.dropDown);

      this.dropDown.focusPrev = function() {
        var focusPrev = function() {
          var prev = this._getNextFocusableChild(this.focusedChild, -1);
          this.focusChild(prev);
          if (prev.option.group) {
            focusPrev();
          }
        }.bind(this);
        focusPrev();
      }.bind(this.dropDown);

      this.dropDown.onItemHover = function(item) {
        if (item.option.group) {
          item._set('hovering', false);
          return;
        }

        if (this.activated) {
          this.set('selected', item);
          if (item.popup && !item.disabled && !this.hover_timer) {
            this.hover_timer = this.defer(function() {
              this._openItemPopup(item);
            }, this.popupDelay);
          }
        } else if (this.passivePopupDelay < Infinity) {
          if (this.passive_hover_timer) {
            this.passive_hover_timer.remove();
          }
          this.passive_hover_timer = this.defer(function() {
            this.onItemClick(item, {
              type: 'click'
            });
          }, this.passivePopupDelay);
        }

        this._hoveredChild = item;

        item._set('hovering', true);
      }.bind(this.dropDown);

      this.dropDown._onItemFocus = function(item) {
        if (item.option.group) {
          return;
        }
        if (this._hoveredChild && this._hoveredChild != item) {
          this.onItemUnhover(this._hoveredChild);
        }
        this.set('selected', item);
      }.bind(this.dropDown);
    }
  });
});
</code>```

If you want a live sample (without using separte file  ) see below snippet :) .

require([
  "dojo/_base/declare",
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(declare, Select, win) {

  var SelectGroup = declare(Select, {
    postCreate: function() {
      //make sur call this , like call super() ; inherited code will be executed
      this.inherited(arguments);

      console.log(this.dropDown);
      this.dropDown._onUpArrow = function() {
        this.focusPrev()
      }.bind(this.dropDown);

      this.dropDown._onDownArrow = function() {
        this.focusNext()
      }.bind(this.dropDown);

      this.dropDown.focusNext = function() {
        var focusNext = function() {
            var next = this._getNextFocusableChild(this.focusedChild, 1);
            this.focusChild(next);
            if (next.option.group) {
              focusNext();
            }
        }.bind(this);
        focusNext();
      }.bind(this.dropDown);

      this.dropDown.focusPrev = function() {
        var focusPrev = function() {
          var prev = this._getNextFocusableChild(this.focusedChild, -1);
          this.focusChild(prev);
          if (prev.option.group) {
            focusPrev();
          }
        }.bind(this);
        focusPrev();
      }.bind(this.dropDown);

      this.dropDown.onItemHover = function(item) {
        if (item.option.group) {
          item._set('hovering', false);
          return;
        }

        if (this.activated) {
          this.set('selected', item);
          if (item.popup && !item.disabled && !this.hover_timer) {
            this.hover_timer = this.defer(function() {
              this._openItemPopup(item);
            }, this.popupDelay);
          }
        } else if (this.passivePopupDelay < Infinity) {
          if (this.passive_hover_timer) {
            this.passive_hover_timer.remove();
          }
          this.passive_hover_timer = this.defer(function() {
            this.onItemClick(item, {
              type: 'click'
            });
          }, this.passivePopupDelay);
        }

        this._hoveredChild = item;

        item._set('hovering', true);
      }.bind(this.dropDown);

      this.dropDown._onItemFocus = function(item) {
        if (item.option.group) {
          return;
        }
        if (this._hoveredChild && this._hoveredChild != item) {
          this.onItemUnhover(this._hoveredChild);
        }
        this.set('selected', item);
      }.bind(this.dropDown);
    }
  });

  var select = new SelectGroup({
    name: 'select2',
    options: [{
        label: 'Colors I love',
        value: 'G 1',
        group: true,
        disabled: true
      },
      {
        label: 'Red',
        value: '1'
      },
      {
        label: 'Green',
        value: '2',
        selected: true
      },
      {
        label: 'Yello',
        value: '3'
      },
      {
        label: 'Purple',
        value: '4'
      },
      {
        label: 'Food I love</',
        value: 'G 2',
        group: true,
        disabled: true
      },
      {
        label: 'Red tomatoes',
        value: '1'
      },
      {
        label: 'Green apples',
        value: '3'
      }
    ]
  }, 'select');

  //decorator(select);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body></code>```

Body:
I would like to know if it possible to convert my decorator function in a custom widget (based on dijit/form/Select) in order to apply a monkey patch.

Or do you know an alternative solution ?

require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {
  var decorator = function(select) {
    select.on('change', function(value) {
      alert(value);
    });

    select.dropDown._onUpArrow = function() {
      this.focusPrev()
    }.bind(select.dropDown);

    select.dropDown._onDownArrow = function() {
      this.focusNext()
    }.bind(select.dropDown);

    select.dropDown.focusNext = function() {
      var focusNext = function() {
        var next = this._getNextFocusableChild(this.focusedChild, 1);
        this.focusChild(next);
        if (next.option.group) {
          focusNext();
        }
      }.bind(this);
      focusNext();
    }.bind(select.dropDown);

    select.dropDown.focusPrev = function() {
      var focusPrev = function() {
        var prev = this._getNextFocusableChild(this.focusedChild, -1);
        this.focusChild(prev);
        if (prev.option.group) {
          focusPrev();
        }
      }.bind(this);
      focusPrev();
    }.bind(select.dropDown);

    select.dropDown.onItemHover = function(item) {
      if (item.option.group) {
        item._set('hovering', false);
        return;
      }

      if (this.activated) {
        this.set('selected', item);
        if (item.popup && !item.disabled && !this.hover_timer) {
          this.hover_timer = this.defer(function() {
            this._openItemPopup(item);
          }, this.popupDelay);
        }
      } else if (this.passivePopupDelay < Infinity) {
        if (this.passive_hover_timer) {
          this.passive_hover_timer.remove();
        }
        this.passive_hover_timer = this.defer(function() {
          this.onItemClick(item, {
            type: 'click'
          });
        }, this.passivePopupDelay);
      }

      this._hoveredChild = item;

      item._set('hovering', true);
    }.bind(select.dropDown);

    select.dropDown._onItemFocus = function(item) {
      if (item.option.group) {
        return;
      }
      if (this._hoveredChild && this._hoveredChild != item) {
        this.onItemUnhover(this._hoveredChild);
      }
      this.set('selected', item);
    }.bind(select.dropDown);
  };

  var select = new Select({
    name: 'select2',
    options: [{
        label: 'Colors I love',
        value: 'G 1',
        group: true,
        disabled: true
      },
      {
        label: 'Red',
        value: '1'
      },
      {
        label: 'Green',
        value: '2',
        selected: true
      },
      {
        label: 'Yello',
        value: '3'
      },
      {
        label: 'Purple',
        value: '4'
      },
      {
        label: 'Food I love</',
        value: 'G 2',
        group: true,
        disabled: true
      },
      {
        label: 'Red tomatoes',
        value: '1'
      },
      {
        label: 'Green apples',
        value: '3'
      }
    ]
  }, 'select');

  decorator(select);

});

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

Code taken from this answer ;

Body:
If you want to create a custom form select js widget in your project , without that decorator ,

For reusability Create JS file (by example app/path/MyCustomSelect.js ) , ( make sure you configuring your dojo to locate the created file
 see here in documentation  ) , after importing the resource (AMD using define )create you widget and inherit the select using the declare class ,

at this stage , you have to ovveride the postCreate ( widget base lifcycle method , this is executed after instantiation and before rendring ) and then add you decorator code (by replacing select by the current scope this ) ,

Why using postcreate , beacause the widget is instantiated and all other referenced ressouce are created , so you can access the this.dropDown property , which is impossible in the constructor method , see the above link for better understand of widget lifecycle phases .

After your use the widget in your app , using require("location_to_your_jsile") , and use its refernce in the callback ,

So the MyCustomSelect.js file should looks like :

define([
  "dojo/_base/declare",
  'dijit/form/Select',
], function(declare, Select) {

  return declare(Select, {
    postCreate: function() {
      //make sur call this , like call super() ; inherited code will be executed
      this.inherited(arguments);

      console.log(this.dropDown);
      this.dropDown._onUpArrow = function() {
        this.focusPrev()
      }.bind(this.dropDown);

      this.dropDown._onDownArrow = function() {
        this.focusNext()
      }.bind(this.dropDown);

      this.dropDown.focusNext = function() {
        var focusNext = function() {
            var next = this._getNextFocusableChild(this.focusedChild, 1);
            this.focusChild(next);
            if (next.option.group) {
              focusNext();
            }
        }.bind(this);
        focusNext();
      }.bind(this.dropDown);

      this.dropDown.focusPrev = function() {
        var focusPrev = function() {
          var prev = this._getNextFocusableChild(this.focusedChild, -1);
          this.focusChild(prev);
          if (prev.option.group) {
            focusPrev();
          }
        }.bind(this);
        focusPrev();
      }.bind(this.dropDown);

      this.dropDown.onItemHover = function(item) {
        if (item.option.group) {
          item._set('hovering', false);
          return;
        }

        if (this.activated) {
          this.set('selected', item);
          if (item.popup && !item.disabled && !this.hover_timer) {
            this.hover_timer = this.defer(function() {
              this._openItemPopup(item);
            }, this.popupDelay);
          }
        } else if (this.passivePopupDelay < Infinity) {
          if (this.passive_hover_timer) {
            this.passive_hover_timer.remove();
          }
          this.passive_hover_timer = this.defer(function() {
            this.onItemClick(item, {
              type: 'click'
            });
          }, this.passivePopupDelay);
        }

        this._hoveredChild = item;

        item._set('hovering', true);
      }.bind(this.dropDown);

      this.dropDown._onItemFocus = function(item) {
        if (item.option.group) {
          return;
        }
        if (this._hoveredChild && this._hoveredChild != item) {
          this.onItemUnhover(this._hoveredChild);
        }
        this.set('selected', item);
      }.bind(this.dropDown);
    }
  });
});

If you want a live sample (without using separte file  ) see below snippet :) .

require([
  "dojo/_base/declare",
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(declare, Select, win) {

  var SelectGroup = declare(Select, {
    postCreate: function() {
      //make sur call this , like call super() ; inherited code will be executed
      this.inherited(arguments);

      console.log(this.dropDown);
      this.dropDown._onUpArrow = function() {
        this.focusPrev()
      }.bind(this.dropDown);

      this.dropDown._onDownArrow = function() {
        this.focusNext()
      }.bind(this.dropDown);

      this.dropDown.focusNext = function() {
        var focusNext = function() {
            var next = this._getNextFocusableChild(this.focusedChild, 1);
            this.focusChild(next);
            if (next.option.group) {
              focusNext();
            }
        }.bind(this);
        focusNext();
      }.bind(this.dropDown);

      this.dropDown.focusPrev = function() {
        var focusPrev = function() {
          var prev = this._getNextFocusableChild(this.focusedChild, -1);
          this.focusChild(prev);
          if (prev.option.group) {
            focusPrev();
          }
        }.bind(this);
        focusPrev();
      }.bind(this.dropDown);

      this.dropDown.onItemHover = function(item) {
        if (item.option.group) {
          item._set('hovering', false);
          return;
        }

        if (this.activated) {
          this.set('selected', item);
          if (item.popup && !item.disabled && !this.hover_timer) {
            this.hover_timer = this.defer(function() {
              this._openItemPopup(item);
            }, this.popupDelay);
          }
        } else if (this.passivePopupDelay < Infinity) {
          if (this.passive_hover_timer) {
            this.passive_hover_timer.remove();
          }
          this.passive_hover_timer = this.defer(function() {
            this.onItemClick(item, {
              type: 'click'
            });
          }, this.passivePopupDelay);
        }

        this._hoveredChild = item;

        item._set('hovering', true);
      }.bind(this.dropDown);

      this.dropDown._onItemFocus = function(item) {
        if (item.option.group) {
          return;
        }
        if (this._hoveredChild && this._hoveredChild != item) {
          this.onItemUnhover(this._hoveredChild);
        }
        this.set('selected', item);
      }.bind(this.dropDown);
    }
  });

  var select = new SelectGroup({
    name: 'select2',
    options: [{
        label: '<i>Colors I love</i>',
        value: 'G 1',
        group: true,
        disabled: true
      },
      {
        label: 'Red',
        value: '1'
      },
      {
        label: 'Green',
        value: '2',
        selected: true
      },
      {
        label: 'Yello',
        value: '3'
      },
      {
        label: 'Purple',
        value: '4'
      },
      {
        label: '<i>Food I love</</i>',
        value: 'G 2',
        group: true,
        disabled: true
      },
      {
        label: 'Red tomatoes',
        value: '1'
      },
      {
        label: 'Green apples',
        value: '3'
      }
    ]
  }, 'select');

  //decorator(select);

});

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body>


问:
Cant Connect to MongoDB server from Client
I am trying to connect from my machine (client) to server, and it says I cant connect to server.
My machine is Windows 10 and Server machine is Windows Server 2016.

And I tried to connect from cmd and it gives me this error.

Help me with this problem please.

答:
You should check the following items on the server running MongoDB.

Firewalls

Whitelists

You should also verify basic network communication using something like ping from the client to the server.

ContentLicense: CC BY-SA 4.0


问:
Check that the file is not binary in pre receive hook
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

```<code>my @new_file_list =  `git diff --name-only $old..$new`;;
</code>```

I get a size of every file, by looping:

```<code>foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;
</code>```

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

答:
You may have noticed that Git sometimes tells you “binary files ... and ... differ”.

According to this answer to
a similar question Git checks whether a file is binary or not by looking at the
first 8,000 bytes. If they contain a NUL byte, then Git considers the file to
be binary.

You can use git diff in your hook and let Git decide:

```<code>if git diff --numstat $old $new -- $file | grep -q -P -e '-\t-\t'; then
    # binary
else
    # text
fi
</code>```

This is even possible for files that have nothing to do with Git and are not in any repository. If

```<code>git diff --no-index --numstat /dev/null $some_file
</code>```

prints dash-TAB-dash-TAB then the file is binary (from Git's point of view). From the
docs:

```<code>git diff --no-index [--options] [--] [<path>…]
</code>```

This form is to compare the given two paths on the filesystem.

...

```<code>--numstat
</code>```

Similar to --stat, but shows number of added and deleted lines in decimal
     notation and pathname without abbreviation, to make it more machine friendly.
     For binary files, outputs two - instead of saying 0 0.

Body:
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

my @new_file_list =  `git diff --name-only $old..$new`;;

I get a size of every file, by looping:

foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

Body:
You may have noticed that Git sometimes tells you “binary files ... and ... differ”.

According to this answer to
a similar question Git checks whether a file is binary or not by looking at the
first 8,000 bytes. If they contain a NUL byte, then Git considers the file to
be binary.

You can use git diff in your hook and let Git decide:

if git diff --numstat $old $new -- $file | grep -q -P -e '-\t-\t'; then
    # binary
else
    # text
fi

This is even possible for files that have nothing to do with Git and are not in any repository. If

git diff --no-index --numstat /dev/null $some_file

prints dash-TAB-dash-TAB then the file is binary (from Git's point of view). From the
docs:

git diff --no-index [--options] [--] [<path>…]

This form is to compare the given two paths on the filesystem.

...

--numstat

Similar to --stat, but shows number of added and deleted lines in decimal
     notation and pathname without abbreviation, to make it more machine friendly.
     For binary files, outputs two - instead of saying 0 0.


问:
jQuery - Stop form submit depending on ajax response, otherwise let it submit
I setup some jQuery code so that when a user tries to submit this form, it checks to see what the ajax response is from our 'check_bid_locked' function in php. If it's 'assigned', 'expired', or 'yes', then it uses e.prevent_default() to stop the submit and show a modal popup message (which is working).

What I can't seem to figure out is how to let the form be SUBMITTED if the response doesn't match any of these. Basically, if the response is 'no' then we want the form to be submitted. Any ideas?

HTML

```<code>    <form onsubmit="return true check_submits();" method="post" action="<?php echo get_permalink($pid); ?>">
   <input type="hidden" name="control_id" value="<?php echo base64_encode($pid); ?>" />
   <input class="submit_bottom" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php _e("Place Bid",'BidTheme'); ?>" />
  </form>
</code>```

Jquery

```<code>$(document).ready("#bid_now_reverse").submit(function(e) {

var allowSubmit = false;
if (allowSubmit == false) {
e.preventDefault();
}

    var data = {
        'action': 'check_bid_locked',
        'pid': <?php echo $pid; ?>,
        'uid': <?php echo $uid; ?>
    };

    jQuery.post('<?php echo admin_url( 'admin-ajax.php' ); ?>', data,
function(response) {
            //If bid NOT locked
            if(response == 'no') {
            allowSubmit == true;
            }
            //If Assigned
            if(response == 'assigned') {
            confirm('<div class="bid_panel_box_title">Task Has Been
Assigned</div><div class="padd10_center">Your offer can\'t be deleted.
</div>', {
                    /*
                    Define your buttons here, can handle multiple buttons
                    with custom title and values
                    */
                    buttons: [
                        { class: "delete_button15", type: "button", title:
"Close", value: "Cancel" }

                    ],
                    modal: true
                },
                //Reload page START
                function(resp) {
                   console.log(resp);
            if(resp == 'Cancel'){
                window.location.reload(true);
            } }
            //Reload page END
        );
        //If Expired
    }else if(response == 'expired'){
        confirm('<div class="bid_panel_box_title">Task Has Expired</div><div class="padd10_center">Your offer can\'t be deleted.</div>', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel" }

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        //If Change Offer Locked
    }else if(response == 'yes'){
    allowSubmit = false;
        confirm('<div class="bid_panel_box_title">Offer Change Locked</div><div class="padd10_center">The Poster is reviewing your offer.<br/><br/>Check back shortly to see if it was accepted or to change it.</div>', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel"}

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        }
});
</code>```

});

答:
Because it was asked, here's the check_submits function. It's basically just used when a form is submitted, to make sure a user isn't trying to submit a blank entry, it checks the length, etc.</p>

```<code> <script type="text/javascript">
   function check_submits()
{

if(jQuery("#days_done").length > 0)
if( jQuery("#days_done").val() == '' )
{
    alert("<?php _e('Please type in the number of days.','ProjectTheme'); ?>");
    return false;
}

if( jQuery("#bid").val() == '' )
{
    alert("<?php _e('Please type in a bid value.','ProjectTheme'); ?>");
    return false;
}

else if( jQuery("#bid").val().length > 4 )
{
    alert("Offer Amount should not be more than 4 digits");
    return false;
}

return true;
}

</script>
</code>```

Body:
I setup some jQuery code so that when a user tries to submit this form, it checks to see what the ajax response is from our 'check_bid_locked' function in php. If it's 'assigned', 'expired', or 'yes', then it uses e.prevent_default() to stop the submit and show a modal popup message (which is working).

What I can't seem to figure out is how to let the form be SUBMITTED if the response doesn't match any of these. Basically, if the response is 'no' then we want the form to be submitted. Any ideas?

HTML

    <form onsubmit="return true check_submits();" method="post" action="<?php echo get_permalink($pid); ?>">
   <input type="hidden" name="control_id" value="<?php echo base64_encode($pid); ?>" />
   <input class="submit_bottom" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php _e("Place Bid",'BidTheme'); ?>" />
  </form>

Jquery

$(document).ready("#bid_now_reverse").submit(function(e) {

var allowSubmit = false;
if (allowSubmit == false) {
e.preventDefault();
}

    var data = {
        'action': 'check_bid_locked',
        'pid': <?php echo $pid; ?>,
        'uid': <?php echo $uid; ?>
    };

    jQuery.post('<?php echo admin_url( 'admin-ajax.php' ); ?>', data,
function(response) {
            //If bid NOT locked
            if(response == 'no') {
            allowSubmit == true;
            }
            //If Assigned
            if(response == 'assigned') {
            confirm('
Task Has Been
Assigned

Your offer can\'t be deleted.

', {
                    /*
                    Define your buttons here, can handle multiple buttons
                    with custom title and values
                    */
                    buttons: [
                        { class: "delete_button15", type: "button", title:
"Close", value: "Cancel" }

                    ],
                    modal: true
                },
                //Reload page START
                function(resp) {
                   console.log(resp);
            if(resp == 'Cancel'){
                window.location.reload(true);
            } }
            //Reload page END
        );
        //If Expired
    }else if(response == 'expired'){
        confirm('
Task Has Expired

Your offer can\'t be deleted.
', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel" }

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        //If Change Offer Locked
    }else if(response == 'yes'){
    allowSubmit = false;
        confirm('
Offer Change Locked

The Poster is reviewing your offer.

Check back shortly to see if it was accepted or to change it.
', {
                /*
                Define your buttons here, can handle multiple buttons
                with custom title and values
                */
                buttons: [
                    { class: "delete_button15", type: "button", title: "Close", value: "Cancel"}

                ],
                modal: true
            },
            //Reload page START
            function(resp) {
               console.log(resp);
        if(resp == 'Cancel'){
            window.location.reload(true);
        } }
            //Reload page END
        );
        }
});

});

Body:
Because it was asked, here's the check_submits function. It's basically just used when a form is submitted, to make sure a user isn't trying to submit a blank entry, it checks the length, etc.

 <script type="text/javascript">
   function check_submits()
{

if(jQuery("#days_done").length > 0)
if( jQuery("#days_done").val() == '' )
{
    alert("<?php _e('Please type in the number of days.','ProjectTheme'); ?>");
    return false;
}

if( jQuery("#bid").val() == '' )
{
    alert("<?php _e('Please type in a bid value.','ProjectTheme'); ?>");
    return false;
}

else if( jQuery("#bid").val().length > 4 )
{
    alert("Offer Amount should not be more than 4 digits");
    return false;
}

return true;
}

</script>


问:
How to do nested iterrows in Pandas
I am trying to take the data from the endResult dataframe'issues' column and put it into the 'Sprint' column in df. When I run this bit of code, it returns a dataframe that has the third entry from the 'issues' column inserted into each row of the 'Sprint' column in df.

```<code>for i, r in endResult.iterrows():
    j = endResult['issues'][i]['key']
for x, y in df.iterrows():
    df['Sprint'][x] = j
</code>```

What I'm getting:

Sprint

0  SPGC-9445

1  SPGC-9445

2  SPGC-9445

What I should be getting:

Sprint

0  SPGC-14075

1  SPGC-9456

2  SPGC-9445

Entries are taken from endResult dataframe which contains json.

```<code>                                         issues
0  {u'key': u'SPGC-14075', u'fields': {u'status':...
1  {u'key': u'SPGC-9456', u'fields': {u'status': ...
2  {u'key': u'SPGC-9445', u'fields': {u'status': ...
</code>```

答:
Because you are assigning everything to j in the first loop, you overwrite this value on each loop. Then you assign each value in sprint to the value of j, which is going to be the last value in issues.

One simple change that fixes this is to change j to a list and append each value as you loop through. This also eliminates the second loop, since you can just make a column out of the created list:

```<code>import pandas as pd

endResult = pd.DataFrame({'issues' : [{'key': 1},{'key': 2},{'key': 3}]})
df = pd.DataFrame()

j = []
for i, r in endResult.iterrows():
    j.append(endResult['issues'][i]['key'])

df['Sprint'] = j
</code>```

Title: How to do nested iterrows in Pandas

Body:
I am trying to take the data from the endResult dataframe'issues' column and put it into the 'Sprint' column in df. When I run this bit of code, it returns a dataframe that has the third entry from the 'issues' column inserted into each row of the 'Sprint' column in df.

for i, r in endResult.iterrows():
    j = endResult['issues'][i]['key']
for x, y in df.iterrows():
    df['Sprint'][x] = j

What I'm getting:

Sprint

0  SPGC-9445

1  SPGC-9445

2  SPGC-9445

What I should be getting:

Sprint

0  SPGC-14075

1  SPGC-9456

2  SPGC-9445

Entries are taken from endResult dataframe which contains json.

                                         issues
0  {u'key': u'SPGC-14075', u'fields': {u'status':...
1  {u'key': u'SPGC-9456', u'fields': {u'status': ...
2  {u'key': u'SPGC-9445', u'fields': {u'status': ...

Body:
Because you are assigning everything to j in the first loop, you overwrite this value on each loop. Then you assign each value in sprint to the value of j, which is going to be the last value in issues.

One simple change that fixes this is to change j to a list and append each value as you loop through. This also eliminates the second loop, since you can just make a column out of the created list:

import pandas as pd

endResult = pd.DataFrame({'issues' : [{'key': 1},{'key': 2},{'key': 3}]})
df = pd.DataFrame()

j = []
for i, r in endResult.iterrows():
    j.append(endResult['issues'][i]['key'])

df['Sprint'] = j


问:
Webpack 2 regex test failing
I cant quite get my head around why my loader tests are failing.

My goal:

Test 1:

Match anything that is not either global.css or global.scss

Test 2

Only match either global.scss or global.css

Reason being is i don't want any files named global to be passed through the module options

Seems like my first test is letting global though. I can see both my regex are correctly returning true/false when using tools such as https://regex101.com/.

Could this be down to my include?

Help! :)

webpack.config.js

```<code>        {

            test: /^(?!global\.s?css$).*\.s?css$/,
            include: SRC_DIR,
            use: extractPlugin.extract({
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            camelCase: true
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: (loader) => [require('autoprefixer')()]
                        }
                    },
                    'resolve-url-loader',
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true }
                    }
                ]
            })
        },

        {

            test: /^global\.s?css$/,
            include: SRC_DIR,
            use: extractPlugin.extract({
                use: [
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: (loader) => [require('autoprefixer')()]
                        }
                    },
                    'resolve-url-loader',
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true }
                    }
                ]
            })
        }
</code>```

答:
For Test 2 try dropping the ^ from your regex. The tests are matched against the file path, not just the file name, so having it start from the beginning of the path will cause it to fail.

For Test 1 you could simplify this negative pattern by using test: \/.s?css$\ to capture all styles and then add exclude: \global.s?css$\ to prevent global from being included.

Title: Webpack 2 regex test failing

Body:
I cant quite get my head around why my loader tests are failing.

My goal:

Test 1:

Match anything that is not either global.css or global.scss

Test 2

Only match either global.scss or global.css

Reason being is i don't want any files named global to be passed through the module options

Seems like my first test is letting global though. I can see both my regex are correctly returning true/false when using tools such as https://regex101.com/.

Could this be down to my include?

Help! :)

webpack.config.js

        {

            test: /^(?!global\.s?css$).*\.s?css$/,
            include: SRC_DIR,
            use: extractPlugin.extract({
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            camelCase: true
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: (loader) => [require('autoprefixer')()]
                        }
                    },
                    'resolve-url-loader',
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true }
                    }
                ]
            })
        },

        {

            test: /^global\.s?css$/,
            include: SRC_DIR,
            use: extractPlugin.extract({
                use: [
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: (loader) => [require('autoprefixer')()]
                        }
                    },
                    'resolve-url-loader',
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true }
                    }
                ]
            })
        }


问:
How can I convert float to int?
```<code>cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
</code>```

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

答:
you need to explicitly convert it:</p>

```<code>cube1.name = string.Format("Terrain_{0}_{1}",
Convert.ToInt32(Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x),
Convert.ToInt32(Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y));
</code>```

Title: How can I convert float to int?

Body:
cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Body:
you need to explicitly convert it:

cube1.name = string.Format("Terrain_{0}_{1}",
Convert.ToInt32(Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x),
Convert.ToInt32(Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y));


问:
SharePoint installation
I have installed MOSS2007 on a server, deplyed the apps, etc. Only to find out that I should have specified a specific locations for the files - not the default C:\Inetpub\wwwroot.

How do I change that? I don't mind reinstalling MOSS, I just don't want to loose all the custom work I did.

Thanks,
Eric

答:
Click Start, and then select Run…

In the Open field enter Regedit and click OK.

Locate the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp key and modify the PathWWWRoot       Value data to D:\Inetpub\vroots.

Locate the HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\ContentIndex\Catalogs\Web key and modify the Location Value data to d:\inetpub.

Locate the HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Control\ContentIndex\Catalogs\Web key and modify the Location Value data to d:\inetpub.

Locate the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ContentIndex\Catalogs\Web key and modify the Location Value data to d:\inetpub.

Repeat steps 1 through 6 on each Web front-end and application server.

Regards
Ashutosh Singh

MyBlog

Title: SharePoint installation


问:
Python Sort string by frequency - cannot sort with sorted() function

I have an issue with sorting a simple string by frequency (I get a string as an input, and I need to give a sorted string back as an output in descending order).
Let me give you an example (the original word contains 4 e's, 2 s's, 1 t, 1 r and 1 d; so these get sorted):

In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"
```

<p>Most solutions on Stack Overflow state that I should use the <code>sorted()</code> function to get my results, however, it only seems to work with certain cases.</p>

<p>I made two functions that supposed to work, but none of them seems to do the trick with my specific inputs (see below).</p>

<p><b>First function:</b></p>

<pre class="lang-py prettyprint-override"><code>def frequency_sort(s):
    s_sorted = sorted(s, key=s.count, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted
</code>```

Second function:

import collections
def frequency_sort_with_counter(s):
    counter = collections.Counter(s)
    s_sorted = sorted(s, key=counter.get, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted
```

<p>With both functions my outputs look like this:</p>

<p>The first output is okay:</p>

<pre class="lang-py prettyprint-override"><code>In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"
</code>```

The second output is not so much

In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"
```

<p>The third output is totally messy:</p>

<pre class="lang-py prettyprint-override"><code>In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"
</code>```

What could have gone wrong? Is it connected to the 'o' and 'l' characters somehow? Or am I just missing something?

答:
In a string where multiple characters have the same frequency, the algorithms you proposed have no way of distinguishing between characters that appear the same number of times. You could address this by sorting using a tuple of the frequency and the character itself; e.g.</p>

```<code>In [7]: def frequency_sort(s):
        s_sorted = sorted(s, key=lambda c: (s.count(c), c), reverse=True)
        s_sorted = ''.join(c for c in s_sorted)
        return s_sorted
   ...:

In [8]: frequency_sort("loveleel")
Out[8]: 'llleeevo'
</code>```

Body:
I have an issue with sorting a simple string by frequency (I get a string as an input, and I need to give a sorted string back as an output in descending order).
Let me give you an example (the original word contains 4 e's, 2 s's, 1 t, 1 r and 1 d; so these get sorted):

In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"

Most solutions on Stack Overflow state that I should use the sorted() function to get my results, however, it only seems to work with certain cases.

I made two functions that supposed to work, but none of them seems to do the trick with my specific inputs (see below).

First function:

def frequency_sort(s):
    s_sorted = sorted(s, key=s.count, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted

Second function:

import collections
def frequency_sort_with_counter(s):
    counter = collections.Counter(s)
    s_sorted = sorted(s, key=counter.get, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted

With both functions my outputs look like this:

The first output is okay:

In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"

The second output is not so much

In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"

The third output is totally messy:

In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"

What could have gone wrong? Is it connected to the 'o' and 'l' characters somehow? Or am I just missing something?

Body:
In a string where multiple characters have the same frequency, the algorithms you proposed have no way of distinguishing between characters that appear the same number of times. You could address this by sorting using a tuple of the frequency and the character itself; e.g.

In [7]: def frequency_sort(s):
        s_sorted = sorted(s, key=lambda c: (s.count(c), c), reverse=True)
        s_sorted = ''.join(c for c in s_sorted)
        return s_sorted
   ...:

In [8]: frequency_sort("loveleel")
Out[8]: 'llleeevo'


问:
Why does hibernate demand a default constructor for java.lang.Double?
I'm using JPA and Hibernate as a provider, I want to map a Map<Embeddable, Double> with @ElementCollection, but when persisiting, I got an hibernate exception:

```<code>javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: java.lang.Double
</code>```

I know that :

if the values of the Map are either embeddable or basic types, the Map
  is mapped as an element collection. [Pro JPA 2 Second edition- Page 102]

So in my case I should use @ElementCollection, but why does hibernate consider Double as an entity and demand a default constructor ?

Hibernate/JPA dependencies:

```<code>    <properties>
        <hibernate.version>5.2.10.Final</hibernate.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
  ....
  <dependencies>
</code>```

My Classes (I'm using generic types with inheritance Single-Table Strategy):

```<code>@Entity
@Table(name = "GENERIC_STAFF")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "My_Discriminator", discriminatorType = DiscriminatorType.STRING, length = 255)
public class FirstLevelBaseClass {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }
}

 @Getter @Setter
 public class SecondLevelBaseClass <K extends Serializable, V extends Serializable, M extends Map<K, V>> extends FirstLevelBaseClass{
     private M value;
 }

@Entity // Class that I want to persist
@DiscriminatorValue(value = "My_DoubleMapClass")
@Access(AccessType.PROPERTY)
public class DoubleMapClass extends SecondLevelBaseClass<EmbeddableDate, Double, SortedMap<EmbeddableDate, Double>>{

    @Override
    @ElementCollection
    @CollectionTable(joinColumns = @JoinColumn(name = "ID_GENERIC"))
    @AttributeOverrides({
        @AttributeOverride(name = "key.start", column = @Column(name = "START")),
        @AttributeOverride(name = "key.end", column = @Column(name = "END"))
    })
    @Column(nullable = false, name = "MyValue")
    @OrderBy
    public SortedMap<EmbeddableDate, Double> getValue() {
        return super.getValue();
    }

    @Override
    public void setValue(SortedMap<EmbeddableDate, Double> value) {
        super.setValue(value);
    }
}
</code>```

答:
As crizzis mention, when I get rid of @AttributeOverride, I can persist without any exception (It seems like a bug in Hibernate), so to keep my ability to override both the key and value column name, I've created a wrapper class of Double as @Embeddable, so my collection becomes SortedMap<EmbeddableDate, EmbeddableDouble>.

the other solution is to not override EmbeddableDate field at all and name their columns directly in EmbeddableDate, but it wasn't possible for my case, as I'm using EmbeddableDate in other entities (and I will lose its reusability!!).

Body:
I'm using JPA and Hibernate as a provider, I want to map a Map<Embeddable, Double> with @ElementCollection, but when persisiting, I got an hibernate exception:

javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: java.lang.Double

I know that :

if the values of the Map are either embeddable or basic types, the Map
  is mapped as an element collection. [Pro JPA 2 Second edition- Page 102]

So in my case I should use @ElementCollection, but why does hibernate consider Double as an entity and demand a default constructor ?

Hibernate/JPA dependencies:

    <properties>
        <hibernate.version>5.2.10.Final</hibernate.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
  ....
  <dependencies>

My Classes (I'm using generic types with inheritance Single-Table Strategy):

@Entity
@Table(name = "GENERIC_STAFF")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "My_Discriminator", discriminatorType = DiscriminatorType.STRING, length = 255)
public class FirstLevelBaseClass {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }
}

 @Getter @Setter
 public class SecondLevelBaseClass <K extends Serializable, V extends Serializable, M extends Map<K, V>> extends FirstLevelBaseClass{
     private M value;
 }

@Entity // Class that I want to persist
@DiscriminatorValue(value = "My_DoubleMapClass")
@Access(AccessType.PROPERTY)
public class DoubleMapClass extends SecondLevelBaseClass<EmbeddableDate, Double, SortedMap<EmbeddableDate, Double>>{

    @Override
    @ElementCollection
    @CollectionTable(joinColumns = @JoinColumn(name = "ID_GENERIC"))
    @AttributeOverrides({
        @AttributeOverride(name = "key.start", column = @Column(name = "START")),
        @AttributeOverride(name = "key.end", column = @Column(name = "END"))
    })
    @Column(nullable = false, name = "MyValue")
    @OrderBy
    public SortedMap<EmbeddableDate, Double> getValue() {
        return super.getValue();
    }

    @Override
    public void setValue(SortedMap<EmbeddableDate, Double> value) {
        super.setValue(value);
    }
}


问:
Append auto-incrementing suffix to duplicated elements of a List
Given the following list :

```<code>val l = List("A", "A", "C", "C", "B", "C")
</code>```

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

```<code>List("A0", "A1", "C0", "C1", "C2", "B0")
</code>```

答:
In a single pass straightforward way :</p>

```<code>def transformList(list : List[String]) : List[String] = {
  val buf: mutable.Map[String, Int] = mutable.Map.empty
  list.map {
    x => {
      val i = buf.getOrElseUpdate(x, 0)
      val result = s"${x.toString}$i"
      buf.put(x, i + 1)
      result
    }
  }
}

transformList( List("A", "A", "C", "C", "B", "C"))
</code>```

Body:
Given the following list :

val l = List("A", "A", "C", "C", "B", "C")

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

List("A0", "A1", "C0", "C1", "C2", "B0")

Body:
In a single pass straightforward way :

def transformList(list : List[String]) : List[String] = {
  val buf: mutable.Map[String, Int] = mutable.Map.empty
  list.map {
    x => {
      val i = buf.getOrElseUpdate(x, 0)
      val result = s"${x.toString}$i"
      buf.put(x, i + 1)
      result
    }
  }
}

transformList( List("A", "A", "C", "C", "B", "C"))