问:
on rotate mobile webview refresh hide menu
i have a problem i am create an app web view to get and website on play store.

the problem is that it have a dropdown Menu html5+jquery+css3. when i rotate the smartphone, the web are refreshed.

this my code Android Studio 3.0:

Activity xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icarosnet.icarosnetsa.IcarosWeb">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/wv"
    />

</android.support.constraint.ConstraintLayout>
</code>```

Main.Java

```<code>package com.icarosnet.icarosnetsa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class IcarosWeb extends AppCompatActivity {
    WebView wv ;

    @Override
    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icaros_web);
        wv= (WebView) findViewById(R.id.wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusable(true);
        wv.setFocusableInTouchMode(true);
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv.loadUrl("https://icarosnet.com");
        wv.setWebViewClient(new WebViewClient());
    }
    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        wv= (WebView) findViewById(R.id.wv);
        wv.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        wv= (WebView) findViewById(R.id.wv);
        wv.restoreState(savedInstanceState);
    }

}
</code>```

Xml Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.icarosnet.icarosnetsa">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IcarosWeb">
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

does not respect the content that was loaded by ajax.

how can i prevent refresh and resize the view; or how can i show it only portrait and block the view.

答:
```<code>  <activity android:name=".TestActivity"
android:screenOrientation="portrait">

write this line and show it only portrait
</code>```

Body:
i have a problem i am create an app web view to get and website on play store.

the problem is that it have a dropdown Menu html5+jquery+css3. when i rotate the smartphone, the web are refreshed.

this my code Android Studio 3.0:

Activity xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icarosnet.icarosnetsa.IcarosWeb">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/wv"
    />

</android.support.constraint.ConstraintLayout>

Main.Java

package com.icarosnet.icarosnetsa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class IcarosWeb extends AppCompatActivity {
    WebView wv ;

    @Override
    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icaros_web);
        wv= (WebView) findViewById(R.id.wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusable(true);
        wv.setFocusableInTouchMode(true);
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv.loadUrl("https://icarosnet.com");
        wv.setWebViewClient(new WebViewClient());
    }
    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        wv= (WebView) findViewById(R.id.wv);
        wv.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        wv= (WebView) findViewById(R.id.wv);
        wv.restoreState(savedInstanceState);
    }

}

Xml Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.icarosnet.icarosnetsa">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IcarosWeb">
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

does not respect the content that was loaded by ajax.

how can i prevent refresh and resize the view; or how can i show it only portrait and block the view.


来源: stackexchange

问:
javac -cp can not find class?
How to use the javac command, want to compile hello.java to hello.class, the file content is as follows:

How to introduce other packages, the directory structure is as follows

It's a mistake for me to run like this:
e:\icenew2\hellotest>javac -sourcepath src hello.java

It's wrong to run like this ： javac -cp "src\com\zeroc\Ice*.class"  hello.java

答:
We can use the wildcard character *:

```<code>javac -cp *; BackBenchers.java
</code>```

Specifying destination directory:

```<code>javac -d classes backbenchers.java
</code>```

Note: The compiler will complain if the specified directory does not exist, and it won’t create one.

If the source file is under a package, the compiler will create package structure in the destination directory.

Specifying source path directory:

```<code>javac -sourcepath src BackBenchers.java
</code>```

ContentLicense: CC BY-SA 3.0

Title: javac -cp can not find class?

Body:
We can use the wildcard character *:

javac -cp *; BackBenchers.java

Specifying destination directory:

javac -d classes backbenchers.java

Note: The compiler will complain if the specified directory does not exist, and it won’t create one.

If the source file is under a package, the compiler will create package structure in the destination directory.

Specifying source path directory:

javac -sourcepath src BackBenchers.java


问:
Crash and Received memory warning
I have below for loop to download files from server to my iPad 3 device.
Running hundred of files, I got error and app crash. The console shown me "Received memory warning. Same logic running on my iPad Air was passed. Anyone can adivse how to resolve the problem.

iPad 3 -> iOS 9.3.5
iPad Air -> iOS 10.3.3

```<code>func download() {
        for (index, subJson): (String, JSON) in serverJson! {

            for (_, subJson): (String, JSON) in subJson {
                    let filepath = subJson["path"].stringValue
                    let nUpdated = subJson["updated"].stringValue

                    if let oUpdated = localJson?[index].array?.filter({ $0["path"].string == filepath}).first?["updated"].stringValue {
                        if (oUpdated == nUpdated)
                        {
                            DispatchQueue.main.async { () -> Void in
                                self.progressView.progress = Float(self.count) / Float(self.totalCount)
                            }

                            count += 1

                            continue
                        }
                    }

                    var absPath = filepath

                    let strIdx = absPath.index(absPath.startIndex, offsetBy: 2)

                    if (absPath.hasPrefix("./"))
                    {
                        absPath = absPath.substring(from: strIdx)
                    }

                    let sourceUrl = URL(string: self.sourceUrl.appending(absPath))

                    do {
                        let fileData = try NSData(contentsOf: sourceUrl!, options: NSData.ReadingOptions())
                        try writeFileToLocal(absPath, fileData)
                    } catch {
                        print(error)
                    }

                    DispatchQueue.main.async { () -> Void in
                        self.progressView.progress = Float(self.count) / Float(self.totalCount)
                    }

                    //print("Path: \(absPath)")
                    //print("%: \(Float(count) / Float(totalCount))")

                    count += 1

                }

        }

        do {
            // Remove temp json file first if exists.
            if fileManager.fileExists(atPath: oldManifestPath) {
                try? fileManager.removeItem(atPath: oldManifestPath)
            }

            // Write temp json file to local.
            try data?.write(to: oldManifestUrl)

            self.defaults.set(hashes, forKey: "LastHash")
        } catch {
            print(error)
        }

        DispatchQueue.main.async {
            self.progressView.isHidden = true
            self.changeViewProperties(2)
        }

    }

}
private func writeFileToLocal(_ url:String, _ data:NSData) throws {

        let url = URL(string: url)
        let path = url?.deletingLastPathComponent().relativePath
        let file = url?.lastPathComponent

        let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let filePath = documentsPath.appendingPathComponent(path!)

            var isDir: ObjCBool = false
            if !FileManager.default.fileExists(atPath: (filePath?.path)!, isDirectory:&isDir) {
                try FileManager.default.createDirectory(atPath: filePath!.path, withIntermediateDirectories: true, attributes: nil)
            }
            FileManager.default.changeCurrentDirectoryPath((filePath?.path)!)
            try data.write(toFile: file!, options: .atomicWrite)
            print("Update: \(filePath!), \(file!)")

        FileManager.default.changeCurrentDirectoryPath(documentsPath.path!)
    }
</code>```

Then I call the function "download" in DispatchQueue.

```<code>DispatchQueue.global().async {
            self.downloadFiles()
}
</code>```

答:
Memory waring is occuring as you are processing hundreds of Things on main thread just a Trick that you can try out if it helps you take that function in background queue instead of main Queue , you may get some ui warnings which you need to manage as updating ui in background thread

I do not know if it will help you or not but you an just give it a try for once

```<code>DispatchQueue.global(qos: .background).async
    {
        //BackGround Queue Update
        self.downloadFiles()

        DispatchQueue.main.async
            {
                //Main Queue Update With All UI

        }
}
</code>```

as background thread is always good to manage huge processing for example kingfisher library take data on main thread and return on main thread but process it in background thread

Title: Crash and Received memory warning

Body:
I have below for loop to download files from server to my iPad 3 device.
Running hundred of files, I got error and app crash. The console shown me "Received memory warning. Same logic running on my iPad Air was passed. Anyone can adivse how to resolve the problem.

iPad 3 -> iOS 9.3.5
iPad Air -> iOS 10.3.3

func download() {
        for (index, subJson): (String, JSON) in serverJson! {

            for (_, subJson): (String, JSON) in subJson {
                    let filepath = subJson["path"].stringValue
                    let nUpdated = subJson["updated"].stringValue

                    if let oUpdated = localJson?[index].array?.filter({ $0["path"].string == filepath}).first?["updated"].stringValue {
                        if (oUpdated == nUpdated)
                        {
                            DispatchQueue.main.async { () -> Void in
                                self.progressView.progress = Float(self.count) / Float(self.totalCount)
                            }

                            count += 1

                            continue
                        }
                    }

                    var absPath = filepath

                    let strIdx = absPath.index(absPath.startIndex, offsetBy: 2)

                    if (absPath.hasPrefix("./"))
                    {
                        absPath = absPath.substring(from: strIdx)
                    }

                    let sourceUrl = URL(string: self.sourceUrl.appending(absPath))

                    do {
                        let fileData = try NSData(contentsOf: sourceUrl!, options: NSData.ReadingOptions())
                        try writeFileToLocal(absPath, fileData)
                    } catch {
                        print(error)
                    }

                    DispatchQueue.main.async { () -> Void in
                        self.progressView.progress = Float(self.count) / Float(self.totalCount)
                    }

                    //print("Path: \(absPath)")
                    //print("%: \(Float(count) / Float(totalCount))")

                    count += 1

                }

        }

        do {
            // Remove temp json file first if exists.
            if fileManager.fileExists(atPath: oldManifestPath) {
                try? fileManager.removeItem(atPath: oldManifestPath)
            }

            // Write temp json file to local.
            try data?.write(to: oldManifestUrl)

            self.defaults.set(hashes, forKey: "LastHash")
        } catch {
            print(error)
        }

        DispatchQueue.main.async {
            self.progressView.isHidden = true
            self.changeViewProperties(2)
        }

    }

}
private func writeFileToLocal(_ url:String, _ data:NSData) throws {

        let url = URL(string: url)
        let path = url?.deletingLastPathComponent().relativePath
        let file = url?.lastPathComponent

        let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let filePath = documentsPath.appendingPathComponent(path!)

            var isDir: ObjCBool = false
            if !FileManager.default.fileExists(atPath: (filePath?.path)!, isDirectory:&isDir) {
                try FileManager.default.createDirectory(atPath: filePath!.path, withIntermediateDirectories: true, attributes: nil)
            }
            FileManager.default.changeCurrentDirectoryPath((filePath?.path)!)
            try data.write(toFile: file!, options: .atomicWrite)
            print("Update: \(filePath!), \(file!)")

        FileManager.default.changeCurrentDirectoryPath(documentsPath.path!)
    }

Then I call the function "download" in DispatchQueue.

DispatchQueue.global().async {
            self.downloadFiles()
}

Body:
Memory waring is occuring as you are processing hundreds of Things on main thread just a Trick that you can try out if it helps you take that function in background queue instead of main Queue , you may get some ui warnings which you need to manage as updating ui in background thread

I do not know if it will help you or not but you an just give it a try for once

DispatchQueue.global(qos: .background).async
    {
        //BackGround Queue Update
        self.downloadFiles()

        DispatchQueue.main.async
            {
                //Main Queue Update With All UI

        }
}

as background thread is always good to manage huge processing for example kingfisher library take data on main thread and return on main thread but process it in background thread


答: You can just add android:screenOrientation = "potrait" inside activity tag in manifest file to make your Activity not rotate to landscape even when phone is rotated.

Title: on rotate mobile webview refresh hide menu


问:
What is the maximum depth of the java call stack?
How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent?</p>

答:
The stack size can be set with the -Xss command line switch but as a rule of thumb, it is deep enough, hundreds if not thousands of calls deep. (The default is platform dependent, but at least 256k in most platforms.)

If you get a stack overflow, 99% of the time it's caused by an error in the code.

ContentLicense: CC BY-SA 2.5


问:
Using for loop PHP to print matrix 10*10 in table form
How do I solve this problem to print out matrix which highlights the first row as image

Using for loop PHP to print matrix 10*10 in table form. Note the first column will color with pink
as image
example

Try this code

```<code><?php

