问:
Bootstrap remote Modal doesn't update content after first run

It comes javaScript and jQuery are beeing a big challenge for me. Like it's not enough I've started to use ajax to get over my problem - which is:

I've got some empty tables on my page. Each cell of a table has got its own id. A php-script is parsing a .xlsx file and puts the right link to the cell of my html table through javaScript code like:

```<code>document.getElementById("cellNrXY").innerHTML = "<a href=".../remoteContent.php">someLink</a>";
</code>```

If the link is clicked, then a Modal (Bootstrap) appears and loads the remote content (which is different depending on the clicked link).

My problem was that the remote content was cached in modal, so it worked only on first run. After closing the modal and choosing another link the previous modal appeared und didn't change to the new remote content.
I've read a lot solutions here that are based on:

```<code> $(this).removeData('bs.modal');
</code>```

but had no luck with it. After some trying with different solutions one worked properly. The only problem was: when I've clicked the second time on some other link, the modal opened up with previous content and it took some seconds for the modal beeing updated. This is why I wanted to show a rotating element while the new modal content is beeing loaded. Somewhere here I've read a solution tu use ajax for this, which I've added "on luck" and ... it worked:

```<code>$("#myModal").on("show.bs.modal", function(e) {
$.ajax({
beforeSend: function() { $('#myModal')
                        .html('<div class="rotatingElement"></div>')
                        .show(); },
complete: function() { $('#myModal').html.hide(); }
});
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
</code>```

The only thing is - I've no idea why this is working. Is there any chance that somebody here explain the functionality of this code to me?

答:
if you read about the event show.bs.modal you will know that this event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. Learn more about Events

