问:
Add AdWordsApi keys to App.config
I an developing a Windows form Application using VB. My software will connect to a SQL Database and to a Google Adwords API. The problem is when I try to Add the keys for the Adwords Api in the App.config file I get the following error: "Configuration system failed to initialize: AdWordsApi configuration section not recognized". I have read some examples about hoy to fill my Appconfig file but nothing seems to work. Could you help me know the proper way to do it? I leave here my App.config file</p>

```<code><?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXX">
            <section name="ReporteExcel.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXX" requirePermission="false"/>
        </sectionGroup>
    </configSections>

    <AdWordsApi>
        <add key="MaskCredentials" value="true"/>
        <add key="EnableSoapExtension" value="true"/>
        <add key="EnableGzipCompression" value="true"/>
        <add key="IncludeUtilitiesInUserAgent" value="true"/>
        <add key="ProxyServer" value=""/>
        <add key="ProxyUser" value=""/>
        <add key="ProxyPassword" value=""/>
        <add key="ProxyDomain" value=""/>
        <add key="DeveloperToken" value="XXXXXXXXXXXXXXXXX"/>
        <add key="GeneralClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="CanalDigitalClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="BanamexClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="AuthorizationMethod" value="OAuth2"/>
        <add key="OAuth2ClientId" value="XXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com"/>
        <add key="OAuth2ClientSecret" value="XXXXXXXXXXXXXX-XXXXXXX"/>
        <add key="OAuth2RefreshToken" value="1/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX-X"/>
        <add key="WebClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="SkipReportHeader" value="true"/>
        <add key="SkipReportSummary" value="true"/>
        <add key="SkipColumnHeader" value="false"/>
    </AdWordsApi>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
    <applicationSettings>
        <ReporteExcel.My.MySettings>
            <setting name="sqlConnectionStr" serializeAs="String">
                <value>Data Source=192.168.2.1;Initial Catalog=CATALOG;User ID=ADMIN;Password=ADMIN;</value>
            </setting>
        </ReporteExcel.My.MySettings>
    </applicationSettings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Google.AdWords" publicKeyToken="XXXXXXXXXXX" culture="neutral"/>
                <bindingRedirect oldVersion="18.33.0.0" newVersion="18.34.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Google.Ads.Common" publicKeyToken="XXXXXXXXXXXXXX" culture="neutral"/>
                <bindingRedirect oldVersion="3.17.0.0" newVersion="3.18.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>
</code>```

答:
As it reads the file, the configSections act as a Table of Contents for the file
Try the following change and see if it will recognize it.  taken from here</p>

```<code>    <configSections>
            <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXX">
                <section name="ReporteExcel.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXX" requirePermission="false"/>
            </sectionGroup>
            <section name="AdWordsApi" type="System.Configuration.DictionarySectionHandler"/>
 </configSections>
</code>```

Title: Add AdWordsApi keys to App.config

Body:
I an developing a Windows form Application using VB. My software will connect to a SQL Database and to a Google Adwords API. The problem is when I try to Add the keys for the Adwords Api in the App.config file I get the following error: "Configuration system failed to initialize: AdWordsApi configuration section not recognized". I have read some examples about hoy to fill my Appconfig file but nothing seems to work. Could you help me know the proper way to do it? I leave here my App.config file

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXX">

        </sectionGroup>
    </configSections>

    <AdWordsApi>
        <add key="MaskCredentials" value="true"/>
        <add key="EnableSoapExtension" value="true"/>
        <add key="EnableGzipCompression" value="true"/>
        <add key="IncludeUtilitiesInUserAgent" value="true"/>
        <add key="ProxyServer" value=""/>
        <add key="ProxyUser" value=""/>
        <add key="ProxyPassword" value=""/>
        <add key="ProxyDomain" value=""/>
        <add key="DeveloperToken" value="XXXXXXXXXXXXXXXXX"/>
        <add key="GeneralClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="CanalDigitalClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="BanamexClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="AuthorizationMethod" value="OAuth2"/>
        <add key="OAuth2ClientId" value="XXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com"/>
        <add key="OAuth2ClientSecret" value="XXXXXXXXXXXXXX-XXXXXXX"/>
        <add key="OAuth2RefreshToken" value="1/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX-X"/>
        <add key="WebClientCustomerId" value="XXX-XXX-XXXX"/>
        <add key="SkipReportHeader" value="true"/>
        <add key="SkipReportSummary" value="true"/>
        <add key="SkipColumnHeader" value="false"/>
    </AdWordsApi>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
    <applicationSettings>
        <ReporteExcel.My.MySettings>
            <setting name="sqlConnectionStr" serializeAs="String">
                <value>Data Source=192.168.2.1;Initial Catalog=CATALOG;User ID=ADMIN;Password=ADMIN;</value>
            </setting>
        </ReporteExcel.My.MySettings>
    </applicationSettings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Google.AdWords" publicKeyToken="XXXXXXXXXXX" culture="neutral"/>
                <bindingRedirect oldVersion="18.33.0.0" newVersion="18.34.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Google.Ads.Common" publicKeyToken="XXXXXXXXXXXXXX" culture="neutral"/>
                <bindingRedirect oldVersion="3.17.0.0" newVersion="3.18.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

Body:
As it reads the file, the configSections act as a Table of Contents for the file
Try the following change and see if it will recognize it.  taken from here

    <configSections>
            <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXX">
                <section name="ReporteExcel.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXX" requirePermission="false"/>
            </sectionGroup>
            <section name="AdWordsApi" type="System.Configuration.DictionarySectionHandler"/>
 </configSections>


来源: stackexchange

问:
error: expected constructor, destructor, or type conversion before '('
I'm just working on a RFID Sniffer on Arduino but something happened that it doesnt't work anymore.

```<code>#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>

SoftwareSerial RDM630 = SoftwareSerial(2, 3); // RFID

LiquidCrystal_I2C lcd(0x3F, 16, 2);
SoftwareSerial ESP = SoftwareSerial(10, 11); // RX, TX
pinMode(13, INPUT);
char rfid;
String dx;
bool connected = false;
String connbuff;
int lf = 10;
int cnt = 0;
bool lcdWAV = false;

void setup() {
  lcd.begin(16, 2);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  Serial.begin(9600);
  RDM630.begin(9600);
  ESP.begin(9600);
  ESP.listen();
}
</code>```

The error says:

```<code>Documents/Arduino/rdm630_test/src/rdm630_test.ino:27:8: error: expected constructor, destructor, or type conversion before  '(' token
lcd.setCursor(0, 0);
^
</code>```

Now there is only the Setup routine and even this don't work. I only get the error...

答: pinMode(13, INPUT); is a method call. Since a method can be called only from within a method so the line pinMode(13, INPUT); should be placed within a method body.

ContentLicense: CC BY-SA 3.0

Body:
I'm just working on a RFID Sniffer on Arduino but something happened that it doesnt't work anymore.

#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>

SoftwareSerial RDM630 = SoftwareSerial(2, 3); // RFID

LiquidCrystal_I2C lcd(0x3F, 16, 2);
SoftwareSerial ESP = SoftwareSerial(10, 11); // RX, TX
pinMode(13, INPUT);
char rfid;
String dx;
bool connected = false;
String connbuff;
int lf = 10;
int cnt = 0;
bool lcdWAV = false;

void setup() {
  lcd.begin(16, 2);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  Serial.begin(9600);
  RDM630.begin(9600);
  ESP.begin(9600);
  ESP.listen();
}

The error says:

Documents/Arduino/rdm630_test/src/rdm630_test.ino:27:8: error: expected constructor, destructor, or type conversion before  '(' token
lcd.setCursor(0, 0);
^

Now there is only the Setup routine and even this don't work. I only get the error...


问:
Remove rows with the same value across all columns
Suppose I have a data frame (df) that looks like below:

```<code>options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0
</code>```

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

```<code> df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]
</code>```

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!

答:
We can also use Map with Reduce

```<code>df[c(Reduce(`+`, Map(function(x,y) x != y & !is.na(x), df[-1], list(df[2]))) != 0),]
#  cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#3 Car3     3     2     5     2     1     1     2
#5 Car5     4     0     2     2     0     1     0
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
</code>```

Or using tidyverse

```<code>library(tidyverse)
df %>%
    filter_at(vars(starts_with("test")), any_vars((. != test1)))
#   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car3     3     2     5     2     1     1     2
#3 Car5     4     0     2     2     0     1     0
#4 Car7     1     2     6     1     1     3     1
#5 Car8     3     5     7     1     3     4     1
</code>```

Body:
Suppose I have a data frame (df) that looks like below:

options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

 df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!

Body:
We can also use Map with Reduce

