问:
.htaccess, hide sub directories
I am new to learning how .htaccess works and I am struggling on getting it to work how I want it to.

Here is my current .htaccess file:

```<code>RewriteOptions inherit

#ErrorDocument 404 https://tsrvtc.com/_pages/404page.html
#ErrorDocument 500 https://tsrvtc.com/_pages/500page.html
#ErrorDocument 403 https://tsrvtc.com/_pages/403page.html

<IfModule mod_rewrite.c>
RewriteBase /
RewriteEngine on

RedirectMatch 301 ^/?$ https://www.tsrvtc.com/index

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+_pages/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^_pages/)^(.*)$ /_pages/$1 [L,NC]
#
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+vtc_manager/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^vtc_manager/)^(.*)$ /vtc_manager/$1 [L,NC]

RewriteCond %{HTTP_HOST} ^tsrvtc\.com$ [NC]
RewriteRule ^(.*)$ http://www.tsrvtc.com/$1 [R=301,L]

</IfModule>
AuthName "public"
AuthUserFile "/home/tsrvtcco/.htpasswds/public_html/passwd"
</code>```

It currently works hiding the _pages directory in the url but when I try to hide the vtc_managerm directory then goto the page within that directory it redirects to my domain name and puts index.php at the end. The I am given this error: https://gyazo.com/0cc504188657beafd2042d6332e4bd9b

Here is the layout of the directories:

```<code>public_html
  _pages
  vtc_manager
</code>```

Any assistance will be greatly appreciated.

答:
The error due to misconfigured .htaccess. When you try to dig into it, the apache log shows this error:

Request exceeded the limit of 10 internal redirects due to probable
  configuration error. Use 'LimitInternalRecursion' to increase the
  limit if necessary. Use 'LogLevel debug' to get a backtrace.

You were making infinite redirects, by these conditions and rules:

```<code>1. RewriteCond %{REQUEST_FILENAME} !-f
2. RewriteRule (?!^_pages/)^(.*)$ /_pages/$1 [L,NC]

3. RewriteCond %{REQUEST_FILENAME} !-f
4. RewriteRule (?!^vtc_manager/)^(.*)$ /vtc_manager/$1 [L,NC]
</code>```

When you made a request / and file is not found in the root directory, then the first condition (1.) meets and rule meets. The request uri is rewritten to /_pages/. The rewritten request is handled, then handed back to the URL parsing engine again. The second attempt, the first condition (1.) meets, but the rule pattern (2.) does not meet. However, the second condition (3.) meets and rule (4.) meets. The request uri is then rewritten to /vtc_manager/_pages/. Then rewritten request is handled and so on.

You should fully read the documentation of mod_rewrite module and RewriteRule Flags to understand what you are trying to do.

Title: .htaccess, hide sub directories

Body:
I am new to learning how .htaccess works and I am struggling on getting it to work how I want it to.

Here is my current .htaccess file:

RewriteOptions inherit

#ErrorDocument 404 https://tsrvtc.com/_pages/404page.html
#ErrorDocument 500 https://tsrvtc.com/_pages/500page.html
#ErrorDocument 403 https://tsrvtc.com/_pages/403page.html

<IfModule mod_rewrite.c>
RewriteBase /
RewriteEngine on

RedirectMatch 301 ^/?$ https://www.tsrvtc.com/index

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+_pages/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^_pages/)^(.*)$ /_pages/$1 [L,NC]
#
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+vtc_manager/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^vtc_manager/)^(.*)$ /vtc_manager/$1 [L,NC]

RewriteCond %{HTTP_HOST} ^tsrvtc\.com$ [NC]
RewriteRule ^(.*)$ http://www.tsrvtc.com/$1 [R=301,L]

</IfModule>
AuthName "public"
AuthUserFile "/home/tsrvtcco/.htpasswds/public_html/passwd"

It currently works hiding the _pages directory in the url but when I try to hide the vtc_managerm directory then goto the page within that directory it redirects to my domain name and puts index.php at the end. The I am given this error: https://gyazo.com/0cc504188657beafd2042d6332e4bd9b

Here is the layout of the directories:

public_html
  _pages
  vtc_manager

Any assistance will be greatly appreciated.

Body:
The error due to misconfigured .htaccess. When you try to dig into it, the apache log shows this error:

Request exceeded the limit of 10 internal redirects due to probable
  configuration error. Use 'LimitInternalRecursion' to increase the
  limit if necessary. Use 'LogLevel debug' to get a backtrace.

You were making infinite redirects, by these conditions and rules:

1. RewriteCond %{REQUEST_FILENAME} !-f
2. RewriteRule (?!^_pages/)^(.*)$ /_pages/$1 [L,NC]

3. RewriteCond %{REQUEST_FILENAME} !-f
4. RewriteRule (?!^vtc_manager/)^(.*)$ /vtc_manager/$1 [L,NC]

When you made a request / and file is not found in the root directory, then the first condition (1.) meets and rule meets. The request uri is rewritten to /_pages/. The rewritten request is handled, then handed back to the URL parsing engine again. The second attempt, the first condition (1.) meets, but the rule pattern (2.) does not meet. However, the second condition (3.) meets and rule (4.) meets. The request uri is then rewritten to /vtc_manager/_pages/. Then rewritten request is handled and so on.

You should fully read the documentation of mod_rewrite module and RewriteRule Flags to understand what you are trying to do.


来源: stackexchange

问:
Storing channels' data in Go
Can we store and retrieve data from a channel?

For instance, can I store c, in the code below, somewhere?

```<code>package main

    import (
        "fmt"
    )

    func main() {

        c := make(chan int)

        go func(){

            c <- 42
        }()
        fmt.Println(<-c)
    }
</code>```

答:
You can store it anywhere you like but channels are only a method for passing information within a Go program. Where the data comes from and what you do with it is entirely up to you.

I strongly recommend going through the Go tour, and specifically here for channels.

ContentLicense: CC BY-SA 3.0

Title: Storing channels' data in Go

Body:
Can we store and retrieve data from a channel?

For instance, can I store c, in the code below, somewhere?

package main

    import (
        "fmt"
    )

    func main() {

        c := make(chan int)

        go func(){

            c <- 42
        }()
        fmt.Println(<-c)
    }


问:
Why does heading stay "null" for geolocation on android with chrome
Well I create a small geolocation watch with:

```<code>navigator.geolocation.watchPosition(
    this.updateLocation.bind(this),
    this.errorLocation.bind(this),
    {enableHighAccuracy: true}
);
</code>```

where updateLocation is defined as:

```<code>private updateLocation(position: Position) {
    this.myLatitude = position.coords.latitude;
    this.myLongitude = position.coords.longitude;
    this.myAccuracy = position.coords.accuracy;
    if (position.coords.heading != null) {
        this.myHeading = Game.toRad(position.coords.heading);
    }
    this.GPSWorking = true;
}
</code>```

Now this code is "working", I see it updating gps data and the accuracy is as expected. - There is just one "but": the heading is always "null". I could expect this when on pc, or even when not having enabled high accuracy.

yet in all settings I tried it gives "null".

I know my mobile phone has a working gyroscope: I can actually get the heading in native android apps. - I also notice that google maps (website, through chrome) is capable of determining my heading; so there must be something I did wrong?

A small fiddle so people could test it: https://jsfiddle.net/8p5rngtk/15/ - I'm only interested in the heading (though rest is there to show gps is working on a device).

Edit:

Well, it "just" started working like expected. (perfectly well), the only thing I still notice is that the update frequency is way slower than when I wrote it as native application - so slow that I can't depend on it for my application.

Anyways, if anyone has an idea why this works "sometimes" it might help future problems.

答:
The heading attribute is currently unsupported by all browsers that I am aware of. Just like altitude.

The Generic Sensors API may offer some future help. (NB: They will never implement the proposed Geolocation "sensor")

I'd like to see altitude and heading supported but just think of the increasing flood of events that would need to be filtered :-(

Body:
Well I create a small geolocation watch with:

navigator.geolocation.watchPosition(
    this.updateLocation.bind(this),
    this.errorLocation.bind(this),
    {enableHighAccuracy: true}
);

where updateLocation is defined as:

private updateLocation(position: Position) {
    this.myLatitude = position.coords.latitude;
    this.myLongitude = position.coords.longitude;
    this.myAccuracy = position.coords.accuracy;
    if (position.coords.heading != null) {
        this.myHeading = Game.toRad(position.coords.heading);
    }
    this.GPSWorking = true;
}

Now this code is "working", I see it updating gps data and the accuracy is as expected. - There is just one "but": the heading is always "null". I could expect this when on pc, or even when not having enabled high accuracy.

yet in all settings I tried it gives "null".

I know my mobile phone has a working gyroscope: I can actually get the heading in native android apps. - I also notice that google maps (website, through chrome) is capable of determining my heading; so there must be something I did wrong?

A small fiddle so people could test it: https://jsfiddle.net/8p5rngtk/15/ - I'm only interested in the heading (though rest is there to show gps is working on a device).

Edit:

Well, it "just" started working like expected. (perfectly well), the only thing I still notice is that the update frequency is way slower than when I wrote it as native application - so slow that I can't depend on it for my application.

