问:
Failed to config the https on the docker nginx container, always report time out
OS:

```<code>LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.3.1611 (Core)
Release:    7.3.1611
Codename:   Core
</code>```

Docker version:

```<code>Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Mon Mar 27 17:05:44 2017
 OS/Arch:      linux/amd64
</code>```

Server:

```<code> Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Mon Mar 27 17:05:44 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

Nginx image is the offical image (latest)

```<code>[root@iZ2zea8ff3mfutp3knnkyyZ ~]# docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
 nginx               latest              3448f27c273f        2 weeks ago         109 MB
</code>```

the command to run nginx：

```<code>docker run -d -p 80:80 -p 443:443 --network=stone --ip=172.18.0.10 --name nginx -v /var/nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro -v /var/nginx/conf/vhosts:/etc/nginx/conf.d:ro -v /var/nginx/conf/certs:/etc/nginx/certs:ro -v /var/nginx/www:/usr/share/nginx:rw -v /var/nginx/log:/var/log/nginx:rw nginx
</code>```

I store the certificate and private key in the /var/nginx/conf/certs, and mount it when running the nginx image, the https certificate is "extensive domain name" (eg: *.domain.com)

nignx config file

```<code>server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;

ssl_certificate     certs/1_domain.com_bundle.crt;
ssl_certificate_key certs/2_domain.com.key;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;

server_name         testfrontend.domain.com;
root /usr/share/nginx/html;

index index.php index.html index.htm;

access_log  /var/log/nginx/access.log;
error_log   /var/log/nginx/error.log debug;

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
 location ~ \.php$ {
    fastcgi_pass   172.18.0.11:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
 }

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.well-known {
    allow  all;
}
}
</code>```

That's it, but when I visit the "testfrontend.domain.com" with Chrome, it is always report time out.

I use wget to test it, too. still report time out.

I have checked the acccess.log and error.log

the access.log is empty.

i turn the level of error.log to debug.
the following is the info it recorded

```<code>2017/05/30 00:40:28 [notice] 1#1: using the "epoll" event method
2017/05/30 00:40:28 [notice] 1#1: nginx/1.13.0
2017/05/30 00:40:28 [notice] 1#1: built by gcc 6.3.0 20170205 (Debian 6.3.0-6)
2017/05/30 00:40:28 [notice] 1#1: OS: Linux 3.10.0-514.10.2.el7.x86_64
2017/05/30 00:40:28 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 65536:65536
2017/05/30 00:40:28 [notice] 1#1: start worker processes
2017/05/30 00:40:28 [notice] 1#1: start worker process 7
</code>```

答: I have figured it out, I made a stupid mistake, I am using ALiYun servers in China, except the firewall installed on the server, there is another firewall called security strategy, I should have open the 443 port on it, unfortunately i was not. ok that's the reason. Thanks, everyone. hope this can help someone. </p>

Body:
OS:

LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.3.1611 (Core)
Release:    7.3.1611
Codename:   Core

Docker version:

Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Mon Mar 27 17:05:44 2017
 OS/Arch:      linux/amd64

Server:

 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Mon Mar 27 17:05:44 2017
 OS/Arch:      linux/amd64
 Experimental: false

Nginx image is the offical image (latest)

[root@iZ2zea8ff3mfutp3knnkyyZ ~]# docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
 nginx               latest              3448f27c273f        2 weeks ago         109 MB

the command to run nginx：

docker run -d -p 80:80 -p 443:443 --network=stone --ip=172.18.0.10 --name nginx -v /var/nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro -v /var/nginx/conf/vhosts:/etc/nginx/conf.d:ro -v /var/nginx/conf/certs:/etc/nginx/certs:ro -v /var/nginx/www:/usr/share/nginx:rw -v /var/nginx/log:/var/log/nginx:rw nginx

I store the certificate and private key in the /var/nginx/conf/certs, and mount it when running the nginx image, the https certificate is "extensive domain name" (eg: *.domain.com)

nignx config file

server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;

ssl_certificate     certs/1_domain.com_bundle.crt;
ssl_certificate_key certs/2_domain.com.key;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;

server_name         testfrontend.domain.com;
root /usr/share/nginx/html;

index index.php index.html index.htm;

access_log  /var/log/nginx/access.log;
error_log   /var/log/nginx/error.log debug;

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
 location ~ \.php$ {
    fastcgi_pass   172.18.0.11:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
 }

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.well-known {
    allow  all;
}
}

That's it, but when I visit the "testfrontend.domain.com" with Chrome, it is always report time out.

I use wget to test it, too. still report time out.

I have checked the acccess.log and error.log

the access.log is empty.

i turn the level of error.log to debug.
the following is the info it recorded

2017/05/30 00:40:28 [notice] 1#1: using the "epoll" event method
2017/05/30 00:40:28 [notice] 1#1: nginx/1.13.0
2017/05/30 00:40:28 [notice] 1#1: built by gcc 6.3.0 20170205 (Debian 6.3.0-6)
2017/05/30 00:40:28 [notice] 1#1: OS: Linux 3.10.0-514.10.2.el7.x86_64
2017/05/30 00:40:28 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 65536:65536
2017/05/30 00:40:28 [notice] 1#1: start worker processes
2017/05/30 00:40:28 [notice] 1#1: start worker process 7


来源: stackexchange

问:
Python Pandas return an array instead of series
I have the following code:

```<code>for j in account_list:
 my_dict['name'] = (df[df['DESC'].str.contains(j)]['Hostname'].iloc[0])
</code>```

This one works fine and returns an array of names, but if I changed it to:

```<code> for j in account_list:
      my_dict['name'] = (df[df['DESC'].str.startswith('Account')]['Hostname'])