df[c(Reduce(`+`, Map(function(x,y) x != y & !is.na(x), df[-1], list(df[2]))) != 0),]
#  cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#3 Car3     3     2     5     2     1     1     2
#5 Car5     4     0     2     2     0     1     0
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1

Or using tidyverse

library(tidyverse)
df %>%
    filter_at(vars(starts_with("test")), any_vars((. != test1)))
#   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car3     3     2     5     2     1     1     2
#3 Car5     4     0     2     2     0     1     0
#4 Car7     1     2     6     1     1     3     1
#5 Car8     3     5     7     1     3     4     1

ContentLicense: CC BY-SA 4.0


问:
how to read a single number as a single character at a time not alphabets
I'm doing the accessibility, where I have a address eg :3156 Stock Avenue Ln B, Stockland, CA 95209. Where I want it to read only digits one at a time means a single character and read the address as it is.
How can I define in Java.
Appreciate your help.</p>

答:
If you need just extract numbers from a string you also can use Java 8 features:</p>

```<code>String result = string.chars().filter(Character::isDigit)
.collect(StringBuilder::new, (sb, i) -> sb.append((char) i), append)
.toString();
</code>```

Body:
If you need just extract numbers from a string you also can use Java 8 features:

String result = string.chars().filter(Character::isDigit)
.collect(StringBuilder::new, (sb, i) -> sb.append((char) i), append)
.toString();


问:
Two Different JSON sources, Update at Different Times; Use Result in ng-Repeat List
I am trying to create a status list from two separate JSON sources. The list will display general info from the first source, and show a status color based on the number of people in the second source.

The first source contains general data that will not be changing much (i.e. feed name, version, description) and likely called only two times a day. See code example below:

/metadata

```<code>{
    data: [
        {
            "feedName": "Feed 1",
            "version": "000001",
            "location": "1234 Main Street, New York, New York"
            "description": "This feed gives information on the number of people in Building A at a given time."
        },
        {
            "feedName": "Feed 2",
            "version": "000001",
            "location": "1000 Broad Street, New York, New York"
            "description": "This feed gives information on the number of people in Building B at a given time."
        },
        {
            "feedName": "Feed 3",
            "version": "000001",
            "location": "1111 Governor Street, New York, New York"
            "description": "This feed gives information on the number of people in Building C at a given time."
        }
    ]
}
</code>```

The second source contains data on each feed that will change very often. This source will be called more frequently; about every hour.

/customers

```<code>{
    data: [
        {
            "metricName": "Feed 1",
            "customerNumber": "10",
            "time": "2012-10-03 15:30:00"

        },
        {
            "metricName": "Feed 2",
            "customerNumber": "5",
            "time": "2012-10-03 15:30:00"
        },
        {
            "metricName": "Feed 3",
            "customerNumber": "15",
            "time": "2012-10-03 15:30:00"
        }
    ]
}
</code>```

Where metricName and feedName are actually the same values.

I've only dealt with one JSON source per list before, where my Javascript would look like this:

```<code>$scope.metadataList = function(){
    $http.get('/metadata')
        .then(function(result) {
            $scope.metadata = result.data.data;
        });
}
</code>```

and corresponding HTML would look like this:

```<code><ul ng-repeat = "data in metadata | orderBy: ['feedName']">
    <li> {{data.feedName}}, {{data.version}} </li>
</ul>
</code>```

So my question is, how to I make async calls to each data source? How do I match them up to populate my list with both the metadata information and the customer information?

Update
Before anyone asks, I did try ng-repeat = "data in metadata.concat(customers)" where "customers" defines the second data source, (as shown in Ng-repeat datas from 2 json Angular) but that only appends to the end of the list ... not quite what I was going for.

Thank you in advance.

答:
First, you can call the all() method from the $q service to resolve multiple promises, in that case the two requests.

```<code>// both promises calling your api to get the jsons
var promises = {
  metadataPromise: $http.get('/echo/json/', {}),
  customersPromise: $http.get('/echo/json/', {})
};

$q.all(promises).then(function(response) {
  metadata = response.metadataPromise;
  customers = response.customersPromise;

  joinMetadataAndCustomers();
}, function(response) {
  // in case any promise is rejected
});
</code>```

After that, you check for every feedName the metricName which matches it using filter. In the end, you can merge both with angular.merge.

```<code>var joinMetadataAndCustomers = function() {
  metadata.data.forEach(function(mtd) {
    customers.data.filter(function(customer) {
      return customer.metricName === mtd.feedName;
    }).forEach(function(customer) {
      $ctrl.metadataAndCustomers.push(angular.merge({}, mtd, customer));
    });
  });
}
</code>```

Not sure if it's the best approach, but it works. Of course can be improved according to your needs. For example, if you only have one single match, the last forEach can be avoided.

Fiddle with an example: https://jsfiddle.net/virgilioafonsojr/tv1ujet0/

I hope it helps.

Body:
I am trying to create a status list from two separate JSON sources. The list will display general info from the first source, and show a status color based on the number of people in the second source.

The first source contains general data that will not be changing much (i.e. feed name, version, description) and likely called only two times a day. See code example below:

/metadata

{
    data: [
        {
            "feedName": "Feed 1",
            "version": "000001",
            "location": "1234 Main Street, New York, New York"
            "description": "This feed gives information on the number of people in Building A at a given time."
        },
        {
            "feedName": "Feed 2",
            "version": "000001",
            "location": "1000 Broad Street, New York, New York"
            "description": "This feed gives information on the number of people in Building B at a given time."
        },
        {
            "feedName": "Feed 3",
            "version": "000001",
            "location": "1111 Governor Street, New York, New York"
            "description": "This feed gives information on the number of people in Building C at a given time."
        }
    ]
}

The second source contains data on each feed that will change very often. This source will be called more frequently; about every hour.

/customers

{
    data: [
        {
            "metricName": "Feed 1",
            "customerNumber": "10",
            "time": "2012-10-03 15:30:00"

        },
        {
            "metricName": "Feed 2",
            "customerNumber": "5",
            "time": "2012-10-03 15:30:00"
        },
        {
            "metricName": "Feed 3",
            "customerNumber": "15",
            "time": "2012-10-03 15:30:00"
        }
    ]
}

Where metricName and feedName are actually the same values.

I've only dealt with one JSON source per list before, where my Javascript would look like this:

$scope.metadataList = function(){
    $http.get('/metadata')
        .then(function(result) {
            $scope.metadata = result.data.data;
        });
}

and corresponding HTML would look like this:

 {{data.feedName}}, {{data.version}}

So my question is, how to I make async calls to each data source? How do I match them up to populate my list with both the metadata information and the customer information?

Update
Before anyone asks, I did try ng-repeat = "data in metadata.concat(customers)" where "customers" defines the second data source, (as shown in Ng-repeat datas from 2 json Angular) but that only appends to the end of the list ... not quite what I was going for.

Thank you in advance.

Body:
First, you can call the all() method from the $q service to resolve multiple promises, in that case the two requests.

// both promises calling your api to get the jsons
var promises = {
  metadataPromise: $http.get('/echo/json/', {}),
  customersPromise: $http.get('/echo/json/', {})
};

$q.all(promises).then(function(response) {
  metadata = response.metadataPromise;
  customers = response.customersPromise;

  joinMetadataAndCustomers();
}, function(response) {
  // in case any promise is rejected
});

After that, you check for every feedName the metricName which matches it using filter. In the end, you can merge both with angular.merge.

var joinMetadataAndCustomers = function() {
  metadata.data.forEach(function(mtd) {
    customers.data.filter(function(customer) {
      return customer.metricName === mtd.feedName;
    }).forEach(function(customer) {
      $ctrl.metadataAndCustomers.push(angular.merge({}, mtd, customer));
    });
  });
}

Not sure if it's the best approach, but it works. Of course can be improved according to your needs. For example, if you only have one single match, the last forEach can be avoided.

Fiddle with an example: https://jsfiddle.net/virgilioafonsojr/tv1ujet0/

I hope it helps.


问:
Three js add object to scene
I'm working off an example from the site and would like to add a textured cube to the scene and ideally have it in a specific position. This is what I've tried so far but it's not appearing:

```<code>var frametexture = new THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );
var artwork = new THREE.BoxBufferGeometry( 200, 200, 20 );
var material = new THREE.MeshBasicMaterial( { map: frametexture } );
artframe = new THREE.Mesh( artwork, frametexture );
scene.add( artframe );
artwork.scale( - 1, 1, 1 );
</code>```

Here's my JSFIDDLE

答:
```<code>var frametexture = new THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );
</code>```

Should instead be

```<code>var frametexture = THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );
</code>```

and

```<code>artframe = new THREE.Mesh( artwork, frametexture );
</code>```

needs to be

```<code>artframe = new THREE.Mesh( artwork, material);
</code>```

Title: Three js add object to scene