so what is happening is every time you open a modal this event triggers and makes an ajax call which you see like this $.ajax({ wchi has 2 options set

A pre-request callback function beforeSend

A function to be called when the request finishes complete

so whenever the modal triggeres the ajax requet is made and every time ajax request i made just before sending the request the modal html is overridden $('#myModal').html('

').show(); and a loader is added in form of a div element with class rotatingElement and as soon as the requet completes that loader is removed via complete function $('#myModal').html.hide(); and then the e.relatedTarget property as described above gets the anchor object and the href of that anchor .../remoteContent.php is loaded in side the modal body in the following 2 steps

```<code>var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
</code>```

Body:
It comes javaScript and jQuery are beeing a big challenge for me. Like it's not enough I've started to use ajax to get over my problem - which is:

I've got some empty tables on my page. Each cell of a table has got its own id. A php-script is parsing a .xlsx file and puts the right link to the cell of my html table through javaScript code like:

document.getElementById("cellNrXY").innerHTML = "someLink";

If the link is clicked, then a Modal (Bootstrap) appears and loads the remote content (which is different depending on the clicked link).

My problem was that the remote content was cached in modal, so it worked only on first run. After closing the modal and choosing another link the previous modal appeared und didn't change to the new remote content.
I've read a lot solutions here that are based on:

 $(this).removeData('bs.modal');

but had no luck with it. After some trying with different solutions one worked properly. The only problem was: when I've clicked the second time on some other link, the modal opened up with previous content and it took some seconds for the modal beeing updated. This is why I wanted to show a rotating element while the new modal content is beeing loaded. Somewhere here I've read a solution tu use ajax for this, which I've added "on luck" and ... it worked:

$("#myModal").on("show.bs.modal", function(e) {
$.ajax({
beforeSend: function() { $('#myModal')
                        .html('

')
                        .show(); },
complete: function() { $('#myModal').html.hide(); }
});
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});

The only thing is - I've no idea why this is working. Is there any chance that somebody here explain the functionality of this code to me?

Body:
if you read about the event show.bs.modal you will know that this event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. Learn more about Events

so what is happening is every time you open a modal this event triggers and makes an ajax call which you see like this $.ajax({ wchi has 2 options set

A pre-request callback function beforeSend

A function to be called when the request finishes complete

so whenever the modal triggeres the ajax requet is made and every time ajax request i made just before sending the request the modal html is overridden $('#myModal').html('<div class="rotatingElement"></div>').show(); and a loader is added in form of a div element with class rotatingElement and as soon as the requet completes that loader is removed via complete function $('#myModal').html.hide(); and then the e.relatedTarget property as described above gets the anchor object and the href of that anchor .../remoteContent.php is loaded in side the modal body in the following 2 steps

var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));


来源: stackexchange

问:
How to set src of img tag with variable in haml?
I would like to set src of img tag with variable.
I tested this variable and checked it in real url.
This is what I have done

```<code>%img{border: "0", height: "95", :src => "#{data[:photo]}", width: "250"}/
</code>```

But it doesn't work still now.
I am not sure what the problem is.
Looking forward your help.
Thanks.

答:
data[:photo] didn't contain http or https
I added this and it work well.
Thanks.</p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to set src of img tag with variable.
I tested this variable and checked it in real url.
This is what I have done

%img{border: "0", height: "95", :src => "#{data[:photo]}", width: "250"}/

But it doesn't work still now.
I am not sure what the problem is.
Looking forward your help.
Thanks.


问:
Android Gradle Plugin 3.0 Output apk to different directory
I have recently upgraded to Gradle 3.0 and now find that the feature to rename the output APK has changed. I think I can get around that, but what I am wondering is whether I can still choose the target directory for the APK. We have existing software that uses a specific APK naming convention and directory structure that I want to maintain. Is there a way to do this?

Here is my current gradle build structure (simplified and renamed to protect the innocent):

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "com.mycompany.myapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 23
        versionName "23.23.23"
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7        }
        signingConfig signingConfigs.config
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.config
        }
    }
    productFlavors.whenObjectAdded { flavor ->
        // Add the property 'myCustomProperty' to each product flavor and set the default value to 'customPropertyValue'
        flavor.ext.set('directoryPath', '')
        flavor.ext.set('apkName', '')
    }
    productFlavors {

        MyCompany {
            signingConfig signingConfigs.config
            directoryPath = mycompany
        }

        Copper {
            applicationId c
            signingConfig signingConfigs.config
            directoryPath = 'copper'
        }

        Steel {
            applicationId 'com.company2.steel'
            signingConfig signingConfigs.config
            directoryPath = 'steel'
        }

        Lead {
            applicationId 'com.company3.coal'
            signingConfig signingConfigs.config
            directoryPath = 'coal'
        }

    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def path = "C:/AndroidBuilds/MyBuilds/" + variant.productFlavors[0].directoryPath + "/"
            logger.error("Path = " + path)
            def SEP = "-"
            def apkName = variant.productFlavors[0].apkName
            def flavor = variant.productFlavors[0].name
            if (apkName != '')
                flavor = apkName;
            def version = variant.versionCode
            def newApkName = path + version + SEP + flavor
            logger.error("newApkName = " + newApkName)
            output.outputFile = new File(newApkName + ".apk")
        }
    }
}
</code>```

I know that there is now a "Flavor Dimension" which I will just default (I removed that just to make the code a wee bit clearer). The results of running this build should be that 4 different APKs would be generated and placed in their own directory structures, prefixed with the version number (eg "64-Iron.apk").

The naming is working by replacing with "outputfile", but the directory structure does not. Is there a new way to do this under the latest Gradle?

UPDATE (FIXED)

Thanks to the info provided by selected solution, for completeness, here is the final gradle config (again, cleaned to protect the innocent):

```<code>android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.mycompany.myapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 23
        versionName "23.23.23"
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7        }
        signingConfig signingConfigs.config
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.config
        }
    }
    productFlavors.whenObjectAdded { flavor ->
        // Add the property 'myCustomProperty' to each product flavor and set the default value to 'customPropertyValue'
        flavor.ext.set('directoryPath', '')
        flavor.ext.set('apkName', '')
    }
    productFlavors {

        MyCompany {
            signingConfig signingConfigs.config
            directoryPath = mycompany
        }

        Copper {
            applicationId c
            signingConfig signingConfigs.config
            directoryPath = 'copper'
        }

        Steel {
            applicationId 'com.company2.steel'
            signingConfig signingConfigs.config
            directoryPath = 'steel'
        }

        Lead {
            applicationId 'com.company3.coal'
            signingConfig signingConfigs.config
            directoryPath = 'coal'
        }

    }

    applicationVariants.all { variant ->
        variant.outputs.all {
            def apkName = variant.productFlavors[0].apkName
            def flavor = variant.productFlavors[0].name
            if (apkName != '')
                flavor = apkName;
            //add here your logic to customize the name of the apk
            outputFileName = "${variant.versionCode}-${flavor}.apk"
        }
        variant.assemble.doLast { assemble ->
            //copy the apk in another directory, add here your
            //logic to customize the destination folder
            copy {
                from variant.outputs*.outputFile
                into "C:/AndroidBuilds/MyBuilds//${variant.productFlavors[0].directoryPath}"
            }
            //if you don't want to delete the file after copying it comment the line below
            delete variant.outputs*.outputFile
        }
    }
}
</code>```

Thanks again MatPag!

答:
UPDATE: Starting from Gradle 3.3.0 assemble property is deprecated. This is the new way to do this:

```<code>applicationVariants.all { variant ->
    variant.outputs.all {
        //add here your logic to customize the name of the apk
        outputFileName = "${variant.name}-${variant.versionName}.apk"
    }
    variant.assembleProvider.configure { assemble ->
        assemble.doLast {
            //copy the apk in another directory, add here your
            //logic to customize the destination folder
            copy {
                from variant.outputs*.outputFile
                //for Windows
                into "C:/my_apks/${variant.dirName}"
            }
            //if you don't want to delete the file after copying it comment the line below
            delete variant.outputs*.outputFile
        }
    }
}
</code>```

in macOS/Linux you can use something like this for the destination
  path:

```<code>into "${System.properties['user.home']}/my_apks/${variant.dirName}"
</code>```

OLD ANSWER (for AGP < 3.3.0):
I've played a bit with Gradle 4.2.1 and AGP 3.0.0, and a possible solution is this one

```<code>applicationVariants.all { variant ->
    variant.outputs.all {
        //add here your logic to customize the name of the apk
        outputFileName = "${variant.name}-${variant.versionName}.apk"
    }
    variant.assemble.doLast { assemble ->
        //copy the apk in another directory, add here your
        //logic to customize the destination folder
        copy {
            from variant.outputs*.outputFile
            into "C:/my_apks/${variant.dirName}"
        }
        //if you don't want to delete the file after copying it comment the line below
        delete variant.outputs*.outputFile
    }
}
</code>```

I think it's a good starting point to customize the folders based on your needs :)

Body:
I have recently upgraded to Gradle 3.0 and now find that the feature to rename the output APK has changed. I think I can get around that, but what I am wondering is whether I can still choose the target directory for the APK. We have existing software that uses a specific APK naming convention and directory structure that I want to maintain. Is there a way to do this?

Here is my current gradle build structure (simplified and renamed to protect the innocent):

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "com.mycompany.myapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 23
        versionName "23.23.23"
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7        }
        signingConfig signingConfigs.config
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.config
        }
    }
    productFlavors.whenObjectAdded { flavor ->
        // Add the property 'myCustomProperty' to each product flavor and set the default value to 'customPropertyValue'
        flavor.ext.set('directoryPath', '')
        flavor.ext.set('apkName', '')
    }
    productFlavors {

        MyCompany {
            signingConfig signingConfigs.config
            directoryPath = mycompany
        }

        Copper {
            applicationId c
            signingConfig signingConfigs.config
            directoryPath = 'copper'
        }

        Steel {
            applicationId 'com.company2.steel'
            signingConfig signingConfigs.config
            directoryPath = 'steel'
        }

        Lead {
            applicationId 'com.company3.coal'
            signingConfig signingConfigs.config
            directoryPath = 'coal'
        }

    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def path = "C:/AndroidBuilds/MyBuilds/" + variant.productFlavors[0].directoryPath + "/"
            logger.error("Path = " + path)
            def SEP = "-"
            def apkName = variant.productFlavors[0].apkName
            def flavor = variant.productFlavors[0].name
            if (apkName != '')
                flavor = apkName;
            def version = variant.versionCode
            def newApkName = path + version + SEP + flavor
            logger.error("newApkName = " + newApkName)
            output.outputFile = new File(newApkName + ".apk")
        }
    }
}

I know that there is now a "Flavor Dimension" which I will just default (I removed that just to make the code a wee bit clearer). The results of running this build should be that 4 different APKs would be generated and placed in their own directory structures, prefixed with the version number (eg "64-Iron.apk").

The naming is working by replacing with "outputfile", but the directory structure does not. Is there a new way to do this under the latest Gradle?

UPDATE (FIXED)

Thanks to the info provided by selected solution, for completeness, here is the final gradle config (again, cleaned to protect the innocent):

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.mycompany.myapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 23
        versionName "23.23.23"
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7        }
        signingConfig signingConfigs.config
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.config
        }
    }
    productFlavors.whenObjectAdded { flavor ->
        // Add the property 'myCustomProperty' to each product flavor and set the default value to 'customPropertyValue'
        flavor.ext.set('directoryPath', '')
        flavor.ext.set('apkName', '')
    }
    productFlavors {

        MyCompany {
            signingConfig signingConfigs.config
            directoryPath = mycompany
        }

        Copper {
            applicationId c
            signingConfig signingConfigs.config
            directoryPath = 'copper'
        }

        Steel {
            applicationId 'com.company2.steel'
            signingConfig signingConfigs.config
            directoryPath = 'steel'
        }

        Lead {
            applicationId 'com.company3.coal'
            signingConfig signingConfigs.config
            directoryPath = 'coal'
        }

    }

    applicationVariants.all { variant ->
        variant.outputs.all {
            def apkName = variant.productFlavors[0].apkName
            def flavor = variant.productFlavors[0].name
            if (apkName != '')
                flavor = apkName;
            //add here your logic to customize the name of the apk
            outputFileName = "${variant.versionCode}-${flavor}.apk"
        }
        variant.assemble.doLast { assemble ->
            //copy the apk in another directory, add here your
            //logic to customize the destination folder
            copy {
                from variant.outputs*.outputFile
                into "C:/AndroidBuilds/MyBuilds//${variant.productFlavors[0].directoryPath}"
            }
            //if you don't want to delete the file after copying it comment the line below
            delete variant.outputs*.outputFile
        }
    }
}

Thanks again MatPag!

Body:
UPDATE: Starting from Gradle 3.3.0 assemble property is deprecated. This is the new way to do this:

applicationVariants.all { variant ->
    variant.outputs.all {
        //add here your logic to customize the name of the apk
        outputFileName = "${variant.name}-${variant.versionName}.apk"
    }
    variant.assembleProvider.configure { assemble ->
        assemble.doLast {
            //copy the apk in another directory, add here your
            //logic to customize the destination folder
            copy {
                from variant.outputs*.outputFile
                //for Windows
                into "C:/my_apks/${variant.dirName}"
            }
            //if you don't want to delete the file after copying it comment the line below
            delete variant.outputs*.outputFile
        }
    }
}

in macOS/Linux you can use something like this for the destination
  path:

into "${System.properties['user.home']}/my_apks/${variant.dirName}"

OLD ANSWER (for AGP < 3.3.0):
I've played a bit with Gradle 4.2.1 and AGP 3.0.0, and a possible solution is this one

applicationVariants.all { variant ->
    variant.outputs.all {
        //add here your logic to customize the name of the apk
        outputFileName = "${variant.name}-${variant.versionName}.apk"
    }
    variant.assemble.doLast { assemble ->
        //copy the apk in another directory, add here your
        //logic to customize the destination folder
        copy {
            from variant.outputs*.outputFile
            into "C:/my_apks/${variant.dirName}"
        }
        //if you don't want to delete the file after copying it comment the line below
        delete variant.outputs*.outputFile
    }
}

I think it's a good starting point to customize the folders based on your needs :)

ContentLicense: CC BY-SA 4.0


问:
Insert text before and after the selected text in javascript
I want to put some specified text (where possible/any editable field) before and after any selected text in an HTML document.
document.getSelection() or document.selection.createRange().text returns only the text itself not the position.
Is there anyway to replace the selected text? Anyway to insert specific text before and after selcted text anywhere in the document?

答:
Try this:</p>

```<code>var r = document.selection.createRange();

r.text = "before" + r.text;
r.text += "after";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this:

var r = document.selection.createRange();

r.text = "before" + r.text;
r.text += "after";


问:
Can we have two separate bin folders within a single Function App?
We have two different azure function app projects, each with a single function. We would like to host them all under a single Function App in Azure and each with it's own bin. I would like to be able for each function to deal with their own versions of external references, i.e. function1 might use json.net 10.0, while function2 stay on json.net 9.0.

Creating an Azure Function App host for each function can become very unmanageable, specially if we have to multiply x3 for each environment: dev, staging, prod.

We tried by doing a normal deployment of the two projects, but they both share the same bin (which resulted in a reference issue):