Anyways, if anyone has an idea why this works "sometimes" it might help future problems.


问:
Populate vector of vectors from input file?

I'm trying to populate a vector of vectors from an input file.

```<code>#include<fstream>
#include<vector>
#include<iostream>
using namespace std;

int main(){
    ofstream inputFile;
    inputFile.open("input.dat");

    if(!inputFile){
            cout << "Error in reading" << "input" << endl;
            return 0;
    }

    vector<vector<double> > A;
    double element;
    vector<double> temp;

    while(inputFile << element){
            temp.push_back(element);
            A.push_back(temp);
    }

    int len = A.size();
    int i, j;

    for(i=0; i<len; i++){
            for(j=0; j<len; j++){
                    cout << A[i] <<"\n";
            }
    }

    return 0;
}
</code>```

I'm using this as a test file, so I am trying to print the matrix A. Any help would be really appreciated.

```<code>test.cpp:33:9: error: no match for ‘operator<<’ (operand types are
‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<double>’)
cout << A[i] <<"\n";
</code>```

答:
Change the while loop to this:

```<code>while(inputFile >> element){
        temp.push_back(element);
        A.push_back(temp);
}
</code>```

And in the nested for loop do cout<<A[i][j]<<endl;

Body:
I'm trying to populate a vector of vectors from an input file.

#include<fstream>
#include<vector>
#include<iostream>
using namespace std;

int main(){
    ofstream inputFile;
    inputFile.open("input.dat");

    if(!inputFile){
            cout << "Error in reading" << "input" << endl;
            return 0;
    }

    vector<vector<double> > A;
    double element;
    vector<double> temp;

    while(inputFile << element){
            temp.push_back(element);
            A.push_back(temp);
    }

    int len = A.size();
    int i, j;

    for(i=0; i<len; i++){
            for(j=0; j<len; j++){
                    cout << A[i] <<"\n";
            }
    }

    return 0;
}

I'm using this as a test file, so I am trying to print the matrix A. Any help would be really appreciated.

test.cpp:33:9: error: no match for ‘operator<<’ (operand types are
‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<double>’)
cout << A[i] <<"\n";

Body:
Change the while loop to this:

while(inputFile >> element){
        temp.push_back(element);
        A.push_back(temp);
}

And in the nested for loop do cout<<A[i][j]<<endl;


问:
Android - Map screen closing automatically
I have a Firebase Chat application that is working fine. However I have some issue with map that is always just closing down.

There is a feature in the app that will allow users to post their (Location).

Whenever I open the map screen - then it utomatically closes.

The application itself is NOT crashing, Im only having issue with the map screen.

This is my build.gradle(Module: app)

```<code>apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.startup.chat"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    //compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'com.android.support:appcompat-v7:26.0.0-beta1'
    compile 'com.android.support:design:26.0.0-alpha1'
    compile 'com.google.firebase:firebase-core:11.0.4'
    compile 'com.google.firebase:firebase-database:11.0.4'
    compile 'com.firebaseui:firebase-ui-database:0.4.1'
    compile 'com.google.firebase:firebase-auth:11.0.4'
    compile 'com.google.firebase:firebase-storage:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:percent:26.0.0-alpha1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'me.himanshusoni.chatmessageview:chat-message-view:1.0.3'
    compile 'com.google.android.gms:play-services-places:11.0.4'
    compile 'life.knowledge4:k4l-video-trimmer:1.1.3-SNAPSHOT'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'ru.alexbykov:nopermission:1.0.7'
    compile 'com.android.support:support-v4:26.0.0-alpha1'
    testCompile 'junit:junit:4.12'
}
</code>```

This is Manifests file

```<code><meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/map_key" />
</code>```

This is Logcat output

```<code>12-08 16:19:14.152 12600-12629/com.senseidev.ipyre V/FA: Inactivity, disconnecting from the service
12-08 16:19:18.332 12600-12600/com.senseidev.ipyre D/AppTracker: App Event: stop
12-08 16:19:18.335 12600-12629/com.senseidev.ipyre V/FA: Recording user engagement, ms: 9189
12-08 16:19:18.336 12600-12629/com.senseidev.ipyre V/FA: Using measurement service
12-08 16:19:18.336 12600-12629/com.senseidev.ipyre V/FA: Connecting to remote service
12-08 16:19:18.338 12600-12629/com.senseidev.ipyre V/FA: Activity paused, time: 4131815
12-08 16:19:18.342 12600-12629/com.startup.chat D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=9189, firebase_screen_class(_sc)=ChatActivity, firebase_screen_id(_si)=3660273493638676481}]
12-08 16:19:18.355 12600-12629/com.startup.chat V/FA: Using measurement service
12-08 16:19:18.355 12600-12629/com.startup.chat V/FA: Connection attempt already in progress
12-08 16:19:18.363 12600-12629/com.startup.chat D/FA: Connected to remote service
12-08 16:19:18.363 12600-12629/com.startup.chat V/FA: Processing queued up service tasks: 2
12-08 16:19:18.412 12600-12629/com.startup.chat V/FA: Activity resumed, time: 4131891
12-08 16:19:18.412 12600-12600/com.startup.chat D/AppTracker: App Event: start
12-08 16:19:18.416 12600-12600/com.startup.chat D/AppTracker: App Event: stop
12-08 16:19:18.420 12600-12629/com.startup.chat V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 9
12-08 16:19:18.421 12600-12629/com.startup.chat V/FA: Activity paused, time: 4131900
12-08 16:19:18.668 12600-12632/com.startup.chat D/OpenGLRenderer: endAllActiveAnimators on 0x723e582800 (MenuPopupWindow$MenuDropDownListView) with handle 0x723ce4ada0
12-08 16:19:18.756 12600-12629/com.startup.chat V/FA: Activity resumed, time: 4132235
12-08 16:19:18.760 12600-12600/com.startup.chat D/AppTracker: App Event: start
12-08 16:19:23.760 12600-12629/com.startup.chat V/FA: Inactivity, disconnecting from the service
12-08 16:19:30.859 12600-12611/com.startup.chat I/zygote64: Do full code cache collection, code=1008KB, data=658KB
12-08 16:19:30.863 12600-12611/com.startup.chat I/zygote64: After code cache collection, code=974KB, data=558KB
</code>```

Im not understanding what the issue is - The map screen opens up but then automatically closes. I hope I can get a fix on this as this is very annoying bug.

Thanks in advance

答: That happens because you have delete nodes in firebase database. reset your database everything will works fine

Body:
I have a Firebase Chat application that is working fine. However I have some issue with map that is always just closing down.

There is a feature in the app that will allow users to post their (Location).

Whenever I open the map screen - then it utomatically closes.

The application itself is NOT crashing, Im only having issue with the map screen.

This is my build.gradle(Module: app)

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.startup.chat"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    //compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'com.android.support:appcompat-v7:26.0.0-beta1'
    compile 'com.android.support:design:26.0.0-alpha1'
    compile 'com.google.firebase:firebase-core:11.0.4'
    compile 'com.google.firebase:firebase-database:11.0.4'
    compile 'com.firebaseui:firebase-ui-database:0.4.1'
    compile 'com.google.firebase:firebase-auth:11.0.4'
    compile 'com.google.firebase:firebase-storage:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:percent:26.0.0-alpha1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'me.himanshusoni.chatmessageview:chat-message-view:1.0.3'
    compile 'com.google.android.gms:play-services-places:11.0.4'
    compile 'life.knowledge4:k4l-video-trimmer:1.1.3-SNAPSHOT'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'ru.alexbykov:nopermission:1.0.7'
    compile 'com.android.support:support-v4:26.0.0-alpha1'
    testCompile 'junit:junit:4.12'
}

This is Manifests file

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/map_key" />

This is Logcat output

12-08 16:19:14.152 12600-12629/com.senseidev.ipyre V/FA: Inactivity, disconnecting from the service
12-08 16:19:18.332 12600-12600/com.senseidev.ipyre D/AppTracker: App Event: stop
12-08 16:19:18.335 12600-12629/com.senseidev.ipyre V/FA: Recording user engagement, ms: 9189
12-08 16:19:18.336 12600-12629/com.senseidev.ipyre V/FA: Using measurement service
12-08 16:19:18.336 12600-12629/com.senseidev.ipyre V/FA: Connecting to remote service
12-08 16:19:18.338 12600-12629/com.senseidev.ipyre V/FA: Activity paused, time: 4131815
12-08 16:19:18.342 12600-12629/com.startup.chat D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=9189, firebase_screen_class(_sc)=ChatActivity, firebase_screen_id(_si)=3660273493638676481}]
12-08 16:19:18.355 12600-12629/com.startup.chat V/FA: Using measurement service
12-08 16:19:18.355 12600-12629/com.startup.chat V/FA: Connection attempt already in progress
12-08 16:19:18.363 12600-12629/com.startup.chat D/FA: Connected to remote service
12-08 16:19:18.363 12600-12629/com.startup.chat V/FA: Processing queued up service tasks: 2
12-08 16:19:18.412 12600-12629/com.startup.chat V/FA: Activity resumed, time: 4131891
12-08 16:19:18.412 12600-12600/com.startup.chat D/AppTracker: App Event: start
12-08 16:19:18.416 12600-12600/com.startup.chat D/AppTracker: App Event: stop
12-08 16:19:18.420 12600-12629/com.startup.chat V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 9
12-08 16:19:18.421 12600-12629/com.startup.chat V/FA: Activity paused, time: 4131900
12-08 16:19:18.668 12600-12632/com.startup.chat D/OpenGLRenderer: endAllActiveAnimators on 0x723e582800 (MenuPopupWindow$MenuDropDownListView) with handle 0x723ce4ada0
12-08 16:19:18.756 12600-12629/com.startup.chat V/FA: Activity resumed, time: 4132235
12-08 16:19:18.760 12600-12600/com.startup.chat D/AppTracker: App Event: start
12-08 16:19:23.760 12600-12629/com.startup.chat V/FA: Inactivity, disconnecting from the service
12-08 16:19:30.859 12600-12611/com.startup.chat I/zygote64: Do full code cache collection, code=1008KB, data=658KB
12-08 16:19:30.863 12600-12611/com.startup.chat I/zygote64: After code cache collection, code=974KB, data=558KB