Body:
I'm working off an example from the site and would like to add a textured cube to the scene and ideally have it in a specific position. This is what I've tried so far but it's not appearing:

var frametexture = new THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );
var artwork = new THREE.BoxBufferGeometry( 200, 200, 20 );
var material = new THREE.MeshBasicMaterial( { map: frametexture } );
artframe = new THREE.Mesh( artwork, frametexture );
scene.add( artframe );
artwork.scale( - 1, 1, 1 );

Here's my JSFIDDLE

Body:
var frametexture = new THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );

Should instead be

var frametexture = THREE.ImageUtils.loadTexture( 'https://threejs.org/examples/textures/crate.gif' );

and

artframe = new THREE.Mesh( artwork, frametexture );

needs to be

artframe = new THREE.Mesh( artwork, material);


问:
How come the output of following code : DoSecond
```<code>#include <stdio.h>
    int main()
    {
        switch (printf("Do"))
        {
        case 1:
            printf("First\n");
            break;
        case 2:
            printf("Second\n");
            break;
        default:
            printf("Default\n");
            break;
        }
    }
</code>```

Can someone explain how above code works? How does switch jump to case2 label?

答:
Check the man page for printf(). It mentions

Return value

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

Here, the return value of the printf() call is used as the switch statement controlling expression value. So, in this case, for printing the string "Do", it returns 2. This matches the case label 2.

Then, the standard output is line buffered. You did not have a flushing instruction or a newline after the first printf(), so the consecutive output from the next printf() call is juxtaposed to the output buffer and finally after meeting the newline, it gets flushed together to the console / terminal, displaying "DoSecond".

That said, int main() should be int main(void), at least, to conform to the standard for a hosted environment.

Body:
#include <stdio.h>
    int main()
    {
        switch (printf("Do"))
        {
        case 1:
            printf("First\n");
            break;
        case 2:
            printf("Second\n");
            break;
        default:
            printf("Default\n");
            break;
        }
    }

Can someone explain how above code works? How does switch jump to case2 label?


问:
Display string method by pressing a button in GUI
How would I be able to display this method in a GUI, just by pressing a button in the GUI

```<code>private String questionFredricton(){
    Object qFredricton = cities.get(1);
    String displayFredricton  = "Where is " + qFredricton + " located?";
    String ansFredricton = provinces.get(1);
    return displayFredricton + ansFredricton;
    }
</code>```

I'm guessing something like this??
nextQuestion is my button

```<code>private void nextQuestionActionPerformed(java.awt.event.ActionEvent evt) {
        print(questionFredricton());

}
</code>```

I don't want to use use setText() or append() in my button because my strings are being displayed in separate textAreas, already defined in my method.  If I do use setText/appnd, it puts all the strings in one box, which is not what I want.

for example by doing:

```<code>outputTextQuestion.setText(questionFredricton());//not what I want
</code>```

Thanks in advance!

答:
I do not think I fully understand what your asking but you could return a custom object rather then a string in your method. The object would have getters and setters for each string value you want to use. Your actionPerformed method then could get the values you need and do whatever with them.

```<code>public class MyFredriction
 private String display;
 private String answer;

 public MyFredriction(String display, String answer) {
   this.display = display;
   this.answer = answer;
 }
 //TODO public String getDisplay()
 //TODO public String getAnswer()
}
</code>```

Body:
How would I be able to display this method in a GUI, just by pressing a button in the GUI

private String questionFredricton(){
    Object qFredricton = cities.get(1);
    String displayFredricton  = "Where is " + qFredricton + " located?";
    String ansFredricton = provinces.get(1);
    return displayFredricton + ansFredricton;
    }

I'm guessing something like this??
nextQuestion is my button

private void nextQuestionActionPerformed(java.awt.event.ActionEvent evt) {
        print(questionFredricton());

}

I don't want to use use setText() or append() in my button because my strings are being displayed in separate textAreas, already defined in my method.  If I do use setText/appnd, it puts all the strings in one box, which is not what I want.

for example by doing:

outputTextQuestion.setText(questionFredricton());//not what I want

Thanks in advance!

Body:
I do not think I fully understand what your asking but you could return a custom object rather then a string in your method. The object would have getters and setters for each string value you want to use. Your actionPerformed method then could get the values you need and do whatever with them.

public class MyFredriction
 private String display;
 private String answer;

 public MyFredriction(String display, String answer) {
   this.display = display;
   this.answer = answer;
 }
 //TODO public String getDisplay()
 //TODO public String getAnswer()
}


问:
Spark Execution Error: Python in worker has different Version
I'm running spark in standalone mode, in Windows 8 using anaconda 3.5, ipython notebook.

The specification, I'm trying to create the environment is the following:

```<code>import os
import sys
import numpy
spark_path = "D:\spark"
os.environ['SPARK_HOME'] = spark_path
os.environ['HADOOP_HOME'] = spark_path

sys.path.append(spark_path + "/bin")
sys.path.append(spark_path + "/python")
sys.path.append(spark_path + "/python/pyspark/")
sys.path.append(spark_path + "/python/lib")
sys.path.append(spark_path + "/python/lib/pyspark.zip")
sys.path.append(spark_path + "/python/lib/py4j-0.10.4-src.zip")

from pyspark import SparkContext
from pyspark import SparkConf

sc = SparkContext("local", "test")
</code>```

When I'm trying to run the following code:

```<code>rdd = sc.parallelize([1,2,3])
rdd.count()
</code>```

it's giving me error:

Python in worker has different version 3.4 than that in driver 3.5,
  PySpark cannot run with different minor versions.Please check
  environment variables PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON are
  correctly set.

I tried this

```<code>import os

os.environ["SPARK_HOME"] = "/usr/local/Cellar/apache-spark/2.1.0/" ## Exact anaconda path in "program files"
</code>```

And I tried this

But both could not solve my problem. Can someone please help me to resolve the issue? I'm bit non-technical in terms of computer system configuration.

Thanks a lot!

答:
First of all, if you are working with Spark, I would like to suggest to use a Virtualbox and install ubuntu 14.04 LTS or CentOs!
Even if you are using it standalone developing applications with a windows backend going to be MUCH MORE HARDER!
Non the less, if you try to connect to a HIVE metastore / hadoop from win it is nearly impossubru...

We had the same problem with cloudera manager the solution was to parse the same version of anaconda on ALL nodes, and change the PATH variable in .bashrc

I think it is better to set the variables outside of jupiter!
Try to reconfigure your path environment in windows for python and spark!

Body:
I'm running spark in standalone mode, in Windows 8 using anaconda 3.5, ipython notebook.

The specification, I'm trying to create the environment is the following:

import os
import sys
import numpy
spark_path = "D:\spark"
os.environ['SPARK_HOME'] = spark_path
os.environ['HADOOP_HOME'] = spark_path

sys.path.append(spark_path + "/bin")
sys.path.append(spark_path + "/python")
sys.path.append(spark_path + "/python/pyspark/")
sys.path.append(spark_path + "/python/lib")
sys.path.append(spark_path + "/python/lib/pyspark.zip")
sys.path.append(spark_path + "/python/lib/py4j-0.10.4-src.zip")

from pyspark import SparkContext
from pyspark import SparkConf

sc = SparkContext("local", "test")

When I'm trying to run the following code:

rdd = sc.parallelize([1,2,3])
rdd.count()

it's giving me error:

Python in worker has different version 3.4 than that in driver 3.5,
  PySpark cannot run with different minor versions.Please check
  environment variables PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON are
  correctly set.

I tried this

import os

os.environ["SPARK_HOME"] = "/usr/local/Cellar/apache-spark/2.1.0/" ## Exact anaconda path in "program files"

And I tried this

But both could not solve my problem. Can someone please help me to resolve the issue? I'm bit non-technical in terms of computer system configuration.

Thanks a lot!


问:
Access index property in javascript using a variable
The api that i am messing with has a limit of 100 items per request. So I am trying to find out the length variable (which works) but why cant i use that variable to get the index. like below.

```<code>var ttl = results.data.length;
const s = results.data[ttl].id;
</code>```

console reads

```<code>TypeError: Cannot read property 'id' of undefined
</code>```

ttl does not work. But if i do the following...

```<code>const s = results.data[100].id;
</code>```

The value is recognized fine... But I don't know what the length will be so I need to set it in a var and try to navigate the object with the length var?

答:
You can't write over a const. What ttl = parseInt(l); means? What you were trying to do? (The code refers to the original version of the question)

```<code>const ttl = results.data.length;
ttl = parseInt(l); // <- It's wrong
const s = results.data[ttl].id;
</code>```

To get the last value you just need this:

```<code>const s = results.data[results.data.length-1].id;
</code>```

Body:
The api that i am messing with has a limit of 100 items per request. So I am trying to find out the length variable (which works) but why cant i use that variable to get the index. like below.