```<code>wwwroot
- bin
- function1
--- function.json (pointing to ../bin/function1.dll)
- function2
--- function.json (pointing to ../bin/function2.dll)
- host.json
</code>```

We also tried creating virtual application directories and deploy to those, but the portal doesn't find the functions. The end structure is:

```<code>wwwroot
- function1
--- bin
--- function1
------ function.json
--- host.json
- function2
--- bin
--- function2
------ function.json
--- host.json
</code>```

moving the function.json file of each function to the root of the virtual directory and fixing the reference to the dll fixes the issue.

It sounds like Virtual Directories would cater to this need, but the portal doesn't seem to support finding function.json two levels deep.

Is what we are wanting to do possible?

答:
There is no process isolation between functions in the same Function App: they all run in the same process and in the same App Domain.

If you need complete isolation, the only way to achieve that is by having the functions in separate Function Apps.

I guess the solution is to automate Function App management to the acceptable level.

Body:
We have two different azure function app projects, each with a single function. We would like to host them all under a single Function App in Azure and each with it's own bin. I would like to be able for each function to deal with their own versions of external references, i.e. function1 might use json.net 10.0, while function2 stay on json.net 9.0.

Creating an Azure Function App host for each function can become very unmanageable, specially if we have to multiply x3 for each environment: dev, staging, prod.

We tried by doing a normal deployment of the two projects, but they both share the same bin (which resulted in a reference issue):

wwwroot
- bin
- function1
--- function.json (pointing to ../bin/function1.dll)
- function2
--- function.json (pointing to ../bin/function2.dll)
- host.json

We also tried creating virtual application directories and deploy to those, but the portal doesn't find the functions. The end structure is:

wwwroot
- function1
--- bin
--- function1
------ function.json
--- host.json
- function2
--- bin
--- function2
------ function.json
--- host.json

moving the function.json file of each function to the root of the virtual directory and fixing the reference to the dll fixes the issue.

It sounds like Virtual Directories would cater to this need, but the portal doesn't seem to support finding function.json two levels deep.

Is what we are wanting to do possible?


问:
Httponly cookie as bearer token - Laravel Passport
I have began building an application using React JS and Laravel 5.5. I have installed the Laravel Passport and have successfully managed to log my user in and out in my React JS app - but I have been told to look into using httponly cookies for security purposes.

In my working code, I have simply stored the access token in localStorage and sent it to the api using Authorization': 'Bearer ' + token in the axios headers, and this works perfectly. However, when I set a cookie using httponly I can't fetch the value of it (which I assume is exactly the point!) - using react-cookie (from npm), if I log cookie.loadAll() to the console then the only cookie I see is a new XSRF-TOKEN cookie, but not the accessToken cookie I set. So how do I go about sending this token to the api?

答:
Httponly cookie as bearer token doesn't make much sense. Having cookies httponly helps to protect you and the user against XSS attack as their not readable by javascript. They can be used e.g. for storing session information and are sent when the user do e.g. a page reload.

Setting Authorization header to 'Bearer ' + token is correct way how to sent token to the api. Before using token on the api server you should always check if the token is still valid.


问:
Yet Another Conditional Operator Nesting Question
As per C precedence tables, the ternary conditional operator has right-to-left
associativity.

So, is it directly convertible to the equivalent if-else ladder?

For example, can:

```<code>x?y?z:u:v;
</code>```

be interpreted as:

```<code>if(x)
{
   if(y)
   { z; }
   else
   { u; }
}
else
{ v; }
</code>```

by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?

答:
Your assumption is correct; however, it is often wise to add in parentheses for readability, e.g.:</p>

```<code>x ? ( y ? z : u ) : v
</code>```

Body:
As per C precedence tables, the ternary conditional operator has right-to-left
associativity.

So, is it directly convertible to the equivalent if-else ladder?

For example, can:

x?y?z:u:v;

be interpreted as:

if(x)
{
   if(y)
   { z; }
   else
   { u; }
}
else
{ v; }

by matching an else (:) with the closest unpaired if (?)? Or does right-to-left associativity imply some other arrangement?

Body:
Your assumption is correct; however, it is often wise to add in parentheses for readability, e.g.:

x ? ( y ? z : u ) : v


问:
Google Chrome localhost | NET::ERR_CERT_AUTHORITY_INVALID
All of a sudden I seem to have an issue with Google Chrome using localhost.

I'm trying to access any of my development sites (using Ampps) and I get the following error:-

Your connection is not private Attackers might be trying to steal your
  information from website.dev (for example, passwords, messages
  or credit cards). Learn more NET::ERR_CERT_AUTHORITY_INVALID

When I visit any of the dev sites it is redirecting from http://website.dev to https://website.dev automatically. I'm not having any issue in Safari or Firefox so I don't understand what is going on.

I've tried re-installing Google Chrome, resetting it to the factory default settings...

I think it could be an issue with Keychain Access --> Certificates but wouldn't that mean it wouldn't work in Firefox and Safari if that was the case?

I've spent a while trying to find a solution but so far nothing has worked so I would appreciate some suggestions on how I can fix this. I can't even proceed passed this warning as I don't get the proceed link (insecure) as shown below:-

答:
After playing around, I came up with one kind of a solution.

First, lets talk about the problem: the cause of this error is that both of us used a .dev domain for our local development. If you go here you will find out that root .dev domain is owned by Google and applying HSTS in Chrome they enforce https-redirect for this domain. Since we use .dev domains,  we get redirected to https version and at the same time we don't have any actual certificates installed. So, we see this annoying error. If you go to chrome://net-internals/#hsts you can check your .dev domain and you will actually find out that

```<code>static_sts_domain: dev
static_upgrade_mode: FORCE_HTTPS
static_sts_include_subdomains: true
</code>```

which confirms that HSTS is enforced on *.dev indeed. The policy type is static and, as I understand, it's kind of hard-coded to https-redirect .dev domains.