</code>```

It returns a series not an array, I have tried asarray() and as_matrix, none of them returns an array like the first one, could you please help me?

Sample from the excel sheet:
https://paste.pound-python.org/show/VfRmfJEWavU14luvFXQs/

EDIT: Expected result should be like this:

```<code>wordpress
wordpress
drupal
magento
</code>```

答:
If you mean a numpy array as elements of my_dict, you should be able to cast it like this:

```<code>np.array(df[df['DESC'].str.startswith('Account')]['Hostname'])
</code>```

Or if you mean a Python list, just use list in place of np.array.

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

for j in account_list:
 my_dict['name'] = (df[df['DESC'].str.contains(j)]['Hostname'].iloc[0])

This one works fine and returns an array of names, but if I changed it to:

 for j in account_list:
      my_dict['name'] = (df[df['DESC'].str.startswith('Account')]['Hostname'])

It returns a series not an array, I have tried asarray() and as_matrix, none of them returns an array like the first one, could you please help me?

Sample from the excel sheet:
https://paste.pound-python.org/show/VfRmfJEWavU14luvFXQs/

EDIT: Expected result should be like this:

wordpress
wordpress
drupal
magento

Body:
If you mean a numpy array as elements of my_dict, you should be able to cast it like this:

np.array(df[df['DESC'].str.startswith('Account')]['Hostname'])

Or if you mean a Python list, just use list in place of np.array.


问:
Delete worksheet queries completely via Excel VBA
I have code that creates a query table. After creating it I pull out the data I want and then I'm done with that query. I don't want a bunch of query tables hanging around taking up space so I want to immediately delete it. I use

```<code>QueryTables.Delete

ActiveWorkbook.Connections.Item(i).Delete
</code>```

The problem is that the query table connection is still there. So if I try to make another query using the same name, it tells me that one already exists and it can't make it.

I want any record of that table existing to be completely gone.

Here is my code:

```<code>Sub Macro8()

Dim currency1 As String
Dim currency2 As String

currency1 = ActiveSheet.Range("currency1")
currency2 = ActiveSheet.Range("currency2")

Range("clear").Select
Selection.ClearContents

ActiveWorkbook.Queries.Add Name:="FXFWD", Formula:= _
    "let" & Chr(13) & "" & Chr(10) & "    Source = Web.Page(Web.Contents(""http://www.investing.com/currencies/" & currency2 & "-" & currency1 & "-forward-rates""))," & Chr(13) & "" & Chr(10) & "    Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data0,{{"""", type text}, {""Name"", type text}, {""Bid"", type number}, {""Ask"", type number}, {""High"", type number}, {""Low"", type number}, {""Chg."", type number}, {""Time""," & _
    " type text}})," & Chr(13) & "" & Chr(10) & "    #""Removed Columns"" = Table.RemoveColumns(#""Changed Type"",{""""})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Removed Columns"""
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Book1"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=FXFWD" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [FXFWD]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = False
    .ListObject.DisplayName = "FXFWD"
    .Refresh BackgroundQuery:=False
End With

Sheets("Book1").Rows("1:33").Copy
Sheet1.Rows("18").PasteSpecial xlPasteValues
Sheets("Book1").Select

Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim con As Object
Dim ws As Worksheet
Dim qryT As QueryTable

For Each con In ThisWorkbook.Connections
    con.Delete
Next con
For Each ws In ThisWorkbook.Worksheets
    For Each qryT In ws.QueryTables
         qryT.Delete
    Next qryT
Next ws

Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Sheet1.Select
End Sub
</code>```

答:
```<code>For Each qr In ThisWorkbook.Queries
    qr.Delete
Next qr
</code>```

Body:
I have code that creates a query table. After creating it I pull out the data I want and then I'm done with that query. I don't want a bunch of query tables hanging around taking up space so I want to immediately delete it. I use

QueryTables.Delete

ActiveWorkbook.Connections.Item(i).Delete

The problem is that the query table connection is still there. So if I try to make another query using the same name, it tells me that one already exists and it can't make it.

I want any record of that table existing to be completely gone.

Here is my code:

Sub Macro8()

Dim currency1 As String
Dim currency2 As String

currency1 = ActiveSheet.Range("currency1")
currency2 = ActiveSheet.Range("currency2")

Range("clear").Select
Selection.ClearContents

ActiveWorkbook.Queries.Add Name:="FXFWD", Formula:= _
    "let" & Chr(13) & "" & Chr(10) & "    Source = Web.Page(Web.Contents(""http://www.investing.com/currencies/" & currency2 & "-" & currency1 & "-forward-rates""))," & Chr(13) & "" & Chr(10) & "    Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data0,{{"""", type text}, {""Name"", type text}, {""Bid"", type number}, {""Ask"", type number}, {""High"", type number}, {""Low"", type number}, {""Chg."", type number}, {""Time""," & _
    " type text}})," & Chr(13) & "" & Chr(10) & "    #""Removed Columns"" = Table.RemoveColumns(#""Changed Type"",{""""})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Removed Columns"""
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Book1"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=FXFWD" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [FXFWD]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = False
    .ListObject.DisplayName = "FXFWD"
    .Refresh BackgroundQuery:=False
End With

Sheets("Book1").Rows("1:33").Copy
Sheet1.Rows("18").PasteSpecial xlPasteValues
Sheets("Book1").Select

Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim con As Object
Dim ws As Worksheet
Dim qryT As QueryTable

For Each con In ThisWorkbook.Connections
    con.Delete
Next con
For Each ws In ThisWorkbook.Worksheets
    For Each qryT In ws.QueryTables
         qryT.Delete
    Next qryT
Next ws

Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Sheet1.Select
End Sub


问:
Error after uninstalling ionic 2 loadash module
I ran the command npm install --save loadash

Then I tried to uninstalling it with the command npm uninstall --save loadash

but after that when I tried to run the app using ionic serve the following error is thrown. What to do?

```<code> Cannot find module 'lodash/assign'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/admin/HybridApps/ayrll/node_modules/xmlbuilder/lib/index.js:5:12)
    at Object.<anonymous> (/Users/admin/HybridApps/ayrll/node_modules/xmlbuilder/lib/index.js:14:4)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