echo "<table>";

for($x=1;$x<=10;$x++){

    echo "<tr>";

    for($y=1;$y<=10;$y++){
        echo "<td>".$x*$y."</td>";
    }

    echo "</tr>";
}

echo "</table>";
</code>```

答:
To achive this we will check if its first row and the first column in nested for loop. Just see the whole there is not much to explain here.

WHOLE CODE

```<code>echo "<table>";
for($x=1;$x<=10;$x++){
    echo "<tr>";

    if($x == 1){
        echo "<td></td>";
        for($i = 1; $i <= 10; $i++){
            echo "<td style='background-color:blue;'>".$i ."</td>";
        }
        echo "</tr><tr>";
    }
    for($y=1;$y<=10;$y++){

        if($y == 1){
            echo "<td style='background-color:blue;'>".$x ."</td>";
        }
        echo "<td>".$x*$y."</td>";

    }
    echo "</tr>";
}
echo "</table>";
</code>```

OUTPUT

You can just edit the design. since you didn't post your css and html code.

Body:
How do I solve this problem to print out matrix which highlights the first row as image

Using for loop PHP to print matrix 10*10 in table form. Note the first column will color with pink
as image
example

Try this code

<?php

echo "
";

for($x=1;$x<=10;$x++){

    echo "
";

    for($y=1;$y<=10;$y++){
        echo "".$x*$y."	";
    }

    echo "
";
}

echo "
";

Body:
To achive this we will check if its first row and the first column in nested for loop. Just see the whole there is not much to explain here.

WHOLE CODE

echo "<table>";
for($x=1;$x<=10;$x++){
    echo "<tr>";

    if($x == 1){
        echo "<td></td>";
        for($i = 1; $i <= 10; $i++){
            echo "<td style='background-color:blue;'>".$i ."</td>";
        }
        echo "</tr><tr>";
    }
    for($y=1;$y<=10;$y++){

        if($y == 1){
            echo "<td style='background-color:blue;'>".$x ."</td>";
        }
        echo "<td>".$x*$y."</td>";

    }
    echo "</tr>";
}
echo "</table>";

OUTPUT

You can just edit the design. since you didn't post your css and html code.


问:
Using Comodo SSL with AWS Certificate Chain
This is basically a follow up to this question. After buying a Comodo SSL Certificate, I was also only sent two files in a zip folder - fake_domain.crt and fake_domain.ca-bundle. Most references I have seen say that I should have received 4 files, such as COMODORSADomainValidationSecureServerCA.crt.

To upload my SSL cert onto the AWS load balancer, it requires the Private Key, Public Key Certificate and Certificate Chain, all in PEM format. The private key and cert are simple enough. For the chain, using the answer from the referred question -

```<code>cat certfile.crt bundle.ca-bundle >> chain.crt
</code>```

did not work. AWS responded with the following error:

Error creating certificate
Unable to validate certificate chain. The certificate chain must start with the immediate signing certificate, followed by any intermediaries in order. The index within the chain of the invalid certificate is: 1

Converting both of the files to PEM format and THEN concatenating also failed. This was the command I used and then copied the output into AWS Certificate Chain field:

```<code>openssl x509 -inform PEM -in fake_domain.crt; openssl x509 -inform PEM -in fake_domain.ca-bundle
</code>```

How do I create the Certificate Chain correctly for AWS load balancers?

答:
Certificate Chain is determined by certificate type that you buy. If you buy ssl certificate from Comodo they will send .crt and .key files which are Certificate body and Certificate Private Key.

Certificate Chain is not related with that file. You can take certificate chain file from Comodo for your ssl type. For example, if you buy ositiveSSL / EssentialSSL SHA-256 from Comodo, you need to verify your certificate with certificate chain below:

```<code>-----BEGIN CERTIFICATE-----
MIIGCDCCA/CgAwIBAgIQKy5u6tl1NmwUim7bo3yMBzANBgkqhkiG9w0BAQwFADCB
hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV
BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTQwMjEy
MDAwMDAwWhcNMjkwMjExMjM1OTU5WjCBkDELMAkGA1UEBhMCR0IxGzAZBgNVBAgT
EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
Q09NT0RPIENBIExpbWl0ZWQxNjA0BgNVBAMTLUNPTU9ETyBSU0EgRG9tYWluIFZh
bGlkYXRpb24gU2VjdXJlIFNlcnZlciBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAI7CAhnhoFmk6zg1jSz9AdDTScBkxwtiBUUWOqigwAwCfx3M28Sh
bXcDow+G+eMGnD4LgYqbSRutA776S9uMIO3Vzl5ljj4Nr0zCsLdFXlIvNN5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R0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0
Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU
cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx
IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN
AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH
YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5
6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC
Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX
c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a
mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ=
-----END CERTIFICATE-----
</code>```

I've copied it from https://www.ssl2buy.com/wiki/comodo-positivessl-essentialssl-sha-2-ca-bundle. You can find appropriate certificate chain for your ssl certificate.

Body:
This is basically a follow up to this question. After buying a Comodo SSL Certificate, I was also only sent two files in a zip folder - fake_domain.crt and fake_domain.ca-bundle. Most references I have seen say that I should have received 4 files, such as COMODORSADomainValidationSecureServerCA.crt.

To upload my SSL cert onto the AWS load balancer, it requires the Private Key, Public Key Certificate and Certificate Chain, all in PEM format. The private key and cert are simple enough. For the chain, using the answer from the referred question -

cat certfile.crt bundle.ca-bundle >> chain.crt

did not work. AWS responded with the following error:

Error creating certificate
Unable to validate certificate chain. The certificate chain must start with the immediate signing certificate, followed by any intermediaries in order. The index within the chain of the invalid certificate is: 1

Converting both of the files to PEM format and THEN concatenating also failed. This was the command I used and then copied the output into AWS Certificate Chain field:

openssl x509 -inform PEM -in fake_domain.crt; openssl x509 -inform PEM -in fake_domain.ca-bundle

How do I create the Certificate Chain correctly for AWS load balancers?

Body:
Certificate Chain is determined by certificate type that you buy. If you buy ssl certificate from Comodo they will send .crt and .key files which are Certificate body and Certificate Private Key.

Certificate Chain is not related with that file. You can take certificate chain file from Comodo for your ssl type. For example, if you buy ositiveSSL / EssentialSSL SHA-256 from Comodo, you need to verify your certificate with certificate chain below:

-----BEGIN CERTIFICATE-----
MIIGCDCCA/CgAwIBAgIQKy5u6tl1NmwUim7bo3yMBzANBgkqhkiG9w0BAQwFADCB
hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV
BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTQwMjEy
MDAwMDAwWhcNMjkwMjExMjM1OTU5WjCBkDELMAkGA1UEBhMCR0IxGzAZBgNVBAgT
EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
Q09NT0RPIENBIExpbWl0ZWQxNjA0BgNVBAMTLUNPTU9ETyBSU0EgRG9tYWluIFZh
bGlkYXRpb24gU2VjdXJlIFNlcnZlciBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAI7CAhnhoFmk6zg1jSz9AdDTScBkxwtiBUUWOqigwAwCfx3M28Sh
bXcDow+G+eMGnD4LgYqbSRutA776S9uMIO3Vzl5ljj4Nr0zCsLdFXlIvNN5IJGS0
Qa4Al/e+Z96e0HqnU4A7fK31llVvl0cKfIWLIpeNs4TgllfQcBhglo/uLQeTnaG6
ytHNe+nEKpooIZFNb5JPJaXyejXdJtxGpdCsWTWM/06RQ1A/WZMebFEh7lgUq/51
UHg+TLAchh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EmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx
IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN
AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH
YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5
6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC
Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX
c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a
mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ=
-----END CERTIFICATE-----

I've copied it from https://www.ssl2buy.com/wiki/comodo-positivessl-essentialssl-sha-2-ca-bundle. You can find appropriate certificate chain for your ssl certificate.


问:
Multiple inheritance from classes 'UIApplication' and 'FBSDKApplicationDelegate'
I'm using iOS SDK from facebook website https://developers.facebook.com/docs/ios , but when I add FBSDKApplicationDelegate into App delegate I receive an error

Multiple inheritance from classes 'UIApplication' and 'FBSDKApplicationDelegate'.

I can't use Swift SDK, because my project is on XCode 8.2.1, Swift SDK for Facebook requires 8.3

答:
Seem like you are using FBSDKApplicationDelegate by this way or something like this

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, FBSDKApplicationDelegate
</code>```