So, there are at least 2 ways - get and set up an actual certificate somehow or just use another (not .dev) root domain in httpd-vhosts.conf for your local  development (also don't forget to update /etc/hosts and launch apache again). I went another root domain route and it solved this issue.

Body:
After playing around, I came up with one kind of a solution.

First, lets talk about the problem: the cause of this error is that both of us used a .dev domain for our local development. If you go here you will find out that root .dev domain is owned by Google and applying HSTS in Chrome they enforce https-redirect for this domain. Since we use .dev domains,  we get redirected to https version and at the same time we don't have any actual certificates installed. So, we see this annoying error. If you go to chrome://net-internals/#hsts you can check your .dev domain and you will actually find out that

static_sts_domain: dev
static_upgrade_mode: FORCE_HTTPS
static_sts_include_subdomains: true

which confirms that HSTS is enforced on *.dev indeed. The policy type is static and, as I understand, it's kind of hard-coded to https-redirect .dev domains.

So, there are at least 2 ways - get and set up an actual certificate somehow or just use another (not .dev) root domain in httpd-vhosts.conf for your local  development (also don't forget to update /etc/hosts and launch apache again). I went another root domain route and it solved this issue.


问:
Some Output Lost in Command Passed to SSH
I'm trying to use an ssh command to ssh to a server and run theuseradd command I passed to it. It seems like its running ok for the most part (no errors produced) but the hashed password in the /etc/shadow file is missing the salt (I believe that's the portion that's missing.).

I'm not sure if the quoting that is incorrect or not. But running this command manually on the server works fine, so I'm assuming its the expansion that's messed up.?

The command below is running inside a Bash script...

Command:

```<code>ssh user@$host "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios"
</code>```

*When I escape the double quotes inside the perl one-liner, I get the error:

Can't find string terminator '"' anywhere before EOF at -e line 1.

Usage: useradd [options] LOGIN

Any idea what I'm doing wrong here?

答:
```<code>echo "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios" > /tmp/tempcommand && scp /tmp/tempcommand root@server1:/tmp && ssh server1 "sh -x /tmp/tempcommand && finger nagios && rm /tmp/tempcommand"
</code>```

In such cases I always prefer to have a local file on the local/remote server from which I execute the command set. Saves a lot of "quotes debugging time". What I am doing above is first to save the long one-liner to a file locally, "as is" and "as works" locally, copy it over with scp to the remote server and execute it there with the shell.
More secure way (no need to copy over the file). Again - save it locally and pass it to the remote bash with -s option :

```<code>echo "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios" > /tmp/tempcommand && echo finger nagios >> /tmp/tempcommand && ssh server1 'bash -s' < /tmp/tempcommand
</code>```

Body:
I'm trying to use an ssh command to ssh to a server and run theuseradd command I passed to it. It seems like its running ok for the most part (no errors produced) but the hashed password in the /etc/shadow file is missing the salt (I believe that's the portion that's missing.).

I'm not sure if the quoting that is incorrect or not. But running this command manually on the server works fine, so I'm assuming its the expansion that's messed up.?

The command below is running inside a Bash script...

Command:

ssh user@$host "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios"

*When I escape the double quotes inside the perl one-liner, I get the error:

Can't find string terminator '"' anywhere before EOF at -e line 1.

Usage: useradd [options] LOGIN

Any idea what I'm doing wrong here?

Body:
echo "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios" > /tmp/tempcommand && scp /tmp/tempcommand root@server1:/tmp && ssh server1 "sh -x /tmp/tempcommand && finger nagios && rm /tmp/tempcommand"

In such cases I always prefer to have a local file on the local/remote server from which I execute the command set. Saves a lot of "quotes debugging time". What I am doing above is first to save the long one-liner to a file locally, "as is" and "as works" locally, copy it over with scp to the remote server and execute it there with the shell.
More secure way (no need to copy over the file). Again - save it locally and pass it to the remote bash with -s option :

echo "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios" > /tmp/tempcommand && echo finger nagios >> /tmp/tempcommand && ssh server1 'bash -s' < /tmp/tempcommand


问:
How to clear the cache of nginx?
I use nginx to as the front server, I have modified the CSS files, but nginx is still serving the old ones.

I have tried to restart nginx, to no success and I have Googled, but not found a valid way to clear it.

Some articles say we can just delete the cache directory: var/cache/nginx, but there is no such directory on my server.

What should I do now?

答:
We have a very large nginx cache (gigabytes) that we occasionally need to wipe. I've worked out a script that instantly clears the cache (as far as Nginx is concerned) and then removes the cache directory without starving the main application for disk I/O.

In summary:

Move the cache folder to a new location (on the same filesystem!) (this doesn't disrupt any open file descriptors)

Recreate the original cache folder, empty

Reload Nginx (graceful reload, where nginx lets old workers finish in-progress requests)

Remove old cached data

Here's the script, tailored to Ubuntu 16.04 LTS, with the cache located at /mnt/nginx-cache:

```<code>#!/bin/bash
set -e

TMPCACHE=`mktemp --directory --tmpdir=/mnt nginx-cache-XXXXXXXXXX`
TMPTEMP=`mktemp --directory --tmpdir=/mnt nginx-temp-XXXXXXXXXX`

# Move the old cache folders out of the way
mv /mnt/nginx-cache $TMPCACHE
mkdir -p /mnt/nginx-cache
chmod -R 775 /mnt/nginx-cache
chown www-data:www-data /mnt/nginx-cache

mv /mnt/nginx-temp $TMPTEMP
mkdir -p /mnt/nginx-temp
chmod -R 775 /mnt/nginx-temp
chown www-data:www-data /mnt/nginx-temp

# Tell Nginx about the new folders.
service nginx reload

# Create an empty folder.
rm -rf /mnt/empty
mkdir -p /mnt/empty

# Remove the old cache and old temp folders w/o thrashing the disk...
# See http://serverfault.com/questions/546177/how-to-keep-subtree-removal-rm-rf-from-starving-other-processes-for-disk-i
# Note: the `ionice` and `nice` may not actually do much, but why not?
ionice -c 3 nice -19 rsync -a --delete /mnt/empty/ $TMPCACHE
ionice -c 3 nice -19 rsync -a --delete /mnt/empty/ $TMPTEMP
rm -rf $TMPCACHE
rm -rf $TMPTEMP

rm -rf /mnt/empty
</code>```

And in case it's helpful, here's the Nginx config we use:

```<code>upstream myapp {
    server localhost:1337 fail_timeout=0;
}

proxy_cache_path /mnt/nginx-cache/app levels=2:2:2 keys_zone=app_cache:100m inactive=1y max_size=10g;
proxy_temp_path  /mnt/nginx-temp/app;

server {
    listen   4316 default;
    server_name  myapp.com;

    location / {
        proxy_pass http://appserv;
        proxy_cache app_cache;
        proxy_cache_valid 200 1y;
        proxy_cache_valid 404 1m;
    }
}
</code>```

Title: How to clear the cache of nginx?

Body:
We have a very large nginx cache (gigabytes) that we occasionally need to wipe. I've worked out a script that instantly clears the cache (as far as Nginx is concerned) and then removes the cache directory without starving the main application for disk I/O.

In summary:

Move the cache folder to a new location (on the same filesystem!) (this doesn't disrupt any open file descriptors)

Recreate the original cache folder, empty

Reload Nginx (graceful reload, where nginx lets old workers finish in-progress requests)

Remove old cached data

Here's the script, tailored to Ubuntu 16.04 LTS, with the cache located at /mnt/nginx-cache:

#!/bin/bash
set -e

TMPCACHE=`mktemp --directory --tmpdir=/mnt nginx-cache-XXXXXXXXXX`
TMPTEMP=`mktemp --directory --tmpdir=/mnt nginx-temp-XXXXXXXXXX`

# Move the old cache folders out of the way
mv /mnt/nginx-cache $TMPCACHE
mkdir -p /mnt/nginx-cache
chmod -R 775 /mnt/nginx-cache
chown www-data:www-data /mnt/nginx-cache

mv /mnt/nginx-temp $TMPTEMP
mkdir -p /mnt/nginx-temp
chmod -R 775 /mnt/nginx-temp
chown www-data:www-data /mnt/nginx-temp

# Tell Nginx about the new folders.
service nginx reload

# Create an empty folder.
rm -rf /mnt/empty
mkdir -p /mnt/empty

# Remove the old cache and old temp folders w/o thrashing the disk...
# See http://serverfault.com/questions/546177/how-to-keep-subtree-removal-rm-rf-from-starving-other-processes-for-disk-i
# Note: the `ionice` and `nice` may not actually do much, but why not?
ionice -c 3 nice -19 rsync -a --delete /mnt/empty/ $TMPCACHE
ionice -c 3 nice -19 rsync -a --delete /mnt/empty/ $TMPTEMP
rm -rf $TMPCACHE
rm -rf $TMPTEMP

rm -rf /mnt/empty

And in case it's helpful, here's the Nginx config we use:

upstream myapp {
    server localhost:1337 fail_timeout=0;
}

proxy_cache_path /mnt/nginx-cache/app levels=2:2:2 keys_zone=app_cache:100m inactive=1y max_size=10g;
proxy_temp_path  /mnt/nginx-temp/app;

server {
    listen   4316 default;
    server_name  myapp.com;

    location / {
        proxy_pass http://appserv;
        proxy_cache app_cache;
        proxy_cache_valid 200 1y;
        proxy_cache_valid 404 1m;
    }
}


问:
Displaying correct information in cellForRowAt
I think I'm close, but seem to be confusing myself as I have access to all the data, but can't get it to behave.

I am trying to display a list of employees under their respective company (section) in a table in a table view.

My CoreData in respect to stored values and relationships is correct.  I know this by using print statements in various places.

Below is my code, but a summary of my issue relating to the cellForRowAt method is...

I can print a list of companies and their employees using print("Company - \(company.name!)  Employee - \(employee.name!)")

Company - Company1  Employee - Fred Smith

Company - Company1  Employee - Betty Boo

Company - Company2  Employee - GI Joe

Company - Company3  Employee - George Jungle

If I set cell.textLabel?.text = allCompanies[indexPath.section].name, I get the correct number of rows (based on employee.count per company) in each section, but it displays the the company name on each row per section

If I set cell.textLabel?.text = employee.name!, I only get the one employee returned across all rows.  The same employee in all sections.

CoreData Entities

Entity - Company

Attribute - name

Relationship - hasEmployee

Entity - Employee

Attribute - name

Relationship - hasCompany

```<code>var allCompanies: [Company] = []

func getCompanies() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Company")
    request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    request.returnsObjectsAsFaults = false

    do {
        allCompanies = try moc.fetch(request) as! [Company]
    } catch let err {
        print(err)
    }
}

//MARK: - Fetched Results
lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<Employee> in

    let fetchRequest: NSFetchRequest<Employee> = Employee.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
    frc.delegate = self
    return frc
}()

func attemptFetch() {

    do {
        try fetchedResultsController.performFetch()
    } catch let err {
        print(err)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell

    for company in allCompanies {
        for employee in company.hasEmployee?.allObjects as! [Employee] {

//                print("Company - \(company.name!)  Employee - \(employee.name!)")
//                cell.textLabel?.text = employee.name!
                cell.textLabel?.text = allCompanies[indexPath.section].name
            }
        }
        return cell
    }
</code>```

Any assistance would be greatly appreciated.  Thanks

答:
If you want to use the Company instances as section and the employees as rows you might write

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell

    let company = allCompanies[indexPath.section]
    let allEmployees = company.hasEmployee?.allObjects as! [Employee]
    let employee = allEmployees[indexPath.row]
    cell.textLabel?.text = employee.name
    return cell
 }

 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let company = allCompanies[section]
    return company.name
 }
</code>```

But I recommend to use the capabilities of NSFetchedResultsController to handle the sections.

PS: The naming hasEmployees for an array is confusing because usually the prefix has or is indicates a Bool. Just name it employees and declare the array (actually a set) as non-optional.

Body:
I think I'm close, but seem to be confusing myself as I have access to all the data, but can't get it to behave.

I am trying to display a list of employees under their respective company (section) in a table in a table view.

My CoreData in respect to stored values and relationships is correct.  I know this by using print statements in various places.

Below is my code, but a summary of my issue relating to the cellForRowAt method is...

I can print a list of companies and their employees using print("Company - \(company.name!)  Employee - \(employee.name!)")

Company - Company1  Employee - Fred Smith

Company - Company1  Employee - Betty Boo

Company - Company2  Employee - GI Joe

Company - Company3  Employee - George Jungle

If I set cell.textLabel?.text = allCompanies[indexPath.section].name, I get the correct number of rows (based on employee.count per company) in each section, but it displays the the company name on each row per section

If I set cell.textLabel?.text = employee.name!, I only get the one employee returned across all rows.  The same employee in all sections.

CoreData Entities

Entity - Company

Attribute - name

Relationship - hasEmployee

Entity - Employee

Attribute - name

Relationship - hasCompany

var allCompanies: [Company] = []

func getCompanies() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Company")
    request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    request.returnsObjectsAsFaults = false

    do {
        allCompanies = try moc.fetch(request) as! [Company]
    } catch let err {
        print(err)
    }
}

//MARK: - Fetched Results
lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<Employee> in

    let fetchRequest: NSFetchRequest<Employee> = Employee.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
    frc.delegate = self
    return frc
}()

func attemptFetch() {

    do {
        try fetchedResultsController.performFetch()
    } catch let err {
        print(err)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell

    for company in allCompanies {
        for employee in company.hasEmployee?.allObjects as! [Employee] {

//                print("Company - \(company.name!)  Employee - \(employee.name!)")
//                cell.textLabel?.text = employee.name!
                cell.textLabel?.text = allCompanies[indexPath.section].name
            }
        }
        return cell
    }

Any assistance would be greatly appreciated.  Thanks

Body:
If you want to use the Company instances as section and the employees as rows you might write

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell

    let company = allCompanies[indexPath.section]
    let allEmployees = company.hasEmployee?.allObjects as! [Employee]
    let employee = allEmployees[indexPath.row]
    cell.textLabel?.text = employee.name
    return cell
 }

 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let company = allCompanies[section]
    return company.name
 }

But I recommend to use the capabilities of NSFetchedResultsController to handle the sections.

PS: The naming hasEmployees for an array is confusing because usually the prefix has or is indicates a Bool. Just name it employees and declare the array (actually a set) as non-optional.


问:
Angular4/Javascript Date changing after Date constructor call with timezone
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

```<code>> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360
</code>```

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.

答:
Nothing is being changed. new Date('1990-03-31T23:00:00-06:00') is valid ISO 8601 so will be parsed correctly by modern browsers (but not older ones).

"Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)" represents the same moment in time as "1990-03-31T23:00:00-06:00", but in a different timezone. Your host system settings seem to have daylight saving for that date (given that your current offset is -0600), hence the different time zone.

Recent versions of ECMA-262 require implementations to apply historic timezone changes, there have been many changes over the years so you can't assume that the current rules always applied (which is what some versions of ECMA-262 required).

new Date().getTimezoneOffset()

Will return the host timezone offset for the current date and time, which may be different to the offset for a different date and time.

Why do you want to remove the timezone? The usual solution is to always use UTC and only use local values when presenting dates and times to users. There is not enough information on how you are using the date to know what will suit you best. Removing the timezone only works if everything should be in the same (host determined) timezone. Otherwise, you will run into issues.

And it will not solve having a different offset during daylight saving.

Note also that some browsers have parsing bugs (e.g. Safari), so removing the timezone (i.e. "1990-03-31T23:00:00") will mean that the string is treated as UTC, not local.

Body:
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.


问:
How to overcome app not installed error when building from Android Studio 3.0?
For giving build for a debug Android app from Android Studio 3.0, it’s not installing in Mobile having Marshmallow and up (in Lollipop not tested).

I have used many solutions from Stack overflow but it’s still not working.

It’s always showing App Not Installed on mobile phone.

答:
Well the original question doesn´t have enough information, but we can have some info getting some comments:

Android studio 3.0 and compileSdkVersion 26, buildToolsVersion '26.0.2',minSdkVersion 15, targetSdkVersion 26

virtual debugging option also on.

I am facing same issue after upgrading android studio from 2.3 to 3.0

Ok the message "App Not Installed" will refer to multiple causes, and please returning to Android Studio 2.3. from 3.0 is not an option!

When we upgrade from Android Studio 2.3 to 3.0  we can find some configuration issues caused mainly by the support libraries, that will cause that our application could not be installed.

To avoid this problem we need to invalidate cache in Android Studio 3.0+ and the problem will be solved.

Please try this option.


问:
Getting database for Cassandra or building one from scratch?
So, I'm new to Cassandra and I was wondering what the best approach would be to learn Cassandra.

Should I first focus on the design of a database and build one from scratch?
And as I was reading that Cassandra is great for writing. How can one observe that? Is there open source data that one can use? (I didn't really know where to look.)

答:
A good point getting started with Cassandra are the free online courses from DataStax (an enterprise grade Cassandra distribution): https://academy.datastax.com/courses

And for Cassandra beeing good at writing data - have a look here: https://docs.datastax.com/en/cassandra/3.0/cassandra/dml/dmlHowDataWritten.html

The write path comes down to these points:

write the data into the commitlog (append only sequentially, no random io - therefore should be on its own disk to prevent head movements, with ssd no issue)

write the data into memtables (kept in memory - very fast)

So in terms of disk, a write is a simple append to the commitlog in the first place. No data is directly written to the sstables (it's in the commitlog and memtable, which becomes flushed to disk at times as sstables), updates are not changing an sstable on disk (sstables are immutable, an update is written separately with a new timestamp), a delete does not remove data from sstables (sstables are immutable - instead a tombstone is written).

All updates and deletes produce new entries in memtable and sstables, to remove deleted data and to get rid of old versions of data from updates sstables on disk are compacted from time to time into a new one.

Also read about the different compaction strategies (can help you provide good performance), replication factor (how many copies of your data the cluster should keep) and consistency levels (how Cassandra should determine when a write or read is successful, hint: ALL is almost wrong all the time, look for QUORUM).


问:
Pandas Resample on Date Columns
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

```<code>import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])
</code>```

Desired Output:

```<code>   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5
</code>```

答:
```<code>import pandas as pd