</code>```

答:
```<code> Cannot find module 'lodash/assign'
</code>```

Means it is looking for lodash assign somewhere in your code base.

There is one major issue with this command npm uninstall --save loadash , what is "loadash"? it should be "lodash", but besides that if lodash has been removed from your package.json it wont remove any references that are in the code based.

You should do a full search for assign in your code. If there is no results then i would recommend completing a fresh ionic serve to rebuild the project.

Body:
I ran the command npm install --save loadash

Then I tried to uninstalling it with the command npm uninstall --save loadash

but after that when I tried to run the app using ionic serve the following error is thrown. What to do?

 Cannot find module 'lodash/assign'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/admin/HybridApps/ayrll/node_modules/xmlbuilder/lib/index.js:5:12)
    at Object.<anonymous> (/Users/admin/HybridApps/ayrll/node_modules/xmlbuilder/lib/index.js:14:4)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)

Body:
 Cannot find module 'lodash/assign'

Means it is looking for lodash assign somewhere in your code base.

There is one major issue with this command npm uninstall --save loadash , what is "loadash"? it should be "lodash", but besides that if lodash has been removed from your package.json it wont remove any references that are in the code based.

You should do a full search for assign in your code. If there is no results then i would recommend completing a fresh ionic serve to rebuild the project.


问:
how to convert cucumber tests into exe file with no main method
I run my tests through either feature file or runner class. I am not able to create a Jar as i dont have a main method in my project . Please let me know how to create a jar file using this or if I need to add anything .  </p>

<p>I want to execute feature scenarios in server so to achieve that I want to create an exe of my current project (Cucumber with selenium webdriver, Java using eclipse IDE and Maven as Build tool) , but unable to since I do not have a main method in my project . Please let me know how to create a jar file using this or if I need to add any other plugins and also how to add main method here .           </p>

```<code>    This is my POM.xml from the project :

    <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.cucumber</groupId>
        <artifactId>BasePolicy</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>BasePolicy</name>
        <url>http://maven.apache.org</url>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-picocontainer</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-junit</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>jdom</groupId>
                <artifactId>jdom</artifactId>
                <version>1.1</version>
            </dependency>
        </dependencies>

    </project>

    --------------------------------------------------------------------
    and My java runner class :

    package com.cucumber.testcases;

    import java.io.File;
    import java.util.concurrent.TimeUnit;

    import org.junit.Before;
    import org.junit.runner.RunWith;
    import org.openqa.selenium.phantomjs.PhantomJSDriver;

    import com.cucumber.Base.BaseDriver;

    import cucumber.api.CucumberOptions;

    import cucumber.api.junit.Cucumber;

    @RunWith(Cucumber.class)
    @CucumberOptions(
            // format = {"pretty","html:target/html/" } ,
            features = "src/test/java")
    public class RunnerClass {

        }
</code>```

答:
You can create a main method to run cucumber by calling the static main method of Main.class (Lots of mains in one sentence).

Create a new class and add the following main method to it.

```<code>public static void main(String[] args) throws Throwable {

            Main.main(new String[]{"-g", "classpath to step definition file", "Full path to feature file"});

          // My stepdefinition is inside java package at cucumber.sample.test
          // My feature file is inside src/test/resources/features/sample.feature

        }
</code>```

For additional parameters like tags or plugin use "-t","@Tags". Important the feature file path has to be the last option.

You can configure this further to make it more flexible by passing these parameters to this class when you run it. You will need to play around with the args argument in your code.

Body:
I run my tests through either feature file or runner class. I am not able to create a Jar as i dont have a main method in my project . Please let me know how to create a jar file using this or if I need to add anything .

I want to execute feature scenarios in server so to achieve that I want to create an exe of my current project (Cucumber with selenium webdriver, Java using eclipse IDE and Maven as Build tool) , but unable to since I do not have a main method in my project . Please let me know how to create a jar file using this or if I need to add any other plugins and also how to add main method here .

    This is my POM.xml from the project :

    <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.cucumber</groupId>
        <artifactId>BasePolicy</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>BasePolicy</name>
        <url>http://maven.apache.org</url>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-picocontainer</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-junit</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>jdom</groupId>
                <artifactId>jdom</artifactId>
                <version>1.1</version>
            </dependency>
        </dependencies>

    </project>

    --------------------------------------------------------------------
    and My java runner class :

    package com.cucumber.testcases;

    import java.io.File;
    import java.util.concurrent.TimeUnit;

    import org.junit.Before;
    import org.junit.runner.RunWith;
    import org.openqa.selenium.phantomjs.PhantomJSDriver;

    import com.cucumber.Base.BaseDriver;

    import cucumber.api.CucumberOptions;

    import cucumber.api.junit.Cucumber;

    @RunWith(Cucumber.class)
    @CucumberOptions(
            // format = {"pretty","html:target/html/" } ,
            features = "src/test/java")
    public class RunnerClass {

        }

Body:
You can create a main method to run cucumber by calling the static main method of Main.class (Lots of mains in one sentence).

Create a new class and add the following main method to it.

public static void main(String[] args) throws Throwable {

            Main.main(new String[]{"-g", "classpath to step definition file", "Full path to feature file"});

          // My stepdefinition is inside java package at cucumber.sample.test
          // My feature file is inside src/test/resources/features/sample.feature

        }

For additional parameters like tags or plugin use "-t","@Tags". Important the feature file path has to be the last option.

You can configure this further to make it more flexible by passing these parameters to this class when you run it. You will need to play around with the args argument in your code.


问:
How to style a text script in html?
I have a hits.php file which passes $x variable  into my index.php file which is the hitcounter of my website. I had tried many css styles in hits.php and also in index.php but none of them is worked! Would anyone tells me how to style my php output in index.php?

Hits.php:

```<code>           <?php
              $counts = ("counter.txt");
              $hits = file($counts);
              $hits[0] ++;
              $fp = fopen($counts, "w");
              fputs($fp , "$hits[0]");
              fclose($fp);
              $x=$hits[0];
              header("Content-type: text/javascript");
              echo "document.write('" . $x . "');";
              ?>
</code>```

Index.php:

```<code>              <script type="text/javascript" src="hits.php"></script>
</code>```

答:
i had tried this and works!

firstly ,i do not need having variable .$x. therefore i will use .$hits[0]. instead. so the code will be like :

```<code>      <?php
          echo '<span class="counter">'.$hits[0].'</span>';
      ?>
        <style type="text/css">
            .counter{
                font-size: 50px;
                color: #ff4d4d;
            }
        </style>
</code>```

Title: How to style a text script in html?

Body:
I have a hits.php file which passes $x variable  into my index.php file which is the hitcounter of my website. I had tried many css styles in hits.php and also in index.php but none of them is worked! Would anyone tells me how to style my php output in index.php?

Hits.php:

           <?php
              $counts = ("counter.txt");
              $hits = file($counts);
              $hits[0] ++;
              $fp = fopen($counts, "w");
              fputs($fp , "$hits[0]");
              fclose($fp);
              $x=$hits[0];
              header("Content-type: text/javascript");
              echo "document.write('" . $x . "');";
              ?>

Index.php:

Body:
i had tried this and works!

firstly ,i do not need having variable .$x. therefore i will use .$hits[0]. instead. so the code will be like :

      <?php
          echo '<span class="counter">'.$hits[0].'</span>';
      ?>
        <style type="text/css">
            .counter{
                font-size: 50px;
                color: #ff4d4d;
            }
        </style>


问:
show ProgressBar above WebView so that it does not hide when scrolling down WebView
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>
</code>```