var ttl = results.data.length;
const s = results.data[ttl].id;

console reads

TypeError: Cannot read property 'id' of undefined

ttl does not work. But if i do the following...

const s = results.data[100].id;

The value is recognized fine... But I don't know what the length will be so I need to set it in a var and try to navigate the object with the length var?

Body:
You can't write over a const. What ttl = parseInt(l); means? What you were trying to do? (The code refers to the original version of the question)

const ttl = results.data.length;
ttl = parseInt(l); // <- It's wrong
const s = results.data[ttl].id;

To get the last value you just need this:

const s = results.data[results.data.length-1].id;


问:
Linq throws exception on .Substring()
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

```<code>var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);
</code>```

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment
</code>```

With this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)
</code>```

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

```<code>var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });
</code>```

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.

答: Correct  - LINQ doesn't support substring, but it's not always very clear from the exception when you try things like that unfortunaltely.</p>

ContentLicense: CC BY-SA 2.5

Title: Linq throws exception on .Substring()

Body:
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment

With this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.


问:
Querying XML file in SQL Server
This is my xml file

```<code><Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parents>
    <Parent id="1234">
      <name>
        <firstname>ABC</firstname>
        <lastname>XYSX</lastname>
      </name>
    </Parent>
    <Parent id="1235">
      <name>
        <firstname>TFU</firstname>
        <lastname>GHY</lastname>
      </name>
    </Parent>
  </Parents>
  <Children>
    <Child id="457" Parentid="1234">
      <name>
        <cfirstname>JOHN</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
    <Child id="459" Parentid="1235">
      <name>
        <cfirstname>DAVID</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
  </Children>
</Detials>
</code>```

I stored it in a table (using Bulk Insert).

When I query like this

```<code>SELECT
    x.c.value('(./Parents/Parent/@id)[1]', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('Detials') AS x(c)
</code>```

I get the result as

```<code>Id
----
1234
</code>```

When I changed it a little bit

```<code>SELECT
    x.c.value('@id', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)
</code>```

I get:

```<code>Id
----
1234
1235
</code>```

I just want to query them to result like this

```<code>Parent_id | firstname | lastname | Child_id | Child_First_name | child_last_name
----------+-----------+----------+----------+------------------+-----------
1234      | ABC       | XYSX     |    457   |      JOHN        | SMITH
1235      | TFU       | GHY      |    459   |      DAVID       | SMITH
</code>```

How could I do this in query ?

In my result I want total no. of rows which depends on the Parentid. If my xml file contains 6 <parent id> then my query should show all 6 rows for each parent id's along with comparing the Childid's to also be included if the Parentid matches in <child> tag.

Thanks, Jayendran

答:
I'd solve this in one single go:

```<code>SELECT Parent.ID
      ,p.value('(name/firstname/text())[1]','nvarchar(max)')
      ,p.value('(name/lastname/text())[1]','nvarchar(max)')
      ,c.value('@id','int')
      ,c.value('(name/cfirstname/text())[1]','nvarchar(max)')
      ,c.value('(name/clastname/text())[1]','nvarchar(max)')
FROM @xml.nodes('/Detials/Parents/Parent') AS A(p)
OUTER APPLY (SELECT p.value('@id','int')) AS Parent(ID)
OUTER APPLY @xml.nodes('/Detials/Children/Child[@Parentid=sql:column("Parent.ID")]') AS B(c);
</code>```

The trick is, to read the Parentid into a named column via APPLY. This value can be used as predicate to fetch the children via sql:column().

Title: Querying XML file in SQL Server

Body:
This is my xml file

<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parents>
    <Parent id="1234">
      <name>
        <firstname>ABC</firstname>
        <lastname>XYSX</lastname>
      </name>
    </Parent>
    <Parent id="1235">
      <name>
        <firstname>TFU</firstname>
        <lastname>GHY</lastname>
      </name>
    </Parent>
  </Parents>
  <Children>
    <Child id="457" Parentid="1234">
      <name>
        <cfirstname>JOHN</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
    <Child id="459" Parentid="1235">
      <name>
        <cfirstname>DAVID</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
  </Children>
</Detials>

I stored it in a table (using Bulk Insert).

When I query like this

SELECT
    x.c.value('(./Parents/Parent/@id)[1]', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('Detials') AS x(c)

I get the result as

Id
----
1234

When I changed it a little bit

SELECT
    x.c.value('@id', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)

I get:

Id
----
1234
1235

I just want to query them to result like this

Parent_id | firstname | lastname | Child_id | Child_First_name | child_last_name
----------+-----------+----------+----------+------------------+-----------
1234      | ABC       | XYSX     |    457   |      JOHN        | SMITH
1235      | TFU       | GHY      |    459   |      DAVID       | SMITH

How could I do this in query ?

In my result I want total no. of rows which depends on the Parentid. If my xml file contains 6 <parent id> then my query should show all 6 rows for each parent id's along with comparing the Childid's to also be included if the Parentid matches in <child> tag.

Thanks, Jayendran

Body:
I'd solve this in one single go:

SELECT Parent.ID
      ,p.value('(name/firstname/text())[1]','nvarchar(max)')
      ,p.value('(name/lastname/text())[1]','nvarchar(max)')
      ,c.value('@id','int')
      ,c.value('(name/cfirstname/text())[1]','nvarchar(max)')
      ,c.value('(name/clastname/text())[1]','nvarchar(max)')
FROM @xml.nodes('/Detials/Parents/Parent') AS A(p)
OUTER APPLY (SELECT p.value('@id','int')) AS Parent(ID)
OUTER APPLY @xml.nodes('/Detials/Children/Child[@Parentid=sql:column("Parent.ID")]') AS B(c);

The trick is, to read the Parentid into a named column via APPLY. This value can be used as predicate to fetch the children via sql:column().


问:
Android receiver for multiple actions?
Simple question - Can I register a single BroadcastReceiver to multiple Intent actions? Here's what I'm considering:

```<code><receiver android:name=".myReceiver">
    <intent-filter android:priority="1000000">
        <action android:name="android.intent.action.MEDIA_BUTTON" />
        <action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
    </intent-filter>
</receiver>
</code>```

So in myReceiver class' onReceive, could I check intent.getAction() for both ACTION_MEDIA_BUTTON and ACTION_HEADSET_PLUG?

答:
about the priority you set:

https://developer.android.com/guide/topics/manifest/intent-filter-element.html

android:priority
      The priority that should be given to the parent component with regard to handling intents of the type described by the filter. This attribute has meaning for both activities and broadcast receivers:

It provides information about how able an activity is to respond to an intent that matches the filter, relative to other activities that could also respond to the intent. When an intent could be handled by multiple activities with different priorities, Android will consider only those with higher priority values as potential targets for the intent.

It controls the order in which broadcast receivers are executed to receive broadcast messages. Those with higher priority values are called before those with lower values. (The order applies only to synchronous messages; it's ignored for asynchronous messages.)

Use this attribute only if you really need to impose a specific order in which the broadcasts are received, or want to force Android to prefer one activity over others.

The value must be an integer, such as "100". Higher numbers have a
  higher priority. The default value is 0. The value must be greater
  than -1000 and less than 1000.

Title: Android receiver for multiple actions?

Body:
Simple question - Can I register a single BroadcastReceiver to multiple Intent actions? Here's what I'm considering:

<receiver android:name=".myReceiver">
    <intent-filter android:priority="1000000">
        <action android:name="android.intent.action.MEDIA_BUTTON" />
        <action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
    </intent-filter>
</receiver>

So in myReceiver class' onReceive, could I check intent.getAction() for both ACTION_MEDIA_BUTTON and ACTION_HEADSET_PLUG?


问:
Children of flex box don't align to bottom (flex end)
I'm just introducing myself to flexbox and from what I understand if I have a flex parent, then I can align the children of the parent that are on a single row with the align-items rule. However, my children are not changning their alignment as seen here: https://jsfiddle.net/b9L09gsa/

The content remains at the top instead of at the bottom like I would like. The idea is to have the logo div and nav items align neatly at the bottom. Clearly I don't understand something, any help would be great!

答:
You need those properties on the flex container, not the flex items:

```<code>#nav-contain {
    display:flex;
    justify-content: flex-end;
    align-items: flex-end;
}
#logo, .nav-item-contain {
    flex-grow: 1;
}
</code>```

https://jsfiddle.net/b9L09gsa/1/

To override individual flex items, use align-self instead:

```<code>#nav-contain {
    display:flex;
    justify-content: flex-end;
}
#logo, .nav-item-contain {
    flex-grow: 1;
    align-self: flex-end;
}
</code>```

https://jsfiddle.net/b9L09gsa/2/

Body:
You need those properties on the flex container, not the flex items:

#nav-contain {
    display:flex;
    justify-content: flex-end;
    align-items: flex-end;
}
#logo, .nav-item-contain {
    flex-grow: 1;
}