Im not understanding what the issue is - The map screen opens up but then automatically closes. I hope I can get a fix on this as this is very annoying bug.

Thanks in advance


问:
Troubles separating C++ source file into multiple files
Let me specify exactly what I'm trying to do, I need to split my foo-bar program into five separate files: main, foo.h, foo.cpp, bar.h, bar.cpp. My header files (foo.h and bar.h) are meant to contain the declarations for their corresponding classes, while the c++ files (foo.cpp and bar.cpp) are meant to define the class.

I'm using Visual Studio, and thus far the only file I have showing red flags is my main file. Here is my code thus far, and I will include the errors that are being thrown in my main file:

main.cpp

```<code>#include <iostream>
#include "foo.h"
#include "foo.cpp"
#include "bar.h"
#include "bar.cpp"
using namespace std;

int main() {
   Bar b(25); /*I am getting a red flag under the 25, stating there is no constructor that can convert int to Bar*/

   b.func1(); /*I'm getting a red flag under func1 and func2 stating neither of them are members of Bar*/
   b.func2(34);

   return 0;}
</code>```

foo.h

```<code>#ifndef foo_h
#define foo_h
#include "foo.cpp"
 class Foo {};
#endif
</code>```

foo.cpp

```<code>#ifndef foo_c
#define foo_c

#include "foo.h"
#include "bar.cpp"
private:
    int data;
public:
Foo(int d) : data(d) {}

int get_data() { return data; }

virtual void func1() = 0;

virtual int func2(int d) = 0;

#endif
</code>```

bar.h

```<code>#ifndef bar_h
#define bar_h
#include "bar.cpp"
#include "foo.h"
class Bar : public Foo {};
#endif
</code>```

bar.cpp

```<code>#ifndef bar_c
#define bar_c

#include "bar.h"
#include "foo.h"
#include "foo.cpp"

Bar(int d) : Foo(d) {}

void func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}

#endif
</code>```

My program worked until I split it up, but now it keeps throwing this message at me when I try to compile it, and there are a couple of red flags in my main code. This is what the console tells me:

No suitable constructor exists to convert int to Bar

func1 is not a member of class Bar

func2 is not a member of class Bar

My question is: What am I doing wrong, and is there a better way to go about what I'm trying to do?

Thank you in advance.

答:
There is more than one misconception manifested in this code. Perhaps it is easier to correct them altogether than to describe and discuss them individually.

Let us start from the bottom of the dependency tree. There at the bottom is a virtual class Foo. Here is its correct declaration.

```<code>#ifndef foo_h
#define foo_h
class Foo {
private:
    int data;
public:
   Foo(int);
   int get_data();
   virtual void func1() = 0;
   virtual int func2(int) = 0;
 };

#endif
</code>```

Note that we include the declarations of all its methods in the header file. However the implementation of the nonvirtual methods is moved out into the foo.cpp file.

```<code>#include "foo.h"

Foo::Foo(int d) : data(d) { }

int Foo::get_data() { return data; }
</code>```

Note that we do not need any special devices to protect from multiple inclusion of the .cpp file because we are not going to include it ever.

Now Foo is the parent of the class Bar that does some real work for us. Once again, all its methods are declared within the class declaration.

```<code>#ifndef bar_h
#define bar_h
#include "foo.h"
class Bar : public Foo {
public:
   Bar(int);
   void func1();
   int func2(int);
};
#endif
</code>```

And its implementation is in the corresponding compilation unit called bar.cpp. When implementing a class method we indicate which class the method belongs to by prepending the class name to the method name, e.g. Bar::func1.

```<code>#include "bar.h"
#include "foo.h"

#include <iostream>

Bar::Bar(int d) : Foo(d) {};

using namespace std;

void Bar::func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int Bar::func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}
</code>```

Finally we use it in the main.cpp where only a small change is required.

```<code>#include <iostream>
#include "foo.h"
#include "bar.h"
using namespace std;

int main() {
   Bar b(25);

   b.func1();
   b.func2(34);

   return 0;}
</code>```

Let's now proceed with building our project. If you were using GCC that would've been easy to describe as a sequence of CLI commands. Since you are using Visual Studio, you would have to perform the corresponding actions through the GUI.

First compile Foo

g++ -c -Wall foo.cpp

Next compile Bar

g++ -c -Wall bar.cpp

Compile main

g++ -c -Wall main.cpp

Now link it all together

g++ -o main foo.o bar.o main.o

Finally run it and voila

```
    Inside func1
        Data is 25
    Inside func2 with 34
        Data is 25
```

Body:
Let me specify exactly what I'm trying to do, I need to split my foo-bar program into five separate files: main, foo.h, foo.cpp, bar.h, bar.cpp. My header files (foo.h and bar.h) are meant to contain the declarations for their corresponding classes, while the c++ files (foo.cpp and bar.cpp) are meant to define the class.

I'm using Visual Studio, and thus far the only file I have showing red flags is my main file. Here is my code thus far, and I will include the errors that are being thrown in my main file:

main.cpp

#include <iostream>
#include "foo.h"
#include "foo.cpp"
#include "bar.h"
#include "bar.cpp"
using namespace std;

int main() {
   Bar b(25); /*I am getting a red flag under the 25, stating there is no constructor that can convert int to Bar*/

   b.func1(); /*I'm getting a red flag under func1 and func2 stating neither of them are members of Bar*/
   b.func2(34);

   return 0;}

foo.h

#ifndef foo_h
#define foo_h
#include "foo.cpp"
 class Foo {};
#endif

foo.cpp

#ifndef foo_c
#define foo_c

#include "foo.h"
#include "bar.cpp"
private:
    int data;
public:
Foo(int d) : data(d) {}

int get_data() { return data; }

virtual void func1() = 0;

virtual int func2(int d) = 0;

#endif

bar.h

#ifndef bar_h
#define bar_h
#include "bar.cpp"
#include "foo.h"
class Bar : public Foo {};
#endif

bar.cpp

#ifndef bar_c
#define bar_c

#include "bar.h"
#include "foo.h"
#include "foo.cpp"

Bar(int d) : Foo(d) {}

void func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}

#endif

My program worked until I split it up, but now it keeps throwing this message at me when I try to compile it, and there are a couple of red flags in my main code. This is what the console tells me:

No suitable constructor exists to convert int to Bar

func1 is not a member of class Bar

func2 is not a member of class Bar

My question is: What am I doing wrong, and is there a better way to go about what I'm trying to do?

Thank you in advance.

Body:
There is more than one misconception manifested in this code. Perhaps it is easier to correct them altogether than to describe and discuss them individually.

Let us start from the bottom of the dependency tree. There at the bottom is a virtual class Foo. Here is its correct declaration.

#ifndef foo_h
#define foo_h
class Foo {
private:
    int data;
public:
   Foo(int);
   int get_data();
   virtual void func1() = 0;
   virtual int func2(int) = 0;
 };

#endif

Note that we include the declarations of all its methods in the header file. However the implementation of the nonvirtual methods is moved out into the foo.cpp file.

#include "foo.h"

Foo::Foo(int d) : data(d) { }

int Foo::get_data() { return data; }

Note that we do not need any special devices to protect from multiple inclusion of the .cpp file because we are not going to include it ever.

Now Foo is the parent of the class Bar that does some real work for us. Once again, all its methods are declared within the class declaration.

#ifndef bar_h
#define bar_h
#include "foo.h"
class Bar : public Foo {
public:
   Bar(int);
   void func1();
   int func2(int);
};
#endif

And its implementation is in the corresponding compilation unit called bar.cpp. When implementing a class method we indicate which class the method belongs to by prepending the class name to the method name, e.g. Bar::func1.

#include "bar.h"
#include "foo.h"

#include <iostream>

Bar::Bar(int d) : Foo(d) {};

using namespace std;

void Bar::func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int Bar::func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}

Finally we use it in the main.cpp where only a small change is required.