How do I keep it fixed at the top so that when I scroll down it does not hide?

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary" >

    <LinearLayout
        android:layout_width="match_parent"
        android:id="@+id/removeWebView"
        android:background="@color/colorPrimary"
        android:orientation="vertical"
        android:layout_centerHorizontal="true"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webViewPage"
            android:background="@color/colorAccent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="37dp"
        android:layout_height="37dp"
        android:gravity="center"
        android:indeterminateDrawable="@drawable/circularprogressbar_webkit"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

use above xml and enjoy
circularprogressbar_webkit.xml  in drawable
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="9"
        android:useLevel="false" >
        <size
            android:width="76dip"
            android:height="76dip" />

        <gradient
            android:angle="0"
            android:endColor="@color/colorAccent"
            android:startColor="@color/colorPrimary"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>
</code>```

Body:
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>

How do I keep it fixed at the top so that when I scroll down it does not hide?


问:
How to save STDOUT outputs to a text file?
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

```<code>RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey
</code>```

The Codes:

```<code>static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }
</code>```

答:
Are you waiting for the child process to finish?  It looks like you start reading its output too early.  It could be done like this:

```<code>process.Start();
process.WaitForExit();
</code>```

Also, you can start receiving the output via delegates before it finishes.  Like this (the delegate is called for each line of text):

```<code>process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
    // Store e.Data somewhere.
};
</code>```

Body:
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey

The Codes:

static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }

Body:
Are you waiting for the child process to finish?  It looks like you start reading its output too early.  It could be done like this:

process.Start();
process.WaitForExit();

Also, you can start receiving the output via delegates before it finishes.  Like this (the delegate is called for each line of text):

process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
    // Store e.Data somewhere.
};

ContentLicense: CC BY-SA 2.5


问:
Change textview properties programatically from a fragment class
I am relatively new to Android Studio and I am starting to explore more the Android Navigation Drawer activities. I have been trying to change the font type of a textview from a fragment class and I just can't. I have tried many different solutions available here and none of them worked. In the picture, you can see my latest attempt.

In this image you can see the last code I tried to change the font from the fragment class

答:
I use this Library and it works superb on all devices

Step:-

1) Add this line in your gradle compile 'com.github.balrampandey19:FontOnText:0.0.1'

If this lines are missing add it in your gradle:-

```<code>allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}
</code>```

2) Add your font in asset folder like this

3) Then replace your view in xml with

```<code><com.balram.library.FotTextView
                    android:id="@+id/vno_tv"
                    .
                    .
                    android:textSize="14sp"
                    app:font="regular.ttf" />
</code>```

this line is important to set custom font you want app:font="regular.ttf"

You can do same for Buttons Edittext

OR

If you want to use same "Font" through whole application you can follow this Guide here

Body:
I use this Library and it works superb on all devices

Step:-

1) Add this line in your gradle compile 'com.github.balrampandey19:FontOnText:0.0.1'

If this lines are missing add it in your gradle:-

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}

2) Add your font in asset folder like this

3) Then replace your view in xml with

<com.balram.library.FotTextView
                    android:id="@+id/vno_tv"
                    .
                    .
                    android:textSize="14sp"
                    app:font="regular.ttf" />

this line is important to set custom font you want app:font="regular.ttf"

You can do same for Buttons Edittext

OR

If you want to use same "Font" through whole application you can follow this Guide here


问:
How can i handle nested queries with promises instead of callback?
how can i do the following with bluebird promises. modules i am using are bluebird, promise-mysql

insert in table A and return a_id

insert records in table B using a_id as foreign key

insert records in table C using a_id as foreign key

now response is send to user that all records are added.

I am using native queries.

答:
The general idea is:</p>

```<code>insetA()
  .then(function(a_id){
    return Promise.all([inserB(a_id), inserC(a_id)])
  })
  .then(function(){
     res.send("all good")
  })
  .catch(function(error){
     res.send("some error")
  })

function insetA(){
  return new Promise(function (resolve, reject) {
    // inserting A
    // resolve(a_id)
  })
}
</code>```

Body:
The general idea is:

insetA()
  .then(function(a_id){
    return Promise.all([inserB(a_id), inserC(a_id)])
  })
  .then(function(){
     res.send("all good")
  })
  .catch(function(error){
     res.send("some error")
  })

function insetA(){
  return new Promise(function (resolve, reject) {
    // inserting A
    // resolve(a_id)
  })
}


问:
How to replace "\\" to "\" C#
Here is an example: "\\\r\\\n\\\u003c"

Expected Result: "\r\n\u003c"

I have tried string.Replace(@"\\\", @"\");, but it doesn't work.

答:
Hard to tell since you don't show your exact code, but possibly you're not saving the result of your string.Replace().  Your code looks good.

The @ symbol in front of your literal strings make them verbatim literal strings, and therefore prevents the backslashes from being uses as escape characters, which is what you want here.

string.Replace() doesn't modify the input string, but rather it returns the modified string.  Perhaps you're not using the return value from string.Replace().

The following code works:

```<code>var stringWithDoubleSlashes = @"\\r\\n\\u003c";