list=df.columns
df_new = pd.DataFrame()

for i in range(int(0.5*len(list))):
    df_new[list[2*i]] = (df[[list[2*i], list[2*i+1]]].mean(axis=1))
</code>```

Output

```<code>       2013-01-01  2013-02-03
A         1.5         3.5
B         5.5         7.5
</code>```

I dont understand your Desired Output:

Title: Pandas Resample on Date Columns

Body:
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])

Desired Output:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5

Body:
import pandas as pd

list=df.columns
df_new = pd.DataFrame()

for i in range(int(0.5*len(list))):
    df_new[list[2*i]] = (df[[list[2*i], list[2*i+1]]].mean(axis=1))

Output

       2013-01-01  2013-02-03
A         1.5         3.5
B         5.5         7.5

I dont understand your Desired Output:


问:
Building Opencv using cmake giving errors involving c++11
I am facing problem with the cmake command while compiling opencv on Ubuntu 16.04. When I execute the cmake command, I get the error

CMake Error at CMakeLists.txt:11 (message):
FATAL: In-source builds are not allowed.
You should create a separate directory for build files.

I have extracted the opencv source file in a folder named opencv-3.3.1
Then I have followed all the processes mentioned in this site

https://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

I use the following commands ::

cd opencv-3.3.1/
mkdir build/
cd build/
cmake -D CMA
KE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.1/modules -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON ..

But I am getting this error!

What can be the possible problem?

The CMakeError.log shows

error "C++11 is not supported

I have tried adding set(CMAKE_CXX_FLAGS "-std=c++11") to the beginning of the CMakeLists.txt and also included the flag -DENABLE_CXX11=ON to the CMAKE command flags. But nothing seems to work.

Please help!!

答:
Try adding:

```<code>add_definitions(-std=c++11)
</code>```

to your cmakelists file.

Body:
Try adding:

add_definitions(-std=c++11)

to your cmakelists file.


问:
Troubles with gitlab scraping via golang
I'm newbie in programming and I need help. Trying to write gitlab scraper on golang.
Something goes wrong when i'm trying to get information about projects in multithreading mode.

Here is the code:

```<code>func (g *Gitlab) getAPIResponce(url string, structure interface{}) error {
    responce, responce_error := http.Get(url)
    if responce_error != nil {
        return responce_error
    }
    ret, _ := ioutil.ReadAll(responce.Body)
    if string(ret) != "[]" {
        err := json.Unmarshal(ret, structure)
        return err
    }
    return errors.New(error_emptypage)
}