https://jsfiddle.net/b9L09gsa/1/

To override individual flex items, use align-self instead:

#nav-contain {
    display:flex;
    justify-content: flex-end;
}
#logo, .nav-item-contain {
    flex-grow: 1;
    align-self: flex-end;
}

https://jsfiddle.net/b9L09gsa/2/


答:
The return value for printf is

Number of characters written if successful or a negative value if an error occurred.

So "Do" has 2 characters, so the switch drops into case 2:

Title: How come the output of following code : DoSecond


问:
scripting fruityloops or propellerheads reason from VB or Python?
I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.

Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?

Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.

Update 2 : If you're interested in this question, check out this too.

答:
There's an opensource music workstation, called Frinika, and you can script that in Javascript. (Insert / delete notes , change midi effects like pitch wheel etc.) It can import / export regular midi files, so it will work with Fruity loops or whatever else you have.

```<code>// Insert New

song.newLane("MyMidiLane", type("Midi"));
lane = song.getLane("MyMidiLane");

part = lane.newPart( time("10.0:000"), time("4.0:000") );

part.insertNote(note("c#3"), time("11.2:000"), time("2:0"), 120 );
part.insertNote(note("f3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("g#3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("b3"), time("11.3:000"), time("0:64"), 100 );
part.removeNote(note("f3"), time("11.3:000"));

part = song.newLane("MyTextLane",
type("Text")).newPart(time("24.0:000"), time("10.0:000"));
part.text = "This is the test text to be inserted.";
part.lane.parts[0].remove(); // remove initially inserted text-part
</code>```

Another example for reading/changing notes:

```<code>lane = song.getLane("MyMidiLane");
// a lane has a fixed instrument assigned

lane.parts[0].notes[0].duration=64
lane.parts[0].notes[1].duration=32
lane.parts[0].notes[1].startTick=120
// Parts are blocks of notes that you can drag around together in the Frinika GUI.
// They're like patterns in trackers.
for (i in lane.parts[0].notes){
  println("i: "+i+", n: "+noteName(lane.parts[0].notes[i].note));
  println("i: "+i+", dur: "+lane.parts[0].notes[i].duration);
  println("i: "+i+", startT: "+lane.parts[0].notes[i].startTick);
}
</code>```

http://frinika.appspot.com/
It has a Java Webstart launcher as well, so you don't even have to
install.

It used to bundle the Javadoc documentation as well, but for some
reason their latest downloads don't include that. It's a pity, because
that's where the Javascript bindings are documented. So, now you have
to browse the source or build the Javadoc yourself. (It has some built-in examples that are accessible from the scripting window, you should check them out first. My first example is from there.)

Here is the sourcefile where you'll find the Javascript docs:

frinika Javascript doc/source

But there are other options as well. You can check out mingus too, which is a Python library for music theory and midi file handling. It requires Fluidsynth, and the demo apps require GamePython too, so it's a bit more complicated to setup than Frinika.

P.S.:
Frinika has a particular bug: when dragging around neighbouring notes, some might not sound the right length. You can help that by transposing forth and back the consecutive notes (fairly fast in piano roll view), or dragging the part that contains the notes forth and back. Restarting Frinika will also help, but that's the slower way. So this bug won't affect saved files, neither midi export.

OwnerDisplayName: interstar

LastEditorDisplayName: interstar

Body:
There's an opensource music workstation, called Frinika, and you can script that in Javascript. (Insert / delete notes , change midi effects like pitch wheel etc.) It can import / export regular midi files, so it will work with Fruity loops or whatever else you have.

// Insert New

song.newLane("MyMidiLane", type("Midi"));
lane = song.getLane("MyMidiLane");

part = lane.newPart( time("10.0:000"), time("4.0:000") );