var stringWithSingleSlashes = stringWithDoubleSlashes.Replace(@"\\", @"\");
Console.WriteLine(stringWithSingleSlashes); // displays \r\n\u003c
</code>```

Title: How to replace "\\" to "\" C#

Body:
Hard to tell since you don't show your exact code, but possibly you're not saving the result of your string.Replace().  Your code looks good.

The @ symbol in front of your literal strings make them verbatim literal strings, and therefore prevents the backslashes from being uses as escape characters, which is what you want here.

string.Replace() doesn't modify the input string, but rather it returns the modified string.  Perhaps you're not using the return value from string.Replace().

The following code works:

var stringWithDoubleSlashes = @"\\r\\n\\u003c";

var stringWithSingleSlashes = stringWithDoubleSlashes.Replace(@"\\", @"\");
Console.WriteLine(stringWithSingleSlashes); // displays \r\n\u003c


问:
Is it beneficial to align VSTS "feature" work type to git feature branching?
We are using git dmz flow. When feature is done it will be merge to dmz branch and be merged to master branch if it pass the CI. A feature might consist of many stories and stories may consist of many task.

Currently we consider user stories and task as "feature" in the context of git dmz flow. We branchout from master to certain stories and tasks. I feel like this is disorganize and not following feature branching and will be better to branch out from master from a feature type of work VSTS and stories and tasks under it.

答:
Actually user story has the same function as you thought “feature” type of work in VSTS.

User stories define the applications, requirements, and elements that
  teams need to create. Product owners typically define and stack rank
  user stories. The team then estimates the effort and work to deliver
  the highest priority items.

When you checkout feature branch from master, you can create a series of user stories which make up the feature(s) you want to develop on this feature branch. And you can view the process of the use stories in Kanban board.

For a certain user story, you can define more detail works (tasks/bugs) in it. And you can view the work process in iterations.


问:
Email Attachment only working when statically coded - Excel Visual Basic
Everything is working for me in sending an email with an attachment from Excel using Visual Basic via Thunderbird when the attachment path is hard-coded.

```<code>attachment=C:\Users\Desktop2017\Desktop\customer\customerNumber\invoiceNumber.pdf"
</code>```

But I need to change part of the file path for attachment based on what's in cell M4 and have the file name change based on what's in cell J4.

Example: M4 value is currently 101.  J4 value is currently 2000-01. The output should be "C:\Users\Desktop2017\Desktop\customer\101\2000-01.pdf"

I have tried using 'Range' to get the value and setting a string but instead of getting the data from the cell or string it just outputs whatever I have after the equals sign.

I've tried adding and moving quotation marks around but nothing has worked at this point.

Thanks in advance for any help, Dalton.

PS: Sorry for hobbled together code.

```<code>Private Sub EmailInvoice_Click()

Dim FileNumber As Integer
Dim retVal As Variant
Dim strName As String
Dim strFile As String
Dim wsCustomer As Worksheet

strName = Range("Q2").Value
strFile = Dir(strFolder & "*.xlsx")
Const MY_FILENAME = "C:\Users\Desktop2017\Dropbox\temp\invoice.BAT"

FileNumber = FreeFile

 'create batch file
Open MY_FILENAME For Output As #FileNumber
Print #FileNumber, "cd ""C:\Program Files (x86)\Mozilla Thunderbird"""
Print #FileNumber, "thunderbird -compose"; _
" to=" + ThisWorkbook.Sheets("hourlyInvoice01").Range("N21") _
+ ",subject=Invoice " + ThisWorkbook.Sheets("hourlyInvoice01").Range("J4") + ",format="; 1; _
",body=""<HTML><BODY>Hello    "; ThisWorkbook.Sheets("hourlyInvoice01").Range("N20") _
+ "&#44<BR><BR>Please see attached.<BR><BR>Thanks&#44 Dalton.<BR><BR><BR>Contact Info Text Line 1<BR>Contact Info Text Line 2<BR>Contact Info Text Line 3</BODY></HTML>"",attachment=C:\Users\Desktop2017\Desktop\test\script\someFile.txt"

Print #FileNumber, "exit"
Close #FileNumber

 'run batch file
retVal = Shell(MY_FILENAME, vbNormalFocus)

 ' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
    MsgBox "An Error Occured"
    Close #FileNumber
    End
End If

 'Delete batch file
'Kill MY_FILENAME

End Sub
</code>```

答:
Add this before that line

```<code>Dim FlName As String

FlName = "C:\Users\Desktop2017\Desktop\customer\" & Range("M4").Value & "\" & Range("J4").Value & ".pdf"
</code>```

and then change the line

```<code>"&#44<BR><BR>Please see attached.<BR><BR>Thanks&#44 Dalton.<BR><BR><BR>Contact Info Text Line 1<BR>Contact Info Text Line 2<BR>Contact Info Text Line 3</BODY></HTML>"",attachment=C:\Users\Desktop2017\Desktop\test\script\someFile.txt"
</code>```

to

```<code>"&#44<BR><BR>Please see attached.<BR><BR>Thanks&#44 Dalton.<BR><BR><BR>Contact Info Text Line 1<BR>Contact Info Text Line 2<BR>Contact Info Text Line 3</BODY></HTML>"",attachment=" & FlName
</code>```

Note: To concatenate strings, use & instead of +

Body:
Everything is working for me in sending an email with an attachment from Excel using Visual Basic via Thunderbird when the attachment path is hard-coded.

attachment=C:\Users\Desktop2017\Desktop\customer\customerNumber\invoiceNumber.pdf"

But I need to change part of the file path for attachment based on what's in cell M4 and have the file name change based on what's in cell J4.

Example: M4 value is currently 101.  J4 value is currently 2000-01. The output should be "C:\Users\Desktop2017\Desktop\customer\101\2000-01.pdf"

I have tried using 'Range' to get the value and setting a string but instead of getting the data from the cell or string it just outputs whatever I have after the equals sign.

I've tried adding and moving quotation marks around but nothing has worked at this point.

Thanks in advance for any help, Dalton.

PS: Sorry for hobbled together code.

Private Sub EmailInvoice_Click()

Dim FileNumber As Integer
Dim retVal As Variant
Dim strName As String
Dim strFile As String
Dim wsCustomer As Worksheet

strName = Range("Q2").Value
strFile = Dir(strFolder & "*.xlsx")
Const MY_FILENAME = "C:\Users\Desktop2017\Dropbox\temp\invoice.BAT"

FileNumber = FreeFile

 'create batch file
Open MY_FILENAME For Output As #FileNumber
Print #FileNumber, "cd ""C:\Program Files (x86)\Mozilla Thunderbird"""
Print #FileNumber, "thunderbird -compose"; _
" to=" + ThisWorkbook.Sheets("hourlyInvoice01").Range("N21") _
+ ",subject=Invoice " + ThisWorkbook.Sheets("hourlyInvoice01").Range("J4") + ",format="; 1; _
",body=""Hello    "; ThisWorkbook.Sheets("hourlyInvoice01").Range("N20") _
+ "&#44

Please see attached.

Thanks&#44 Dalton.

Contact Info Text Line 1
Contact Info Text Line 2
Contact Info Text Line 3"",attachment=C:\Users\Desktop2017\Desktop\test\script\someFile.txt"

Print #FileNumber, "exit"
Close #FileNumber

 'run batch file
retVal = Shell(MY_FILENAME, vbNormalFocus)

 ' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
    MsgBox "An Error Occured"
    Close #FileNumber
    End
End If

 'Delete batch file
'Kill MY_FILENAME

End Sub

Body:
Add this before that line

Dim FlName As String

FlName = "C:\Users\Desktop2017\Desktop\customer\" & Range("M4").Value & "\" & Range("J4").Value & ".pdf"

and then change the line

"&#44<BR><BR>Please see attached.<BR><BR>Thanks&#44 Dalton.<BR><BR><BR>Contact Info Text Line 1<BR>Contact Info Text Line 2<BR>Contact Info Text Line 3</BODY></HTML>"",attachment=C:\Users\Desktop2017\Desktop\test\script\someFile.txt"

to

"&#44<BR><BR>Please see attached.<BR><BR>Thanks&#44 Dalton.<BR><BR><BR>Contact Info Text Line 1<BR>Contact Info Text Line 2<BR>Contact Info Text Line 3</BODY></HTML>"",attachment=" & FlName

Note: To concatenate strings, use & instead of +


问:
Running a .sql script using MySQL with JDBC
I am starting to use MySQL with JDBC.

```<code>Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///x", "x", "x");
stmt = conn.createStatement();
stmt.execute( "CREATE TABLE amigos" +
            "("+
            "id          int AUTO_INCREMENT          not null,"+
            "nombre      char(20)                    not null,"+
            "primary key(id)" +
            ")");
</code>```

I have 3-4 tables to create and this doesn't look good.

Is there a way to run a .sql script from MySQL JDBC?

答:
Can you use this:

```<code>public static void executeSQL(File f, Connection c) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(f));
    String sql = "", line;
    while ((line = br.readLine()) != null) sql += (line+"\n");
    c.prepareCall(sql).execute(sql);
}
</code>```

This function gets SQL file and DB connection.
Then it reads the file line-by-line using BufferedReader from java.io.

And, finally, executes the read statements.

Java 8+ version:

```<code>public static void executeSQL(Path p, Connection c) throws Exception {
    List<String> lines = Files.readAllLines(p);
    String s = String.join("\n", lines.toArray(new String[0]));
    c.prepareCall(s).execute(s);
}
</code>```

Body:
I am starting to use MySQL with JDBC.

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///x", "x", "x");
stmt = conn.createStatement();
stmt.execute( "CREATE TABLE amigos" +
            "("+
            "id          int AUTO_INCREMENT          not null,"+
            "nombre      char(20)                    not null,"+
            "primary key(id)" +
            ")");

I have 3-4 tables to create and this doesn't look good.

Is there a way to run a .sql script from MySQL JDBC?

Body:
Can you use this:

public static void executeSQL(File f, Connection c) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(f));
    String sql = "", line;
    while ((line = br.readLine()) != null) sql += (line+"\n");
    c.prepareCall(sql).execute(sql);
}

This function gets SQL file and DB connection.
Then it reads the file line-by-line using BufferedReader from java.io.

And, finally, executes the read statements.

Java 8+ version:

public static void executeSQL(Path p, Connection c) throws Exception {
    List<String> lines = Files.readAllLines(p);
    String s = String.join("\n", lines.toArray(new String[0]));
    c.prepareCall(s).execute(s);
}

ContentLicense: CC BY-SA 4.0


问:
Massive azure wasp JSON folder(450 GB) read in spark optimized way
i have processed file in azure spark . It takes long time to process the file . can anyone please suggest me the optimized way to achieve less process timings . Also attached my sample code with this.

```<code>// Azure container filesystem, it is contain source, destination, archive and result files
val azureContainerFs = FileSystem.get(sc.hadoopConfiguration)