...

func (g *Gitlab) GetProjects() {
    projects_chan := make(chan Project, g.LatestProjectID)
    var waitGroup sync.WaitGroup
    queue := make(chan struct{}, 50)
    for i := g.LatestProjectID; i > 0; i-- {
        url := g.BaseURL + projects_url + "/" + strconv.Itoa(i) + g.Token
        waitGroup.Add(1)
        go func(url string, channel chan Project) {
            queue <- struct{}{}
            defer waitGroup.Done()

            var oneProject Project
            err := g.getAPIResponce(url, &oneProject)
            if err != nil {
                fmt.Println(err.Error())
            }

            fmt.Printf(".")
            channel <- oneProject
            <-queue
        }(url, projects_chan)
    }

    go func() {
        waitGroup.Wait()
        close(projects_chan)
    }()

    for project := range projects_chan {
        if project.ID != 0 {
            g.Projects = append(g.Projects, project)
        }
    }
}
</code>```

And here is the output:

```<code>$ ./gitlab-auditor
latest project = 1532
Gathering projects...
.......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................Get https://gitlab.example.com/api/v4/projects/563&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/558&private_token=SeCrEt_ToKeN: unexpected EOF
..Get https://gitlab.example.com/api/v4/projects/531&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/571&private_token=SeCrEt_ToKeN: unexpected EOF
.Get https://gitlab.example.com/api/v4/projects/570&private_token=SeCrEt_ToKeN: unexpected EOF
..Get https://gitlab.example.com/api/v4/projects/467&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/573&private_token=SeCrEt_ToKeN: unexpected EOF
................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
</code>```

Every time it's different projects, but it's id is around 550.

When I'm trying to curl links from output, i'm getting normal JSON. When I'm trying to run this code with queue := make(chan struct{}, 1) (in single thread) - everything is fine.

What can it be?

答:
i would say this not a very clear way to achieve concurrency.
what seems to be happening here is

you create a buffered channel that has a size of 50.

then you fire up 1532 goroutines

the first 50 of them enqueue themselves and start processing. by the time they <-queue and free up somespace a random one from the next manages to get on the queue.

as people say in the comments most certainly you hit some limits around the time it the blast has made it around id 550. Then gitlab's API is angry at you and rate limits.

then another goroutine is fired that will close the channel to notify the main goroutine

the main goroutine reads messages.

the talk go concurrency patterns
as well as this blog post concurrency in go might help.
personally i rarely use buffered channels. for your problem i would go like:

define a number of workers

have the main goroutine fire up the workers with a func listening on a channel of ints , doing the api call, writing to a channel of projects

have the main goroutine send to a channel of ints the project number to be fetched and read from the channel of projects.

maybe ratelimit by firing a ticker and have main read from it before it sends the next request?

main closes the number channel to notify the others to die.

Body:
I'm newbie in programming and I need help. Trying to write gitlab scraper on golang.
Something goes wrong when i'm trying to get information about projects in multithreading mode.

Here is the code:

func (g *Gitlab) getAPIResponce(url string, structure interface{}) error {
    responce, responce_error := http.Get(url)
    if responce_error != nil {
        return responce_error
    }
    ret, _ := ioutil.ReadAll(responce.Body)
    if string(ret) != "[]" {
        err := json.Unmarshal(ret, structure)
        return err
    }
    return errors.New(error_emptypage)
}

...

func (g *Gitlab) GetProjects() {
    projects_chan := make(chan Project, g.LatestProjectID)
    var waitGroup sync.WaitGroup
    queue := make(chan struct{}, 50)
    for i := g.LatestProjectID; i > 0; i-- {
        url := g.BaseURL + projects_url + "/" + strconv.Itoa(i) + g.Token
        waitGroup.Add(1)
        go func(url string, channel chan Project) {
            queue <- struct{}{}
            defer waitGroup.Done()

            var oneProject Project
            err := g.getAPIResponce(url, &oneProject)
            if err != nil {
                fmt.Println(err.Error())
            }

            fmt.Printf(".")
            channel <- oneProject
            <-queue
        }(url, projects_chan)
    }

    go func() {
        waitGroup.Wait()
        close(projects_chan)
    }()

    for project := range projects_chan {
        if project.ID != 0 {
            g.Projects = append(g.Projects, project)
        }
    }
}

And here is the output:

$ ./gitlab-auditor
latest project = 1532
Gathering projects...
.......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................Get https://gitlab.example.com/api/v4/projects/563&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/558&private_token=SeCrEt_ToKeN: unexpected EOF
..Get https://gitlab.example.com/api/v4/projects/531&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/571&private_token=SeCrEt_ToKeN: unexpected EOF
.Get https://gitlab.example.com/api/v4/projects/570&private_token=SeCrEt_ToKeN: unexpected EOF
..Get https://gitlab.example.com/api/v4/projects/467&private_token=SeCrEt_ToKeN: unexpected EOF
Get https://gitlab.example.com/api/v4/projects/573&private_token=SeCrEt_ToKeN: unexpected EOF
................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................

Every time it's different projects, but it's id is around 550.

When I'm trying to curl links from output, i'm getting normal JSON. When I'm trying to run this code with queue := make(chan struct{}, 1) (in single thread) - everything is fine.

What can it be?


问:
C string arrays
I just wrote a string splitting function:

```<code>typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}
</code>```

Example:

```<code>char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);
</code>```

should output:

```<code>component: aaa
component: c
component: ddddee
component: k
</code>```

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

```<code>int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}
</code>```

答:
First of all it is more correct to use for(int i = 0; i < stringLength; i++), but it shouldn't be a big mistake in your case.

If you want to return an array of char * you should pass char *** result and assign
*result = (char**) malloc(...).

I do not see where you saving component pointer into your result array

I think it is better to use strdup or strcpy to copy strings

Title: C string arrays

Body:
I just wrote a string splitting function:

typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}

Example:

char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);

should output:

component: aaa
component: c
component: ddddee
component: k

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}


问:
Windows Forms C# - Make DataGridView push down other controls as rows are added
I have a handful of different DGV's that all need to be displayed on the same tab in my form. Sometimes the forms will have nothing added to them, others will have many rows added to them.  I have tried using a TableLayoutPanel, a FlowLayoutPanel, and a regular Panel to hold all my containers/controls, and have tried various settings of "Dock: Fill; Dock: Top" and "Grow: True" but I cannot seem to find the right combination of controls and properties.

I am about to resort to trying to handle this programatically, but if I could handle exclusively in properties that would be great.

答:
My resolution was to use a TableLayoutPanel, and programmatically grow each DGV as rows are added, which will force the panel that is containing the DGV to grow and push down the following cells.

My C# code for those who would really like to see it (haha):

```<code>    private void AddFeature_Click(object sender, EventArgs e)
    {
        presenter.AddFeature_Click();
        presenter.GrowDataGridView(FeatureGridView);
    }
</code>```

```<code>    public void AddFeature_Click()
    {
        if (view.BindingSource == null)
        {
            return;
        }

        AddFeatureRow((DataTable)(view.BindingSource.DataSource));

    }
</code>```

```<code>    public void GrowDataGridView(DataGridView dgv)
    {
        dgv.Height += 22;
    }