#include <iostream>
#include "foo.h"
#include "bar.h"
using namespace std;

int main() {
   Bar b(25);

   b.func1();
   b.func2(34);

   return 0;}

Let's now proceed with building our project. If you were using GCC that would've been easy to describe as a sequence of CLI commands. Since you are using Visual Studio, you would have to perform the corresponding actions through the GUI.

First compile Foo

g++ -c -Wall foo.cpp

Next compile Bar

g++ -c -Wall bar.cpp

Compile main

g++ -c -Wall main.cpp

Now link it all together

g++ -o main foo.o bar.o main.o

Finally run it and voila

    Inside func1
        Data is 25
    Inside func2 with 34
        Data is 25


问:
Why doesn't the Value get replaced in the variable?
```<code>A='A'
B='B'
C='C'
D='D'
E='E'
F='F'
G='G'
H='H'
I='I'
list1=[A,B,C]
list2=[D,E,F]
list3=[G,H,I]

def Output():
    print(list1)
    print(list2)
    print(list3)

Output()

print('The object of Tic Tac Toe is to get three in a row. You play on a three by three game board. The first player is known as X and the second is O. Players alternate placing Xs and Os on the game board until either oppent has three in a row or all nine squares are filled. X always goes first, and in the event that no one has three in a row, the stalemate is called a cat game.')
print()
print('This is a two player game. Single-player Coming soon!')
print()
print('You must place your letter by choosing a letter from above to decide the co-ordinates. The first player starts with X, and the second player starts with O.')

Decision=input('Enter Co-ordinate of First player:')
if Decision == A:
    A ='X'
if Decision == B:
    B = 'X'
if Decision == C:
    C ='X'
if Decision == D:
    D ='X'
if Decision == E:
    E ='X'
if Decision == F:
    F ='X'
if Decision == G:
    G ='X'
if Decision == H:
    H ='X'
if Decision == I:
    I ='X'
Output()
</code>```

<p>This was a code I started writing for Tic Tac Toe. Whenever I enter the Co-ordinate and then use the Output Function, the letter X doesn't appear in the place of the co-ordinate entered. </p>

答:
A is a reference to 'A', Not list1[0]. Just because you initialized list1 with the first value as A does not mean changes in the variable A will affect the value in the list. Also, you use == for a variable assignment. == is an equality checker. Here's what you should do instead:

```<code>if decision == 'A':
    list1[0] = 'X'
</code>```

this way the value in the list will be changed, and you don't need any of the variable assignments such as A = 'A', B = 'B', etc.

Body:
A='A'
B='B'
C='C'
D='D'
E='E'
F='F'
G='G'
H='H'
I='I'
list1=[A,B,C]
list2=[D,E,F]
list3=[G,H,I]

def Output():
    print(list1)
    print(list2)
    print(list3)

Output()

print('The object of Tic Tac Toe is to get three in a row. You play on a three by three game board. The first player is known as X and the second is O. Players alternate placing Xs and Os on the game board until either oppent has three in a row or all nine squares are filled. X always goes first, and in the event that no one has three in a row, the stalemate is called a cat game.')
print()
print('This is a two player game. Single-player Coming soon!')
print()
print('You must place your letter by choosing a letter from above to decide the co-ordinates. The first player starts with X, and the second player starts with O.')

Decision=input('Enter Co-ordinate of First player:')
if Decision == A:
    A ='X'
if Decision == B:
    B = 'X'
if Decision == C:
    C ='X'
if Decision == D:
    D ='X'
if Decision == E:
    E ='X'
if Decision == F:
    F ='X'
if Decision == G:
    G ='X'
if Decision == H:
    H ='X'
if Decision == I:
    I ='X'
Output()

This was a code I started writing for Tic Tac Toe. Whenever I enter the Co-ordinate and then use the Output Function, the letter X doesn't appear in the place of the co-ordinate entered.

Body:
A is a reference to 'A', Not list1[0]. Just because you initialized list1 with the first value as A does not mean changes in the variable A will affect the value in the list. Also, you use == for a variable assignment. == is an equality checker. Here's what you should do instead:

if decision == 'A':
    list1[0] = 'X'

this way the value in the list will be changed, and you don't need any of the variable assignments such as A = 'A', B = 'B', etc.


问:
My JPanel is appearing gray
I am trying to make a title screen with buttons, and use a JFrame object to have a background as a picture (BufferedImage). However, the screen appears gray and only updates parts of the screen when I mouse over the buttons.

The JFrame class:

```<code>//import statements
public class StartGame extends JFrame{
    private JLabel title=new JLabel("Title");
    private JButton start=new JButton("New Game");
    private JButton quit=new JButton("Quit");
    public static final int WIDTH = 1280;
    public static final int HEIGHT = 720;

    public static void main(String [] args){
        StartGame g1=new StartGame();
        g1.play();
    }

    public StartGame(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle( "Title" );
        setResizable( false );
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize( WIDTH, HEIGHT );
        setPreferredSize( new Dimension(WIDTH, HEIGHT) );
        setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        setUndecorated(true);
        setVisible(true);

        StartGamePanel sgp = new StartGamePanel();
        sgp.setSize( StartGame.WIDTH,StartGame.HEIGHT );
        sgp.setLayout( null );
        sgp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        sgp.setVisible(true);

        start.setBackground(Color.BLACK);
        start.setBorder(BorderFactory.createEmptyBorder());
        start.setBounds( WIDTH/2-105, HEIGHT/9*6, 210, 40 );
        start.setForeground(Color.WHITE);

        quit.setBackground(Color.BLACK);
        quit.setBorder(BorderFactory.createEmptyBorder());
        quit.setBounds( WIDTH/2-75, HEIGHT/9*8, 150, 40 );
        quit.setForeground(Color.WHITE);

        title.setBounds( WIDTH/2-216, HEIGHT/8*2, 432, 100 );
        title.setForeground(Color.WHITE);

        ButtonListener spy = new ButtonListener();
        start.addActionListener( spy );
        quit.addActionListener( spy );

        sgp.add(title);
        sgp.add(start);
        sgp.add(quit);
        getContentPane().add( sgp );
        pack();
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }
    private class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(quit)) {
                System.exit(0);
            } else if (e.getSource().equals(start)){
                //start
            dispose();
            }
        }
    }
}
</code>```

and the JPanel class:

```<code>//import statements
public class StartGamePanel extends JPanel{
    private BufferedImage bg;
    public StartGamePanel(){
        setBackground( Color.WHITE );
        setSize( StartGame.WIDTH, StartGame.HEIGHT );
        setPreferredSize( new Dimension(StartGame.WIDTH, StartGame.HEIGHT) );
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        setLayout( null );

        try {
            bg = ImageIO.read(new File("pics/SplashScreen.png"));
        } catch (IOException e) {
            System.out.println ( "No splash screen image in StartGamePanel" );
        }
    }

    @Override
    public void paintComponent( Graphics g ) {
        super.paintComponent( g );

        g.drawImage( bg, 0, 0, null );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }
}
</code>```

I'm fairly sure that the issue lies within the JPanel class, as I am able to replace it with another JPanel class from a different part of my program, and it worked.

答:
Don't Place setVisible(true); at the start or you need to repaint(); it afterwards.

Because it have a time to update for those adds at the bottom, this is why your program is gray or the default color of Java Application.

Title: My JPanel is appearing gray

Body:
I am trying to make a title screen with buttons, and use a JFrame object to have a background as a picture (BufferedImage). However, the screen appears gray and only updates parts of the screen when I mouse over the buttons.

The JFrame class:

//import statements
public class StartGame extends JFrame{
    private JLabel title=new JLabel("Title");
    private JButton start=new JButton("New Game");
    private JButton quit=new JButton("Quit");
    public static final int WIDTH = 1280;
    public static final int HEIGHT = 720;

    public static void main(String [] args){
        StartGame g1=new StartGame();
        g1.play();
    }

    public StartGame(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle( "Title" );
        setResizable( false );
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setSize( WIDTH, HEIGHT );
        setPreferredSize( new Dimension(WIDTH, HEIGHT) );
        setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        setUndecorated(true);
        setVisible(true);

        StartGamePanel sgp = new StartGamePanel();
        sgp.setSize( StartGame.WIDTH,StartGame.HEIGHT );
        sgp.setLayout( null );
        sgp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        sgp.setVisible(true);

        start.setBackground(Color.BLACK);
        start.setBorder(BorderFactory.createEmptyBorder());
        start.setBounds( WIDTH/2-105, HEIGHT/9*6, 210, 40 );
        start.setForeground(Color.WHITE);

        quit.setBackground(Color.BLACK);
        quit.setBorder(BorderFactory.createEmptyBorder());
        quit.setBounds( WIDTH/2-75, HEIGHT/9*8, 150, 40 );
        quit.setForeground(Color.WHITE);

        title.setBounds( WIDTH/2-216, HEIGHT/8*2, 432, 100 );
        title.setForeground(Color.WHITE);

        ButtonListener spy = new ButtonListener();
        start.addActionListener( spy );
        quit.addActionListener( spy );

        sgp.add(title);
        sgp.add(start);
        sgp.add(quit);
        getContentPane().add( sgp );
        pack();
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }
    private class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(quit)) {
                System.exit(0);
            } else if (e.getSource().equals(start)){
                //start
            dispose();
            }
        }
    }
}