part.insertNote(note("c#3"), time("11.2:000"), time("2:0"), 120 );
part.insertNote(note("f3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("g#3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("b3"), time("11.3:000"), time("0:64"), 100 );
part.removeNote(note("f3"), time("11.3:000"));

part = song.newLane("MyTextLane",
type("Text")).newPart(time("24.0:000"), time("10.0:000"));
part.text = "This is the test text to be inserted.";
part.lane.parts[0].remove(); // remove initially inserted text-part

Another example for reading/changing notes:

lane = song.getLane("MyMidiLane");
// a lane has a fixed instrument assigned

lane.parts[0].notes[0].duration=64
lane.parts[0].notes[1].duration=32
lane.parts[0].notes[1].startTick=120
// Parts are blocks of notes that you can drag around together in the Frinika GUI.
// They're like patterns in trackers.
for (i in lane.parts[0].notes){
  println("i: "+i+", n: "+noteName(lane.parts[0].notes[i].note));
  println("i: "+i+", dur: "+lane.parts[0].notes[i].duration);
  println("i: "+i+", startT: "+lane.parts[0].notes[i].startTick);
}

http://frinika.appspot.com/
It has a Java Webstart launcher as well, so you don't even have to
install.

It used to bundle the Javadoc documentation as well, but for some
reason their latest downloads don't include that. It's a pity, because
that's where the Javascript bindings are documented. So, now you have
to browse the source or build the Javadoc yourself. (It has some built-in examples that are accessible from the scripting window, you should check them out first. My first example is from there.)

Here is the sourcefile where you'll find the Javascript docs:

frinika Javascript doc/source

But there are other options as well. You can check out mingus too, which is a Python library for music theory and midi file handling. It requires Fluidsynth, and the demo apps require GamePython too, so it's a bit more complicated to setup than Frinika.

P.S.:
Frinika has a particular bug: when dragging around neighbouring notes, some might not sound the right length. You can help that by transposing forth and back the consecutive notes (fairly fast in piano roll view), or dragging the part that contains the notes forth and back. Restarting Frinika will also help, but that's the slower way. So this bug won't affect saved files, neither midi export.


问:
How make a stage in Jenkins Pipeline that will check a URL for a specific JSON response and succeed/fail?
I am deploying a WAR using Jenkins and I want the final pipeline stage to actually hit the endpoint and check the JSON response. If it comes up and has the right value, then it succeeds, otherwise the build should fail.

How would I do this?

答:
```<code>pipeline {
    agent any

    environment{
        CHECK_URL = "https://stackoverflow.com"
        CMD = "curl --write-out %{http_code} --silent --output /dev/null ${CHECK_URL}"

    }

    stages {
        stage('Stage-One') {
            steps {
                script{
                    sh "${CMD} > commandResult"
                    env.status = readFile('commandResult').trim()
                }
            }
        }
        stage('Stage-Two') {
            steps {
                script {
                    sh "echo ${env.status}"
                    if (env.status == '200') {
                        currentBuild.result = "SUCCESS"
                    }
                    else {
                        currentBuild.result = "FAILURE"
                    }
                }
            }
        }
    }
}
</code>```

Please change the CMD as per your need and also the post section can be used to set the build status. Thanks!

Below curl is one example of printing the Jason value

```<code>  curl -s 'YOUR-URL' | \
        python -c "import sys, json; print json.load(sys.stdin)['VARIABLE-TOFILTER']"
</code>```

Parsing JSON with Unix tools

Body:
pipeline {
    agent any

    environment{
        CHECK_URL = "https://stackoverflow.com"
        CMD = "curl --write-out %{http_code} --silent --output /dev/null ${CHECK_URL}"

    }

    stages {
        stage('Stage-One') {
            steps {
                script{
                    sh "${CMD} > commandResult"
                    env.status = readFile('commandResult').trim()
                }
            }
        }
        stage('Stage-Two') {
            steps {
                script {
                    sh "echo ${env.status}"
                    if (env.status == '200') {
                        currentBuild.result = "SUCCESS"
                    }
                    else {
                        currentBuild.result = "FAILURE"
                    }
                }
            }
        }
    }
}

Please change the CMD as per your need and also the post section can be used to set the build status. Thanks!

Below curl is one example of printing the Jason value

  curl -s 'YOUR-URL' | \
        python -c "import sys, json; print json.load(sys.stdin)['VARIABLE-TOFILTER']"

Parsing JSON with Unix tools


问:
ruby Class.new(arg).method equivalent to Class.method(arg)
I have a class that includes a method to return a calculation based on the instance of the class.

```<code>class Foo
  def initialize(arg)
    @arg = arg
  end

  def baz
    @arg.dosomething
  end
end
</code>```

Is it possible to reformat this such that calling Foo.new(bar).baz is equal to Foo.baz(bar)?

答:
Call Class Method from Instance Method

[I]t's just an exercise in scoring Scrabble plays but the exercise prompt calls for it to return a score if called as Scrabble.new(word).score or as Scrabble.score(word).

The key to your X/Y problem is in your own comment, quoted above. The easiest solution is to ensure the instance method always calls the class method. For example:

```<code>class Scrabble
  def initialize word=nil
    @word = word
  end

  def score
    self.class.score @word
  end

  def self.score word
    "Class method: #{word.inspect}"
  end
end

Scrabble.new('foo').score
#=> "Class method: foo"

Scrabble.score('foo')
#=> "Class method: foo"

Scrabble.new('foo').score == Scrabble.score('foo')
#=> true
</code>```

There may be other ways to get the job done, but this certainly seems like a simple and clear approach that demonstrably works.

Body:
I have a class that includes a method to return a calculation based on the instance of the class.

class Foo
  def initialize(arg)
    @arg = arg
  end

  def baz
    @arg.dosomething
  end
end

Is it possible to reformat this such that calling Foo.new(bar).baz is equal to Foo.baz(bar)?

Body:
Call Class Method from Instance Method

[I]t's just an exercise in scoring Scrabble plays but the exercise prompt calls for it to return a score if called as Scrabble.new(word).score or as Scrabble.score(word).

The key to your X/Y problem is in your own comment, quoted above. The easiest solution is to ensure the instance method always calls the class method. For example:

class Scrabble
  def initialize word=nil
    @word = word
  end

  def score
    self.class.score @word
  end

  def self.score word
    "Class method: #{word.inspect}"
  end
end

Scrabble.new('foo').score
#=> "Class method: foo"

Scrabble.score('foo')
#=> "Class method: foo"

Scrabble.new('foo').score == Scrabble.score('foo')
#=> true

There may be other ways to get the job done, but this certainly seems like a simple and clear approach that demonstrably works.


问:
making a query using COUNT
I want to have one table with many tables.
Before I put the Count(taskid), it works well.

```<code>private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}
</code>```

But when I add Count(taskid) it doesn't work.
 SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID; I want to add these queries, any ideas?

```<code>private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}
</code>```

答:
You need to fix your query.
 when you are using aggregate function (Count())   you must include all fields inside GROUP BY clause.
also,change the wrong syntax of that line d.Count(Taskid) as 'taskKid' (and give an alias name ) to  Count(d.Taskid) as 'taskKid'

another fix: a.[Open Date] >= cast(cast(getdate() as date) as datetime is wrong changed it to a.[Open Date] >= getdate()

this should work:

```<code>    SELECT a.Name,
           b.Restaurant,
           a.City,
           c.[Postal Code],
           a.[Open Date],
           a.POSSystem,
           Count(d.Taskid) as 'taskKid'
      FROM Stores a,
           tblConcepts b,
           tblStates c,
           tblAssignedTasks d
     WHERE a.ConceptID = b.Restaurantid
       AND a.State = c.Stateid
       AND a.[Open Date] >= getdate()
       AND b.Restaurantid = d.StoreID
       AND d.Complete = 'True'
  GROUP BY a.Name,
           b.Restaurant,
           a.City,
           c.[Postal Code],
           a.[Open Date],
           a.POSSystem
</code>```

Title: making a query using COUNT

Body:
I want to have one table with many tables.
Before I put the Count(taskid), it works well.

private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

But when I add Count(taskid) it doesn't work.
 SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID; I want to add these queries, any ideas?

private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

Body:
You need to fix your query.
 when you are using aggregate function (Count())   you must include all fields inside GROUP BY clause.
also,change the wrong syntax of that line d.Count(Taskid) as 'taskKid' (and give an alias name ) to  Count(d.Taskid) as 'taskKid'

another fix: a.[Open Date] >= cast(cast(getdate() as date) as datetime is wrong changed it to a.[Open Date] >= getdate()

this should work:

    SELECT a.Name,
           b.Restaurant,
           a.City,
           c.[Postal Code],
           a.[Open Date],
           a.POSSystem,
           Count(d.Taskid) as 'taskKid'
      FROM Stores a,
           tblConcepts b,
           tblStates c,
           tblAssignedTasks d
     WHERE a.ConceptID = b.Restaurantid
       AND a.State = c.Stateid
       AND a.[Open Date] >= getdate()
       AND b.Restaurantid = d.StoreID
       AND d.Complete = 'True'
  GROUP BY a.Name,
           b.Restaurant,
           a.City,
           c.[Postal Code],
           a.[Open Date],
           a.POSSystem


问:
how to close child of other components?
enter image description here

When I open one of three copmonent A child open,I want to close two others child if they are open.

答: Use a prop to handle the open state of each child. Pass open={false} to the other two children and pass open={true} to the child you want to open. Hard to give a meaningful answer without any code examples to work off of.

Title: how to close child of other components?


问:
MySQL HIGHEST/LOWEST 5 from a ROW of data
I have the following query:

```<code>SELECT AVG(q1) AS q1, AVG (q2) AS q2, AVG(q3) AS q3, AVG(q4) AS q4, AVG(q5) AS q5 FROM tresults_acme

q1    q2    q3    q4    q5
8.23  5.23  7.65  8.00  7.99
</code>```

This query brings back a single row of data, headed q1, q2, q3, q4, q5 - is it possible in MySQL to just show the Highest two (q1 & q4) or Lowest two (q2 & q3) - if not in MySQL can it be done via PHP?

Thanks in advance,

Homer.

答:
You could use a procedure, but here is a pure SQL way of doing it:

```<code>    select greatest(q1,q2,q3,q4,q5) as highest_1,
           least( greatest(q1,q2,q3,q4),
                  greatest(q1,q2,q3,q5),
                  greatest(q1,q2,q4,q5),
                  greatest(q1,q3,q4,q5),
                  greatest(q2,q3,q4,q5) ) as highest_2
    from ( SELECT AVG(q1) AS q1,
                  AVG(q2) AS q2,
                  AVG(q3) AS q3,
                  AVG(q4) AS q4,
                  AVG(q5) AS q5
           FROM tresults_acme ) t;
</code>```

tested with:

```<code>create view tresults_acme as select 1 as q1, 2 as q2, 3 as q3, 4 as q4, 5 as q5;
</code>```

result:

```<code>         highest_1      |     highest_2
    --------------------+--------------------
     5.0000000000000000 | 4.0000000000000000
</code>```

Body:
I have the following query:

SELECT AVG(q1) AS q1, AVG (q2) AS q2, AVG(q3) AS q3, AVG(q4) AS q4, AVG(q5) AS q5 FROM tresults_acme

q1    q2    q3    q4    q5
8.23  5.23  7.65  8.00  7.99

This query brings back a single row of data, headed q1, q2, q3, q4, q5 - is it possible in MySQL to just show the Highest two (q1 & q4) or Lowest two (q2 & q3) - if not in MySQL can it be done via PHP?

Thanks in advance,

Homer.

Body:
You could use a procedure, but here is a pure SQL way of doing it:

    select greatest(q1,q2,q3,q4,q5) as highest_1,
           least( greatest(q1,q2,q3,q4),
                  greatest(q1,q2,q3,q5),
                  greatest(q1,q2,q4,q5),
                  greatest(q1,q3,q4,q5),
                  greatest(q2,q3,q4,q5) ) as highest_2
    from ( SELECT AVG(q1) AS q1,
                  AVG(q2) AS q2,
                  AVG(q3) AS q3,
                  AVG(q4) AS q4,
                  AVG(q5) AS q5
           FROM tresults_acme ) t;

tested with:

create view tresults_acme as select 1 as q1, 2 as q2, 3 as q3, 4 as q4, 5 as q5;

result:

         highest_1      |     highest_2
    --------------------+--------------------
     5.0000000000000000 | 4.0000000000000000


问:
What is the best Head Cascade Classifier in OpenCV
I am using OpenCV 3.1 on a Raspbian Jessie OS using pi zero board.

I used "haarcascade_frontalface_alt" for face detection and it works really good on low resolution images using Python. What i want to do is to detect the heads of people since i may not have their faces in the captured images.

What is the best cascade to use in this case? also is there a catalog page that describe existing cascades and the use case for each one?

Thanks.

答:
You can have a look at all the haarcascade files of opencv by listing the contents of data/haarcascades/ in you opencv folder. The names of the xml files are pretty self explanatory.

This website http://alereimondo.no-ip.org/OpenCV/34/ contains other cascades files and particularly a file for "head and shoulders" that could be appropriate for you.


问:
Is ASP.net C# codebehind considered to be server-side or client-side?
I want to say it is server-side just from my reading and understanding, but I was hoping for a bit of clarification. Thanks. </p>

答:
Code-behind is definitely server-side. It runs on your web server, and not in the user's browser client.

Additionally, anything marked runat="server" in your *.as?x files (aspx, ashx, asmx, etc) are handled server-side.


问:
Performing Convolution (NOT cross-correlation) in pytorch
I have a network that I am trying to implement in pytorch, and I cannot seem to figure out how to implement "pure" convolution. In tensorflow it could be accomplished like this:

```<code>def conv2d_flipkernel(x, k, name=None):
    return tf.nn.conv2d(x, flipkernel(k), name=name,
                        strides=(1, 1, 1, 1), padding='SAME')
</code>```

With the flipkernel function being:

```<code>def flipkernel(kern):
      return kern[(slice(None, None, -1),) * 2 + (slice(None), slice(None))]
</code>```

How can something similar be done in pytorch?

答:
TLDR Use the convolution from the functional toolbox, torch.nn.fuctional.conv2d, not torch.nn.Conv2d, and flip your filter around the vertical and horizontal axis.

torch.nn.Conv2d is a convolutional layer for a network. Because weights are learned, it does not matter if it is implemented using cross-correlation, because the network will simply learn a mirrored version of the kernel (Thanks @etarion for this clarification).

torch.nn.fuctional.conv2d performs convolution with the inputs and weights provided as arguments, similar to the tensorflow function in your example. I wrote a simple test to determine whether, like the tensorflow function, it is actually performing cross-correlation and it is necessary to flip the filter for correct convolutional results.

import torch
import torch.nn.functional as F
import torch.autograd as autograd
import numpy as np

#A vertical edge detection filter.
#Because this filter is not symmetric, for correct convolution the filter must be flipped before element-wise multiplication
filters = autograd.Variable(torch.FloatTensor([[[[-1, 1]]]]))

#A test image of a square
inputs = autograd.Variable(torch.FloatTensor([[[[0,0,0,0,0,0,0], [0, 0, 1, 1, 1, 0, 0],
                                             [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0],
                                            [0,0,0,0,0,0,0]]]]))
print(F.conv2d(inputs, filters))
```
<p>This outputs</p>
<pre class="lang-none prettyprint-override"><code>Variable containing:
(0 ,0 ,.,.) =
  0  0  0  0  0  0
  0  1  0  0 -1  0
  0  1  0  0 -1  0
  0  1  0  0 -1  0
  0  0  0  0  0  0
[torch.FloatTensor of size 1x1x5x6]
</code>```

This output is the result for cross-correlation. Therefore, we need to flip the filter

def flip_tensor(t):
    flipped = t.numpy().copy()

    for i in range(len(filters.size())):
        flipped = np.flip(flipped,i) #Reverse given tensor on dimention i
    return torch.from_numpy(flipped.copy())

print(F.conv2d(inputs, autograd.Variable(flip_tensor(filters.data))))
```
<p>The new output is the correct result for convolution.</p>
<pre class="lang-none prettyprint-override"><code>Variable containing:
(0 ,0 ,.,.) =
  0  0  0  0  0  0
  0 -1  0  0  1  0
  0 -1  0  0  1  0
  0 -1  0  0  1  0
  0  0  0  0  0  0
[torch.FloatTensor of size 1x1x5x6]
</code>```

Body:
I have a network that I am trying to implement in pytorch, and I cannot seem to figure out how to implement "pure" convolution. In tensorflow it could be accomplished like this:

def conv2d_flipkernel(x, k, name=None):
    return tf.nn.conv2d(x, flipkernel(k), name=name,
                        strides=(1, 1, 1, 1), padding='SAME')

With the flipkernel function being:

def flipkernel(kern):
      return kern[(slice(None, None, -1),) * 2 + (slice(None), slice(None))]

How can something similar be done in pytorch?

Body:
TLDR Use the convolution from the functional toolbox, torch.nn.fuctional.conv2d, not torch.nn.Conv2d, and flip your filter around the vertical and horizontal axis.

torch.nn.Conv2d is a convolutional layer for a network. Because weights are learned, it does not matter if it is implemented using cross-correlation, because the network will simply learn a mirrored version of the kernel (Thanks @etarion for this clarification).

torch.nn.fuctional.conv2d performs convolution with the inputs and weights provided as arguments, similar to the tensorflow function in your example. I wrote a simple test to determine whether, like the tensorflow function, it is actually performing cross-correlation and it is necessary to flip the filter for correct convolutional results.

import torch
import torch.nn.functional as F
import torch.autograd as autograd
import numpy as np

#A vertical edge detection filter.
#Because this filter is not symmetric, for correct convolution the filter must be flipped before element-wise multiplication
filters = autograd.Variable(torch.FloatTensor([[[[-1, 1]]]]))

#A test image of a square
inputs = autograd.Variable(torch.FloatTensor([[[[0,0,0,0,0,0,0], [0, 0, 1, 1, 1, 0, 0],
                                             [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0],
                                            [0,0,0,0,0,0,0]]]]))
print(F.conv2d(inputs, filters))

This outputs

Variable containing:
(0 ,0 ,.,.) =
  0  0  0  0  0  0
  0  1  0  0 -1  0
  0  1  0  0 -1  0
  0  1  0  0 -1  0
  0  0  0  0  0  0
[torch.FloatTensor of size 1x1x5x6]

This output is the result for cross-correlation. Therefore, we need to flip the filter

def flip_tensor(t):
    flipped = t.numpy().copy()

    for i in range(len(filters.size())):
        flipped = np.flip(flipped,i) #Reverse given tensor on dimention i
    return torch.from_numpy(flipped.copy())

print(F.conv2d(inputs, autograd.Variable(flip_tensor(filters.data))))

The new output is the correct result for convolution.

Variable containing:
(0 ,0 ,.,.) =
  0  0  0  0  0  0
  0 -1  0  0  1  0
  0 -1  0  0  1  0
  0 -1  0  0  1  0
  0  0  0  0  0  0
[torch.FloatTensor of size 1x1x5x6]


问:
SSRS Interactive Sorting by Value within multiple groups - how?
This should be easy but I can't seem to figure it out. All I want to do is be able to sort ascending/descending by Value across 4 groups. Here is my design...

This is the report (note that all the child groups are toggled by their parents)...

Toggling the sort widget doesn't do anything. I tried sorting by group but that just sorts the group values by alpha. Would appreciate some help with this.

Thanks!

答:
I finally figured out what was holding me back. I based my sort expression on this expression: =Sum(Fields!MergedTotalValue.Value, "tbl_AUM_Summary")
rather than this one: [Sum(MergedTotalValue)]

Not sure why the former didn't work, though.


问:
How to use react native image onError get error message?
I use react native v0.44 image component for android , but image can not load , code:

```<code><View style={styles.slide1} key={index}>
                  <Image
                    style={styles.image}
                    resizeMode = 'contain'
                    onError = {(e)=>{
                      console.log(e)
                    }}
                    source={{uri:`http://i01.appmifile.com/webfile/globalimg/hk/cms/92247F5D-CC6E-273F-5710-841E891CB96F.jpg`}}
                  />
                </View>
</code>```

the image can't show , onError handle get error , but how to know what error in load image ?

答:
Your onError function is as it should be.

But remember, when you use remote picture you need to define width and height for Image.

Body:
I use react native v0.44 image component for android , but image can not load , code:

<View style={styles.slide1} key={index}>
                  <Image
                    style={styles.image}
                    resizeMode = 'contain'
                    onError = {(e)=>{
                      console.log(e)
                    }}
                    source={{uri:`http://i01.appmifile.com/webfile/globalimg/hk/cms/92247F5D-CC6E-273F-5710-841E891CB96F.jpg`}}
                  />
                </View>

the image can't show , onError handle get error , but how to know what error in load image ?


问:
Ajax get function with endpoints
I have an endpoint on the server:

```<code>app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);
</code>```

After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:

```<code>  $.ajax({
      type: 'GET',
      url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
      // result is NaN
}
</code>```

What should be the correct endpoint in this case?

答:
First off, you're not actually providing any data to the ajax call.

```<code>API_URL = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C"
$.ajax({
    type:'GET', //mostly here for readability; is default for ajax
    url:API_URL,
    data:{
        startTimeUtc:user_input_for_start_time
        endTimeUtc:user_input_for_end_time
    }
}).done(function(result){
    console.log(result);
}).always(function(result, status){
    console.log(result);
    console.log(status);
});
</code>```

Not sure whether the always will help you at all, but thought it might be worth a shot. You also need to include the full URL. As a wikipedia api example, it'd be : "https://en.wikipedia.org/w/api.php". i.e. you just need to go to the ?, and then the ? is optional for GET calls (regardless of whether or not the type is supplied, see jQuery ajax documentation).

An alternative approach is pasting the entire URL:
url:API_URL + "?startTimeUtc=03:00:00&endTimeUtc=05:00:00". I personally prefer using data, but it's totally up to you.

Title: Ajax get function with endpoints

Body:
I have an endpoint on the server:

app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);

After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:

  $.ajax({
      type: 'GET',
      url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
      // result is NaN
}

What should be the correct endpoint in this case?

Body:
First off, you're not actually providing any data to the ajax call.

API_URL = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C"
$.ajax({
    type:'GET', //mostly here for readability; is default for ajax
    url:API_URL,
    data:{
        startTimeUtc:user_input_for_start_time
        endTimeUtc:user_input_for_end_time
    }
}).done(function(result){
    console.log(result);
}).always(function(result, status){
    console.log(result);
    console.log(status);
});

Not sure whether the always will help you at all, but thought it might be worth a shot. You also need to include the full URL. As a wikipedia api example, it'd be : "https://en.wikipedia.org/w/api.php". i.e. you just need to go to the ?, and then the ? is optional for GET calls (regardless of whether or not the type is supplied, see jQuery ajax documentation).

An alternative approach is pasting the entire URL:
url:API_URL + "?startTimeUtc=03:00:00&endTimeUtc=05:00:00". I personally prefer using data, but it's totally up to you.


问:
Create Queue and Download Agent means in TFS 2015 (on premise)
Trying to make my CI/CD work using TFS. Have to overcome some of this user role setup. Also not really getting my head around the terminology and the workflow (kinda different with how Jenkins works) and at the same time I have to figure the myriad of TFS versions(2010/2012/2013/2015/2017) and the online Visual Studio team services. I have to unlearn what I already know somehow, thus my basic questions:

What are agent queue? What are pools? (when i click create queue, it will ask me to create new pool)

What does "Download Agent" means? I thought this agent will be installed on the server side like a plugin that you install in Jenkins.

答:
I think this might help clarify:

An agent pool defines the sharing boundary for all agents in that
  pool. In TFS, pools are scoped across all of your Team Foundation
  Server (TFS); so you can share an agent pool across team project
  collections and team projects. In Team Services, agent pools are
  scoped to the Team Services account; so you can share an agent pool
  across team projects.

An agent queue provides access to an agent pool. When you create a
  build or release definition, you specify which queue it uses. Queues
  are scoped to your team project in TFS 2017 and in Team Services, so
  you can only use them across build and release definitions within a
  team project.

An agent in TFS / VSTS does work (like a build or a release).  Microsoft offers agents they host if you are using VSTS.  Alternatively, you can setup your own agents.  For example, if you need to run your build on a particular machine because it has some needed items to do compilation or you're using TFS and can't use the hosted, you'd need to download the agent and configure it on a machine.  You can have multiple agents on one machine.  I'd recommend not installing an agent on the same machine as the TFS application tier if you're working with an on premise installation.


问:
Rails: Stripe appears to work but no charge is created
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

```<code>No route matches [POST] "/charges/new"
</code>```

Even though my routes are like this:

```<code>resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'
</code>```

My charges_controller reads like this:

```<code>class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end
</code>```

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

答:
The problem is this part here in your controller:

```<code>    rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
</code>```

You should remove redirect_to new_charge_path, and simply just let Stripe render the error message. No need to redirect upon error. Stripe takes care of the error-handling for you (which is one of the things making Stripe great).

Currently, your redirect_to is being treated as the path after each successful purchase. Not just on errors.

Update

Upon further looking at your code. You don´t seem to actually have a redirect_to after each successful purchase. So regardless, you should remove the redirect_to new_charge_path because it´s currently arbitrary to => e. It might look like it has something to do with the Error handiling, cause it's below that block, but in fact it doesn't. You should instead add redirect_to successful_path or render :success (for instance) right above the rescue Stripe::CardError =>. And then let Stripe handle (or rescue) failed attempts to make a purchase, as explained before.

Body:
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

No route matches [POST] "/charges/new"

Even though my routes are like this:

resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'

My charges_controller reads like this:

class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

Body:
The problem is this part here in your controller:

    rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path

You should remove redirect_to new_charge_path, and simply just let Stripe render the error message. No need to redirect upon error. Stripe takes care of the error-handling for you (which is one of the things making Stripe great).

Currently, your redirect_to is being treated as the path after each successful purchase. Not just on errors.

Update

Upon further looking at your code. You don´t seem to actually have a redirect_to after each successful purchase. So regardless, you should remove the redirect_to new_charge_path because it´s currently arbitrary to => e. It might look like it has something to do with the Error handiling, cause it's below that block, but in fact it doesn't. You should instead add redirect_to successful_path or render :success (for instance) right above the rescue Stripe::CardError =>. And then let Stripe handle (or rescue) failed attempts to make a purchase, as explained before.


问:
Where are the English pluralization rules for ActiveSupport defined?
I found the ActiveSupport inflector class. Where can I find the code that initializes the inflector for English?</p>

答: The English rules are in ActiveSupport (specifically in lib/active_support/inflections.rb).</p>


问:
Nvidia's nvprof outputs for FLOPS
I see that nvprof can profile the number of flop in the kernel (using the parameters as below). Also when I browse through the documentation (here http://docs.nvidia.com/cuda... it says flop_count_sp is "Number of single-precision floating-point operations executed by non-predicated threads (add, multiply, multiply-accumulate and special). Each multiply-accumulate operation contributes 2 to the count."

However when I run, the result of flop_count_sp (which is supposed to be flop_count_sp_add + flop_count_sp_mul + flop_count_sp_special + 2 * flop_count_sp_fma) I find that it does not include in the summation the value of flop_count_sp_special.

Could you suggest me what I am supposed to use? Should I add this value to the sum of flop_count_sp or I should consider the formula does not include the value of flop_count_sp_special?

Also could you please tell me what are these special operations?

I'm using the following command line:

```<code>nvprof --metrics flops_sp --metrics flops_sp_add --metrics flops_sp_mul --metrics flops_sp_fma --metrics flops_sp_special myKernel args
</code>```

Where myKernel is the name of my CUDA kernel which has some input arguments given by args.

A section of my nvprof outputs for instance is as shown below:

```<code> ==20549== Profiling result:
 ==20549== Metric result:
 Invocations                               Metric Name                        Metric Description         Min         Max         Avg
 Device "Tesla K40c (0)"
    Kernel: mykernel(float*, int, int, float*, int, float*, int*)
           2                             flop_count_sp  Floating Point Operations(Single Precisi       70888       70888       70888
           2                         flop_count_sp_add  Floating Point Operations(Single Precisi       14465       14465       14465
           2                         flop_count_sp_mul  Floating Point Operation(Single Precisio       14465       14465       14465
           2                         flop_count_sp_fma  Floating Point Operations(Single Precisi       20979       20979       20979
           2                     flop_count_sp_special  Floating Point Operations(Single Precisi       87637       87637       87637
</code>```

答:
The "special" operations are listed in the arithmetic throughput table in the Programming Guide, they are: reciprocal, recip sqrt, log, exp, sin, cos. Note that these are less precise (but faster) than the default versions, you have to opt-in using the intrinsic or a compiler flag (-use_fast_math).

Despite what the documentation says, it seems the special operations are not included in the flop_count_sp total. That's a bug in the current version (8.0), I've filed a bug so it should be fixed in a future release (so this paragraph will be out of date at some point).

Title: Nvidia's nvprof outputs for FLOPS

Body:
I see that nvprof can profile the number of flop in the kernel (using the parameters as below). Also when I browse through the documentation (here http://docs.nvidia.com/cuda... it says flop_count_sp is "Number of single-precision floating-point operations executed by non-predicated threads (add, multiply, multiply-accumulate and special). Each multiply-accumulate operation contributes 2 to the count."

However when I run, the result of flop_count_sp (which is supposed to be flop_count_sp_add + flop_count_sp_mul + flop_count_sp_special + 2 * flop_count_sp_fma) I find that it does not include in the summation the value of flop_count_sp_special.

Could you suggest me what I am supposed to use? Should I add this value to the sum of flop_count_sp or I should consider the formula does not include the value of flop_count_sp_special?

Also could you please tell me what are these special operations?

I'm using the following command line:

nvprof --metrics flops_sp --metrics flops_sp_add --metrics flops_sp_mul --metrics flops_sp_fma --metrics flops_sp_special myKernel args

Where myKernel is the name of my CUDA kernel which has some input arguments given by args.

A section of my nvprof outputs for instance is as shown below:

 ==20549== Profiling result:
 ==20549== Metric result:
 Invocations                               Metric Name                        Metric Description         Min         Max         Avg
 Device "Tesla K40c (0)"
    Kernel: mykernel(float*, int, int, float*, int, float*, int*)
           2                             flop_count_sp  Floating Point Operations(Single Precisi       70888       70888       70888
           2                         flop_count_sp_add  Floating Point Operations(Single Precisi       14465       14465       14465
           2                         flop_count_sp_mul  Floating Point Operation(Single Precisio       14465       14465       14465
           2                         flop_count_sp_fma  Floating Point Operations(Single Precisi       20979       20979       20979
           2                     flop_count_sp_special  Floating Point Operations(Single Precisi       87637       87637       87637