Please take a look at FBSDKApplicationDelegate carefully.

Discussion:
  The methods in this class are designed to mirror those in UIApplicationDelegate, and you should call them in the respective methods in your AppDelegate implementation.

It isn't used that way. Don't make AppDelegate inheritance from FBSDKApplicationDelegate. Let use FBSDKApplicationDelegate's methods inside AppDelegate's methods

You can learn how to use FBSDKApplicationDelegate by following answer in this question Integration new facebook SDK by swift

```<code>func applicationDidBecomeActive(application: UIApplication!) {
    FBSDKAppEvents.activateApp()
}

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
</code>```

For more detail and easy understanding, i create a demo project with Facebook iOS SDK IntegrateFBSDK. You can try it.

Body:
Seem like you are using FBSDKApplicationDelegate by this way or something like this

class AppDelegate: UIResponder, UIApplicationDelegate, FBSDKApplicationDelegate

Please take a look at FBSDKApplicationDelegate carefully.

Discussion:
  The methods in this class are designed to mirror those in UIApplicationDelegate, and you should call them in the respective methods in your AppDelegate implementation.

It isn't used that way. Don't make AppDelegate inheritance from FBSDKApplicationDelegate. Let use FBSDKApplicationDelegate's methods inside AppDelegate's methods

You can learn how to use FBSDKApplicationDelegate by following answer in this question Integration new facebook SDK by swift

func applicationDidBecomeActive(application: UIApplication!) {
    FBSDKAppEvents.activateApp()
}

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}

For more detail and easy understanding, i create a demo project with Facebook iOS SDK IntegrateFBSDK. You can try it.

ContentLicense: CC BY-SA 4.0


问:
How to sequence authentication using Express and Angular 2
this is a authentication sequence question. I currently have a website that is hosted with an Express back-end, which manages the routing for both my main website and the API points. For any of my routes, the request has to come with a posted OAuth token for the website, which corresponds to a specific GMail account.

I have a function which checks this token/corresponding email to be authorized to access my website (although auth function is not done, this is not the problem).

```<code>function validateUser(token) {
    return new Promise(
        (resolve, reject) => {
            if (!token)
                reject("Empty token");
            request(
                'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + token,
                (error, response, body) => {
                    console.log(body);
                    if (error) {
                        return reject("Error");
                    } else if (JSON.parse(body)['error_description']) {
                        return reject(JSON.parse(body)['error_description']);
                    } else if (body) {
                        let theDict = JSON.parse(body);
                        theDict['oauth_token'] = token;
                        return resolve(theDict);
                    }

                    return reject("some other error");

                }
            );
        }
    );

}
</code>```

Then I have a route that manages get requests at any location (which then redirects to the login page, and once user is logged in it posts to the  route with the token to get the content).

```<code>router.post(
    '/*',
    (req, res, next) => {
        var token = req.body['token'];
        validateUser(token).then(
            (data) => {
                request(
                    'http://localhost:4200',
                    (err, remoteResponse, remoteBody) => {
                        if (err) {
                            return res.status(500).end('Error');
                        }
                        res.send(remoteBody);
                    }
                );
            },

            (err) => {
                res.redirect('/login');
            }
        );

    }
);
</code>```

Now, the problem here is, whenever I go to the main page of my site (which reverse proxies back to the dev server), loading the index.html file works fine, but obviously loading everything else like "/assets/js" or default Angular 2 files does not work because they are not similarly authenticated.

Is there a way in Angular 2 to send these requests using the same authentication method? I have the oauth token being stored in my Angular 2 application once the index.html is loaded, so maybe I can use that somehow?

Alternatively, I can also setup another API route in Express to load the files from there, but when Angular 2 generates my index.html with the extra script tag for loading vendor.js or other files, can I tell it this new location instead?

Appreciate the help.