// Read source file list
val sourceFiles = azureContainerFs.listStatus(new Path("/"+sourcePath +"/"),new PathFilter {
  override def accept(path: Path): Boolean = {
    val name = path.getName
    name.endsWith(".json")
  }
}).toList.par

// Ingestion processing to each file
for (sourceFile <- sourceFiles) {

  // Tokenize file name from path
  val sourceFileName = sourceFile.getPath.toString.substring(sourceFile.getPath.toString.lastIndexOf('/') + 1)

  // Create a customer invoice DF from source json
  val customerInvoiceDf = sqlContext.read.format("json").schema(schemaDf.schema).json("/"+sourcePath +"/"+sourceFileName).cache()
</code>```

Thanks in Advance!

答: Please write us a bit more about your stack, and processing power (number of masters, slaves, how you deploy code, things like that)</p>

Body:
i have processed file in azure spark . It takes long time to process the file . can anyone please suggest me the optimized way to achieve less process timings . Also attached my sample code with this.

// Azure container filesystem, it is contain source, destination, archive and result files
val azureContainerFs = FileSystem.get(sc.hadoopConfiguration)

// Read source file list
val sourceFiles = azureContainerFs.listStatus(new Path("/"+sourcePath +"/"),new PathFilter {
  override def accept(path: Path): Boolean = {
    val name = path.getName
    name.endsWith(".json")
  }
}).toList.par

// Ingestion processing to each file
for (sourceFile <- sourceFiles) {

  // Tokenize file name from path
  val sourceFileName = sourceFile.getPath.toString.substring(sourceFile.getPath.toString.lastIndexOf('/') + 1)

  // Create a customer invoice DF from source json
  val customerInvoiceDf = sqlContext.read.format("json").schema(schemaDf.schema).json("/"+sourcePath +"/"+sourceFileName).cache()

Thanks in Advance!


问:
AWS API SDK export for Android does not accept body content on POST
I can use POST to call the AWS API Gateway OK when there is no body.  When there is a body I get this error, where 9 is the length of the String body:

com.amazonaws.mobileconnectors.apigateway.ApiClientException: expected
  0 bytes but received 9 (Service: null; Status Code: 0; Error Code:
  null; Request ID: null)

When I used Postman, I set up Body html key/pair as Body/BLUE and it worked fine.  I wonder why the export SDK for Android doesn't accept a body content.  Thanks for the help.

My code is:

```<code>final MyAPIClient client = factory.build(MyAPIClient.class);
String body = "Body=BLUE";
byte[] content = body.getBytes("UTF-8");
ApiRequest request = new ApiRequest(client.getClass().getSimpleName())
                    .withPath("/vote")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .withBody(content);

ApiResponse response = client.execute(request);
</code>```

答:
It appears you send 9 bytes of data while your request headers indicate you'll send 0 bytes of data (as the Content-Length isnt set).

While validating your request the server gets aware of that fact and therefore gives you given error.

From my point of view you should call addHeader a second time and set the Content-Length.

```<code>ApiRequest request = new ApiRequest(client.getClass().getSimpleName())
                    .withPath("/vote")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Content-Length", [insert byte count here])
                    .withBody(content);
</code>```

For more information on how Content-Length works please refer to https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html (Scroll to 14.13 Content-Length)

Body:
I can use POST to call the AWS API Gateway OK when there is no body.  When there is a body I get this error, where 9 is the length of the String body:

com.amazonaws.mobileconnectors.apigateway.ApiClientException: expected
  0 bytes but received 9 (Service: null; Status Code: 0; Error Code:
  null; Request ID: null)

When I used Postman, I set up Body html key/pair as Body/BLUE and it worked fine.  I wonder why the export SDK for Android doesn't accept a body content.  Thanks for the help.

My code is:

final MyAPIClient client = factory.build(MyAPIClient.class);
String body = "Body=BLUE";
byte[] content = body.getBytes("UTF-8");
ApiRequest request = new ApiRequest(client.getClass().getSimpleName())
                    .withPath("/vote")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .withBody(content);

ApiResponse response = client.execute(request);

Body:
It appears you send 9 bytes of data while your request headers indicate you'll send 0 bytes of data (as the Content-Length isnt set).

While validating your request the server gets aware of that fact and therefore gives you given error.

From my point of view you should call addHeader a second time and set the Content-Length.

ApiRequest request = new ApiRequest(client.getClass().getSimpleName())
                    .withPath("/vote")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Content-Length", [insert byte count here])
                    .withBody(content);

For more information on how Content-Length works please refer to https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html (Scroll to 14.13 Content-Length)


问:
Continuous Delivery of NodeJS App using AWS Services
Can someone share the thoughts that what could be the best way to do CI/CD of a NodeJS app using only AWS Services.

I have gone through some blogs but I did not find any where complete AWS Services stack has been used.

Suggestions would be appreciated.

Please advise what could be done otherwise if not AWS Services stack completely.

Thanks

答: If you need to use AWS services, then your option is to use AWS Code Pipeline which is tailor made for doing CI/CD on AWS. It integrates with other AWS services such as CodeCommit, CodeDeploy. Code Pipeline can also work with other non-AWS platforms such as Jenkins and GitHub. You can have a look at the aws official documentation for details on how to implement a CI/CD pipeline.</p>


问:
How to open Excel with VBA Macros without warning
I created Excel using VBA macros but for opening this .xls sheet it is asking permission like enable content before opening.

Please check the screen shot where I marked with red color.

I want avoid that warning from code or back end, So please suggest something how to avoid it.

答:
One can go to Excel Options -> Trust Center on the Trust Center button -> under External Content choose the Enable All Data Connections option.

In Excel go to Options -> Trust Center -> Protected View and disable all three options

Last option is to enable all macro content


问:
Optimized mysql queries in mysql database
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

```<code> 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';
</code>```

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

```<code>**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|
</code>```

Result required:
Student I,Student N and Student K

答: select * from (select * from class order by id desc, class_name) x group by class_name

Body:
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

Result required:
Student I,Student N and Student K


问:
Word VBA: Findtext pattern with an optional character (Find method)
I have what should be a simple question. I am searching a document for occurrences of bracketed numbers, e.g.  [4] or [14] etc. I can write a pattern to find either a single digit or a double digit, but how do I use a single FindText pattern that matches both cases?

Here is my working code for the single digit case:

```<code>set fnd=ActiveDocument.Range.Find
While (fnd.Execute(FindText:="\[[0-9]\]", MatchWildcards:=True))
    ...
    Do Stuff
    ...
Wend
</code>```

How can I adapt this to include the possibility of a second digit? Thanks for your help!

答:
```<code>Sub SearchNumbersInSqBrackets()

    Dim rng
    Set rng = ActiveDocument.Range

    With rng.Find
        .Text = "\[[0-9]{1,2}\]"
        .MatchWildcards = True

        Do While .Execute(Forward:=True)
            Debug.Print rng.Text
        Loop

    End With
End Sub
</code>```

See #7 here - http://wordmvp.com/FAQs/General/UsingWildcards.htm

Body:
I have what should be a simple question. I am searching a document for occurrences of bracketed numbers, e.g.  [4] or [14] etc. I can write a pattern to find either a single digit or a double digit, but how do I use a single FindText pattern that matches both cases?

Here is my working code for the single digit case:

set fnd=ActiveDocument.Range.Find
While (fnd.Execute(FindText:="\[[0-9]\]", MatchWildcards:=True))
    ...
    Do Stuff
    ...
Wend

How can I adapt this to include the possibility of a second digit? Thanks for your help!

Body:
Sub SearchNumbersInSqBrackets()

    Dim rng
    Set rng = ActiveDocument.Range

    With rng.Find
        .Text = "\[[0-9]{1,2}\]"
        .MatchWildcards = True

        Do While .Execute(Forward:=True)
            Debug.Print rng.Text
        Loop

    End With
End Sub

See #7 here - http://wordmvp.com/FAQs/General/UsingWildcards.htm


问:
android custom layout doesn't align correctly in gridView
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>
</code>```

and here is the gridView layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>
</code>```

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

答:
This may help. </p>

<p>custom_layout: </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_gravity"center"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|bottom"/>

</FrameLayout>
</code>```

Body:
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>

and here is the gridView layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

Body:
This may help.

custom_layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_gravity"center"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|bottom"/>

</FrameLayout>


问:
How to rewrite this Java class to a Kotlin data class?
I have this in Java :

```<code>public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}
</code>```

In a Kotlin class its something like this :

```<code>class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}
</code>```

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters

答: Android studio provides an extremely simply method to achieve convert any Java class to Kotlin. Just type "convert java to kotlin" in your file search tab and the IDE will do that for you

Body:
I have this in Java :

public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}