</code>```

Body:
My resolution was to use a TableLayoutPanel, and programmatically grow each DGV as rows are added, which will force the panel that is containing the DGV to grow and push down the following cells.

My C# code for those who would really like to see it (haha):

    private void AddFeature_Click(object sender, EventArgs e)
    {
        presenter.AddFeature_Click();
        presenter.GrowDataGridView(FeatureGridView);
    }

    public void AddFeature_Click()
    {
        if (view.BindingSource == null)
        {
            return;
        }

        AddFeatureRow((DataTable)(view.BindingSource.DataSource));

    }

    public void GrowDataGridView(DataGridView dgv)
    {
        dgv.Height += 22;
    }


问:
Detect when no buttons are being pushed PyQt
I have a GUI that is controlling a device over USB.
The way I have it set up is with basically two buttons, forward and back, and while the button is pressed that function is transmitted to the motor, when the button is released, the off signal is triggered once.

```<code>    def on_release():
        print('Off')
        self.off()

    def on_click():
        print('forward')
        self.forward()
    button = QPushButton('Cut', self)
    button.move(100,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)

    def on_click():
        print('back')
        self.back()
    button = QPushButton('back', self)
    button.move(200,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)
</code>```

I've recently encountered an interesting failure mode where if the USB connection is paused (in my case I was using GDB and hit a breakpoint, released the button, then released the breakpoint) at the moment the button is released, the kill signal is never sent and the motor will continue going back or forward forever. (It can be killed by either clicking one of back or forward and releasing, or by killing USB entirely")

I already have protections in place (a threaded heartbeat signal) for turning off the motor in the condition that a USB connection is severed but I'd like to make this fail a little more safely in case that one particular USB off transmission were to fail.

Is there a way for me to check if no buttons are pressed so I can use this to trigger the off signal?

答:
Learning material from tjmarkham stepper.py script at [https://github.com/tjmarkham/python-stepper] for a raspberry Pi which can be put behind your buttons:

```<code>#CURRENT APPLICATION INFO
#200 steps/rev
#12V, 350mA
#Big Easy driver = 1/16 microstep mode
#Turn a 200 step motor left one full revolution: 3200

from time import sleep
import RPi.GPIO as gpio #https://pypi.python.org/pypi/RPi.GPIO
#import exitHandler #uncomment this and line 58 if using exitHandler

class stepper:
    #instantiate stepper
    #pins = [stepPin, directionPin, enablePin]
    def __init__(self, pins):
        #setup pins
        self.pins = pins
        self.stepPin = self.pins[0]
        self.directionPin = self.pins[1]
        self.enablePin = self.pins[2]

        #use the broadcom layout for the gpio
        gpio.setmode(gpio.BCM)

        #set gpio pins
        gpio.setup(self.stepPin, gpio.OUT)
        gpio.setup(self.directionPin, gpio.OUT)
        gpio.setup(self.enablePin, gpio.OUT)

        #set enable to high (i.e. power is NOT going to the motor)
        gpio.output(self.enablePin, True)

        print("Stepper initialized (step=" + self.stepPin + ", direction=" + self.directionPin + ", enable=" + self.enablePin + ")")

    #clears GPIO settings
    def cleanGPIO(self):
        gpio.cleanup()

    #step the motor
    # steps = number of steps to take
    # dir = direction stepper will move
    # speed = defines the denominator in the waitTime equation: waitTime = 0.000001/speed. As "speed" is increased, the waitTime between steps is lowered
# stayOn = defines whether or not stepper should stay "on" or not. If stepper will need to receive a new step command immediately, this should be set to "True." Otherwise, it should remain at "False."

    def step(self, steps, dir, speed=1, stayOn=False):
        #set enable to low (i.e. power IS going to the motor)
        gpio.output(self.enablePin, False)

        #set the output to true for left and false for right
        turnLeft = True
        if (dir == 'right'):
            turnLeft = False;
        elif (dir != 'left'):
            print("STEPPER ERROR: no direction supplied")
            return False
        gpio.output(self.directionPin, turnLeft)

        stepCounter = 0

        waitTime = 0.000001/speed #waitTime controls speed

        while stepCounter < steps:
            #gracefully exit if ctr-c is pressed
            #exitHandler.exitPoint(True) #exitHandler.exitPoint(True, cleanGPIO)

            #turning the gpio on and off tells the easy driver to take one step
            gpio.output(self.stepPin, True)
            gpio.output(self.stepPin, False)
            stepCounter += 1

            #wait before taking the next step thus controlling rotation speed
            sleep(waitTime)

        if (stayOn == False):
            #set enable to high (i.e. power is NOT going to the motor)
            gpio.output(self.enablePin, True)

print("stepperDriver complete (turned " + dir + " " + str(steps) + " steps)")
</code>```

teststepper.py:

```<code>from Stepper import Stepper

#stepper variables
#[stepPin, directionPin, enablePin]
testStepper = Stepper([22, 17, 23])

#test stepper
testStepper.step(3200, "right"); #steps, dir, speed, stayOn
</code>```

Body:
I have a GUI that is controlling a device over USB.
The way I have it set up is with basically two buttons, forward and back, and while the button is pressed that function is transmitted to the motor, when the button is released, the off signal is triggered once.

    def on_release():
        print('Off')
        self.off()

    def on_click():
        print('forward')
        self.forward()
    button = QPushButton('Cut', self)
    button.move(100,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)

    def on_click():
        print('back')
        self.back()
    button = QPushButton('back', self)
    button.move(200,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)

I've recently encountered an interesting failure mode where if the USB connection is paused (in my case I was using GDB and hit a breakpoint, released the button, then released the breakpoint) at the moment the button is released, the kill signal is never sent and the motor will continue going back or forward forever. (It can be killed by either clicking one of back or forward and releasing, or by killing USB entirely")

I already have protections in place (a threaded heartbeat signal) for turning off the motor in the condition that a USB connection is severed but I'd like to make this fail a little more safely in case that one particular USB off transmission were to fail.

Is there a way for me to check if no buttons are pressed so I can use this to trigger the off signal?

Body:
Learning material from tjmarkham stepper.py script at [https://github.com/tjmarkham/python-stepper] for a raspberry Pi which can be put behind your buttons:

#CURRENT APPLICATION INFO
#200 steps/rev
#12V, 350mA
#Big Easy driver = 1/16 microstep mode
#Turn a 200 step motor left one full revolution: 3200

from time import sleep
import RPi.GPIO as gpio #https://pypi.python.org/pypi/RPi.GPIO
#import exitHandler #uncomment this and line 58 if using exitHandler

class stepper:
    #instantiate stepper
    #pins = [stepPin, directionPin, enablePin]
    def __init__(self, pins):
        #setup pins
        self.pins = pins
        self.stepPin = self.pins[0]
        self.directionPin = self.pins[1]
        self.enablePin = self.pins[2]

        #use the broadcom layout for the gpio
        gpio.setmode(gpio.BCM)

        #set gpio pins
        gpio.setup(self.stepPin, gpio.OUT)
        gpio.setup(self.directionPin, gpio.OUT)
        gpio.setup(self.enablePin, gpio.OUT)

        #set enable to high (i.e. power is NOT going to the motor)
        gpio.output(self.enablePin, True)

        print("Stepper initialized (step=" + self.stepPin + ", direction=" + self.directionPin + ", enable=" + self.enablePin + ")")

    #clears GPIO settings
    def cleanGPIO(self):
        gpio.cleanup()

    #step the motor
    # steps = number of steps to take
    # dir = direction stepper will move
    # speed = defines the denominator in the waitTime equation: waitTime = 0.000001/speed. As "speed" is increased, the waitTime between steps is lowered
# stayOn = defines whether or not stepper should stay "on" or not. If stepper will need to receive a new step command immediately, this should be set to "True." Otherwise, it should remain at "False."

    def step(self, steps, dir, speed=1, stayOn=False):
        #set enable to low (i.e. power IS going to the motor)
        gpio.output(self.enablePin, False)

        #set the output to true for left and false for right
        turnLeft = True
        if (dir == 'right'):
            turnLeft = False;
        elif (dir != 'left'):
            print("STEPPER ERROR: no direction supplied")
            return False
        gpio.output(self.directionPin, turnLeft)

        stepCounter = 0

        waitTime = 0.000001/speed #waitTime controls speed

        while stepCounter < steps:
            #gracefully exit if ctr-c is pressed
            #exitHandler.exitPoint(True) #exitHandler.exitPoint(True, cleanGPIO)

            #turning the gpio on and off tells the easy driver to take one step
            gpio.output(self.stepPin, True)
            gpio.output(self.stepPin, False)
            stepCounter += 1

            #wait before taking the next step thus controlling rotation speed
            sleep(waitTime)

        if (stayOn == False):
            #set enable to high (i.e. power is NOT going to the motor)
            gpio.output(self.enablePin, True)

print("stepperDriver complete (turned " + dir + " " + str(steps) + " steps)")

teststepper.py:

from Stepper import Stepper

#stepper variables
#[stepPin, directionPin, enablePin]
testStepper = Stepper([22, 17, 23])

#test stepper
testStepper.step(3200, "right"); #steps, dir, speed, stayOn


问:
Hovering a decluttered label in open layers
I've recently used the declutter feature for labels in openlayers 4.5 and it works great. However, the hover event I have still fires when a "decluttered" label is moused over. Is there a way I can tell if a label has been turned off by decluttering? I can't seem to find a property or setting that has changed.</p>

答: There was a bug, which was solved with the version 4.6.0 that was released yesterday. Just upgrade to the latest OpenLayers version.</p>


问:
How can I combine two excel columns during import to a database?

I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

```<code>Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using
</code>```

答: The way I got around this was by using excel actual formula of CONCATENATE. You can either put it in your code or in the spreadsheet add a new column and call the value of that cell.</p>

Body:
I am trying to combine a date and time columns in excel and map it to one column in a database using sqlbulkcopy. I am getting an error:

Date][time does not match any column mapping

See my sample code below. Any ideas on how to accomplish this without copying it to a Datatable?

Dim sSourceConstr As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath)

Dim sDestConstr As String = ConfigurationManager.ConnectionStrings("SolCards").ConnectionString
Dim sSourceConnection As New OleDbConnection(sSourceConstr)
Using sSourceConnection
    Dim sql As String = String.Format("Select [Customer Cod],[Customer],[PAN],[Vehicle],[Date],[Station],[Driver],[Authorized],[Product]" &
                                          ", [Pump], [Tran No], [Odo], [Metric], [UPrice], [Qty], [Amount], [TimeFormat] FROM [{0}$]", "trans")
    Dim command As New OleDbCommand(sql, sSourceConnection)

    sSourceConnection.Open()
    Using dr As OleDbDataReader = command.ExecuteReader()
        Using bulkCopy As New SqlBulkCopy(sDestConstr)
            bulkCopy.DestinationTableName = "FuelInformation"
            'column mapping

          bulkCopy.ColumnMappings.Add("[Date] [Time]", "DatePurchased")

            bulkCopy.WriteToServer(dr)
        End Using
    End Using
End Using


问:
Logical operator with different types
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}```

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