答:
In express, you can use serve-static to serve static files, which would take precedence over your /* route. See https://expressjs.com/en/starter/static-files.html for more details.

Note: this assumes your static assets don't require authentication (which they usually don't).

```<code>app.use(express.static('public'))
</code>```

Note: this should be above the block declaring the /* route in order for it to take precendence.

If you script.js file lives in the /public folder, it will be served at the root of the express server.

Body:
this is a authentication sequence question. I currently have a website that is hosted with an Express back-end, which manages the routing for both my main website and the API points. For any of my routes, the request has to come with a posted OAuth token for the website, which corresponds to a specific GMail account.

I have a function which checks this token/corresponding email to be authorized to access my website (although auth function is not done, this is not the problem).

function validateUser(token) {
    return new Promise(
        (resolve, reject) => {
            if (!token)
                reject("Empty token");
            request(
                'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + token,
                (error, response, body) => {
                    console.log(body);
                    if (error) {
                        return reject("Error");
                    } else if (JSON.parse(body)['error_description']) {
                        return reject(JSON.parse(body)['error_description']);
                    } else if (body) {
                        let theDict = JSON.parse(body);
                        theDict['oauth_token'] = token;
                        return resolve(theDict);
                    }

                    return reject("some other error");

                }
            );
        }
    );

}

Then I have a route that manages get requests at any location (which then redirects to the login page, and once user is logged in it posts to the  route with the token to get the content).

router.post(
    '/*',
    (req, res, next) => {
        var token = req.body['token'];
        validateUser(token).then(
            (data) => {
                request(
                    'http://localhost:4200',
                    (err, remoteResponse, remoteBody) => {
                        if (err) {
                            return res.status(500).end('Error');
                        }
                        res.send(remoteBody);
                    }
                );
            },

            (err) => {
                res.redirect('/login');
            }
        );

    }
);

Now, the problem here is, whenever I go to the main page of my site (which reverse proxies back to the dev server), loading the index.html file works fine, but obviously loading everything else like "/assets/js" or default Angular 2 files does not work because they are not similarly authenticated.

Is there a way in Angular 2 to send these requests using the same authentication method? I have the oauth token being stored in my Angular 2 application once the index.html is loaded, so maybe I can use that somehow?

Alternatively, I can also setup another API route in Express to load the files from there, but when Angular 2 generates my index.html with the extra script tag for loading vendor.js or other files, can I tell it this new location instead?

Appreciate the help.

Body:
In express, you can use serve-static to serve static files, which would take precedence over your /* route. See https://expressjs.com/en/starter/static-files.html for more details.

Note: this assumes your static assets don't require authentication (which they usually don't).

app.use(express.static('public'))

Note: this should be above the block declaring the /* route in order for it to take precendence.

If you script.js file lives in the /public folder, it will be served at the root of the express server.


答:
```<code> <activity
                android:name="YourActivity"
                android:screenOrientation="portrait"
                android:configChanges="orientation|keyboardHidden|screenSize"/>
</code>```


问:
how to get the previous 3 months with the current month in php
How to get the previous 3 months with the current month in php?</p>

答:
Something like this

```<code>mktime(0, 0, 0, date("m")); //it's 00:00 first day of current month
mktime(0, 0, 0, date("m")-1); //it's 00:00 first day of previous month
mktime(0, 0, 0, date("m")-2); //it's 00:00 first day 2 month before
mktime(0, 0, 0, date("m")-3); //it's 00:00 first day 3 month before
</code>```

This functions return unix timestamp, and can be formated with date function.

You will need to read about functions: date(), mktime()

Body:
Something like this

mktime(0, 0, 0, date("m")); //it's 00:00 first day of current month
mktime(0, 0, 0, date("m")-1); //it's 00:00 first day of previous month
mktime(0, 0, 0, date("m")-2); //it's 00:00 first day 2 month before
mktime(0, 0, 0, date("m")-3); //it's 00:00 first day 3 month before

This functions return unix timestamp, and can be formated with date function.

You will need to read about functions: date(), mktime()


问:
joining midpoints of a histogram by line
how do i take a midpoint of each bar in a histogram and draw a line joining those midpoints using matplotlib.

Here is sample data

```<code>test_scores = [55,45,88,75,43,56,89,98,55,54,65,77,88,81,82,89,92,98,65,\
               76,76,73,72,84]
test_scores1 = [55,45,88,73,43,55,89,98,44,54,65,77,80,81,84,89,92,98,65,\
                71,75,73,70,81]
bins = [10,20,30,40,50,60,70,80,90,100]
plt.hist(test_scores, bins, histtype='bar')
plt.hist(test_scores1, bins, histtype='bar')
plt.show()
</code>```

答:
The hist() function returns edges of the bins and their heights. We can use it to compute the centers of the bars and join them into a line as follows:

```<code>import numpy as np
import matplotlib.pyplot as plt

test_scores = [55,45,88,75,43,56,89,98,55,54,65,77,88,81,82,89,92,98,65,\
               76,76,73,72,84]
test_scores1 = [55,45,88,73,43,55,89,98,44,54,65,77,80,81,84,89,92,98,65,\
                71,75,73,70,81]
bins = [0,10,20,30,40,50,60,70,80,90,100]

#y,edges,_ = plt.hist(test_scores1, bins)
y,edges = np.histogram(test_scores1, bins)
centers = 0.5*(edges[1:]+ edges[:-1])
plt.plot(centers,y,'-*')
plt.show()
</code>```

Body:
how do i take a midpoint of each bar in a histogram and draw a line joining those midpoints using matplotlib.

Here is sample data

test_scores = [55,45,88,75,43,56,89,98,55,54,65,77,88,81,82,89,92,98,65,\
               76,76,73,72,84]
test_scores1 = [55,45,88,73,43,55,89,98,44,54,65,77,80,81,84,89,92,98,65,\
                71,75,73,70,81]
bins = [10,20,30,40,50,60,70,80,90,100]
plt.hist(test_scores, bins, histtype='bar')
plt.hist(test_scores1, bins, histtype='bar')
plt.show()

Body:
The hist() function returns edges of the bins and their heights. We can use it to compute the centers of the bars and join them into a line as follows:

import numpy as np
import matplotlib.pyplot as plt

test_scores = [55,45,88,75,43,56,89,98,55,54,65,77,88,81,82,89,92,98,65,\
               76,76,73,72,84]
test_scores1 = [55,45,88,73,43,55,89,98,44,54,65,77,80,81,84,89,92,98,65,\
                71,75,73,70,81]
bins = [0,10,20,30,40,50,60,70,80,90,100]

#y,edges,_ = plt.hist(test_scores1, bins)
y,edges = np.histogram(test_scores1, bins)
centers = 0.5*(edges[1:]+ edges[:-1])
plt.plot(centers,y,'-*')
plt.show()


问:
Case sensitiveness issue when calling an external DLL in Fortran and compiling with gfortran
I'm trying to call a DLL from a Fortran code compiled with gfortran. I'm importing DISCON_32.dll with:

```<code>!GCC$ ATTRIBUTES DLLIMPORT :: DISCON
</code>```

and compiling with:

```<code>mingw32-gfortran "DISCON_32.dll" -cpp -ffree-line-length-none -fno-automatic -Wall -fdefault-real-8 -fno-underscoring -static BladedDLLInterface.o -o "my_program"
</code>```

I get the error:

```<code>BladedDLLInterface.o:BladedDLLInterface.f90(.text+0x6cd): undefined reference to 'discon'
</code>```

Note that entry point "discon" is here called as lowercase. When looking into the DLL with Dependency Walker, entry point is "DISCON" (uppercase).

I cannot change the case of the DLL. Is there a way to tell my Fortran code to look for "DISCON" entry point instead of "discon"?

(My extended googling of the question did not get me closer to a solution)

答:
There are 3 ways to do this: let's make an example DLL and Fortran main to demonstrate the problem.

```<code>! dll1.f90
! gfortran dll1.f90 -shared -odll1.dll -Wl,--out-implib,libdll1.a
module not_used
   use ISO_C_BINDING
   implicit none
   contains
      function F(x) bind(C,name='F')
!GCC$ ATTRIBUTES DLLEXPORT :: F
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) ::x
         F = x**2
      end function F
end module not_used
</code>```

The command line use to build dll1.dll is shown in the comments.

Now we have a Fortran main:

```<code>! main1.f90
! fails:
! gfortran main1.f90 dll1.dll -omain1
! gfortran main1.f90 -L. -ldll1 -omain1
! works:
! gfortran main1.f90 dll1.dll -L. -ldll2 -omain1
! gfortran main1.f90 -L. -ldll1 -ldll2 -omain1
module mod1
   implicit none
   interface
      function F(x)
         import
         implicit none
!GCC$ ATTRIBUTES DLLIMPORT :: F
         double precision F
         double precision, intent(in) :: x
      end function F
   end interface
end module mod1

program main1
   use mod1
   implicit none
   double precision x, y
   x = 13
   y = f(x)
   write(*,*) y
end program main1
</code>```

The first two gfortran commands shown above fail to build main1.exe. The second two work, but we need a libdll2.a file, and we can create it with dlltool.exe. We start with dll2.def

```<code>; dlltool -z dll2.def --export-all-symbol dll1.dll
; dlltool -d dll2.def -l libdll2.a
LIBRARY dll1.dll
EXPORTS
    f = F
</code>```

The first comment line above shows how to dlltool.exe to create a starting point for dll2.def. The output is not very useful in our case, so mostly we used a text editor to modify the starting point. The dll2.def file will create a libdll2.a file that is usefule for linking with dll1.dll, thus the LIBRARY line above. The symbol that got exported was 'F', but gfortran is going to look for 'f', so we rename it in the exports section.

Then we use dlltool.exe to create libdll2.a via the second comment line above. Having a libdll2.a means we can compile main1.f90 according to the comments in lines 6 or 7.

The second method uses a binding name for the function. This requires the function to be interoperable, but if it isn't then you probably couldn't invoke it in any simple way given that it probably wasn't compiled by gfortran. Here we don't need an extra dll2.lib, just a different declaration of the function in main2.f90:

```<code>! main2.f90
! gfortran main2.f90 dll1.dll -omain2
! gfortran main2.f90 -L. -ldll1 -omain2
module mod2
   use ISO_C_BINDING
   implicit none
   interface
      function F(x) bind(C,name='F')
         import
         implicit none
!GCC$ ATTRIBUTES DLLIMPORT :: F
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) :: x
      end function F
   end interface
end module mod2

program main2
   use mod2
   implicit none
   double precision x, y
   x = 13
   y = f(x)
   write(*,*) y
end program main2
</code>```

This compiles with either of the gfortran commands given in the comments.

Finally you could use dynamic linking as in main3.f90:

```<code>! main3.f90
! gfortran main3.f90 dll1.dll -omain3
! gfortran main3.f90 -L. -ldll1 -omain3
module mod3
   use ISO_C_BINDING
   use ISO_C_BINDING, HANDLE => C_INTPTR_T
   use ISO_C_BINDING, C_INTPTR_T => C_INTPTR_T
   implicit none
   abstract interface
      function F(x) bind(C)
         import
         implicit none
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) :: x
      end function F
   end interface
   interface
      function LoadLibrary(lpFileName) bind(C,name='LoadLibraryA')
         import
         implicit none
!GCC$ ATTRIBUTES STDCALL :: LoadLibrary
         integer(HANDLE) :: LoadLibrary
         character(kind=C_CHAR) lpFIleName(*)
      end function LoadLibrary
      function GetProcAddress(hModule,lpProcName) bind(C,name='GetProcAddress')
         import
         implicit none
!GCC$ ATTRIBUTES STDCALL :: GetProcAddress
         type(C_FUNPTR) GetProcAddress
         integer(HANDLE), value :: hModule
         character(kind=C_CHAR) lpProcName(*)
      end function GetProcAddress
   end interface
end module mod3

program main3
   use mod3, F1 => F
   implicit none
   double precision x, y
   type(C_FUNPTR) ptr
   procedure(F1), pointer :: F
   integer(HANDLE) hModule
   hModule = LoadLibrary('dll1.dll'//C_NULL_CHAR)
   ptr = GetProcAddress(hModule,'F'//C_NULL_CHAR)
   call C_F_PROCPOINTER(ptr,F)
   x = 13
   y = f(x)
   write(*,*) y
end program main3
</code>```

Either of the gfortran commands in the comments successfully builds main3.exe.

Note: on retesting, the main2.f90 and main3.f90 methods worked, but for some reason the method with main1.f90 and dll2.def no longer works, failing at runtime because it's trying to find the symbol 'f' in main1.exe rather than dll1.dll. Can't figure out why at this point.

EDIT: Well, I found a way to make the first approach work with the dll1.dll created above and the main1.f90 as it is, but I don't really like it so I'll wait a few days to see if someone else comes up with a more palatable solution. If, after that time, this hasn't happened and someone is still interested, he should remind me and I may post what I came up with.

Body:
I'm trying to call a DLL from a Fortran code compiled with gfortran. I'm importing DISCON_32.dll with:

!GCC$ ATTRIBUTES DLLIMPORT :: DISCON

and compiling with:

mingw32-gfortran "DISCON_32.dll" -cpp -ffree-line-length-none -fno-automatic -Wall -fdefault-real-8 -fno-underscoring -static BladedDLLInterface.o -o "my_program"

I get the error:

BladedDLLInterface.o:BladedDLLInterface.f90(.text+0x6cd): undefined reference to 'discon'

Note that entry point "discon" is here called as lowercase. When looking into the DLL with Dependency Walker, entry point is "DISCON" (uppercase).

I cannot change the case of the DLL. Is there a way to tell my Fortran code to look for "DISCON" entry point instead of "discon"?

(My extended googling of the question did not get me closer to a solution)

Body:
There are 3 ways to do this: let's make an example DLL and Fortran main to demonstrate the problem.

! dll1.f90
! gfortran dll1.f90 -shared -odll1.dll -Wl,--out-implib,libdll1.a
module not_used
   use ISO_C_BINDING
   implicit none
   contains
      function F(x) bind(C,name='F')
!GCC$ ATTRIBUTES DLLEXPORT :: F
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) ::x
         F = x**2
      end function F
end module not_used

The command line use to build dll1.dll is shown in the comments.

Now we have a Fortran main:

! main1.f90
! fails:
! gfortran main1.f90 dll1.dll -omain1
! gfortran main1.f90 -L. -ldll1 -omain1
! works:
! gfortran main1.f90 dll1.dll -L. -ldll2 -omain1
! gfortran main1.f90 -L. -ldll1 -ldll2 -omain1
module mod1
   implicit none
   interface
      function F(x)
         import
         implicit none
!GCC$ ATTRIBUTES DLLIMPORT :: F
         double precision F
         double precision, intent(in) :: x
      end function F
   end interface
end module mod1

program main1
   use mod1
   implicit none
   double precision x, y
   x = 13
   y = f(x)
   write(*,*) y
end program main1

The first two gfortran commands shown above fail to build main1.exe. The second two work, but we need a libdll2.a file, and we can create it with dlltool.exe. We start with dll2.def

; dlltool -z dll2.def --export-all-symbol dll1.dll
; dlltool -d dll2.def -l libdll2.a
LIBRARY dll1.dll
EXPORTS
    f = F

The first comment line above shows how to dlltool.exe to create a starting point for dll2.def. The output is not very useful in our case, so mostly we used a text editor to modify the starting point. The dll2.def file will create a libdll2.a file that is usefule for linking with dll1.dll, thus the LIBRARY line above. The symbol that got exported was 'F', but gfortran is going to look for 'f', so we rename it in the exports section.

Then we use dlltool.exe to create libdll2.a via the second comment line above. Having a libdll2.a means we can compile main1.f90 according to the comments in lines 6 or 7.

The second method uses a binding name for the function. This requires the function to be interoperable, but if it isn't then you probably couldn't invoke it in any simple way given that it probably wasn't compiled by gfortran. Here we don't need an extra dll2.lib, just a different declaration of the function in main2.f90:

! main2.f90
! gfortran main2.f90 dll1.dll -omain2
! gfortran main2.f90 -L. -ldll1 -omain2
module mod2
   use ISO_C_BINDING
   implicit none
   interface
      function F(x) bind(C,name='F')
         import
         implicit none
!GCC$ ATTRIBUTES DLLIMPORT :: F
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) :: x
      end function F
   end interface
end module mod2

program main2
   use mod2
   implicit none
   double precision x, y
   x = 13
   y = f(x)
   write(*,*) y
end program main2

This compiles with either of the gfortran commands given in the comments.

Finally you could use dynamic linking as in main3.f90:

! main3.f90
! gfortran main3.f90 dll1.dll -omain3
! gfortran main3.f90 -L. -ldll1 -omain3
module mod3
   use ISO_C_BINDING
   use ISO_C_BINDING, HANDLE => C_INTPTR_T
   use ISO_C_BINDING, C_INTPTR_T => C_INTPTR_T
   implicit none
   abstract interface
      function F(x) bind(C)
         import
         implicit none
         real(C_DOUBLE) F
         real(C_DOUBLE), intent(in) :: x
      end function F
   end interface
   interface
      function LoadLibrary(lpFileName) bind(C,name='LoadLibraryA')
         import
         implicit none
!GCC$ ATTRIBUTES STDCALL :: LoadLibrary
         integer(HANDLE) :: LoadLibrary
         character(kind=C_CHAR) lpFIleName(*)
      end function LoadLibrary
      function GetProcAddress(hModule,lpProcName) bind(C,name='GetProcAddress')
         import
         implicit none
!GCC$ ATTRIBUTES STDCALL :: GetProcAddress
         type(C_FUNPTR) GetProcAddress
         integer(HANDLE), value :: hModule
         character(kind=C_CHAR) lpProcName(*)
      end function GetProcAddress
   end interface
end module mod3

program main3
   use mod3, F1 => F
   implicit none
   double precision x, y
   type(C_FUNPTR) ptr
   procedure(F1), pointer :: F
   integer(HANDLE) hModule
   hModule = LoadLibrary('dll1.dll'//C_NULL_CHAR)
   ptr = GetProcAddress(hModule,'F'//C_NULL_CHAR)
   call C_F_PROCPOINTER(ptr,F)
   x = 13
   y = f(x)
   write(*,*) y
end program main3

Either of the gfortran commands in the comments successfully builds main3.exe.

Note: on retesting, the main2.f90 and main3.f90 methods worked, but for some reason the method with main1.f90 and dll2.def no longer works, failing at runtime because it's trying to find the symbol 'f' in main1.exe rather than dll1.dll. Can't figure out why at this point.

EDIT: Well, I found a way to make the first approach work with the dll1.dll created above and the main1.f90 as it is, but I don't really like it so I'll wait a few days to see if someone else comes up with a more palatable solution. If, after that time, this hasn't happened and someone is still interested, he should remind me and I may post what I came up with.


问:
How to write two operations at a time inside function in node.js?
I have two tables in my database, i want to get both datas with one function using nodejs

My table name is ContactGroup and Group

My code:

```<code>exports.getNewGroup = function (req, res) {
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => {
        console.log('seenData:', seenData);
    });

    Group.findAll().then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};
</code>```

Like above code, i am writing ContactGroup.findandcount and Group.findall, i checked this api via postman, but only one working here,
I want both of them working? help me!

答:
you take a global array or object and use it in follwing manner</p>

```<code>exports.getNewGroup = function (req, res) {
    var globalObj={};
        ContactGroup.findAndCountAll({
            attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
                'contactCount'
            ]],
            include: [{
                model: Group,
            }],
        }).then(seenData => { globalObj.seendata=seenData;return Group.findAll();})

        .then(function (data) {
    globalObj.alldata=data;
            return res.status(200).send(globalObj);
        }).catch(function (err) {
            return res.status(400).send(err.message);
        });
    };
</code>```

Body:
I have two tables in my database, i want to get both datas with one function using nodejs

My table name is ContactGroup and Group

My code:

exports.getNewGroup = function (req, res) {
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => {
        console.log('seenData:', seenData);
    });

    Group.findAll().then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};

Like above code, i am writing ContactGroup.findandcount and Group.findall, i checked this api via postman, but only one working here,
I want both of them working? help me!

Body:
you take a global array or object and use it in follwing manner

exports.getNewGroup = function (req, res) {
    var globalObj={};
        ContactGroup.findAndCountAll({
            attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
                'contactCount'
            ]],
            include: [{
                model: Group,
            }],
        }).then(seenData => { globalObj.seendata=seenData;return Group.findAll();})

        .then(function (data) {
    globalObj.alldata=data;
            return res.status(200).send(globalObj);
        }).catch(function (err) {
            return res.status(400).send(err.message);
        });
    };


问:
attachment field in MS Access
I want to alter a table and create a new field with the type Attachment.

First I thought of the following:

```<code>Dim SQL_Attachement_Str As String
SQL_Attachement_Str = "ALTER TABLE tbl_FinalTable_summerized ADD CoCAttachement ATTACHMENT"
DoCmd.RunSQL SQL_Attachement_Str
</code>```

But unfortunately (in my case) this is not possible.

My second attempt was it to first create the field as a TEXT type and then later change the type into Attachment as the following:

```<code>Dim SQL_Attachement_Str As String
SQL_Attachement_Str = "ALTER TABLE tbl_FinalTable_summerized ADD CoCAttachement TEXT"
DoCmd.RunSQL SQL_Attachement_Str

Dim tbl As TableDef

Set db = CurrentDb
Set tbl = db.TableDefs("tbl_FINALtable_Summerized")
tbl.Fields("CoCAttachement").Type = dbAttachment

Set tbl = Nothing
Set db = Nothing
</code>```

So What I need is a way to add a field with the type Attachment to the table

thank you people :D

答:
If anyone is searching for an answer to this question, this does the trick:

```<code>Dim fld As DAO.Field

Set fld = CurrentDb().TableDefs("MyTable").CreateField("NewField", 101&)
CurrentDb().TableDefs("MyTable").Fields.Append fld
CurrentDb().TableDefs.Refresh

Set fld = Nothing
</code>```

FieldType values for other complex data types can be found here:
http://allenbrowne.com/func-DAO.html#FieldTypeName

Title: attachment field in MS Access

Body:
I want to alter a table and create a new field with the type Attachment.

First I thought of the following:

Dim SQL_Attachement_Str As String
SQL_Attachement_Str = "ALTER TABLE tbl_FinalTable_summerized ADD CoCAttachement ATTACHMENT"
DoCmd.RunSQL SQL_Attachement_Str

But unfortunately (in my case) this is not possible.

My second attempt was it to first create the field as a TEXT type and then later change the type into Attachment as the following:

Dim SQL_Attachement_Str As String
SQL_Attachement_Str = "ALTER TABLE tbl_FinalTable_summerized ADD CoCAttachement TEXT"
DoCmd.RunSQL SQL_Attachement_Str

Dim tbl As TableDef

Set db = CurrentDb
Set tbl = db.TableDefs("tbl_FINALtable_Summerized")
tbl.Fields("CoCAttachement").Type = dbAttachment

Set tbl = Nothing
Set db = Nothing

So What I need is a way to add a field with the type Attachment to the table

thank you people :D

Body:
If anyone is searching for an answer to this question, this does the trick:

Dim fld As DAO.Field

Set fld = CurrentDb().TableDefs("MyTable").CreateField("NewField", 101&)
CurrentDb().TableDefs("MyTable").Fields.Append fld
CurrentDb().TableDefs.Refresh

Set fld = Nothing

FieldType values for other complex data types can be found here:
http://allenbrowne.com/func-DAO.html#FieldTypeName


问:
Pass function to optional argument in Python
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

```<code>NameError: name 'self' is not defined
</code>```

Please see the sample code below:

```<code>class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()
</code>```

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

答:
It's not possible using self as your optional argument but defining static properties would work.

https://repl.it/@marksman/ravijoshi

```<code>class Test(object):
    rand = 4 # statically defined

    def print_rand(self, num=rand):
        print(num)

t = Test()
t.print_rand()
</code>```

Body:
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

NameError: name 'self' is not defined

Please see the sample code below:

class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

Body:
It's not possible using self as your optional argument but defining static properties would work.

https://repl.it/@marksman/ravijoshi

class Test(object):
    rand = 4 # statically defined

    def print_rand(self, num=rand):
        print(num)

t = Test()
t.print_rand()


问:
Python: Comparing two Directories for Different Filenames
I have to compare two directories with .xyz files in them. One directory has original files (names xa02-1-1-1-1, xa02-1-1-1-2 etc.). I process all these files (molecules) and each file gives rise to 3 new files whose file names just have -1, -2, -3 added at the end. (e.g., xa02-1-1-1-1 would give rise to xa02-1-1-1-1-1, xa02-1-1-1-1-2, and xa02-1-1-1-1-3). During this operation some files just produce two new files and don't produce the 3rd or some produce just one new file and some even do not produce any output. I want to compare first folder with the new one seeing which files have not generated 3 new files. Basically I want t list of the files in the first folder which did not give rise to 3 new files.
I did not find how to do it with Python so I printed all the filenames using bash without the extensions. Now I have two text files with all the filenames and I compare those two text files. I am trying to remove the last -1, -2, -3 from the new list and see if an item in original file is present in the new list less than 3 times. The code still gives me count 1 for all the files.
Can anyone please guide me on that how to do it efficiently using Python. I need this for my PhD research as doing this manually takes days just to compare two folders because of lots of files (molecules) in them.
Here is the code I wrote:

```<code># Define the lists which contain the filenames to compare
originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

def read_input_file(input_filename):
    f = open(input_filename, 'r')
    fr = f.readlines()
    f.close()
    return fr
# Read the files with filenames and without extensions
original_files = read_input_file(originals)
next_step_files = read_input_file(next_step_filenames)

original_files_trimmed = []  # Removing the last \n from every line
for a in original_files:
    original_files_trimmed.append(a[:-1])

next_step_files_trimmed = []  # A list with the last -1, -2, -3 removed
for i in next_step_files:
    next_step_files_trimmed.append(i[:-3])

Final_list = [] # List for Files who generate <3 files
for m in original_files_trimmed:
    for n in next_step_files_trimmed:
        count = 0
        if m in n:
            count =+ 1
            if count < 3:
                Final_list.append(m)

for b in Final_list:
    print(b)
</code>```

And here are the files with names in them.
orig-files.txt

```<code>xa02-1-1-1-1
xa02-1-1-1-2
xa02-1-1-2-3
xa02-1-3-3-3
xa06-3-1-2-1
xa07-1-2-1-1
</code>```

new-files.txt

```<code>xa02-1-1-1-1-1
xa02-1-1-1-1-2
xa02-1-1-1-1-3
xa02-1-1-1-2-1
xa02-1-1-1-2-2
xa02-1-1-1-2-3
xa02-1-1-2-3-1
xa02-1-3-3-3-1
xa02-1-3-3-3-2
xa06-3-1-2-1-1
xa06-3-1-2-1-2
xa06-3-1-2-1-3
</code>```

You can see in the files that xa02-1-1-2-3 and xa02-1-3-3-3 generate 1 and 2 files, respectively while xa07-1-2-1-1 did not generate any output file. I want the output to look like this:

```<code>xa02-1-1-2-3   1
xa02-1-3-3-3   2
xa07-1-2-1-1   0
</code>```

Please help me here. I would be highly thankful for any help.

答:
Use a Counter to count occurrence of filename having trimmed away the last 2 characters.
The resulting counter object can be used to filter original_files_trimmed where items don't count up to 3.

Example:

```<code>from collections import Counter

original_files_trimmed = [
  'xa02-1-1-1-1',
  'xa02-1-1-1-2',
  'xa02-1-1-2-3',
  'xa02-1-3-3-3',
  'xa06-3-1-2-1',
  'xa07-1-2-1-1',
]
next_step_files_trimmed = [
  'xa02-1-1-1-1-1',
  'xa02-1-1-1-1-2',
  'xa02-1-1-1-1-3',
  'xa02-1-1-1-2-1',
  'xa02-1-1-1-2-2',
  'xa02-1-1-1-2-3',
  'xa02-1-1-2-3-1',
  'xa02-1-3-3-3-1',
  'xa02-1-3-3-3-2',
  'xa06-3-1-2-1-1',
  'xa06-3-1-2-1-2',
  'xa06-3-1-2-1-3'
]

# These next few lines diff original_files_trimmed and
# next_step_files_trimmed using the defined rules
next_step_files_without_num = (n[:-2] for n in next_step_files_trimmed) ## trim last 2 chars
next_step_files_without_num_cnt = Counter(next_step_files_without_num)
final_list = [
   m for m in original_files_trimmed
   if next_step_files_without_num_cnt[m] < 3
]

print(final_list)
</code>```

Body:
I have to compare two directories with .xyz files in them. One directory has original files (names xa02-1-1-1-1, xa02-1-1-1-2 etc.). I process all these files (molecules) and each file gives rise to 3 new files whose file names just have -1, -2, -3 added at the end. (e.g., xa02-1-1-1-1 would give rise to xa02-1-1-1-1-1, xa02-1-1-1-1-2, and xa02-1-1-1-1-3). During this operation some files just produce two new files and don't produce the 3rd or some produce just one new file and some even do not produce any output. I want to compare first folder with the new one seeing which files have not generated 3 new files. Basically I want t list of the files in the first folder which did not give rise to 3 new files.
I did not find how to do it with Python so I printed all the filenames using bash without the extensions. Now I have two text files with all the filenames and I compare those two text files. I am trying to remove the last -1, -2, -3 from the new list and see if an item in original file is present in the new list less than 3 times. The code still gives me count 1 for all the files.
Can anyone please guide me on that how to do it efficiently using Python. I need this for my PhD research as doing this manually takes days just to compare two folders because of lots of files (molecules) in them.
Here is the code I wrote:

# Define the lists which contain the filenames to compare
originals = "orig-files.txt"
next_step_filenames = "new-files.txt"

def read_input_file(input_filename):
    f = open(input_filename, 'r')
    fr = f.readlines()
    f.close()
    return fr
# Read the files with filenames and without extensions
original_files = read_input_file(originals)
next_step_files = read_input_file(next_step_filenames)

original_files_trimmed = []  # Removing the last \n from every line
for a in original_files:
    original_files_trimmed.append(a[:-1])

next_step_files_trimmed = []  # A list with the last -1, -2, -3 removed
for i in next_step_files:
    next_step_files_trimmed.append(i[:-3])

Final_list = [] # List for Files who generate <3 files
for m in original_files_trimmed:
    for n in next_step_files_trimmed:
        count = 0
        if m in n:
            count =+ 1
            if count < 3:
                Final_list.append(m)

for b in Final_list:
    print(b)

And here are the files with names in them.
orig-files.txt

xa02-1-1-1-1
xa02-1-1-1-2
xa02-1-1-2-3
xa02-1-3-3-3
xa06-3-1-2-1
xa07-1-2-1-1

new-files.txt

xa02-1-1-1-1-1
xa02-1-1-1-1-2
xa02-1-1-1-1-3
xa02-1-1-1-2-1
xa02-1-1-1-2-2
xa02-1-1-1-2-3
xa02-1-1-2-3-1
xa02-1-3-3-3-1
xa02-1-3-3-3-2
xa06-3-1-2-1-1
xa06-3-1-2-1-2
xa06-3-1-2-1-3

You can see in the files that xa02-1-1-2-3 and xa02-1-3-3-3 generate 1 and 2 files, respectively while xa07-1-2-1-1 did not generate any output file. I want the output to look like this:

xa02-1-1-2-3   1
xa02-1-3-3-3   2
xa07-1-2-1-1   0

Please help me here. I would be highly thankful for any help.

Body:
Use a Counter to count occurrence of filename having trimmed away the last 2 characters.
The resulting counter object can be used to filter original_files_trimmed where items don't count up to 3.

Example:

from collections import Counter

original_files_trimmed = [
  'xa02-1-1-1-1',
  'xa02-1-1-1-2',
  'xa02-1-1-2-3',
  'xa02-1-3-3-3',
  'xa06-3-1-2-1',
  'xa07-1-2-1-1',
]
next_step_files_trimmed = [
  'xa02-1-1-1-1-1',
  'xa02-1-1-1-1-2',
  'xa02-1-1-1-1-3',
  'xa02-1-1-1-2-1',
  'xa02-1-1-1-2-2',
  'xa02-1-1-1-2-3',
  'xa02-1-1-2-3-1',
  'xa02-1-3-3-3-1',
  'xa02-1-3-3-3-2',
  'xa06-3-1-2-1-1',
  'xa06-3-1-2-1-2',
  'xa06-3-1-2-1-3'
]

# These next few lines diff original_files_trimmed and
# next_step_files_trimmed using the defined rules
next_step_files_without_num = (n[:-2] for n in next_step_files_trimmed) ## trim last 2 chars
next_step_files_without_num_cnt = Counter(next_step_files_without_num)
final_list = [
   m for m in original_files_trimmed
   if next_step_files_without_num_cnt[m] < 3
]

print(final_list)


问:
iOS 9 (Xcode 7) Facebook API/FBSDKCoreKit.framework/FBSDKCoreKit(FBSDKAccessToken.o)' does not contain bitcode
I am trying to build the my app containing Facebook SDK with Xcode 7 in iOS 9.0. I am getting this error.

Thanks

答:
Okay I'm just gonna add my own answer.

Import using Cocoapods.

https://github.com/facebook/facebook-ios-sdk.git

That will get bitcode compiled into the framework.


答:
This can be done by appyling the string-to-time method of PHP

```<code>$lastMonth = date('m', strtotime('last month'));
$twoMonthsAgo = date('m', strtotime('-2 months'));
$threeMonthsAgo = date('m', strtotime('-3 months'));
</code>```

You can read more about strtotime here: http://www.php.net/strtotime

Title: how to get the previous 3 months with the current month in php

Body: How to get the previous 3 months with the current month in php?

Body:
This can be done by appyling the string-to-time method of PHP

$lastMonth = date('m', strtotime('last month'));
$twoMonthsAgo = date('m', strtotime('-2 months'));
$threeMonthsAgo = date('m', strtotime('-3 months'));

You can read more about strtotime here: http://www.php.net/strtotime


问:
How does the Shell executor run scripts?
We've recently moved to Gitlab and have started using pipelines. We've set up a build server (an Ubuntu 16.04 instance) and installed a runner that uses a Shell executor but I'm unsure of how it actually executes the scripts defined in the .gitlab-ci.yml file. Consider the following snippet of code:

```<code>script:
    - sh authenticate.sh $DEPLOY_KEY
    - cd MAIN && sh deploy.sh && cd ..
    - sh deploy_service.sh MATCHMAKING
    - sh deauthenticate.sh
</code>```

I was under the impression that it will just pipe these commands to Bash, and hence I was expecting the default Bash behaviour. What happens, however, is that the deploy.sh fails because of an ssh error ; Bash then continues to execute deploy_service.sh (which is expected behaviour) however this fails with a can't open deploy_service.sh error and the job terminates without Bash executing the last statement.

From what I understand, Bash will only abort on error if you do a set -e first and hence I was expecting all the statements to be executed. I've tried adding the set -e as the first statement but this makes no difference whatsoever - it doesn't terminate on the first ssh error.

I've added the exact output from Gitlab below:

Without set -e

```<code>$ cd MAIN && sh deploy.sh && cd ..
deploy.sh: 72: deploy.sh: Bad substitution
Building JS bundles locally...

> better-npm-run build

running better-npm-run in x
Executing script: build

to be executed: node ./bin/build
-> building js bundle...
-> minifying js bundle...
Uploading JS bundles to server temp folder...
COMMENCING RESTART. 5,4,3,2,1...
ssh: Could not resolve hostname $: Name or service not known
$ sh deploy_service.sh MATCHMAKING
sh: 0: Can't open deploy_service.sh
ERROR: Job failed: exit status 1
</code>```

With set -e

```<code>$ set -e
$ cd MAIN && sh deploy.sh && cd ..
deploy.sh: 72: deploy.sh: Bad substitution
Building JS bundles locally...

> better-npm-run build

running better-npm-run in x
Executing script: build

to be executed: node ./bin/build
-> building js bundle...
-> minifying js bundle...
Uploading JS bundles to server temp folder...
COMMENCING RESTART. 5,4,3,2,1...
ssh: Could not resolve hostname $: Name or service not known
$ sh deploy_service.sh MATCHMAKING
sh: 0: Can't open deploy_service.sh
ERROR: Job failed: exit status 1
</code>```

Why is it, without set -e, terminating on error (also, why is it terminating on the second error only and not the ssh error)? Any insights would be greatly appreciated.

答:
I don't think your sh deploy.sh is generating a non-zero exit code.

You are using set -e to tell the current process to exit if a command exits with a non-zero return code, but you are creating a sub-process to run the shell script.

Here's a simple example script that I've called deploy.sh:

```<code>#!/bin/bash
echo "First."
echox "Error"
echo "Second"
</code>```

If I run the script, you can see how the error is not handled:

```<code>$ sh deploy.sh
First.
deploy.sh: line 5: echox: command not found
Second
</code>```

If I run set -e first, you will see it has no effect.

```<code>$ set -e
$ sh deploy.sh
First.
deploy.sh: line 5: echox: command not found
Second
</code>```

Now, I add -e to the /bin/bash shebang:

```<code>#!/bin/bash -e
echo "First."
echox "Error"
echo "Second"
</code>```

When I run the script with sh the -e still takes no effect.

```<code>$ sh ./deploy.sh
First.
./deploy.sh: line 3: echox: command not found
Second
</code>```

When this script is run directly using bash, the -e takes effect.

```<code>$ ./deploy.sh
First.
./deploy.sh: line 3: echox: command not found
</code>```

To fix your issue I believe you need to:

Add -e to the script shebang line (#!/bin/bash -e)

Call the script direct from bash using ./deploy.sh and not run the script through sh.

Bear in mind that if deploy.sh does fail then the cd .. will not run (&& means run the next command if the preceding one succeeded), which would mean you were in the wrong directory to run the deploy_service.sh.  You would be better with cd MAIN; sh deploy.sh; cd .., but I suggest replacing your call to deploy.sh with simpler alternative:

```<code>script:
  - sh authenticate.sh $DEPLOY_KEY
  - (cd MAIN && sh deploy.sh)
  - sh deploy_service.sh MATCHMAKING
  - sh deauthenticate.sh
</code>```

This is not wildly different, but will result in the cd MAIN && sh deploy.sh to be run in a sub-process (that's what the brackets do), which means that the current directory of the overall script is not affected.  Think of it like "spawn a sub-process, and in the sub-process change directory and run that script", and when the sub-process finishes you end up where you started.

As other users have commented, you're actually running your scripts in sh, not bash, so all round this might be better:

```<code>script:
  - ./authenticate.sh $DEPLOY_KEY
  - (cd MAIN && ./deploy.sh)
  - ./deploy_service.sh MATCHMAKING
  - ./deauthenticate.sh
</code>```

Body:
We've recently moved to Gitlab and have started using pipelines. We've set up a build server (an Ubuntu 16.04 instance) and installed a runner that uses a Shell executor but I'm unsure of how it actually executes the scripts defined in the .gitlab-ci.yml file. Consider the following snippet of code:

script:
    - sh authenticate.sh $DEPLOY_KEY
    - cd MAIN && sh deploy.sh && cd ..
    - sh deploy_service.sh MATCHMAKING
    - sh deauthenticate.sh

I was under the impression that it will just pipe these commands to Bash, and hence I was expecting the default Bash behaviour. What happens, however, is that the deploy.sh fails because of an ssh error ; Bash then continues to execute deploy_service.sh (which is expected behaviour) however this fails with a can't open deploy_service.sh error and the job terminates without Bash executing the last statement.

From what I understand, Bash will only abort on error if you do a set -e first and hence I was expecting all the statements to be executed. I've tried adding the set -e as the first statement but this makes no difference whatsoever - it doesn't terminate on the first ssh error.

I've added the exact output from Gitlab below:

Without set -e

$ cd MAIN && sh deploy.sh && cd ..
deploy.sh: 72: deploy.sh: Bad substitution
Building JS bundles locally...

> better-npm-run build

running better-npm-run in x
Executing script: build

to be executed: node ./bin/build
-> building js bundle...
-> minifying js bundle...
Uploading JS bundles to server temp folder...
COMMENCING RESTART. 5,4,3,2,1...
ssh: Could not resolve hostname $: Name or service not known
$ sh deploy_service.sh MATCHMAKING
sh: 0: Can't open deploy_service.sh
ERROR: Job failed: exit status 1

With set -e

$ set -e
$ cd MAIN && sh deploy.sh && cd ..
deploy.sh: 72: deploy.sh: Bad substitution
Building JS bundles locally...

> better-npm-run build

running better-npm-run in x
Executing script: build

to be executed: node ./bin/build
-> building js bundle...
-> minifying js bundle...
Uploading JS bundles to server temp folder...
COMMENCING RESTART. 5,4,3,2,1...
ssh: Could not resolve hostname $: Name or service not known
$ sh deploy_service.sh MATCHMAKING
sh: 0: Can't open deploy_service.sh
ERROR: Job failed: exit status 1

Why is it, without set -e, terminating on error (also, why is it terminating on the second error only and not the ssh error)? Any insights would be greatly appreciated.

Body:
I don't think your sh deploy.sh is generating a non-zero exit code.

You are using set -e to tell the current process to exit if a command exits with a non-zero return code, but you are creating a sub-process to run the shell script.

Here's a simple example script that I've called deploy.sh:

#!/bin/bash
echo "First."
echox "Error"
echo "Second"

If I run the script, you can see how the error is not handled:

$ sh deploy.sh
First.
deploy.sh: line 5: echox: command not found
Second

If I run set -e first, you will see it has no effect.

$ set -e
$ sh deploy.sh
First.
deploy.sh: line 5: echox: command not found
Second

Now, I add -e to the /bin/bash shebang:

#!/bin/bash -e
echo "First."
echox "Error"
echo "Second"

When I run the script with sh the -e still takes no effect.

$ sh ./deploy.sh
First.
./deploy.sh: line 3: echox: command not found
Second

When this script is run directly using bash, the -e takes effect.

$ ./deploy.sh
First.
./deploy.sh: line 3: echox: command not found

To fix your issue I believe you need to:

Add -e to the script shebang line (#!/bin/bash -e)

Call the script direct from bash using ./deploy.sh and not run the script through sh.

Bear in mind that if deploy.sh does fail then the cd .. will not run (&& means run the next command if the preceding one succeeded), which would mean you were in the wrong directory to run the deploy_service.sh.  You would be better with cd MAIN; sh deploy.sh; cd .., but I suggest replacing your call to deploy.sh with simpler alternative:

script:
  - sh authenticate.sh $DEPLOY_KEY
  - (cd MAIN && sh deploy.sh)
  - sh deploy_service.sh MATCHMAKING
  - sh deauthenticate.sh

This is not wildly different, but will result in the cd MAIN && sh deploy.sh to be run in a sub-process (that's what the brackets do), which means that the current directory of the overall script is not affected.  Think of it like "spawn a sub-process, and in the sub-process change directory and run that script", and when the sub-process finishes you end up where you started.

As other users have commented, you're actually running your scripts in sh, not bash, so all round this might be better:

script:
  - ./authenticate.sh $DEPLOY_KEY
  - (cd MAIN && ./deploy.sh)
  - ./deploy_service.sh MATCHMAKING
  - ./deauthenticate.sh


问:
Force Repaint of Node in JavaFx
I've been working with the new JavaFx 3D api. JavaFx 8 introduced the subscene node, which contains its own scene graph and can simultaneously be rendered as a node in a scene. This allows you to render 3D nodes with a perspective camera within the subscene while rendering the HUD nodes on top orthogonaly. This works fine until you try and move HUD components. If the nodes within the subscene have not moved, JavaFx will not redraw it. So it just leaves black artifacts where the HUD used to be. Is there some way to force the subscene to be redrawn?

EDIT: One way I've managed to fix the problem is rendering a cube off screen that spins indefinitely. Because it is always spinning, the subscene is always being updated. This seems like a ridiculous way to fix it but it is the best I can do for now. Still looking for better solutions...

答:
Node.setCache(boolean) will do the job and will clear your black artifacts after move HUD components.
use Caching  with the Cache hints , For example before you start moving, you set the cache hint to SPEED
Once you are done with Animation you switch back to QUALITY , it will re-render your Node (like repaint() in swing)

Title: Force Repaint of Node in JavaFx


问:
AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS RN48
I installed react-native-maps in my project in Android works perfectly but in I always the error appears, compiles well but has an error when executing in ios:

console.error: "react-native-maps: AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS".

```<code>"dependencies": {

"react": "16.0.0-alpha.6",

"react-native": "0.48.4",

"react-native-maps": "^ 0.17.1",

... }
</code>```

答:
I had faced this problem a week ago, and I solved it yesterday.

First of all, My file structure like below and my version totally same as you.

```<code>MyApp--- ios
       |
       - android
       |
       - js- node-modules
           |
           - index.js
           |
           - etc...
</code>```

Maybe it is little different with you, but just a file structure.

I use pod to install react-native-maps and I never link with react-native.
After you install react-native-maps, you can use iOS native map now.
Make sure you already able to use iOS map after which I will take you through.

In your xcode project left sidebar click right and click Add files to "your project" and choose node_modules/react-native-maps/lib/ios/AirGoogleMap

Go to your project => target => Build Setting => Header Search Paths
and double click to add path $(SRCROOT)/../js/node_modules/react-native-maps/lib/ios(this is my file structure) and turn non-recursive to recursive.

 If your file structure is following official like react-native, you should add path like this$(SRCROOT)/../node_modules/react-native-maps/lib/ios.

That is done, I hope it will help you.

Body:
I installed react-native-maps in my project in Android works perfectly but in I always the error appears, compiles well but has an error when executing in ios:

console.error: "react-native-maps: AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS".

"dependencies": {

"react": "16.0.0-alpha.6",

"react-native": "0.48.4",

"react-native-maps": "^ 0.17.1",

... }

Body:
I had faced this problem a week ago, and I solved it yesterday.

First of all, My file structure like below and my version totally same as you.

MyApp--- ios
       |
       - android
       |
       - js- node-modules
           |
           - index.js
           |
           - etc...

Maybe it is little different with you, but just a file structure.

I use pod to install react-native-maps and I never link with react-native.
After you install react-native-maps, you can use iOS native map now.
Make sure you already able to use iOS map after which I will take you through.

In your xcode project left sidebar click right and click Add files to "your project" and choose node_modules/react-native-maps/lib/ios/AirGoogleMap

Go to your project => target => Build Setting => Header Search Paths
and double click to add path $(SRCROOT)/../js/node_modules/react-native-maps/lib/ios(this is my file structure) and turn non-recursive to recursive.

 If your file structure is following official like react-native, you should add path like this$(SRCROOT)/../node_modules/react-native-maps/lib/ios.

That is done, I hope it will help you.


问:
malloc error -[CFString release]
For some reason my app was crashing on a particular action. After investigation, I found out it is because of releasing something that has already been released. Then I read on the internet that I can track down the cause of this using NSZombie and MallocStackLogging which I implemented and got this as the result.

NSZombie: 2011-01-19 14:39:09.523
  iota[13649:207] * -[CFString
  release]: message sent to deallocated
  instance 0xeeaf510

malloc_history

ALLOC 0xeeaf510-0xeeaf52f [size=32]:
  thread_a0041500 |start | main |
  UIApplicationMain | GSEventRun |
  GSEventRunModal | CFRunLoopRunInMode |
  CFRunLoopRunSpecific | CFRunLoopRun
  | __CFRunLoopDoTimer |
  __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION
  | __NSFireDelayedPerform |
  -[UITableView _userSelectRowAtIndexPath:] | -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:]
  | -[CorpDirViewController
  tableView:didSelectRowAtIndexPath:] |
  -[CorpDirPersonViewController corpDirViewController:shouldContinueAfterSelectingContact:]
  | -[ContactItem mergeWithContact:] |
  -[ContactItem getValueForProperty:] | ABRecordCopyValue |
  CPRecordCopyProperty |
  CPRecordGetProperty |
  ABCMultiValueLoad |
  ABCDBContextFetchMultiValuePropertyIntoRecord
  | ABCDBContextFetchMultiValueEntries |
  CPSqliteStatementSendResults |
  CollectMultiValueEntries |
  _sqliteStatementApplyValuesFromRecordWithNullValue
  | CFStringCreateWithCString |
  __CFStringCreateImmutableFunnel3 | _CFRuntimeCreateInstance | malloc_zone_malloc

Now I am unable to find out particularly what is causing the crash. Can anyone help me out with it?

答:
As you already know, you are calling release on an object that is already destroyed. That is, you've called release one time too many on the object (in this case an NSString). The exception done via NSZombieEnabled now tells you where the "one time too many" release is done. But most of the time you are searching for the release in between, and that is harder to do...

Now that you know where it is crashing (and should thus know which variable is involved) you need to read through your code where you're also releasing this variable or how objects get assigned to that variable and then inspect those sources. That is, you need to "backtrack" where the object originated from and what you've done with it. Somewhere along its life you either forgot to retain it, or you accidentially release/autoreleased it where you shouldn't.

Title: malloc error -[CFString release]


问:
Reshaping only some columns into a single column
```<code>import pandas as pd
from datetime import datetime

df = pd.DataFrame({'origin': ['japan', 'japan','japan','japan'],
                       'pastime': ['baseball', 'sumo', 'keirin', 'football'],
                       datetime(2000,1,1) : [4,5,4,5],
                   datetime(2005,1,1) : [4, 3, 2, 1],
                   datetime(2010,1,1) : [4, 2, 2, 1]
                  })
</code>```

My dataframe has lots of date-labelled columns:

```<code>Index(['origin','pastime', 2000-01-01 00:00:00,
       2005-01-01 00:00:00, 2010-01-01 00:00:00],
      dtype='object')
</code>```

I would like to reshape the dataframe to have columns: origin, pastime, date, value

Where the first entry row would be:

```<code>origin = japan
pastime = baseball
date = 2001-01-01
value = 4
</code>```

I've seen examples using stack to push columns into the rows as an index,  but in my case, it pushes the 'origin' and 'pastime' columns down too.

How would I do this transformation?

答:
set_index and stack

```<code>df.set_index(['origin','pastime']).stack().reset_index()
Out[150]:
   origin   pastime    level_2  0
0   japan  baseball 2010-01-01  4
1   japan  baseball 2000-01-01  4
2   japan  baseball 2005-01-01  4
3   japan      sumo 2010-01-01  2
4   japan      sumo 2000-01-01  5
5   japan      sumo 2005-01-01  3
6   japan    keirin 2010-01-01  2
7   japan    keirin 2000-01-01  4
8   japan    keirin 2005-01-01  2
9   japan  football 2010-01-01  1
10  japan  football 2000-01-01  5
11  japan  football 2005-01-01  1
</code>```

PS. you can use rename for change the column name

Body:
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'origin': ['japan', 'japan','japan','japan'],
                       'pastime': ['baseball', 'sumo', 'keirin', 'football'],
                       datetime(2000,1,1) : [4,5,4,5],
                   datetime(2005,1,1) : [4, 3, 2, 1],
                   datetime(2010,1,1) : [4, 2, 2, 1]
                  })

My dataframe has lots of date-labelled columns:

Index(['origin','pastime', 2000-01-01 00:00:00,
       2005-01-01 00:00:00, 2010-01-01 00:00:00],
      dtype='object')

I would like to reshape the dataframe to have columns: origin, pastime, date, value

Where the first entry row would be:

origin = japan
pastime = baseball
date = 2001-01-01
value = 4

I've seen examples using stack to push columns into the rows as an index,  but in my case, it pushes the 'origin' and 'pastime' columns down too.

How would I do this transformation?

Body:
set_index and stack

df.set_index(['origin','pastime']).stack().reset_index()
Out[150]:
   origin   pastime    level_2  0
0   japan  baseball 2010-01-01  4
1   japan  baseball 2000-01-01  4
2   japan  baseball 2005-01-01  4
3   japan      sumo 2010-01-01  2
4   japan      sumo 2000-01-01  5
5   japan      sumo 2005-01-01  3
6   japan    keirin 2010-01-01  2
7   japan    keirin 2000-01-01  4
8   japan    keirin 2005-01-01  2
9   japan  football 2010-01-01  1
10  japan  football 2000-01-01  5
11  japan  football 2005-01-01  1

PS. you can use rename for change the column name