and the JPanel class:

//import statements
public class StartGamePanel extends JPanel{
    private BufferedImage bg;
    public StartGamePanel(){
        setBackground( Color.WHITE );
        setSize( StartGame.WIDTH, StartGame.HEIGHT );
        setPreferredSize( new Dimension(StartGame.WIDTH, StartGame.HEIGHT) );
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        setLayout( null );

        try {
            bg = ImageIO.read(new File("pics/SplashScreen.png"));
        } catch (IOException e) {
            System.out.println ( "No splash screen image in StartGamePanel" );
        }
    }

    @Override
    public void paintComponent( Graphics g ) {
        super.paintComponent( g );

        g.drawImage( bg, 0, 0, null );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }
}

I'm fairly sure that the issue lies within the JPanel class, as I am able to replace it with another JPanel class from a different part of my program, and it worked.


问:
How to connect Azure Paas Database using Powershell with intergrated security
How can I connect to an Azure SQLDatabase (Paas Instance) using Powershell without a username & password but rather with Active Directory. I can connect with a username and password when I use invoke-sqlcmd  as below

```<code>$Servername = "XXXXXX.database.windows.net"
$params = @{

   Database = $databasename

   ServerInstance = $ServerName

   Username = $UserName

   Password = $password

   'OutputSqlErrors' = $true

   Query = $QueryString

}

Invoke-Sqlcmd  @params
</code>```

