问:
I want to add a label border in the layout file
I want to make a label look exactly like

iphone button.

In my case I want to show Active but I want the border of label like given image.
need XML code for that.

答:
create button_background.xml in drawable folder and paste this code

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item >
    <shape android:shape="rectangle" >

        <padding android:left="10dip" android:right="10dip" android:top="5dip" android:bottom="5dip"/>
        <corners android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"
                android:topLeftRadius="5dp" android:topRightRadius="5dp"/>

        <solid
            android:color="#f5f5f5"/>
        <stroke android:width="2dp" android:color="#42A5F5"/>
    </shape>
</item>
</code>```

Body:
create button_background.xml in drawable folder and paste this code

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item >
    <shape android:shape="rectangle" >

        <padding android:left="10dip" android:right="10dip" android:top="5dip" android:bottom="5dip"/>
        <corners android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"
                android:topLeftRadius="5dp" android:topRightRadius="5dp"/>

        <solid
            android:color="#f5f5f5"/>
        <stroke android:width="2dp" android:color="#42A5F5"/>
    </shape>
</item>


来源: stackexchange

问:
Get variable value from the response of an HTTP Sampler to Beanshell PostProcessor
In HTTP Sampler,response I have a javascript variable

```<code>int a=1;
</code>```

I want to get the value of this 'a' in BeanShell Post Processor, How do I get it in JMeter?

答:
Be aware that since JMeter 3.1 it is recommended to use Groovy for any form of scripting in JMeter so I would suggest going for JSR223 PostProcessor instead. The relevant Groovy code would be something like:

```<code>def text = prev.getResponseDataAsString()
log.info('Response text is' + text)
def match = text =~ /int a=(\d+)/
if (match.find()) {
    def value = match.group(1)
    log.info('------------------')
    log.info('a value=' + value)
    vars.put('a', value)
}
</code>```

Demo:

References:

Groovy: Regular expression operators

Apache Groovy - Why and How You Should Use It

ContentLicense: CC BY-SA 3.0

Body:
In HTTP Sampler,response I have a javascript variable

int a=1;

I want to get the value of this 'a' in BeanShell Post Processor, How do I get it in JMeter?

Body:
Be aware that since JMeter 3.1 it is recommended to use Groovy for any form of scripting in JMeter so I would suggest going for JSR223 PostProcessor instead. The relevant Groovy code would be something like:

def text = prev.getResponseDataAsString()
log.info('Response text is' + text)
def match = text =~ /int a=(\d+)/
if (match.find()) {
    def value = match.group(1)
    log.info('------------------')
    log.info('a value=' + value)
    vars.put('a', value)
}

Demo:

References:

Groovy: Regular expression operators

Apache Groovy - Why and How You Should Use It


问:
Spring Boot REST Controller returns 404 when deployed on external tomcat 9 server
I have a spring boot rest web application which works perfectly on the embedded server. However after following the steps mentioned in the is blog https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file, I got a 404 error message whan I send a resquest to a resource on the server.I have used java 1.8.0_212 locally and used java 1.8.0_131 and deployed my app on tomcat 9 on the server. One thing that's puzzling me is that the repositories which extends CrudRepository can be accessed. Below is my application's entry point.

```<code>@SpringBootApplication
@ComponentScan(basePackages = "com.dbe.ref")
public class RefmsApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(RefmsApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(RefmsApplication.class, args);
    }