In a Kotlin class its something like this :

class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters


问:
Fast linq query with join and count
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

```<code>select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode
</code>```

Not able to translate it to linq in efficient way.
Can anybody help with it?

答:
Is this you're looking for?

```<code>var result = from technician in Technicians
                join job in Jobs on technician.TechnicianCode equals job.TechnicianCode into A
                from job in A.DefaultIfEmpty()
                where job.TxnCode == "Jc" || job.TxnCode == "Jcd"
                select new
                {
                    Tech = technician,
                    Job = job
                };
</code>```

To get the count you can simply use:

```<code>var count = result.Where(r => r.Job != null).Count();
</code>```

Title: Fast linq query with join and count

Body:
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode

Not able to translate it to linq in efficient way.
Can anybody help with it?

Body:
Is this you're looking for?

var result = from technician in Technicians
                join job in Jobs on technician.TechnicianCode equals job.TechnicianCode into A
                from job in A.DefaultIfEmpty()
                where job.TxnCode == "Jc" || job.TxnCode == "Jcd"
                select new
                {
                    Tech = technician,
                    Job = job
                };

To get the count you can simply use:

var count = result.Where(r => r.Job != null).Count();


问:
Need to delete all data after third colon of a string
i have a file say test.txt with the following contents

```<code>apple:orange:mango:123:1234:12345
</code>```