I need the ability to do it with Active Directory. I have read a few articles on how to connect with active directory as long as you specify it on the connection string (Context of C#) Using ODBC connection or other data sources. Since Powershell is based on .Net; this should be do-able..

```<code>    $ConnString = "DRIVER=ODBC Driver 13 for SQL Server;SERVER=xxxxx.database.windows.net;DATABASE=DBName;Trusted_Connection=Yes"
    $Conn = new-object System.Data.Odbc.OdbcConnection($ConnString)
    $conn.open()
    $cmd = new-object System.Data.Odbc.OdbcCommand("select getdate() as X", $Conn)
    $data = new-object System.Data.Odbc.OdbcDataAdapter($cmd)
    $dt = new-object System.Data.DataColumn
    $data.Fill($dt)
    $Conn.Close()

#`server=Server;database=Database;Authentication=ActiveDirectoryIntegrated;`
</code>```

The objective of trying to use Active Directory is that, within Paas, only AD Accounts can Add other AD accounts. I want to be able to add other accounts with method rather than logging in the Azure portal and adding an AD account manually.

答:
AAD does not / can not parse Kerbs tokens.  In order to get integrated auth to work from your desktop, you need to have ADFS (or similar) in your environment.  That way your desktop will authenticate against AAD, redirect to ADFS, and your kerbs token will be recognized.

See https://learn.microsoft.com/en-us/azure/sql-database/sql-database-aad-authentication for more information.

ContentLicense: CC BY-SA 4.0

Body:
How can I connect to an Azure SQLDatabase (Paas Instance) using Powershell without a username & password but rather with Active Directory. I can connect with a username and password when I use invoke-sqlcmd  as below

$Servername = "XXXXXX.database.windows.net"
$params = @{

   Database = $databasename

   ServerInstance = $ServerName

   Username = $UserName

   Password = $password

   'OutputSqlErrors' = $true

   Query = $QueryString

}

Invoke-Sqlcmd  @params

I need the ability to do it with Active Directory. I have read a few articles on how to connect with active directory as long as you specify it on the connection string (Context of C#) Using ODBC connection or other data sources. Since Powershell is based on .Net; this should be do-able..

    $ConnString = "DRIVER=ODBC Driver 13 for SQL Server;SERVER=xxxxx.database.windows.net;DATABASE=DBName;Trusted_Connection=Yes"
    $Conn = new-object System.Data.Odbc.OdbcConnection($ConnString)
    $conn.open()
    $cmd = new-object System.Data.Odbc.OdbcCommand("select getdate() as X", $Conn)
    $data = new-object System.Data.Odbc.OdbcDataAdapter($cmd)
    $dt = new-object System.Data.DataColumn
    $data.Fill($dt)
    $Conn.Close()

#`server=Server;database=Database;Authentication=ActiveDirectoryIntegrated;`

The objective of trying to use Active Directory is that, within Paas, only AD Accounts can Add other AD accounts. I want to be able to add other accounts with method rather than logging in the Azure portal and adding an AD account manually.


问:
Data structure converting order sorting from list to set
basically, my defines this

```<code>nodes = ['Unix', 'BSD', 'Linux']
</code>```

and when I try this

```<code>print(set(nodes))
</code>```

I expect the result of it

```<code>{'Unix', 'BSD', 'Linux'}
</code>```

but I got this

```<code>{'BSD', 'Linux', 'Unix'}
</code>```

I don't want to break order of nodes is there good way for it?

答:
Sets and Dictionaries are not ordered as they are hash based, so depending on what the input is, a hash value is calculated to associate your given element with a key. That's why access to a dictionary or set is fast O(1) but if you need ordered data, it might not be the best choice.

So you probably are trying to get rid of duplicates by creating a set? Instead you can use anOrderedDict and access the keys to get a unique list.

```<code>from collections import OrderedDict

nodes = ['Unix', 'BSD', 'Linux']
uniques = OrderedDict((x, True) for x in nodes).keys()
</code>```

Body:
basically, my defines this

nodes = ['Unix', 'BSD', 'Linux']

and when I try this

print(set(nodes))

I expect the result of it

{'Unix', 'BSD', 'Linux'}

but I got this

{'BSD', 'Linux', 'Unix'}

I don't want to break order of nodes is there good way for it?

Body:
Sets and Dictionaries are not ordered as they are hash based, so depending on what the input is, a hash value is calculated to associate your given element with a key. That's why access to a dictionary or set is fast O(1) but if you need ordered data, it might not be the best choice.

So you probably are trying to get rid of duplicates by creating a set? Instead you can use anOrderedDict and access the keys to get a unique list.

from collections import OrderedDict

nodes = ['Unix', 'BSD', 'Linux']
uniques = OrderedDict((x, True) for x in nodes).keys()


问:
Need help with While Loop
I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.

I need to create a script in Python using a while loop that does this:

```
zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza
```

Keep in mind that the script should be able to do this with any word.  For example, right now a = 'zebra'.  If a = 'cat' the the script should look like:

```
cat tac
atc cta
tca cat
```

I've figured out how to do it with a for loop...just can't figure out exactly how to implement it with a while loop.

My for loop:

```<code>a = 'zebra'
for i in range(len(a)):
    print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
</code>```

If anyone could help me out, or give me hints...I'd really appreciate it!
thanks!

答:
Here is some code that will work for any sized word, using a While loop:</p>

```<code>word = "alpha"
index = 0

while (index < len(word)):
    print word + "   " + word[::-1]
    word = word[1:] + word[0]
    index += 1
</code>```

ContentLicense: CC BY-SA 2.5

Title: Need help with While Loop

Body:
I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.

I need to create a script in Python using a while loop that does this:

zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza

Keep in mind that the script should be able to do this with any word.  For example, right now a = 'zebra'.  If a = 'cat' the the script should look like:

cat tac
atc cta
tca cat

I've figured out how to do it with a for loop...just can't figure out exactly how to implement it with a while loop.

My for loop:

a = 'zebra'
for i in range(len(a)):
    print a[i:] + a[:i], (a[i:] + a[:i])[::-1]

If anyone could help me out, or give me hints...I'd really appreciate it!
thanks!

Body:
Here is some code that will work for any sized word, using a While loop:

word = "alpha"
index = 0

while (index < len(word)):
    print word + "   " + word[::-1]
    word = word[1:] + word[0]
    index += 1


问:
Post parent as current id not working
I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.

The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.

I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.

The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.

Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.

```<code>/**
* Handle ajax file upload to media library.
*
* @since    1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'],   'wpday_dz_protect')) {
    // Including file library if not exist
    if (!function_exists('wp_handle_upload')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }

    // Uploading file to server
    $movefile = wp_handle_upload($_FILES['file'], ['test_form' =>  false]);

    // If uploading success & No error
    if ($movefile && !isset($movefile['error'])) {
        $filename = $movefile['file'];
        $filetype = wp_check_filetype(basename($filename), null);
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
            'post_mime_type' => $filetype['type'],
            'post_parent' => $post->ID,
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit',
        );

        // Adding file to media
        $attachment_id = wp_insert_attachment($attachment, $filename);

        // If attachment success
        if ($attach_id) {
            require_once ABSPATH . 'wp-admin/includes/image.php';

            // Updating attachment metadata
            $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
            wp_update_attachment_metadata($attach_id, $attach_data);
        }

        $message['error'] = 'false';
        $message['data'] = wp_get_attachment_url($attach_id);
    } else {
        $message['error'] = 'true';
        $message['data'] = $movefile['error'];
    }

    wp_send_json($message);
}
}
      add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
      add_action('wp_ajax_nopriv_wpday_dz',  'wpday_dz_ajax_upload_handle');
</code>```

EDIT:

Have tried:

```<code>$id = get_the_ID();

    // If uploading success & No error
    if ($movefile && !isset($movefile['error'])) {
        $filename = $movefile['file'];
        $filetype = wp_check_filetype(basename($filename), null);
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
            'post_mime_type' => $filetype['type'],
            'post_parent' => $id,
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit',
        );
</code>```

Still returns unattached

答:
I downloaded WP Dropzone and had a look at the code.  AFAICT the function you are working on is called via AJAX, once a file is dropped/uploaded.  In that case, there is no "post" in the current request - you're in an AJAX file unrelated to any post.

So the question becomes how to get the ID of the post that called the current AJAX request.  I found this SO answer which answers that:

```<code>$url     = wp_get_referer();
$post_id = url_to_postid( $url );
</code>```

Title: Post parent as current id not working

Body:
I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.

The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.

I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.

The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.

Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.

/**
* Handle ajax file upload to media library.
*
* @since    1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'],   'wpday_dz_protect')) {
    // Including file library if not exist
    if (!function_exists('wp_handle_upload')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }

    // Uploading file to server
    $movefile = wp_handle_upload($_FILES['file'], ['test_form' =>  false]);

    // If uploading success & No error
    if ($movefile && !isset($movefile['error'])) {
        $filename = $movefile['file'];
        $filetype = wp_check_filetype(basename($filename), null);
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
            'post_mime_type' => $filetype['type'],
            'post_parent' => $post->ID,
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit',
        );

        // Adding file to media
        $attachment_id = wp_insert_attachment($attachment, $filename);

        // If attachment success
        if ($attach_id) {
            require_once ABSPATH . 'wp-admin/includes/image.php';

            // Updating attachment metadata
            $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
            wp_update_attachment_metadata($attach_id, $attach_data);
        }

        $message['error'] = 'false';
        $message['data'] = wp_get_attachment_url($attach_id);
    } else {
        $message['error'] = 'true';
        $message['data'] = $movefile['error'];
    }

    wp_send_json($message);
}
}
      add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
      add_action('wp_ajax_nopriv_wpday_dz',  'wpday_dz_ajax_upload_handle');

EDIT:

Have tried:

$id = get_the_ID();

    // If uploading success & No error
    if ($movefile && !isset($movefile['error'])) {
        $filename = $movefile['file'];
        $filetype = wp_check_filetype(basename($filename), null);
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
            'post_mime_type' => $filetype['type'],
            'post_parent' => $id,
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit',
        );

Still returns unattached

Body:
I downloaded WP Dropzone and had a look at the code.  AFAICT the function you are working on is called via AJAX, once a file is dropped/uploaded.  In that case, there is no "post" in the current request - you're in an AJAX file unrelated to any post.

So the question becomes how to get the ID of the post that called the current AJAX request.  I found this SO answer which answers that:

$url     = wp_get_referer();
$post_id = url_to_postid( $url );


问:
c++ size of a struct with a function
The result says 12.

Where is the function foobar stored in the memory?

```<code>#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}
</code>```

答:
The function is stored inside .text segment.

A compiled program’s memory is divided into five segments: text,
  data, bss, heap, and stack. Each segment represents a special portion
  of memory that is set aside for a certain purpose. The text segment is
  also sometimes called the code segment. This is where the assembled
  machine language instructions of the program are located.

The memory layout of the object itself is:

```<code>class ABC_ {
public:
    int a; // 0x4 (4)
    int b; // 0x8 (8)
    int c; // 0xC (12)
    int foobar(int a) { // you can print address using &foobar
        return a;
    }
};
</code>```

When your class contains virtual functions they're stored in the same way but memory layout of your class changes... it will have one invisible 4 byte(on 32 bit) pointer to the virtual function table or virtual method table/ VMT (this table simply holds addresses of the functions to allow polymorphism, such table is created for each class separately, when it inherits another table is stored in memory) so in that case the size would be 16. It also depends on alignment setting of the compiler...

If you want to get pointer to a vtable you can do it this way:

```<code>void **get_vtable(void *obj) {
    return *(void ***)obj;
}
</code>```

Vtable is usually stored at the beginning in every compiler I know.

You can notice the difference when function is virtual and when not by looking at the way it's called. Normal functions are directly called/jmped but virtual ones, they're called by function pointer stored in their table.

(some x86 asm out of my mind, could be wrong)

```<code>mov edx, [ecx] // ecx = this pointer
add edx, 12h // let's say 0x12 is the offset divided by 4 is 4 = index in vtable
call edx // you know it's virtual function
</code>```

or simply

```<code>mov edx, [ecx+12h]
call edx
</code>```

The best way to learn how things are stored in memory is to use some disassembler and/or debugger. I recommend IDA Pro and x64dbg.

Title: c++ size of a struct with a function

Body:
The result says 12.

Where is the function foobar stored in the memory?

#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}

Body:
The function is stored inside .text segment.

A compiled program’s memory is divided into five segments: text,
  data, bss, heap, and stack. Each segment represents a special portion
  of memory that is set aside for a certain purpose. The text segment is
  also sometimes called the code segment. This is where the assembled
  machine language instructions of the program are located.

The memory layout of the object itself is:

class ABC_ {
public:
    int a; // 0x4 (4)
    int b; // 0x8 (8)
    int c; // 0xC (12)
    int foobar(int a) { // you can print address using &foobar
        return a;
    }
};

When your class contains virtual functions they're stored in the same way but memory layout of your class changes... it will have one invisible 4 byte(on 32 bit) pointer to the virtual function table or virtual method table/ VMT (this table simply holds addresses of the functions to allow polymorphism, such table is created for each class separately, when it inherits another table is stored in memory) so in that case the size would be 16. It also depends on alignment setting of the compiler...

If you want to get pointer to a vtable you can do it this way:

void **get_vtable(void *obj) {
    return *(void ***)obj;
}

Vtable is usually stored at the beginning in every compiler I know.

You can notice the difference when function is virtual and when not by looking at the way it's called. Normal functions are directly called/jmped but virtual ones, they're called by function pointer stored in their table.

(some x86 asm out of my mind, could be wrong)

mov edx, [ecx] // ecx = this pointer
add edx, 12h // let's say 0x12 is the offset divided by 4 is 4 = index in vtable
call edx // you know it's virtual function

or simply

mov edx, [ecx+12h]
call edx

The best way to learn how things are stored in memory is to use some disassembler and/or debugger. I recommend IDA Pro and x64dbg.


问:
Left Outer Join returns duplicate records - Oracle
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

```<code>ID NAME PRICE GST
1  Book 100   10
2  CD   50    5
</code>```

Ex:

Table ORDER

```<code>ID   NAME  COST
1    Book  110
2    CD    55
</code>```

Table COST

```<code>ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5
</code>```

LEFT OUTER JOIN returns multiple rows when below condition is used

```<code>SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID
</code>```

答:
This is what i found working in my case.

Had to use 2 LEFT OUTER JOIN's and alias to get it working

```<code>SELECT ID, NAME, PRICE.value as PRICE, GST.value as GST
from ORDER

LEFT OUTER JOIN COST as PRICE
ON ORDER.ID = COST.ORDER_ID
AND PRICE.COST_TYPE = 'PRICE'

LEFT OUTER JOIN COST as GST
ON ORDER.ID = COST.ORDER_ID
AND GST.COST_TYPE = 'GST'
</code>```

Body:
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

ID NAME PRICE GST
1  Book 100   10
2  CD   50    5

Ex:

Table ORDER

ID   NAME  COST
1    Book  110
2    CD    55

Table COST

ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5

LEFT OUTER JOIN returns multiple rows when below condition is used

SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID

Body:
This is what i found working in my case.

Had to use 2 LEFT OUTER JOIN's and alias to get it working

SELECT ID, NAME, PRICE.value as PRICE, GST.value as GST
from ORDER

LEFT OUTER JOIN COST as PRICE
ON ORDER.ID = COST.ORDER_ID
AND PRICE.COST_TYPE = 'PRICE'

LEFT OUTER JOIN COST as GST
ON ORDER.ID = COST.ORDER_ID
AND GST.COST_TYPE = 'GST'


问:
issue with using stat_summary to produce error bars for line graphs when faceting
I'm trying to add error bars to line graphs using stat_summary in ggplot2 but it won't work when I facet the graphs

My data:

```<code>    date week year location imidacloprid block wickhami virescens sexta
1 15-May    1 2015  kinston           tp     1        0         0     0
2 15-May    1 2015  kinston           gh     1        0         0     0
3 15-May    1 2015  kinston          utc     1        0         0     0
4 15-May    1 2015  kinston           gh     2        0         0     0
5 15-May    1 2015  kinston          utc     2        0         0     0
6 15-May    1 2015  kinston           tp     2        0         0     0

'data.frame':   576 obs. of  9 variables:
 $ date        : Factor w/ 27 levels "1-Jul","12-Jun",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ week        : Factor w/ 12 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ year        : Factor w/ 2 levels "2015","2016": 1 1 1 1 1 1 1 1 1 1 ...
 $ location    : Factor w/ 2 levels "kinston","rocky mount": 1 1 1 1 1 1 1 1 1 1 ...
 $ imidacloprid: Factor w/ 3 levels "gh","tp","utc": 2 1 3 1 3 2 3 2 1 2 ...
 $ block       : Factor w/ 4 levels "1","2","3","4": 1 1 1 2 2 2 3 3 3 4 ...
 $ wickhami    : num  0 0 0 0 0 0 0 0 0 0 ...
 $ virescens   : num  0 0 0 0 0 0 0 0 0 0 ...
 $ sexta       : num  0 0 0 0 0 0 0 0 0 0 ...
</code>```

Summarizing the data for graphing:

```<code>wickhami_sum = summarySE(bug_subset_final,
                measurevar="wickhami",
                groupvars=c("imidacloprid","week","year"))

   imidacloprid week year N wickhami         sd          se         ci
1            gh    1 2015 8   0.0000  0.0000000  0.00000000  0.0000000
2            gh    1 2016 8   0.0000  0.0000000  0.00000000  0.0000000
3            gh    2 2015 8   0.0000  0.0000000  0.00000000  0.0000000
4            gh    2 2016 8   0.0000  0.0000000  0.00000000  0.0000000
5            gh    3 2015 8   0.0000  0.0000000  0.00000000  0.0000000
6            gh    3 2016 8   0.1250  0.2314550  0.08183171  0.1935012
7            gh    4 2015 8   0.0000  0.0000000  0.00000000  0.0000000
8            gh    4 2016 8   0.5000  0.4629100  0.16366342  0.3870025
9            gh    5 2015 8   0.5000  0.3779645  0.13363062  0.3159862
</code>```

The code below gives me no issue and produces a line graph of the two years of my data combined, and produces error bars via stat_summary

```<code>ggplot(wickhami_sum, aes(x=week, y=wickhami,linetype=imidacloprid,group=imidacloprid))+
  stat_summary(fun.data=mean_se,geom="errorbar",width=.2,color="black",position=position_dodge(0.2))+
  stat_summary(fun.y=mean,geom="line",position=position_dodge(0.2))
</code>```

However, when I try and facet the data by year (as below), I can't get stat_summary to produce error bars and get the error message below

```<code>ggplot(wickhami_sum, aes(x=week, y=wickhami,linetype=imidacloprid,group=imidacloprid))+
  stat_summary(fun.y=mean,geom="line",position=position_dodge(0.2))+facet_grid(year~.)+
  stat_summary(fun.data=mean_se,geom="errorbar",width=.2,color="black",position=position_dodge(0.2))

Warning message:
Removed 72 rows containing missing values (geom_errorbar).
</code>```

I've tried expanding the range/limits of the y axis to include the error bars but I still get the same warning message and no error bars.
I'm hoping to use stat_summary to produce the error bars for the faceted graphs and not have to calculate standard errors again. Any help is appreciated in understanding why faceting isn't allow stat_summary to function properly, or what I'm not doing correctly.

答:
Here's what I think is happening: There are two rows of data per week in the unfacetted plot, but only one row per week in each panel of the facetted plot, causing the standard error calculation to return NA. stat_summary is intended for unsummarized data and does the data summaries internally. Use bug_subset_final with stat_summary, or switch to geom_errorbar to continue using wickhami_sum. Details below.

You've pre-summarized the data, but stat_summary is intended to work on the raw data and calculate the summary values internally. In the summary data frame wickhami_sum that you've passed to ggplot, there are two rows per week, one for each week of 2015 and one for each week of 2016. All of the data by week and year has been collapsed down to a single row for each week and year by the summary operation.

Thus, in the unfacetted plot, there are two rows of data for stat_summary to operate on for each week. But in the facetted plot, it's trying to calculate a standard error from a single observation, which is probably returning NA, hence nothing gets plotted. Even in the unfacetted plot, your error bars are being calculated from the two mean values for each year, which isn't what you want either.

Instead, either continue to use wickhami_sum, but instead of stat_summary do:

```<code>geom_errorbar(aes(ymin = wickhami - se, ymax=wickhami + se))
</code>```

Or, use the raw data (which looks like it's called bug_subset_final) with stat_summary:

```<code>ggplot(bug_subset_final, aes(x=week, y=wickhami)) +
  stat_summary(fun.data=mean_se, geom="errorbar)`.
</code>```

Body:
I'm trying to add error bars to line graphs using stat_summary in ggplot2 but it won't work when I facet the graphs

My data:

    date week year location imidacloprid block wickhami virescens sexta
1 15-May    1 2015  kinston           tp     1        0         0     0
2 15-May    1 2015  kinston           gh     1        0         0     0
3 15-May    1 2015  kinston          utc     1        0         0     0
4 15-May    1 2015  kinston           gh     2        0         0     0
5 15-May    1 2015  kinston          utc     2        0         0     0
6 15-May    1 2015  kinston           tp     2        0         0     0

'data.frame':   576 obs. of  9 variables:
 $ date        : Factor w/ 27 levels "1-Jul","12-Jun",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ week        : Factor w/ 12 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ year        : Factor w/ 2 levels "2015","2016": 1 1 1 1 1 1 1 1 1 1 ...
 $ location    : Factor w/ 2 levels "kinston","rocky mount": 1 1 1 1 1 1 1 1 1 1 ...
 $ imidacloprid: Factor w/ 3 levels "gh","tp","utc": 2 1 3 1 3 2 3 2 1 2 ...
 $ block       : Factor w/ 4 levels "1","2","3","4": 1 1 1 2 2 2 3 3 3 4 ...
 $ wickhami    : num  0 0 0 0 0 0 0 0 0 0 ...
 $ virescens   : num  0 0 0 0 0 0 0 0 0 0 ...
 $ sexta       : num  0 0 0 0 0 0 0 0 0 0 ...

Summarizing the data for graphing:

wickhami_sum = summarySE(bug_subset_final,
                measurevar="wickhami",
                groupvars=c("imidacloprid","week","year"))

   imidacloprid week year N wickhami         sd          se         ci
1            gh    1 2015 8   0.0000  0.0000000  0.00000000  0.0000000
2            gh    1 2016 8   0.0000  0.0000000  0.00000000  0.0000000
3            gh    2 2015 8   0.0000  0.0000000  0.00000000  0.0000000
4            gh    2 2016 8   0.0000  0.0000000  0.00000000  0.0000000
5            gh    3 2015 8   0.0000  0.0000000  0.00000000  0.0000000
6            gh    3 2016 8   0.1250  0.2314550  0.08183171  0.1935012
7            gh    4 2015 8   0.0000  0.0000000  0.00000000  0.0000000
8            gh    4 2016 8   0.5000  0.4629100  0.16366342  0.3870025
9            gh    5 2015 8   0.5000  0.3779645  0.13363062  0.3159862

The code below gives me no issue and produces a line graph of the two years of my data combined, and produces error bars via stat_summary

ggplot(wickhami_sum, aes(x=week, y=wickhami,linetype=imidacloprid,group=imidacloprid))+
  stat_summary(fun.data=mean_se,geom="errorbar",width=.2,color="black",position=position_dodge(0.2))+
  stat_summary(fun.y=mean,geom="line",position=position_dodge(0.2))

However, when I try and facet the data by year (as below), I can't get stat_summary to produce error bars and get the error message below

ggplot(wickhami_sum, aes(x=week, y=wickhami,linetype=imidacloprid,group=imidacloprid))+
  stat_summary(fun.y=mean,geom="line",position=position_dodge(0.2))+facet_grid(year~.)+
  stat_summary(fun.data=mean_se,geom="errorbar",width=.2,color="black",position=position_dodge(0.2))

Warning message:
Removed 72 rows containing missing values (geom_errorbar).

I've tried expanding the range/limits of the y axis to include the error bars but I still get the same warning message and no error bars.
I'm hoping to use stat_summary to produce the error bars for the faceted graphs and not have to calculate standard errors again. Any help is appreciated in understanding why faceting isn't allow stat_summary to function properly, or what I'm not doing correctly.

Body:
Here's what I think is happening: There are two rows of data per week in the unfacetted plot, but only one row per week in each panel of the facetted plot, causing the standard error calculation to return NA. stat_summary is intended for unsummarized data and does the data summaries internally. Use bug_subset_final with stat_summary, or switch to geom_errorbar to continue using wickhami_sum. Details below.

You've pre-summarized the data, but stat_summary is intended to work on the raw data and calculate the summary values internally. In the summary data frame wickhami_sum that you've passed to ggplot, there are two rows per week, one for each week of 2015 and one for each week of 2016. All of the data by week and year has been collapsed down to a single row for each week and year by the summary operation.

Thus, in the unfacetted plot, there are two rows of data for stat_summary to operate on for each week. But in the facetted plot, it's trying to calculate a standard error from a single observation, which is probably returning NA, hence nothing gets plotted. Even in the unfacetted plot, your error bars are being calculated from the two mean values for each year, which isn't what you want either.

Instead, either continue to use wickhami_sum, but instead of stat_summary do:

geom_errorbar(aes(ymin = wickhami - se, ymax=wickhami + se))

Or, use the raw data (which looks like it's called bug_subset_final) with stat_summary:

ggplot(bug_subset_final, aes(x=week, y=wickhami)) +
  stat_summary(fun.data=mean_se, geom="errorbar)`.


问:
Hide button based on reference from firebase
I am trying to hide some buttons based on whether the user is an admin. I have added this in the database to show true or false. I have created an if statement so that when oncreate starts if the users admin is false the buttons should be hidden but this is not what is happening

The buttons are showing as normal

// this is the code i have in the on create

```<code>        databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                User user = venueSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                                    {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

//This is the entire oncreate
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        buttonAddBeverages = (Button) findViewById(R.id.buttonAddBeverages);
        buttonAddProducts = (Button) findViewById(R.id.buttonAddProducts);
        databaseUsers = FirebaseDatabase.getInstance().getReference("users");
        //initializing firebase authentication object
        firebaseAuth = FirebaseAuth.getInstance();

        buttonAddProducts.setVisibility(View.GONE);
        buttonAddBeverages.setVisibility(View.GONE);

        //if the user is not logged in
        //that means current user will return null
        if(firebaseAuth.getCurrentUser() == null){
            //closing this activity
            finish();
            //starting login activity
            startActivity(new Intent(this, LoginActivity.class));
        }

        //getting current user
        FirebaseUser user = firebaseAuth.getCurrentUser();

        //initializing views
        textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
        buttonLogout = (Button) findViewById(R.id.buttonLogout);

        //displaying logged in user name
        textViewUserEmail.setText("Welcome "+user.getEmail());

        databaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                    User user = venueSnapshot.getValue(User.class);

                    if(user.getAdminUser() == true)
                                        {
                        buttonAddProducts.setVisibility(View.VISIBLE);
                        buttonAddBeverages.setVisibility(View.VISIBLE);
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

        buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //logging out the user
                firebaseAuth.signOut();
                //closing activity
                finish();
                //starting login activity
                startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
            }
        });
    }
</code>```

答:
```<code>buttonAddProducts.setVisibility(View.INVISIBLE);
buttonAddBeverages.setVisibility(View.INVICIBLE);
</code>```

in your xml file use button as invicible first and if users is and admin try to use visible that will work

Body:
I am trying to hide some buttons based on whether the user is an admin. I have added this in the database to show true or false. I have created an if statement so that when oncreate starts if the users admin is false the buttons should be hidden but this is not what is happening

The buttons are showing as normal

// this is the code i have in the on create

        databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                User user = venueSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                                    {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

//This is the entire oncreate
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        buttonAddBeverages = (Button) findViewById(R.id.buttonAddBeverages);
        buttonAddProducts = (Button) findViewById(R.id.buttonAddProducts);
        databaseUsers = FirebaseDatabase.getInstance().getReference("users");
        //initializing firebase authentication object
        firebaseAuth = FirebaseAuth.getInstance();

        buttonAddProducts.setVisibility(View.GONE);
        buttonAddBeverages.setVisibility(View.GONE);

        //if the user is not logged in
        //that means current user will return null
        if(firebaseAuth.getCurrentUser() == null){
            //closing this activity
            finish();
            //starting login activity
            startActivity(new Intent(this, LoginActivity.class));
        }

        //getting current user
        FirebaseUser user = firebaseAuth.getCurrentUser();

        //initializing views
        textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
        buttonLogout = (Button) findViewById(R.id.buttonLogout);

        //displaying logged in user name
        textViewUserEmail.setText("Welcome "+user.getEmail());

        databaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                    User user = venueSnapshot.getValue(User.class);

                    if(user.getAdminUser() == true)
                                        {
                        buttonAddProducts.setVisibility(View.VISIBLE);
                        buttonAddBeverages.setVisibility(View.VISIBLE);
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

        buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //logging out the user
                firebaseAuth.signOut();
                //closing activity
                finish();
                //starting login activity
                startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
            }
        });
    }

Body:
buttonAddProducts.setVisibility(View.INVISIBLE);
buttonAddBeverages.setVisibility(View.INVICIBLE);

in your xml file use button as invicible first and if users is and admin try to use visible that will work


问:
Simplest way to remove something from the FPU stack
I've been having some trouble lately with FPU stack overflows.  I managed to track it back to a buggy library function that pushes a garbage value onto the FPU stack every time it's called and never cleans it up.

Fortunately, this is easily reproducible and I know exactly what conditions cause it.  I can drop a block of inline ASM into the routine that calls this routine to pop the top value back off the FPU stack... except I don't quite know what to write.  My ASM-fu is fair to middlin', but not that strong.

So what's the simplest way to get rid of the top value on the FPU stack in x86 assembly, assuming it's garbage data and I don't care about the value?

答:
just pop it off the stack with any (fast) instruction that pops.
8087 instruction set

if that doesn't work, FUCOMPP pops twice.


问:
Complex query combining
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

```<code>+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+
</code>```

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

```<code>+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+
</code>```

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id
</code>```

And also the query:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
</code>```

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

答:
For the extended answer (to your question in my first answer, since it's too long to leave as a comment), use :

SELECT
t1.user_id, t2.consumption_november, t3.consumption_q, t1.consumption_overall
FROM (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
   FROM fillings
   GROUP BY user_id
 ) t1
 LEFT JOIN
 (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
   FROM fillings
   WHERE [date] BETWEEN '2017-11-01' AND '2017-11-31'
   GROUP BY user_id
 ) t2
 ON t1.user_id = t2.user_id
 LEFT JOIN
 (
   SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_q
   FROM fillings
   WHERE [date] BETWEEN '2017-08-01' AND '2017-11-31'
   GROUP BY user_id
 ) t3
 ON t1.user_id = t3.user_id;

for a subsequent left join, just remove the semicolon from the final left join and extend the pattern, and add the new field in the SELECT clause.

Title: Complex query combining

Body:
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id

And also the query:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.


问:
How do I execute a .scm script (outside of the REPL) with MIT-Scheme?
I want to type something like 'scheme file.scm' and have it interpret the file, and then take me back to my shell, rather than loading it in the REPL.

edit: I tried scheme < test.scm and it still uses the REPL, the only difference is that scheme exits when the stream ends.

答:
To run a scheme program using MIT Scheme:

```<code>scheme --quiet < program.scm
</code>```

The --quiet option ensures that the output from your program is the only thing that is displayed (i.e. you won't see the REPL, as per your requirements).

Caveat: This will not work if your program prompts the user for input using the input procedures (e.g. read, read-char, read-line, etc.). This is because of the shell input redirection (<) (See: relevant question). Unfortunately, there is currently no proper way of executing an MIT Scheme script from the command line when input  procedures are used. The best option is probably mit-scheme --quiet --load 'myscript', but you'd have to manually exit MIT Scheme when the script finishes. Relevant mailing list thread: [MIT-Scheme-devel] How to run a script and exit?

EDIT: Due to the possibility that you may mistype < as >, resulting in the overwrite of your source code, I would suggest encapsulating the above command within a shell script or a shell function. For example:

```<code>runscheme () {
    scheme --quiet < "$1"
}
</code>```

Then you can run runscheme program.scm without fear that your source code will be overwritten. (Special thanks to Paul Rooney for bringing this potential mistake to my attention).

References

scheme --help:

--batch-mode, --quiet, --silent

Suppresses the startup report of versions and copyrights, and the
  valediction.

This command line option seems to have been mistakenly ommitted from the list of command line options in the documentation, but I think this is a legimate command line option because scheme --help shows it, and because --batch-mode is used in other parts of the reference manual (e.g. here).

OwnerDisplayName: Rusty

LastEditorDisplayName: Rusty

Body:
To run a scheme program using MIT Scheme:

scheme --quiet < program.scm

The --quiet option ensures that the output from your program is the only thing that is displayed (i.e. you won't see the REPL, as per your requirements).

Caveat: This will not work if your program prompts the user for input using the input procedures (e.g. read, read-char, read-line, etc.). This is because of the shell input redirection (<) (See: relevant question). Unfortunately, there is currently no proper way of executing an MIT Scheme script from the command line when input  procedures are used. The best option is probably mit-scheme --quiet --load 'myscript', but you'd have to manually exit MIT Scheme when the script finishes. Relevant mailing list thread: [MIT-Scheme-devel] How to run a script and exit?

EDIT: Due to the possibility that you may mistype < as >, resulting in the overwrite of your source code, I would suggest encapsulating the above command within a shell script or a shell function. For example:

runscheme () {
    scheme --quiet < "$1"
}

Then you can run runscheme program.scm without fear that your source code will be overwritten. (Special thanks to Paul Rooney for bringing this potential mistake to my attention).

References

scheme --help:

--batch-mode, --quiet, --silent

Suppresses the startup report of versions and copyrights, and the
  valediction.

This command line option seems to have been mistakenly ommitted from the list of command line options in the documentation, but I think this is a legimate command line option because scheme --help shows it, and because --batch-mode is used in other parts of the reference manual (e.g. here).