</code>```

and also my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dbe.ref</groupId>
    <artifactId>refms</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>refms</name>
    <description>project for Rural electrification fund</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>LATEST</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.RefmsApplication</start-class>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>angularjs</artifactId>
            <version>1.4.10</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.4</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>font-awesome</artifactId>
            <version>4.7.0</version>
        </dependency>
        <dependency>
            <groupId>eu.michael-simons</groupId>
            <artifactId>wro4j-spring-boot-starter</artifactId>
            <version>0.3.4</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.dynamicreports</groupId>
            <artifactId>dynamicreports-core</artifactId>
            <version>5.0.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>refms</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Here is part of the log:

```<code>2017-09-19 10:38:20.564  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'errorPageFilter' to: [/*]
2017-09-19 10:38:20.565  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-19 10:38:20.566  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-19 10:38:20.568  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-19 10:38:20.568  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-19 10:38:20.571  INFO 6660 --- [           main] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-09-19 10:38:20.571  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'configurableWroFilter' to urls: [/wro4j/*]
2017-09-19 10:38:20.572  INFO 6660 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServletRegistration' to [/refms/*]
2017-09-19 10:38:20.573  INFO 6660 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
</code>```

答:
in your comments you mentioned /authenticate is giving 404, this is because you have set the login process URL to “authenticate”. It’s the URL that the login form is posted to. If unspecified, it defaults to /login.
Spring Security framework intercepts that URL and gets login and password parameter.</p>

Body:
I have a spring boot rest web application which works perfectly on the embedded server. However after following the steps mentioned in the is blog https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file, I got a 404 error message whan I send a resquest to a resource on the server.I have used java 1.8.0_212 locally and used java 1.8.0_131 and deployed my app on tomcat 9 on the server. One thing that's puzzling me is that the repositories which extends CrudRepository can be accessed. Below is my application's entry point.

@SpringBootApplication
@ComponentScan(basePackages = "com.dbe.ref")
public class RefmsApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(RefmsApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(RefmsApplication.class, args);
    }

and also my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dbe.ref</groupId>
    <artifactId>refms</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>refms</name>
    <description>project for Rural electrification fund</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>LATEST</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.RefmsApplication</start-class>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>angularjs</artifactId>
            <version>1.4.10</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.4</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>font-awesome</artifactId>
            <version>4.7.0</version>
        </dependency>
        <dependency>
            <groupId>eu.michael-simons</groupId>
            <artifactId>wro4j-spring-boot-starter</artifactId>
            <version>0.3.4</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.dynamicreports</groupId>
            <artifactId>dynamicreports-core</artifactId>
            <version>5.0.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>refms</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Here is part of the log:

2017-09-19 10:38:20.564  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'errorPageFilter' to: [/*]
2017-09-19 10:38:20.565  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-19 10:38:20.566  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-19 10:38:20.568  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-19 10:38:20.568  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-19 10:38:20.571  INFO 6660 --- [           main] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-09-19 10:38:20.571  INFO 6660 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'configurableWroFilter' to urls: [/wro4j/*]
2017-09-19 10:38:20.572  INFO 6660 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServletRegistration' to [/refms/*]
2017-09-19 10:38:20.573  INFO 6660 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]


问:
Emacs buffer creation/switching function
I would like to make function that creates a buffer named 'console', if it does not exist and runs a few commands.  If the buffer already exists I want it to only switch to it.</p>

答:
Try this, obviously replacing (insert "something\n") with the commands you want to run:

```<code>(defun jump-to-console ()
  "go to console buffer if it exists, otherwise create"
  (interactive)
  (let ((buffer-name "console"))
    (if (get-buffer buffer-name)
        (pop-to-buffer buffer-name)
      (pop-to-buffer (get-buffer-create buffer-name))
      (insert "something\n"))))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this, obviously replacing (insert "something\n") with the commands you want to run:

(defun jump-to-console ()
  "go to console buffer if it exists, otherwise create"
  (interactive)
  (let ((buffer-name "console"))
    (if (get-buffer buffer-name)
        (pop-to-buffer buffer-name)
      (pop-to-buffer (get-buffer-create buffer-name))
      (insert "something\n"))))


问:
How to add live speech to text data for microsoft bot framework(exactly what google speech does)
I am new to microsoft bot framework. I already build a simple chatbot, and when I publish it and deloyed it to webapp channel, it looks like this

where user will select or type text and bot will respond. Now what i need is, I need to add a mic near by send option so that if user clicks on the mic and starts speaking then it should be typed automatically by bot(exactly how google speech does)

Im having bing speech to text api ref key but I dont know how to add and activate the mic functionality in it.

If anyone knows please help me to resolve this

答:
You can leverage Embeddable web chat control for the Microsoft Bot Framework plugin in your web application. You can refer to https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/speech/index.html for a speech sample.

And generally speaking for some points in code for quick test:

Include style and script files in your web page:

    <link href='https://cdn.botframework.com/botframework-webchat/latest/botchat.css' rel="stylesheet"/>
    ...

Init speech options:

```<code>const speechOptions = {
  speechRecognizer: new CognitiveServices.SpeechRecognizer({ subscriptionKey: 'YOUR_COGNITIVE_SPEECH_API_KEY' }),
  speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
    gender: CognitiveServices.SynthesisGender.Female,
    subscriptionKey: 'YOUR_COGNITIVE_SPEECH_API_KEY',
    voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'
  })
};
</code>```

Init BotChat in script:

```<code>BotChat.App({
  bot: bot,
  locale: params['locale'],
  resize: 'detect',
  // sendTyping: true,    // defaults to false. set to true to send 'typing' activities to bot (and other users) when user is typing
  speechOptions: speechOptions,
  user: user,
  // locale: 'es-es', // override locale to Spanish
  directLine: {
    domain: params['domain'],
    secret: params['s'],
    token: params['t'],
    webSocket: params['webSocket'] && params['webSocket'] === 'true' // defaults to true
  }
}, document.getElementById('BotChatGoesHere'));
</code>```

Body:
You can leverage Embeddable web chat control for the Microsoft Bot Framework plugin in your web application. You can refer to https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/speech/index.html for a speech sample.

And generally speaking for some points in code for quick test:

Include style and script files in your web page:

    <link href='https://cdn.botframework.com/botframework-webchat/latest/botchat.css' rel="stylesheet"/>
    ...
    <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/CognitiveServices.js"></script>

Init speech options:

const speechOptions = {
  speechRecognizer: new CognitiveServices.SpeechRecognizer({ subscriptionKey: 'YOUR_COGNITIVE_SPEECH_API_KEY' }),
  speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
    gender: CognitiveServices.SynthesisGender.Female,
    subscriptionKey: 'YOUR_COGNITIVE_SPEECH_API_KEY',
    voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'
  })
};

Init BotChat in script:

BotChat.App({
  bot: bot,
  locale: params['locale'],
  resize: 'detect',
  // sendTyping: true,    // defaults to false. set to true to send 'typing' activities to bot (and other users) when user is typing
  speechOptions: speechOptions,
  user: user,
  // locale: 'es-es', // override locale to Spanish
  directLine: {
    domain: params['domain'],
    secret: params['s'],
    token: params['t'],
    webSocket: params['webSocket'] && params['webSocket'] === 'true' // defaults to true
  }
}, document.getElementById('BotChatGoesHere'));


问:
R curve drawing not expected line
I have this R code:

```<code>mm_fn <- function(x){
  (x)/(1+2*x)
}

curve(mm_fn, -10,10)
</code>```

And this draws the function but with a vertical line that I think it is not expected to be.

Would you have any idea why?

Best

答:
As Andrey Kolyadin has said, curve by default draws lines, so there is two options, or draw points instead, or add lines in two commands:</p>

```<code>mm_fn <- function(x){
  (x)/(1+2*x)
}
curve(mm_fn, -10,-0.51, xlim=c(-10,10), ylim = c(-25, 25) )
curve(mm_fn, -0.49,10, add = T )
</code>```

Title: R curve drawing not expected line

Body:
I have this R code:

mm_fn <- function(x){
  (x)/(1+2*x)
}

curve(mm_fn, -10,10)

And this draws the function but with a vertical line that I think it is not expected to be.

Would you have any idea why?

Best

Body:
As Andrey Kolyadin has said, curve by default draws lines, so there is two options, or draw points instead, or add lines in two commands:

mm_fn <- function(x){
  (x)/(1+2*x)
}
curve(mm_fn, -10,-0.51, xlim=c(-10,10), ylim = c(-25, 25) )
curve(mm_fn, -0.49,10, add = T )


问:
How to list objects by extension from s3 api?
Can i somehow search objects in S3 by extension, not only by prefix?

Here is what i have now:

```<code>ListObjectsResponse r = s3Client.ListObjects(new Amazon.S3.Model.ListObjectsRequest()
{
    BucketName = BucketName,
    Marker = marker,
    Prefix = folder,
    MaxKeys = 1000
});
</code>```

So, I need to list all *.xls files in my bucket.

答:
I don't believe this is possible with S3.

The best solution is to 'index' S3 using a database (Sql Server, MySql, SimpleDB etc) and do your queries against that.

Body:
Can i somehow search objects in S3 by extension, not only by prefix?

Here is what i have now:

ListObjectsResponse r = s3Client.ListObjects(new Amazon.S3.Model.ListObjectsRequest()
{
    BucketName = BucketName,
    Marker = marker,
    Prefix = folder,
    MaxKeys = 1000
});

So, I need to list all *.xls files in my bucket.


问:
Creating generic classes and functions in javascript ES06
I'm from java background. I use Generics in java in following way:

```<code>  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }
</code>```

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?

答:
Javascript in itself doesn't provide any syntax to support generic classes. But it's possible using:

Flow

or

Typescript

Let me show an example of using generic class using Flow in javascript ES06:

```<code>export class ApiResponse<T> {

    data: ?T = null
}
</code>```

Body:
I'm from java background. I use Generics in java in following way:

  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?

Body:
Javascript in itself doesn't provide any syntax to support generic classes. But it's possible using:

Flow

or

Typescript

Let me show an example of using generic class using Flow in javascript ES06:

export class ApiResponse<T> {

    data: ?T = null
}


问:
Do the parentheses like "()" in the following code have some meaning?
The python code is:         </p>

```<code> #========= RPN ============
 (self.feed('conv5_3').conv(3,3,512,1,1,name='rpn_conv/3x3'))
 (self.feed('rpn_conv/3x3').lstm(512,128,name='lstm_o'))
 (self.feed('lstm_o').lstm_bbox(128,len(anchor_scales) * 10 * 4, name='rpn_bbox_pred'))
 (self.feed('lstm_o').lstm_bbox(128,len(anchor_scales) * 10 * 2,name='rpn_cls_score'))
</code>```

答:
No, all of the outer parentheses are redundant.

The above code can (and should) be written as (well, it could be simplified more, but this question is not about PEP-8):

```<code>self.feed('conv5_3').conv(3, 3, 512, 1, 1,name='rpn_conv/3x3')
self.feed('rpn_conv/3x3').lstm(512 ,128, name='lstm_o')
self.feed('lstm_o').lstm_bbox(128, len(anchor_scales) * 10 * 4, name='rpn_bbox_pred')
self.feed('lstm_o').lstm_bbox(128, len(anchor_scales) * 10 * 2, name='rpn_cls_score')
</code>```

Body:
The python code is:

 #========= RPN ============
 (self.feed('conv5_3').conv(3,3,512,1,1,name='rpn_conv/3x3'))
 (self.feed('rpn_conv/3x3').lstm(512,128,name='lstm_o'))
 (self.feed('lstm_o').lstm_bbox(128,len(anchor_scales) * 10 * 4, name='rpn_bbox_pred'))
 (self.feed('lstm_o').lstm_bbox(128,len(anchor_scales) * 10 * 2,name='rpn_cls_score'))

Body:
No, all of the outer parentheses are redundant.

The above code can (and should) be written as (well, it could be simplified more, but this question is not about PEP-8):

self.feed('conv5_3').conv(3, 3, 512, 1, 1,name='rpn_conv/3x3')
self.feed('rpn_conv/3x3').lstm(512 ,128, name='lstm_o')
self.feed('lstm_o').lstm_bbox(128, len(anchor_scales) * 10 * 4, name='rpn_bbox_pred')
self.feed('lstm_o').lstm_bbox(128, len(anchor_scales) * 10 * 2, name='rpn_cls_score')


问:
How do i synchronize an entity after saving a child object to the database?
I have a User object that gets loaded from the database during user login. This user has a OneToMany relationship (messageList) with the Message entity. When another user sends a new message to that user this message is stored in the database. After that has happened I need to have the messageList of the logged in user to be synchronized automatically with the Database. In other words, the new message needs to appear in the messageList list of the receiving user.

Is there a Spring-data way of accomplishing this? I prefer not to refresh the entire userEntity after the message has been saved. (Using entitymanager.refresh()) because it seems like overkill to retrieve all the child objects inside the userEntity just for the sake of synchronizing the messageList.

I could add the new message to the userEntity and then save the userEntity, but sometimes the same message gets sent to multiple users and I don't want to have to retrieve all the user object just to be able to save a message.

The solution I currently have is to make a Spring AspectJ listener method that listens to all methods saving a message. When that happens the save message gets manually added to the concerning user entity messageList. Why all this effort you may ask? Because I want the message to automatically appear in the frontend (I'm using Angular 4 framework). Angular 4 listens for changes in the data model.

But before I implement this solution I was wondering whether there is a more simpler way of achieving messagelist synchronization.

Thank you.

答: I will have to use websockets in order to achieve what I want. Since i'm using Spring in my project I will use the Spring websocket module for this.</p>


问:
Am I babying the platform/hardware?
I can't tell if I'm being respectful and courteous to the user or if I'm unnecessarily handicapping the utility of my app in the name of treating the phone like a china doll.

I have a successful app in the Android Market. One main functionality is that it records sports stats from a game the user is scoring. The current level of detail is fairly basic: a row for each player and a field for each basic stat. However, I could conceivably dramatically increase the detail and level of usefulness of the app if I recorded additional information, blowing this up to numerous relational tables and conceivably thousands upon thousands of records.

My question is, is this a responsible thing to do? Up to this point, I've shied away from it, thinking that "it's just a phone" and "it's just SQLite", but I've never really looked at whether that's a legitimate reason to hold back on doing things that I wouldn't give a second thought to doing on a web or desktop app.

So with that, how much data (very quantifiable, I know) is it reasonable to expect a phone app to do in regards to storing and sifting through database records?

EDIT:
To be clear, I'm not simply talking about adding more fields as I know the impact of that is trivial. I'm talking about going from the level of detail of "This player has 5 singles and 3 homers" to storing information about each pitch that comprised each at-bat that lead to 5 singles and three homers. Obviously this will call for additional tables and conceivably a great many records.

答:
For my masters thesis project at CMU, I worte an Android app that collected roughly 300mb (2.5 Million rows in the main table) of data during one day in sqlite. It drained the battery of the phone in about 10 hours and CPU utilization was at around 50%, but nothing of that had a lot to do with data. We were doing online learning on physiological data coming in over bluetooth with 72Hz. With the math intensive parts cut out, the phone was quite fine and useabel while the service was running. And the 10 hours were mostly due to bluetooth running continously. Without bluetooth, we got about 16-18 hours of continous uptime. Which I don't even get these days on the HTC Desire.

AND THIS WAS ON A G1

I think you're fine if you stay in the Megabytes or maybe low 10's of megabytes. As long as you have a a good design and don't do expensive querys in the main thread. SQLite handles well formed queries quite well, and dumping data into it is REALLY fast.

[edit:] just thought of something: Why don't you provide a second version of your app with the additional fields? More calculation obviously means a bit more battery drain, so I would give users some kind of choice. But my intution is that the performance hog won't really be noticeable.

Title: Am I babying the platform/hardware?


问:
Clicking on radio button
I have following rendered HTML

```<code><div class="col-xs-8 no-padding">
    <label class="radio-inline gender-label">
        <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        <label for="male-signup">Male</label>
    </label>
    <label class="radio-inline gender-label">
        <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        <label for="female-signup">Female</label>
    </label>
</div>
</code>```

So, to select Male radio button I did the following

```<code>element(by.id('male-signup')).click();
</code>```

It complained Element not visible

Then i did

```<code>var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();
</code>```

It complained Failed: Wait timed out after 5005ms

What is wrong with code?
I simply want to click on Gender male radio button

Update:

As per one of the answer below from 'Ernst Zwingli' I tried following. However, It still complains Failed: Wait timed out after 5005ms

```<code>var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();
</code>```

答:
As you probably can also click the label to select the radio-button, the element, which is to be clicked effectively might be its parent.

Try this:

```<code>//select your element, then go to its parent-element.
element(by.id('male-signup')).element(by.xpath('..')).click();
</code>```

Or with your wait-statement:

```<code>var EC = protractor.ExpectedConditions;
//this selects the <label class="radio-inline gender-label"> above "male-signup"
//potentially the parent-element is visible instead of the id-element
var gender = element(by.id('male-signup')).element(by.xpath('..'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();
</code>```

And here is your HTML-Page as snippet, where you see, that clicking the label also works.

          <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
          Male

          <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
          Female

```

Title: Clicking on radio button

Body:
I have following rendered HTML

        <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        Male

        <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        Female

So, to select Male radio button I did the following

element(by.id('male-signup')).click();

It complained Element not visible

Then i did

var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();

It complained Failed: Wait timed out after 5005ms

What is wrong with code?
I simply want to click on Gender male radio button

Update:

As per one of the answer below from 'Ernst Zwingli' I tried following. However, It still complains Failed: Wait timed out after 5005ms

var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();

Body:
As you probably can also click the label to select the radio-button, the element, which is to be clicked effectively might be its parent.

Try this:

//select your element, then go to its parent-element.
element(by.id('male-signup')).element(by.xpath('..')).click();

Or with your wait-statement:

var EC = protractor.ExpectedConditions;
//this selects the <label class="radio-inline gender-label"> above "male-signup"
//potentially the parent-element is visible instead of the id-element
var gender = element(by.id('male-signup')).element(by.xpath('..'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();

And here is your HTML-Page as snippet, where you see, that clicking the label also works.

<html>
<head></head>
<body>
  <div class="col-xs-8 no-padding">
      <label class="radio-inline gender-label">
          <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
          <label for="male-signup">Male</label>
      </label>
      <label class="radio-inline gender-label">
          <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
          <label for="female-signup">Female</label>
      </label>
  </div>
</body>


问:
Tensorflow: How to create confusion matrix
I am new to tensorflow, I used this tutorial:

https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/.

I have trained the same model on new dataset which contains 3 labels. I am trying to create the confusion matrix.

tf.confusion_matrix function is very confusing.

Can someone please help using same code example.

答:
You have 3 labels (say 0,1,2). Let's assume that you have a test set of size 10 and you get the following tensors:
truth: [0,0,0,0,1,1,2,2,2,2]
prediction: [2,0,0,1,1,1,2,1,2,2]
Then you can do as,

```<code>>>> import tensorflow as tf
>>> truth = [0,0,0,0,1,1,2,2,2,2]
>>> prediction = [2,0,0,1,1,1,2,1,2,2]
>>> cm = tf.contrib.metrics.confusion_matrix(truth, prediction)
>>> with tf.Session() as sess:
...     sess.run(cm)
...
array([[2, 1, 1],
       [0, 2, 0],
       [0, 1, 3]], dtype=int32)
</code>```

Note the following:
The result is a 3x3 matrix. The first row says that 2 times label 0 was predicted correctly, once it was mistaken as label 1 and once it was mistaken as label 2.

Body:
You have 3 labels (say 0,1,2). Let's assume that you have a test set of size 10 and you get the following tensors:
truth: [0,0,0,0,1,1,2,2,2,2]
prediction: [2,0,0,1,1,1,2,1,2,2]
Then you can do as,

>>> import tensorflow as tf
>>> truth = [0,0,0,0,1,1,2,2,2,2]
>>> prediction = [2,0,0,1,1,1,2,1,2,2]
>>> cm = tf.contrib.metrics.confusion_matrix(truth, prediction)
>>> with tf.Session() as sess:
...     sess.run(cm)
...
array([[2, 1, 1],
       [0, 2, 0],
       [0, 1, 3]], dtype=int32)

Note the following:
The result is a 3x3 matrix. The first row says that 2 times label 0 was predicted correctly, once it was mistaken as label 1 and once it was mistaken as label 2.


问:
Get WinWord version from Python program
in one simple Python program for testing users environment, I should also get version of installed Word (example: WinWord 16, 64-bit).
Any idea how to do that? I'm sure, that different GUIDs should exist, but where can I find them :-)

**** edit

I checked both suggestions, but it isn't enough. I have to get an information if Word is 32- or 64-bit. Until now, I have checked location of "winword.exe". For example: 1. location for 64-bit Office 15 c:\program files\microsoft office\office15\winword.exe 2. location for 32-bit Office 15 c:\program files (x86)\microsoft office\office15\winword.exe

I'm sure that M$ has list of GUIDs (used in registry) for latest versions of Word. But I can't find the list :-) With suggested solutions, I can't check 32- or 64- technology.

答:
Another way is using OLE/ActiveX/COM technology. This is a some kind of high-level version of provided "registry method".
Assuming you're on Windows machine since this will not work on Linux in most cases:

```<code>#!/usr/bin/env python3
from win32com.client.dynamic import Dispatch

word = Dispatch('Word.Application')
print (word)
word_version = word.version
print (word_version)
</code>```

Create virtualenv: $ python -m venv ve

Activate virtualenv: $ ve\Scripts\activate.bat

Install pypiwin32: (ve)$ pip install pypiwin32

Execute: (ve)$ python detect_msword_version.py

On my Windows machine output was:

Microsoft Word

16.0

Title: Get WinWord version from Python program

Body:
Another way is using OLE/ActiveX/COM technology. This is a some kind of high-level version of provided "registry method".
Assuming you're on Windows machine since this will not work on Linux in most cases:

#!/usr/bin/env python3
from win32com.client.dynamic import Dispatch

word = Dispatch('Word.Application')
print (word)
word_version = word.version
print (word_version)

Create virtualenv: $ python -m venv ve

Activate virtualenv: $ ve\Scripts\activate.bat

Install pypiwin32: (ve)$ pip install pypiwin32

Execute: (ve)$ python detect_msword_version.py

On my Windows machine output was:

Microsoft Word

16.0


问:
How to refresh dropdownlist without reloading the page?
I have two dropdownlists in my page:

```<code><asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
    <asp:ListItem Text="BY LOCATION" Value="1" />
    <asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>

<br /><br />

<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</code>```

My code-behind to handle the dropdownlist change is:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;

public partial class physicians : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {

    if (!Page.IsPostBack) {
        PopulatePhysician();
    }
    //PopulateSpecialty();
    //PopulateLocation();

    }

    public void PopulatePhysician() {
        SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        //cmd.CommandType = Data.CommandType.StoredProcedure
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Physician's Name";
            Item.Value = "0";
            //Item.Selected = True
            ddlDrillDown.Items.Insert(0, Item);
        //}
    cmd.Connection.Close();
    cmd.Connection.Dispose();
    }

    public void PopulateSpecialty() {
        SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Specialty";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void PopulateLocation() {
        SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();

            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Location";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
        switch(ddlMain.SelectedIndex) {
            case 0:
                PopulatePhysician();
                break;
            case 1:
                PopulateLocation();
                break;
            case 2:
                PopulateSpecialty();
                break;
        }
    }
}
</code>```

The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.

How can I achieve it?

UPDATE:

```<code><asp:ScriptManager ID="ScriptManager"
                               runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1"
                             UpdateMode="Conditional"
                             runat="server">
                <ContentTemplate>
                    <asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                        <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
                        <asp:ListItem Text="BY LOCATION" Value="1" />
                        <asp:ListItem Text="BY SPECIALTY" Value="2" />
                    </asp:DropDownList>
                    <br /><br />
                    <asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                    </asp:DropDownList>
                    </ContentTemplate>
            </asp:UpdatePanel>
</code>```

答:
Another way you can use is Asp.Net [Webmethod] Attribute.

Create a method with [Webmethod] attribute on your server-side code.
On the front end, use window.PageMethods.(your method name) to invoke the server call.

Body:
I have two dropdownlists in my page:

<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
    <asp:ListItem Text="BY LOCATION" Value="1" />
    <asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>

<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>

My code-behind to handle the dropdownlist change is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;

public partial class physicians : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {

    if (!Page.IsPostBack) {
        PopulatePhysician();
    }
    //PopulateSpecialty();
    //PopulateLocation();

    }

    public void PopulatePhysician() {
        SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        //cmd.CommandType = Data.CommandType.StoredProcedure
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Physician's Name";
            Item.Value = "0";
            //Item.Selected = True
            ddlDrillDown.Items.Insert(0, Item);
        //}
    cmd.Connection.Close();
    cmd.Connection.Dispose();
    }

    public void PopulateSpecialty() {
        SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Specialty";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void PopulateLocation() {
        SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();

            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Location";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
        switch(ddlMain.SelectedIndex) {
            case 0:
                PopulatePhysician();
                break;
            case 1:
                PopulateLocation();
                break;
            case 2:
                PopulateSpecialty();
                break;
        }
    }
}

The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.

How can I achieve it?

UPDATE:

<asp:ScriptManager ID="ScriptManager"
                               runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1"
                             UpdateMode="Conditional"
                             runat="server">
                <ContentTemplate>
                    <asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                        <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
                        <asp:ListItem Text="BY LOCATION" Value="1" />
                        <asp:ListItem Text="BY SPECIALTY" Value="2" />
                    </asp:DropDownList>

                    <asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                    </asp:DropDownList>
                    </ContentTemplate>
            </asp:UpdatePanel>


问:
How to append value in an existing object without change the first object with javascript?
My javascript code like this :

```<code>var data= {product_id: 4, name: 'nike'}
console.log(data)

var dataNew = data
dataNew.id = 1

console.log(dataNew)
</code>```

Demo is like this : https://jsfiddle.net/oscar11/69dw8dv1/

I append value in the object like that

The result of console.log(data) and console.log(dataNew) is there exist id

I want var data is no id

So there is only var dataNew that has id

How can I do it?

答:
In JavaScript, object references are assigned, instead of the object values, unless the object is of primitive data types.

That's why dataNew and data refers to the same object when you do this:

```<code>var dataNew = data;
</code>```

To prevent this, you need to create a copy of data like this:

```<code>var dataNew = Object.assign({}, data);
</code>```

Now, the changes in dataNew won't affect data.

Body:
My javascript code like this :

var data= {product_id: 4, name: 'nike'}
console.log(data)

var dataNew = data
dataNew.id = 1

console.log(dataNew)

Demo is like this : https://jsfiddle.net/oscar11/69dw8dv1/

I append value in the object like that

The result of console.log(data) and console.log(dataNew) is there exist id

I want var data is no id

So there is only var dataNew that has id

How can I do it?

Body:
In JavaScript, object references are assigned, instead of the object values, unless the object is of primitive data types.

That's why dataNew and data refers to the same object when you do this:

var dataNew = data;

To prevent this, you need to create a copy of data like this:

var dataNew = Object.assign({}, data);

Now, the changes in dataNew won't affect data.


问:
Determine if any kind of list, sequence, array, or IEnumerable is empty
I am writing a Xamarin.Forms app using XAML for my views, and I am trying to write an IValueConverter whose job should be returning false if the input is "empty" for types where those semantics make sense (strings/lists/sequences/arrays/IEnumerables). I have started with the following, which returns false for empty strings, but I can't figure out how to extend this to lists, sequences, arrays, and IEnumerables:

```<code>type FalseIfEmptyConverter() =
  interface IValueConverter with
    member __.Convert(value:obj, _, _, _) =
      match value with
      | :? string as s -> (s <> "" && not (isNull s)) |> box
      // TODO: extend to enumerables
      | x -> invalidOp <| "unsupported type " + x.GetType().FullName

    member __.ConvertBack(_, _, _, _) =
      raise <| System.NotImplementedException()
</code>```

Things I've tried that don't work:

:? list<_> does not match a (boxed) list (at least not of ints) and produces a warning This construct causes code to be less generic than indicated by its type annotations. The type variable implied by the use of a '#', '_' or other type annotation at or near [...] has been constrained to be type 'obj'

:? list<obj> does not produce the warning, but also doesn't match a boxed list of ints

It's the same with :? seq<_> and :? seq<obj>

It's the same with :? System.Collections.Generic.IEnumerable<obj> and IEnumerable<_> (and if I place it below a similar seq match as given above, it warns that the rule will never be matched, which makes sense since AFAIK seq corresponds to IEnumerable)

答:
Using Foggy Finder's idea to use the non-generic IEnumerable:

```<code>let isEmpty (x:obj) =
    match x with
    | null -> true
    | :? System.Collections.IEnumerable as xs -> xs |> Seq.cast |> Seq.isEmpty
    | _ -> invalidOp <| "unsupported type " + x.GetType().FullName

isEmpty "" // true
isEmpty [] // true
isEmpty (set []) // true
isEmpty [||] // true
isEmpty null // true

isEmpty "a" // false
isEmpty [|1|] // false

isEmpty 1 // exception
</code>```

All of the types that you want to test are sub-types of Seq<'a>, which is exactly the same as IEnumerable<'a> (including string, which is a seq<char>). But this is also sub-type of a non-generic type called IEnumerable (note the lack of type parameter). This is similar to an IEnumerable<obj>, where every item has been boxed. This is why we can cast all of these to IEnumerable, then use Seq.cast to convert that into IEnumerable<obj> so that we can use Seq.empty, which only works on the generic type.

Body:
I am writing a Xamarin.Forms app using XAML for my views, and I am trying to write an IValueConverter whose job should be returning false if the input is "empty" for types where those semantics make sense (strings/lists/sequences/arrays/IEnumerables). I have started with the following, which returns false for empty strings, but I can't figure out how to extend this to lists, sequences, arrays, and IEnumerables:

type FalseIfEmptyConverter() =
  interface IValueConverter with
    member __.Convert(value:obj, _, _, _) =
      match value with
      | :? string as s -> (s <> "" && not (isNull s)) |> box
      // TODO: extend to enumerables
      | x -> invalidOp <| "unsupported type " + x.GetType().FullName

    member __.ConvertBack(_, _, _, _) =
      raise <| System.NotImplementedException()

Things I've tried that don't work:

:? list<_> does not match a (boxed) list (at least not of ints) and produces a warning This construct causes code to be less generic than indicated by its type annotations. The type variable implied by the use of a '#', '_' or other type annotation at or near [...] has been constrained to be type 'obj'

:? list<obj> does not produce the warning, but also doesn't match a boxed list of ints

It's the same with :? seq<_> and :? seq<obj>

It's the same with :? System.Collections.Generic.IEnumerable<obj> and IEnumerable<_> (and if I place it below a similar seq match as given above, it warns that the rule will never be matched, which makes sense since AFAIK seq corresponds to IEnumerable)

Body:
Using Foggy Finder's idea to use the non-generic IEnumerable:

let isEmpty (x:obj) =
    match x with
    | null -> true
    | :? System.Collections.IEnumerable as xs -> xs |> Seq.cast |> Seq.isEmpty
    | _ -> invalidOp <| "unsupported type " + x.GetType().FullName

isEmpty "" // true
isEmpty [] // true
isEmpty (set []) // true
isEmpty [||] // true
isEmpty null // true

isEmpty "a" // false
isEmpty [|1|] // false

isEmpty 1 // exception

All of the types that you want to test are sub-types of Seq<'a>, which is exactly the same as IEnumerable<'a> (including string, which is a seq<char>). But this is also sub-type of a non-generic type called IEnumerable (note the lack of type parameter). This is similar to an IEnumerable<obj>, where every item has been boxed. This is why we can cast all of these to IEnumerable, then use Seq.cast to convert that into IEnumerable<obj> so that we can use Seq.empty, which only works on the generic type.


问:
svn export and revision in single command
I am newbie in shell scripting.
I have an existing command in a script.

```<code>svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY
</code>```

this command shows a lot of output and finally ends with below string

```<code>Exported revision 3779.
</code>```

I want to capture and store this value (3779) in to a variable.
How can I do this.

Please avoid svn info or svn export --force -r

UPDATE

I tried below line

```<code>svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY | tail -n 1 | sed 's/Exported\ revision\ \([0-9][0-9]*\)\./\1/'
</code>```

But the problem I face is, this line stopped showing the console messages.

答:
I tried below line

```<code>svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY | tail -n 1 | sed 's/Exported\ revision\ \([0-9][0-9]*\)\./\1/'
</code>```

But the problem I face is, this line stopped showing the console
  messages.

This copies the messages to stderr so that they still show, and assigns the value to $revision:

```<code>revision=`svn export --force…|tee /dev/fd/2|sed -n 's/Exported revision \([0-9]*\)./\1/p'`
</code>```

Body:
I am newbie in shell scripting.
I have an existing command in a script.

svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY

this command shows a lot of output and finally ends with below string

Exported revision 3779.

I want to capture and store this value (3779) in to a variable.
How can I do this.

Please avoid svn info or svn export --force -r

UPDATE

I tried below line

svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY | tail -n 1 | sed 's/Exported\ revision\ \([0-9][0-9]*\)\./\1/'

But the problem I face is, this line stopped showing the console messages.

Body:
I tried below line

svn export --force "https://$svn_url/SVN_SOURCE_PATH" A_DIRECTORY | tail -n 1 | sed 's/Exported\ revision\ \([0-9][0-9]*\)\./\1/'

But the problem I face is, this line stopped showing the console
  messages.

This copies the messages to stderr so that they still show, and assigns the value to $revision:

revision=`svn export --force…|tee /dev/fd/2|sed -n 's/Exported revision \([0-9]*\)./\1/p'`


问:
specify keyPath with multiple tables in indexedDb
in my project I'm using indexedDb through the wrapper Dexie.js. The goal is to fetch the data directly from the indexedDb instead of calling api all the time.

Since I might change/delete some data, from time to time, I use a version number to keep track of what is present in the user cache. So when the application starts I receive the version of the db, if that matches the version in the cache I fetch the indexedDb, otherwise I will delete the indexedDb and fetch from the server the new data.

The problem is that I can't find a way to update the version value without adding another entry. Right now this is what I'm doing:

```<code>       db.version(1).stores({
              buildings: "id, name, address, lat, long, purchased, [lat+long]",
              versions: "id, version",
          });

          db.open().then((el) => {
              console.log(el);
              this.eventBus.$on("refresh-map", () => {
                  this.fetchHexagons();
              });
          }).catch(Dexie.MissingAPIError, (e) => {
              console.log("Couldn't find indexedDB API");
              console.log(e);
              rollback = true;
          }).catch((error) => {
              console.log(`error: ${error}`);
          });

          db.versions.toArray((res) => {
              if (res.length > 0 && res[0].version != version.body.model_version) {
                  db.buildings.clear().then(() => {
                      console.log("clearing buildings");
                  });
              }

              db.versions.update(1, { version: "2"}).then((update) => {
                  if (!update) {
                      db.versions.put({ version: version.body.model_version });
                  }
              });
</code>```

The problem is that I get the following error:

```<code>dexie.es.js?f8d5:1384 Unhandled rejection: Error: Failed to execute 'put' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.
</code>```

I just want to make sure that whenever I add/put the version field I only substitute that value without adding anything else: that way the db in the "versions" table will always have one element.

How can I solve this?

答:
This line:

```<code>db.versions.put({ version: version.body.model_version });
</code>```

...needs to provide an id:

```<code>db.versions.put({ id: someUniqueId, version: version.body.model_version });
</code>```

Another option is to use an auto-incremented primary key. If so, you would need to recreate the DB (primary keys may not be changed on existing db):

```<code>db.version(1).stores({
    buildings: "id, name, address, lat, long, purchased, [lat+long]",
    versions: "++id, version",
});
</code>```

To recreate the db:

```<code>db.delete().then(()=>db.open())
</code>```

Body:
in my project I'm using indexedDb through the wrapper Dexie.js. The goal is to fetch the data directly from the indexedDb instead of calling api all the time.

Since I might change/delete some data, from time to time, I use a version number to keep track of what is present in the user cache. So when the application starts I receive the version of the db, if that matches the version in the cache I fetch the indexedDb, otherwise I will delete the indexedDb and fetch from the server the new data.

The problem is that I can't find a way to update the version value without adding another entry. Right now this is what I'm doing:

       db.version(1).stores({
              buildings: "id, name, address, lat, long, purchased, [lat+long]",
              versions: "id, version",
          });

          db.open().then((el) => {
              console.log(el);
              this.eventBus.$on("refresh-map", () => {
                  this.fetchHexagons();
              });
          }).catch(Dexie.MissingAPIError, (e) => {
              console.log("Couldn't find indexedDB API");
              console.log(e);
              rollback = true;
          }).catch((error) => {
              console.log(`error: ${error}`);
          });

          db.versions.toArray((res) => {
              if (res.length > 0 && res[0].version != version.body.model_version) {
                  db.buildings.clear().then(() => {
                      console.log("clearing buildings");
                  });
              }

              db.versions.update(1, { version: "2"}).then((update) => {
                  if (!update) {
                      db.versions.put({ version: version.body.model_version });
                  }
              });

The problem is that I get the following error:

dexie.es.js?f8d5:1384 Unhandled rejection: Error: Failed to execute 'put' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.

I just want to make sure that whenever I add/put the version field I only substitute that value without adding anything else: that way the db in the "versions" table will always have one element.

How can I solve this?

Body:
This line:

db.versions.put({ version: version.body.model_version });

...needs to provide an id:

db.versions.put({ id: someUniqueId, version: version.body.model_version });

Another option is to use an auto-incremented primary key. If so, you would need to recreate the DB (primary keys may not be changed on existing db):

db.version(1).stores({
    buildings: "id, name, address, lat, long, purchased, [lat+long]",
    versions: "++id, version",
});

To recreate the db:

db.delete().then(()=>db.open())


问:
Meteor not loading external CSS and JS files
I am trying to load my stylesheets and js files in Meteor. I have an index.html file. This is what I was doing at first:

```<code><link href="assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>
</code>```

There were lots of stylesheet files and script files. This was working fine but if i wrote a url like: 'localhost:3000/manage-user/add', everything stopped working. I have read loads of answers where they have mentioned that I need to make a lib folder and in that folder, I need to make a css and a js folder, but it's not picking up my files, especially my 'style.css' file which overrides styles of bootstrap and all.

答:
assets folder should be inside the /public folder, then try add the / to the begining of the href value.</p>

```<code><link href="/assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="/assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="/assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>
</code>```

Body:
I am trying to load my stylesheets and js files in Meteor. I have an index.html file. This is what I was doing at first:

<link href="assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>

There were lots of stylesheet files and script files. This was working fine but if i wrote a url like: 'localhost:3000/manage-user/add', everything stopped working. I have read loads of answers where they have mentioned that I need to make a lib folder and in that folder, I need to make a css and a js folder, but it's not picking up my files, especially my 'style.css' file which overrides styles of bootstrap and all.

Body:
assets folder should be inside the /public folder, then try add the / to the begining of the href value.

<link href="/assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="/assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="/assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>


问:
Using interface realization thru generic class
I try to use a interface realization through a generic class. Wondering on some abstraction magic, but get compiler errors with this approach.

```<code>cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
</code>```

Here a simplified example:

//Very simple generic with only data access, no internal manipulation
class GClass<T> {
    T value;
    public GClass(T value) {
        this.value = value;
    }
    public T Get() {
        return value;
    }
}

//Simple interface
interface IPos {
    int GetPos();
}

//Simple realization
class PosClass : IPos {
    //Interface realization
    public int GetPos() {
        return 1;
    }
    public int GetAnotherImportantData() {
        return -1;
    }
}

class MainTrouble {
    public int DoUsingInterface(GClass<IPos> interfaceableItem) {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance() {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());
        //Next line error me
        //cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
        var r = DoUsingInterface(item);
        //So, next I should execute a several methods using PosClass
        return item.Get().GetAnotherImportantData();
    }
}
```

Some suggestions? Maybe some tricky cast which I miss with it?

答:
Based on this answer addressing a problem not far from yours, it will not work because there is no relation between GClass<IPos> and GClass<PosClass>. Indeed, a list of GClass<PosClass> is not a list of GClass<IPos>.

In order to help you understand better those problems, I suggest you to read this article about covariance and contravariance.

Body:
I try to use a interface realization through a generic class. Wondering on some abstraction magic, but get compiler errors with this approach.

cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'

Here a simplified example:

//Very simple generic with only data access, no internal manipulation
class GClass<T> {
    T value;
    public GClass(T value) {
        this.value = value;
    }
    public T Get() {
        return value;
    }
}

//Simple interface
interface IPos {
    int GetPos();
}

//Simple realization
class PosClass : IPos {
    //Interface realization
    public int GetPos() {
        return 1;
    }
    public int GetAnotherImportantData() {
        return -1;
    }
}

class MainTrouble {
    public int DoUsingInterface(GClass<IPos> interfaceableItem) {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance() {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());
        //Next line error me
        //cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
        var r = DoUsingInterface(item);
        //So, next I should execute a several methods using PosClass
        return item.Get().GetAnotherImportantData();
    }
}

Some suggestions? Maybe some tricky cast which I miss with it?


问:
Selecting everything from table 1 with average AND distinct values from table 2 and table 3
I am not entirely sure even how to name this post, because I do not know exactly how to ask it.

I have three tables. One with users, one with foods and one with the users rating of the foods, like such (simplified example):

```<code>Foods
id  name    type
---------------------
1   Apple   fruit
2   Banana  fruit
3   Steak   meat

Users
id  username
-----------------
1   Mark
2   Harrison
3   Carrie

Scores (fid = food id, uid = user id)
fid uid score
---------------------
1   1   3
1   2   5
2   1   2
3   2   3
</code>```

Now, I have this query, which works perfectly:

```<code>SELECT fn.name as Food, ROUND(AVG(s.score),1) AS AvgScore FROM Foods fn LEFT JOIN Scores s ON fn.id = s.fid GROUP BY fn.id ORDER BY fn.name ASC
</code>```

As you can tell, it lists all names from Foods including an average from all users ratings of the food.

I also want to add the unique users own score. (Assume that when Mark is logged in, his uid is set in a session variable or whatever)

I need the following output, if you are logged in as Mark:

```<code>Food    AvgScore    Your Score
Apple   4           3
</code>```

I have made several attempts to make this happen, but I cannot find the solution. I have learned that if you have a question, it is very likely that someone else has asked it before you do, but I do not quite know how to phrase the question, so I get no answers when googling. A pointer in the right direction would be much appreciated.

答:
You can try with case:

```<code>SELECT fn.name as Food,
       ROUND(AVG(s.score),1) AS AvgScore,
       sum(case s.uid = $uid when s.score else 0 end) as YourScore
FROM Foods fn
LEFT JOIN Scores s ON fn.id = s.fid
GROUP BY fn.id
ORDER BY fn.name ASC
</code>```

$uid is variable off course.

Body:
I am not entirely sure even how to name this post, because I do not know exactly how to ask it.

I have three tables. One with users, one with foods and one with the users rating of the foods, like such (simplified example):

Foods
id  name    type
---------------------
1   Apple   fruit
2   Banana  fruit
3   Steak   meat

Users
id  username
-----------------
1   Mark
2   Harrison
3   Carrie

Scores (fid = food id, uid = user id)
fid uid score
---------------------
1   1   3
1   2   5
2   1   2
3   2   3

Now, I have this query, which works perfectly:

SELECT fn.name as Food, ROUND(AVG(s.score),1) AS AvgScore FROM Foods fn LEFT JOIN Scores s ON fn.id = s.fid GROUP BY fn.id ORDER BY fn.name ASC

As you can tell, it lists all names from Foods including an average from all users ratings of the food.

I also want to add the unique users own score. (Assume that when Mark is logged in, his uid is set in a session variable or whatever)

I need the following output, if you are logged in as Mark:

Food    AvgScore    Your Score
Apple   4           3

I have made several attempts to make this happen, but I cannot find the solution. I have learned that if you have a question, it is very likely that someone else has asked it before you do, but I do not quite know how to phrase the question, so I get no answers when googling. A pointer in the right direction would be much appreciated.

Body:
You can try with case:

SELECT fn.name as Food,
       ROUND(AVG(s.score),1) AS AvgScore,
       sum(case s.uid = $uid when s.score else 0 end) as YourScore
FROM Foods fn
LEFT JOIN Scores s ON fn.id = s.fid
GROUP BY fn.id
ORDER BY fn.name ASC

$uid is variable off course.


问:
Android Studio doesn't see device
The AVD Manager in Android Studio doesn't show my device but adb devices does show it. Am I missing something obvious here?

答: None of above answers solved my problem until I updated SDK platform-tools.This maybe one of the causes of this issue.</p>

ContentLicense: CC BY-SA 4.0

Title: Android Studio doesn't see device


问:
Stop MySQL service windows
I am developing a website and need to refresh data. Therefore MySQL must be stopped.

How can I stop the service?

When I look at control panel services it is started without stop or restart option.

答:
Start Powershell as administrator and run:

```<code>net start [MySQL-service-name]
</code>```

Find the service name:

run 'services.msc', look for MySQL and click on properties

Title: Stop MySQL service windows

Body:
Start Powershell as administrator and run:

net start [MySQL-service-name]

Find the service name:

run 'services.msc', look for MySQL and click on properties


问:
Find gmail account associated with Wordpress google cloud project
I had multiple gmail accounts for project hosting on google cloud (Bad management). Now after more than 1 year I want to remove the project from google cloud.

I am struggling with finding the Cloud project ID as I am unable to find the gmail account associated with that project.

Project is basic Wordpress blog site - successfollows.com
and I dont have wordpress username and password either.
Any help would be great.

答: You can go to http://www.successfollows.com/wp-login.php?action=lostpassword and try your emails one-by-one. If it gives "ERROR: There is no user registered with that email address." error, skip to the next email. When you at last enter correct email, it will give success message about "Email has been sent".</p>


问:
Indexing uploaded documents - searchable only by the users that uploaded them
If someone could point me in the right direction that would be most helpful.

I have written a custom CMS where I want to be able to allow each individual user to upload documents (.doc .docx .pdf .rtf .txt etc) and then be able to search the contents of those files for keywords.

The CMS is written entirely in PHP and MySQL within a Linux environment.

Once uploaded the documents would be stored in the users  private folder on the server "as is". There will be hundreds if not thousands of documents stored by each user.

It is very important that the specific users files are searchable only by that user.

Could anyone point me in the right direction? I have had a look at Solr but these types of solutions seem so complicated. I have spent an entire week looking at different solutions and this is my last attempt at finding a solution.

Thank you in advance.

答: keep the files outside of the public directory tree, keep a reference to the file's filepath and creator's user id in a database table, then they can search for the files using database queries. you will of course have to let users create accounts and have a log in. you can they let them download the files using php.</p>


问:
tabs container property change using jquery
I want to change the property of inpected code

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="false">
  <a class="t-Tabs-link" href="#SR_R1" role="presentation" tabindex="-1">
    <span>1<span>
  </a>
</li>

<div id="SR_R1" class="a-Tabs-panel a-Tabs-before" data-label="1" role="tabpanel" aria-labelledby="SR_R1_tab" aria-hidden="true" style="display: block;" >
</code>```

into

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="true">
<a class="t-Tabs-link" href="#SR_R1" role="presentation" >
    <span>1<span>
  </a>
</li>

<div id="SR_R1"  class="a-Tabs-panel a-Tabs-before a-Tabs-element-selected" data-label="1" role="tabpanel" aria-labelledby="SR_R1_tab" aria-hidden="false" style="display: block;" >
</code>```

using js function or jquery. I am using oracle apex. I have less knowledge in jquery and js . How can I do this?

答:
```<code>Please Try below javascript.

1. Add the style first

    div.tab {
        overflow: hidden;
        border: 1px solid #ccc;
        background-color: #f1f1f1;
    }
    div.tab button {
        background-color: inherit;
        float: left;
        border: none;
        outline: none;
        cursor: pointer;
        padding: 14px 16px;
        transition: 0.3s;
        font-size: 17px;
    }
    div.tab button:hover {
        background-color: #ddd;
    }
    div.tab button.active {
        background-color: #ccc;
    }
    .tabcontent {
        display: none;
        padding: 6px 12px;
        border: 1px solid #ccc;
        border-top: none;
    }

2. Copy and paste below HTML

 <div class="tab">
              <button class="tablinks" onclick="openCity(event, 'London')">London</button>
              <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
              <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
            </div>

            <div id="London" class="tabcontent">
              <h3>London</h3>
              <p>London is the capital city of England.</p>
            </div>

            <div id="Paris" class="tabcontent">
              <h3>Paris</h3>
              <p>Paris is the capital of France.</p>
            </div>

            <div id="Tokyo" class="tabcontent">
              <h3>Tokyo</h3>
              <p>Tokyo is the capital of Japan.</p>
            </div>

3. Add below script in your webpage.

    function openCity(evt, cityName) {
        var i, tabcontent, tablinks;
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(cityName).style.display = "block";
        evt.currentTarget.className += " active";
    }
</code>```

Body:
I want to change the property of inpected code

    1

into

    1

using js function or jquery. I am using oracle apex. I have less knowledge in jquery and js . How can I do this?


问:
Live Streaming Between Two Devices With 4G Network
i want to cast live streaming video from Linux machine i.e Raspberry Pi to another Linux/Windows/Android Machine.

Both system have 4G Internet connection (No Public IP),
Is there a way that i can accomplish this thing.

Please help me.

答:
There are several ways to achieve this. One of the widely used framework is GStreamer. You can think of media framework tool like GStreamer.

You can used UDP for communicating the data from your Pi to host machine.

GStreamer allows you to stream video with very low latency.

Reference of Gstreamer with Pi.


问:
shouldChangeCharactersIn range function not being called
The code below works fine when I have used it with a view controller, though my current view controller has a header and text fields are in their and it doesn't bring up an error in the code though it has no effect; the function is never called?

Here is the code - first put the func in class ProfileEditor

```<code>class ProfileEditor: UICollectionViewController, UICollectionViewDelegateFlowLayout, ProfileEditorHeaderDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    print("text field func called")

    let currentCharacterCount = textField.text?.characters.count ?? 0

    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    var maxLength = 0
    if textField.isEqual(header.displayNameTextFeild) {
        maxLength = 13

    return newLength <= maxLength
}
</code>```

then I put the func in the delegate

```<code> protocol ProfileEditorHeaderDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

 }

 class ProfileHeaderEditor: UICollectionViewCell {

    let displayNameTextField: UITextField = {
       let tf = UITextField()
       tf.placeholder = "Display name"
       tf.font?.withSize(10)
       tf.backgroundColor = UIColor.white
       tf.textColor = UIColor.black
       tf.borderStyle = .roundedRect

       return tf
    }()
}
</code>```

答:
First of all you should implement UITextFieldDelegate which contains method: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

add this line where you create your Cell

```<code>profileHeaderEditor.displayNameTextField.delegate = self // add this
</code>```

Body:
The code below works fine when I have used it with a view controller, though my current view controller has a header and text fields are in their and it doesn't bring up an error in the code though it has no effect; the function is never called?

Here is the code - first put the func in class ProfileEditor

class ProfileEditor: UICollectionViewController, UICollectionViewDelegateFlowLayout, ProfileEditorHeaderDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    print("text field func called")

    let currentCharacterCount = textField.text?.characters.count ?? 0

    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    var maxLength = 0
    if textField.isEqual(header.displayNameTextFeild) {
        maxLength = 13

    return newLength <= maxLength
}

then I put the func in the delegate

 protocol ProfileEditorHeaderDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

 }

 class ProfileHeaderEditor: UICollectionViewCell {

    let displayNameTextField: UITextField = {
       let tf = UITextField()
       tf.placeholder = "Display name"
       tf.font?.withSize(10)
       tf.backgroundColor = UIColor.white
       tf.textColor = UIColor.black
       tf.borderStyle = .roundedRect

       return tf
    }()
}

Body:
First of all you should implement UITextFieldDelegate which contains method: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

add this line where you create your Cell

profileHeaderEditor.displayNameTextField.delegate = self // add this


问:
JAVA - File I/O cant get file to read
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

```<code>public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}
</code>```

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.
```

答:
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.

In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here

Title: JAVA - File I/O cant get file to read

Body:
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.


问:
Best approach to developing a cross-browser JavaScript widget that populates from a MySQL database?
I'm currently researching the best way to approach building a JavaScript widget someone can embed on their site, which would retrieve and display information from an external MySQL database.

The gist of the widget would mimic the needs/functionality of Twitter's widget (http://twitter.com/about/resources/widgets), where it uses some combination of JavaScript, PHP and/or AJAX and retrieves information from a MySQL database with secure (or at least somewhat safe) cross-browser access. Does anyone have thoughts or ideas on the best and most reliable way to approach something like this?

答: Should be simple. Encapsulate your widget entirely in a JS file if possible (minus images) and use AJAX for calling a REST or SOAP (probably want to stick to REST) webservice for any data access you need.</p>


问:
Redirect to a particular viewcontroller when redirecting from reset password mail ios
In my app I have a Home viewcontroller from where user can login, reset password, and skip to other pages.

If I click "Forgot password", I will get a mail where I can reset password. When I redirect back from email, I want the app to stay in the same Home viewcontroller.

If my flow is : click on "Forgot password" from home viewcontroller -> then move to ForgotPassword viewcontrollers -> exit app -> then go to my mail and do reset password , even then I want the app to open in the home page itself when it comes to foreground, not on any other viewcontrollers from where I exited the app or minimised the app.

How can I do this? Thank you

答:
As far as I understand your question:
You want that whenever user taps on "Forgot password" on HomeScreen, user will be directed to ForgotPasswordScreen and then user receive a mail(with a link to reset the password [all these done by your server]). Coming back to app, user should be shown HomeScreen, whether its launching the app or already at background.

If above is the scenario then I guess there is an extra task that you are performing.

I would suggest that there is no need of ForgotPasswordScreen, just show an alert with a textfield to let user enter the email id to send password reset mail to it.

And you should just set one flag isLoggedIn

If isLoggedIn == true only then load your other viewControllers.

isLoggedIn has to be a global variable which should be set only at the time of successful login/logout


问:
Allow only 3 rows to be added to a table for a specific value
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

```<code>Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)
</code>```

Can anyone suggest what approach to take to implement this?

答:
I would do the following:

Create one SP for both operation insert/update.

Check with IF not exists Project_manager_employee_id(FK) count < 3
then only proceed for insert/update. otherwise send Throw error.

Body:
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)

Can anyone suggest what approach to take to implement this?


问:
Rename a file in C#
How do I rename a file using C#?</p>

答:
In my case, I want the name of the renamed file to be unique, so I add a date-time stamp to the name. This way, the filename of the 'old' log is always unique:</p>

```<code>if (File.Exists(clogfile))
{
    Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
    if (fileSizeInBytes > 5000000)
    {
        string path = Path.GetFullPath(clogfile);
        string filename = Path.GetFileNameWithoutExtension(clogfile);
        System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
    }
}
</code>```

Title: Rename a file in C#

Body: How do I rename a file using C#?

Body:
In my case, I want the name of the renamed file to be unique, so I add a date-time stamp to the name. This way, the filename of the 'old' log is always unique:

if (File.Exists(clogfile))
{
    Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
    if (fileSizeInBytes > 5000000)
    {
        string path = Path.GetFullPath(clogfile);
        string filename = Path.GetFileNameWithoutExtension(clogfile);
        System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
    }
}


问:
JQuery-UI draggable elements appear on top of others when they are dropped
I'm using JQuery-UI to be able to drag items from one div to another, but when I drop the element in another div, it appears on top of other dropped elements. What am I doing wrong?

```<code>        //These are my draggable elements
        $('#interface li').draggable({
            helper: 'clone',
            revert: 'invalid'
        });

        //This function makes dropped elements draggable again.
        function foo(){
            $('.foo').each(function() {
                $(this).draggable({
                    containment: $(this).parent(),
                    stack: '.foo'
                });
            });
        }

        //This function forms table around dropped item
        var fooCount = $('.foo').length;
        $('#mainDiv').droppable({
            drop: function(event, ui) {
                if (!ui.draggable.hasClass('foo')) {
                    var Class = ui.draggable.attr("class");
                    var title = ui.draggable.text().trim();
                    var item = $('<table class="foo elementTable ' + Class + '" name="' + title + '" id="'+(fooCount+1)+'"><tr class="tableHeader"><th class="thClass"><button class="settings">set</button>' + title + '<span class="close">x</span></th></tr><tr><td class="add"><span class="addList">Add new link</span></td></tr></table>');
                    $(this).append(item);
                    fooCount += 1;
                    foo();
                }
            }
        });
</code>```

This is my CSS code for styling newly created tables:

```<code>.foo {
    min-width: 250px;
    max-width: 300px;
    text-align: center;
    min-height: 50px;
    border: 1px solid white;
    border-radius: 10px;
    position: absolute;
    padding: 0;
}
</code>```

But the dropped elements appear like this:

I want them to appear like this:

EDIT: Here is a working jsfiffle: https://jsfiddle.net/vaxobasilidze/79kd1uLL/

答:
Just remove position: absolute; from newly created element. It should be

```<code>.foo {
    min-width: 250px;
    max-width: 300px;
    text-align: center;
    min-height: 50px;
    border: 1px solid white;
    border-radius: 10px;
    /*position: absolute;*/
    padding: 0;
}
</code>```

Check updated fiddle here

Body:
I'm using JQuery-UI to be able to drag items from one div to another, but when I drop the element in another div, it appears on top of other dropped elements. What am I doing wrong?

        //These are my draggable elements
        $('#interface li').draggable({
            helper: 'clone',
            revert: 'invalid'
        });

        //This function makes dropped elements draggable again.
        function foo(){
            $('.foo').each(function() {
                $(this).draggable({
                    containment: $(this).parent(),
                    stack: '.foo'
                });
            });
        }

        //This function forms table around dropped item
        var fooCount = $('.foo').length;
        $('#mainDiv').droppable({
            drop: function(event, ui) {
                if (!ui.draggable.hasClass('foo')) {
                    var Class = ui.draggable.attr("class");
                    var title = ui.draggable.text().trim();
                    var item = $('

<button class="settings">set</button>' + title + 'x

Add new link

');
                    $(this).append(item);
                    fooCount += 1;
                    foo();
                }
            }
        });

This is my CSS code for styling newly created tables:

.foo {
    min-width: 250px;
    max-width: 300px;
    text-align: center;
    min-height: 50px;
    border: 1px solid white;
    border-radius: 10px;
    position: absolute;
    padding: 0;
}

But the dropped elements appear like this:

I want them to appear like this:

EDIT: Here is a working jsfiffle: https://jsfiddle.net/vaxobasilidze/79kd1uLL/

Body:
Just remove position: absolute; from newly created element. It should be

.foo {
    min-width: 250px;
    max-width: 300px;
    text-align: center;
    min-height: 50px;
    border: 1px solid white;
    border-radius: 10px;
    /*position: absolute;*/
    padding: 0;
}

Check updated fiddle here