答:
Use let to fix the output's scope:

for (var num = 1; num <= 100; num++) {
  let output;
  if (num % 5 === 0 && num % 3 === 0) {
    output = "FizzBuzz";
  } else if (num % 5 === 0) {
    output = "Buzz";
  } else if (num % 3 === 0) {
    output = "Fizz";
  }
  console.log(output || num);
}```
</div>
</div>
</p>

<hr>

<p>Also, the <code>||</code> could be removed if you initialize <code>output</code> with <code>num</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var num = 1; num <= 100; num++) {
  let output = num;
  if (num % 5 === 0 && num % 3 === 0) {
    output = "FizzBuzz";
  } else if (num % 5 === 0) {
    output = "Buzz";
  } else if (num % 3 === 0) {
    output = "Fizz";
  }
  console.log(output);
}</code>```

Title: Logical operator with different types

Body:
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

Body:
Use let to fix the output's scope:

for (var num = 1; num <= 100; num++) {
  let output;
  if (num % 5 === 0 && num % 3 === 0) {
    output = "FizzBuzz";
  } else if (num % 5 === 0) {
    output = "Buzz";
  } else if (num % 3 === 0) {
    output = "Fizz";
  }
  console.log(output || num);
}

Also, the || could be removed if you initialize output with num:

for (var num = 1; num <= 100; num++) {
  let output = num;
  if (num % 5 === 0 && num % 3 === 0) {
    output = "FizzBuzz";
  } else if (num % 5 === 0) {
    output = "Buzz";
  } else if (num % 3 === 0) {
    output = "Fizz";
  }
  console.log(output);
}


问:
Multiple File Exists Checking? A Better way?
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

```<code>if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}
</code>```

There has to be a better way than this... anyone have any ideas?

答:
Okay... this is what I finalized on:</p>

```<code>$searches = array(
    $folder . "nodes/" . $node . ".png",
    $folder . "nodes/" . $node . ".jpg",
    $folder . "nodes/" . $node . ".gif",
    $folder . "users/" . $user . ".png",
    $folder . "users/" . $user . ".jpg",
    $folder . "users/" . $user . ".gif"
);

foreach ($searches AS $search)
{
    if (file_exists($search))
    {
        $img = $search;
        break;
    }
}

if (!$img)
{
    random image generator script...
}
</code>```

Body:
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}

There has to be a better way than this... anyone have any ideas?

Body:
Okay... this is what I finalized on:

$searches = array(
    $folder . "nodes/" . $node . ".png",
    $folder . "nodes/" . $node . ".jpg",
    $folder . "nodes/" . $node . ".gif",
    $folder . "users/" . $user . ".png",
    $folder . "users/" . $user . ".jpg",
    $folder . "users/" . $user . ".gif"
);

foreach ($searches AS $search)
{
    if (file_exists($search))
    {
        $img = $search;
        break;
    }
}

if (!$img)
{
    random image generator script...
}


问:
Running Multiple Scripts from Startup Folder on Windows 7
Wondering if anyone can shed light on this issue I am having.

I have two python scripts which I want to run when anyone logs into the computer. I have added the scripts to the Startup folder for all users. When I log in the scripts should run with pythonw.exe, both scripts have the pyw extension.

When I log in to my own account, it will only start one script. When I log in to a guest account both scripts start fine.

I have checked AV and the script is not being blocked. Both files access a txt file on the C: drive. I have ensured all users have permissions to access the files.

I can run the second script manually and it works as expected but cannot figure out why it will not run at startup on the admin account.

答: Well thanks for the tip about adding the shebang line. I now know what the issue was. I had python2.7 installed also and the scripts were trying to start with this instead of 3.6. The guest account had the files associatted correctly, that why it worked. All good now. Thanks guys.</p>


答:
For Oracle 11g and above you can use LISTAGG (Oracle Doc.) as follow :

```<code>SELECT cd.id,
       cd.name,
       cd.dob,
       LISTAGG(cc1.codes ,'#') WITHIN GROUP (ORDER BY cd.id) AS "Codes Table1",
       LISTAGG(cc2.codes ,'#') WITHIN GROUP (ORDER BY cd.id) AS "Codes Table2"
  FROM CustomerDetails cd,
       CustomersCode1 cc1,
       CustomersCode2 cc2
 WHERE cd.id = cc1.id (+)
   AND cd.id = cc2.id (+);
</code>```

Title: Manipulating resultsets in sql

Body:
I'm trying to achieve the below result in the target table by querying data from three source tables.

Expected Target Table result:

ID  Name    DOB       Codes Table1   Codes Table2
=================================================
A1  Bob   29-8-1972     2#5#8#3       5#8#4#2
-----------------------------------------------
A2  Tim   10/2/1954     4#3#7          1#7#5
-------------------------------------------------

Sources Tables:

CustomerDetails Table

ID  Name    DOB
=========================
A1  Bob    29/08/1972
-------------------------
A2  Tim    10/2/1954
-------------------------

Customer Codes 1

ID  Codes Table1
=================
A1  2
-----------
A1  5
----------------
A1  8
-------------
A1  3
----------
A2  4
--------------
A2  3
-------------
A2  7
-------------

Customer Codes Table 2

ID  Codes Table2
===================
A1  5
--------------
A1  8
--------------
A1  4
-------------
A1  2
--------------
A2  1
--------------
A2  7
---------------
A2  5
----------------

What is the best way to code this over millions of records?

Body:
For Oracle 11g and above you can use LISTAGG (Oracle Doc.) as follow :

SELECT cd.id,
       cd.name,
       cd.dob,
       LISTAGG(cc1.codes ,'#') WITHIN GROUP (ORDER BY cd.id) AS "Codes Table1",
       LISTAGG(cc2.codes ,'#') WITHIN GROUP (ORDER BY cd.id) AS "Codes Table2"
  FROM CustomerDetails cd,
       CustomersCode1 cc1,
       CustomersCode2 cc2
 WHERE cd.id = cc1.id (+)
   AND cd.id = cc2.id (+);