i want all data after third colon to be removed

Expected output

```<code>apple:orange:mango:
</code>```

Kinldy help

Body:
i have a file say test.txt with the following contents

apple:orange:mango:123:1234:12345

i want all data after third colon to be removed

Expected output

apple:orange:mango:

Kinldy help

Body:
Using backreference:

sed 's/\([^:]*:[^:]*:[^:]*:\).*/\1/' test.txt

or with GNU sed:

sed -E 's/(([^:]*:){3}).*/\1/' test.txt


问:
Node JS, run same function after it is finished
My applications need to poll every 2 seconds if there are changes. For now i use setInterval, but sometimes myFunction takes longer then 2 seconds to execute and records in the mysql database will be inserted twice. I make use of the async lib in myFunction..

So i need this...

When myFunction is finished

method.myFunction() =>

It needs to run again (but only when it is finished). setInterval with x seconds is not an option. This is because they can run at the same time if the scripts takes longer then  x seconds.

How can i run myFunction again after x seconds, but only when myFunction is done with processing
So in psuedo code it would be this

if method.myFunction == finished
wait 2 seconds
 run method.myFunction again

答:
so with the below code, your method will be called once every seconds when the function execution is over.

```<code>function godMethod(){
    /* do what ever you want but call executor once you are done with everything */
    someCallbackForInsertion(data, function(){
        executor()
    })
}

function executor(){
    setInterval(function(){
        godMethod()
    }, 2000);
}

executor();
</code>```

So here you call the executor on start of the server, then after 2 seconds it calls the godMethod then do your insertion/whatever. After successfully inserted call the executor again.

Body:
so with the below code, your method will be called once every seconds when the function execution is over.

function godMethod(){
    /* do what ever you want but call executor once you are done with everything */
    someCallbackForInsertion(data, function(){
        executor()
    })
}

function executor(){
    setInterval(function(){
        godMethod()
    }, 2000);
}

executor();

So here you call the executor on start of the server, then after 2 seconds it calls the godMethod then do your insertion/whatever. After successfully inserted call the executor again.


问:
Java: Writing array to text file inconsistencies
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

```<code>    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }
</code>```

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.

答: Perhaps you forget to flush and/or close the Writer at the end?</p>

Body:
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.


问:
Office 365 add-in outlook get AAD token to Call WebAPI
Now that I'm developing the Office 365 outlook add-in, I need call WebAPI in the Office 365 add-in, and WebAPI is protected by AAD. To ask, how do I get AAD token from the Office 365 add-in and can be used in both browser and outlook application?</p>

答:
No matter the office add-in is for the Office desktop or online version, the office add-in is a web app.

There are two usual flows we can authenticate in a web app, one is implicit flow and the other is authorization Code flow. Here is the difference between these two flows:

Implicit flow: Communication between the add-in and the online service is implemented with client-side JavaScript.

Authorization Code flow: Communication is server-to-server between your add-in's web application and the online service. So, it is implemented with server-side code.

And more detail about the authentication/authorization you can refer the
document below:

Authorize external services in your Office Add-in


问:
How to retrieve the Outlook folder of a mail item (Outlook.MailItem)?
I am getting my default inbox folder via inboxFolder = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox

Elsewhere in my code, I begin doing a foreach loop to extract specific information I want from these MailItems

```<code>foreach (var item in this.inboxFolder.Items)
{
   Outlook.MailItem mailItem = (Outlook.MailItem)item;
   //.... doing stuff here
   string SenderEmail = mailItem.SenderEmailAddress;
   string SenderName = mailItem.SenderName;
   string FolderLocation = mailItem.???;  //how to retrieve folder location?
   //.... more stuff here
}
</code>```

For example: A user may have created a subfolder called 'Test' shown below.

答:
Thank you for the pointer guys. However I was having some trouble implementing the same initially. Here is how I solved it, just in case if some one faces the same issue.

```<code>Outlook.MAPIFolder parentFolder = mailItemToDelete.Parent as Outlook.MAPIFolder;
string FolderLocation = parentFolder.FolderPath;
</code>```

The Parent object is dynamic and hence was causing issue.

Body:
I am getting my default inbox folder via inboxFolder = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox

Elsewhere in my code, I begin doing a foreach loop to extract specific information I want from these MailItems

foreach (var item in this.inboxFolder.Items)
{
   Outlook.MailItem mailItem = (Outlook.MailItem)item;
   //.... doing stuff here
   string SenderEmail = mailItem.SenderEmailAddress;
   string SenderName = mailItem.SenderName;
   string FolderLocation = mailItem.???;  //how to retrieve folder location?
   //.... more stuff here
}

For example: A user may have created a subfolder called 'Test' shown below.

Body:
Thank you for the pointer guys. However I was having some trouble implementing the same initially. Here is how I solved it, just in case if some one faces the same issue.

Outlook.MAPIFolder parentFolder = mailItemToDelete.Parent as Outlook.MAPIFolder;
string FolderLocation = parentFolder.FolderPath;

The Parent object is dynamic and hence was causing issue.


答: SELECT * from class where class_name = '5' or class_name = '6' or class_name = '7'</p>

Title: Optimized mysql queries in mysql database