问:
Google Cloud Storage, reads/writes limitations
We have an AppEngine FLEXIBLE application which stores images in a bucket of the Cloud Storage.
Our application should read each selected image and save several cropped part of the image into the same bucket which original image is stored in. For example we can say crop 5 parts of an images, so 5 new images going to be stored in the bucket and this should be done for many images. the app works perfectly if we choose few images ( 2 to 5 ) with few number of coping part (2-3), but if we select more than 10 images and many cropping parts then after a while we see the following error:

```<code>Failed to load resource: the server responded with a status of 502 ()
</code>```

Any Idea how to resolve this problem ?

答:
I could resolve the problem by putting the thread to sleep for 5 seconds after each image saving into the storage. I have just added the following line into "for" loop where I save an image:

```<code>Thread.sleep(5000);
</code>```

So in this case, the procedure gets longer but it won't get blocked by Cloud Storage!

Body:
We have an AppEngine FLEXIBLE application which stores images in a bucket of the Cloud Storage.
Our application should read each selected image and save several cropped part of the image into the same bucket which original image is stored in. For example we can say crop 5 parts of an images, so 5 new images going to be stored in the bucket and this should be done for many images. the app works perfectly if we choose few images ( 2 to 5 ) with few number of coping part (2-3), but if we select more than 10 images and many cropping parts then after a while we see the following error:

Failed to load resource: the server responded with a status of 502 ()

Any Idea how to resolve this problem ?

Body:
I could resolve the problem by putting the thread to sleep for 5 seconds after each image saving into the storage. I have just added the following line into "for" loop where I save an image:

Thread.sleep(5000);

So in this case, the procedure gets longer but it won't get blocked by Cloud Storage!


来源: stackexchange

问:
Tkinter checkbuttons defaults to show a minus sign on Mac
I have an issue with checkboxes displaying a minus sign by default on Mac:

The following code was used to produce these inside a labelframe:

```<code>for x in ["Why", "Do", "These", "Have", "Minus", "Signs", "On", "Them?", "Clicked once", "Clicked twice"]:
    check_button = ttk.Checkbutton(
        check_button_labelframe,
        text=x,
    )
    check_button.grid(column=0, row=current_button_row, sticky="W")
    current_button_row += 1
</code>```

What does the minus sign mean? I want them to either be checked or blank (as in "Clicked once" and "Clicked twice" in the screenshot, respectively). I've tried providing variable=somevariable where

```<code>somevariable=tk.IntVar()
somevariable.set(1)
</code>```

but that doesn't change anything. I'm using ttk.checkbuttons here, when using tk.checkbuttons, all the boxes are just blank.

EDIT: A more complete example:

```<code>        cases = {
            "case1": {
                "description": "This is case 1",
                "enabled_or_not": 0,
                "enabled_var": tk.IntVar()
            },
            "case2": {
                "description": "This is case 2",
                "enabled_or_not": 1,
                "enabled_var": tk.IntVar()
            }
        }

        for case in cases.keys():
            case_info = cases[case]
            case_info["enabled_var"].set(case_info["enabled_or_not"])
            check_button = ttk.Checkbutton(
                check_button_labelframe,
                text=case_info["description"],
                variable=case_info["enabled_var"],
                onvalue=1,
                offvalue=0
            )
            check_button.grid(column=0, row=current_button_row, sticky="W")
            current_button_row += 1
</code>```

which yields this:

EDIT 2:
This appears to have something to do with how Macs animate checkboxes, check it out:

EDIT 1000 (MCVE): You're right, guys, if I strip away everything but the checkboxes, it works:

```<code>app = tk.Tk()
app.wm_title("MCVE")
app.geometry("320x240")

# Tk checkbuttons
first_var = tk.IntVar()
first_var.set(1)
first_checkbox = tk.Checkbutton(app, text="This should be enabled", variable=first_var, onvalue=1, offvalue=0)
first_checkbox.grid(column=0, row=0, sticky="W")

second_var = tk.IntVar()
second_var.set(0)
second_checkbox = tk.Checkbutton(app, text="This should be disabled", variable=second_var, onvalue=1, offvalue=0)
second_checkbox.grid(column=0, row=1)

# Ttk checkbuttons
third_var = tk.IntVar()
third_var.set(1)
third_checkbox = ttk.Checkbutton(app, text="This should be enabled", variable=third_var, onvalue=1, offvalue=0)
third_checkbox.grid(column=0, row=2)

fourth_var = tk.IntVar()
fourth_var.set(0)
fourth_checkbox = ttk.Checkbutton(app, text="This should be disabled", variable=fourth_var, onvalue=1, offvalue=0)
fourth_checkbox.grid(column=0, row=3)

app.mainloop()
</code>```

So does it have anything to do with the variables being stored in a dictionary?

答:
Minus sign is default state, on windows it is check sign with grey background.

I prefer using .deselect() method after creating checkbox - looks better.

ContentLicense: CC BY-SA 3.0

Body:
I have an issue with checkboxes displaying a minus sign by default on Mac:

The following code was used to produce these inside a labelframe:

for x in ["Why", "Do", "These", "Have", "Minus", "Signs", "On", "Them?", "Clicked once", "Clicked twice"]:
    check_button = ttk.Checkbutton(
        check_button_labelframe,
        text=x,
    )
    check_button.grid(column=0, row=current_button_row, sticky="W")
    current_button_row += 1

What does the minus sign mean? I want them to either be checked or blank (as in "Clicked once" and "Clicked twice" in the screenshot, respectively). I've tried providing variable=somevariable where

somevariable=tk.IntVar()
somevariable.set(1)

but that doesn't change anything. I'm using ttk.checkbuttons here, when using tk.checkbuttons, all the boxes are just blank.

EDIT: A more complete example:

        cases = {
            "case1": {
                "description": "This is case 1",
                "enabled_or_not": 0,
                "enabled_var": tk.IntVar()
            },
            "case2": {
                "description": "This is case 2",
                "enabled_or_not": 1,
                "enabled_var": tk.IntVar()
            }
        }

        for case in cases.keys():
            case_info = cases[case]
            case_info["enabled_var"].set(case_info["enabled_or_not"])
            check_button = ttk.Checkbutton(
                check_button_labelframe,
                text=case_info["description"],
                variable=case_info["enabled_var"],
                onvalue=1,
                offvalue=0
            )
            check_button.grid(column=0, row=current_button_row, sticky="W")
            current_button_row += 1

which yields this:

EDIT 2:
This appears to have something to do with how Macs animate checkboxes, check it out:

EDIT 1000 (MCVE): You're right, guys, if I strip away everything but the checkboxes, it works:

app = tk.Tk()
app.wm_title("MCVE")
app.geometry("320x240")

# Tk checkbuttons
first_var = tk.IntVar()
first_var.set(1)
first_checkbox = tk.Checkbutton(app, text="This should be enabled", variable=first_var, onvalue=1, offvalue=0)
first_checkbox.grid(column=0, row=0, sticky="W")

second_var = tk.IntVar()
second_var.set(0)
second_checkbox = tk.Checkbutton(app, text="This should be disabled", variable=second_var, onvalue=1, offvalue=0)
second_checkbox.grid(column=0, row=1)

# Ttk checkbuttons
third_var = tk.IntVar()
third_var.set(1)
third_checkbox = ttk.Checkbutton(app, text="This should be enabled", variable=third_var, onvalue=1, offvalue=0)
third_checkbox.grid(column=0, row=2)

fourth_var = tk.IntVar()
fourth_var.set(0)
fourth_checkbox = ttk.Checkbutton(app, text="This should be disabled", variable=fourth_var, onvalue=1, offvalue=0)
fourth_checkbox.grid(column=0, row=3)

app.mainloop()

So does it have anything to do with the variables being stored in a dictionary?


问:
URL Rewrite with parameter and php query
Directories:
 eventfinder is project folder

Localhost

-- project1

-- project2

-- eventfinder

--- .htaccess

User comes to the page http://localhost/eventfinder/ and types 'randomevent123' after /eventfinder/

then php query happens with ?event=randomevent123

```<code>$event = $_GET['event'];

$stmt = $conn->prepare("SELECT * FROM events WHERE name = :name");
$stmt->bindParam(":name", $event);
$stmt->execute();
</code>```

and returns data from database

I am trying to rewrite my url but I don't understand what is the problem...

```<code>http://localhost/eventfinder/index.php?event=randomevent123
</code>```

to

```<code>http://localhost/eventfinder/randomevent123
</code>```

With .htaccess

```<code>RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?event=$1 [L]
</code>```

But query won't work.

答:
Give the following a try:

Confirm that mod_rewrite is loaded

Check that AllowOverride allows htaccess parsing

The following rule (inside eventfinder directory):

```<code>RewriteEngine On
RewriteBase /eventfinder/

RewriteCond %{THE_REQUEST} ^GET\ /eventfinder/index\.php\?event=([^\s&]+) [NC]
RewriteRule ^index\.php$ %1 [R,L,QSD]

RewriteRule ^(?!index\.php([^/]+))$ index.php?event=$1 [L]
</code>```

Body:
Directories:
 eventfinder is project folder

Localhost

-- project1

-- project2

-- eventfinder

--- .htaccess

User comes to the page http://localhost/eventfinder/ and types 'randomevent123' after /eventfinder/

then php query happens with ?event=randomevent123

$event = $_GET['event'];

$stmt = $conn->prepare("SELECT * FROM events WHERE name = :name");
$stmt->bindParam(":name", $event);
$stmt->execute();

and returns data from database

I am trying to rewrite my url but I don't understand what is the problem...

http://localhost/eventfinder/index.php?event=randomevent123

to

http://localhost/eventfinder/randomevent123

With .htaccess

RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?event=$1 [L]

But query won't work.

Body:
Give the following a try:

Confirm that mod_rewrite is loaded

Check that AllowOverride allows htaccess parsing

The following rule (inside eventfinder directory):

RewriteEngine On
RewriteBase /eventfinder/

RewriteCond %{THE_REQUEST} ^GET\ /eventfinder/index\.php\?event=([^\s&]+) [NC]
RewriteRule ^index\.php$ %1 [R,L,QSD]

RewriteRule ^(?!index\.php([^/]+))$ index.php?event=$1 [L]


问:
Getting a Run Time Error on the following Code
The Question:-
https://www.codechef.com/JUNE17/problems/NEO01

My solution, which according to me should be the right solution to the aforementioned question but I am constantly getting a RTE.

https://ideone.com/COnlog

```<code>#include<stdio.h>
int main()
{
    long arr[10000];
    int t,n,p=0;
    scanf("%d",&t);

    while(t--)
    {
        long hap1=0,hap2=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&arr[i]);
        }

        for(int i=0;i<n;i++)
        {
            if(arr[i]>=0)
            {
                hap1+=arr[i];
                p++;
            }
            else
            {
                hap2+=arr[i];
            }
        }
        printf("%d\n",hap1*p+hap2);
    }
    return 0;
}
</code>```

Edit: Sorry, I am a beginner who usually uses cout and cin, used scanf and printf to save time, and just forgot to add & while using scanf.

Although my code works fine on Dev-C++ 5.11 it shows a Runtime error(SIGSEGV) and I have no idea why is it happening.

答: You're using scnaf incorrectly. Change scanf("%d",t); into scanf("%d",&t);

Body:
The Question:-
https://www.codechef.com/JUNE17/problems/NEO01

My solution, which according to me should be the right solution to the aforementioned question but I am constantly getting a RTE.

https://ideone.com/COnlog

#include<stdio.h>
int main()
{
    long arr[10000];
    int t,n,p=0;
    scanf("%d",&t);

    while(t--)
    {
        long hap1=0,hap2=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&arr[i]);
        }

        for(int i=0;i<n;i++)
        {
            if(arr[i]>=0)
            {
                hap1+=arr[i];
                p++;
            }
            else
            {
                hap2+=arr[i];
            }
        }
        printf("%d\n",hap1*p+hap2);
    }
    return 0;
}

Edit: Sorry, I am a beginner who usually uses cout and cin, used scanf and printf to save time, and just forgot to add & while using scanf.

Although my code works fine on Dev-C++ 5.11 it shows a Runtime error(SIGSEGV) and I have no idea why is it happening.


问:
React env variables with .env
I'm trying to follow docs on adding env variables from react-create-app without success:

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables

inside root of the document I have a ".env" file (default .env properties)

.env file contains only one variable 'REACT_APP_API_HOST=http://localhost:8080'

trying to access process.env inside my app (created with create react app) gives me undefined

This is app.js where I'm trying to access process.env without success.

I can't access process.env inside the code. Is there any working example on how to do it?

答:
In your package.json you will eventually have to add NODE_ENV=development at your start script. E.g. NODE_ENV=development && node scripts/start.js for the ejected create-react-app and NODE_ENV=development react-scripts start for the unejected one.

Edit: Apparently NODE_ENV=development is not required since it is already hardcoded when you run the start or build script. Per the docs your custom environment variables should have the following format REACT_APP* as you have already done.

A snippet would be helpful.

Title: React env variables with .env


问:
how to remove \ from json data?
I use .net wcf services in my angular project, but i get the response like that:

```<code>{
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}
</code>```

but the desired result;

```<code>[{"state_id":"1","state_name":"Madhya Pradesh","IsActive":"True"},{"state_id":"2","state_name":"Gujrat","IsActive":"True"},{"state_id":"3","state_name":"Goa","IsActive":"True"},{"state_id":"4","state_name":"Maharashtra","IsActive":"True"}]
</code>```

答:
You can just parse that result, like so:</p>

```<code>let result = {
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}
result = JSON.parse(result.stateResult);
</code>```

Title: how to remove \ from json data?

Body:
I use .net wcf services in my angular project, but i get the response like that:

{
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}

but the desired result;

[{"state_id":"1","state_name":"Madhya Pradesh","IsActive":"True"},{"state_id":"2","state_name":"Gujrat","IsActive":"True"},{"state_id":"3","state_name":"Goa","IsActive":"True"},{"state_id":"4","state_name":"Maharashtra","IsActive":"True"}]

Body:
You can just parse that result, like so:

let result = {
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}
result = JSON.parse(result.stateResult);


问:
setLayoutParams of a layout inside a Fragment from an Activity
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

```<code>public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}
</code>```

These are the MenuItem that are calling the methods:

```<code>getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });
</code>```

This is how I define the fragment inside the activity in onCreate:

```<code>patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
</code>```

And this is the error:

```<code>06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
</code>```

答:
Base on stackTrace which you provide looks like your PatientFragment is null when you want to call searcherOpen().
So you need to instantiate it first and then call that method.
This call:

```<code>patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");
</code>```

is wrong, you should create it throught newInstance() call and add it to an activity using FragmentManager, please read this arcticle for related questions

Body:
I have an Activity that has many fragment inside. When on a particular fragment I inflate a menu and when clicking on the inflated MenuItem I should call a method of the Fragment class that change the layout params of a Constraint Layout inside the fragment. The problem is that I get a NPE on the Constraint Layout I'm trying to change.

These are the methods I'm trying to call:

public void searcherOpen() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    searchText.setFocusable(true);
}
public void searcherClose() {
    searchLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0, 0));
    searchText.setFocusable(false);
}

These are the MenuItem that are calling the methods:

getMenuInflater().inflate(R.menu.patient_fragment_menu, menu);
        final MenuItem search = menu.findItem(R.id.menu_search);
        final MenuItem close_search = menu.findItem(R.id.menu_search_close);
        search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherOpen();
                search.setVisible(false);
                close_search.setVisible(true);
                return true;
            }
        });
        close_search.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                patientFragment.searcherClose();
                search.setVisible(true);
                close_search.setVisible(false);
                return true;
            }
        });

This is how I define the fragment inside the activity in onCreate:

patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");

And this is the error:

06-06 14:52:23.314 3682-3682/com.medishare.zeeromed E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.medishare.zeeromed, PID: 3682
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.medishare.zeeromed.fragments.PatientFragment.searcherOpen()' on a null object reference
                                                                      at com.medishare.zeeromed.DrawerActivity$3.onMenuItemClick(DrawerActivity.java:255)
                                                                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22393)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:173)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)

Body:
Base on stackTrace which you provide looks like your PatientFragment is null when you want to call searcherOpen().
So you need to instantiate it first and then call that method.
This call:

patientFragment = (PatientFragment)getFragmentManager().findFragmentByTag("patientFragment");

is wrong, you should create it throught newInstance() call and add it to an activity using FragmentManager, please read this arcticle for related questions


问:
I want to disable Jquery tablednd
Hi i have used jquery tablednd. I have written a function which initializes the tablednd to a table

But i want to know if there is any option of disabling the tablednd...??

答:
you can remove the cssclasses nodrop and nodrag

```<code>rows.removeClass('nodrop nodrag');
</code>```

where rows are the table rows

ContentLicense: CC BY-SA 2.5

Title: I want to disable Jquery tablednd

Body:
you can remove the cssclasses nodrop and nodrag

rows.removeClass('nodrop nodrag');

where rows are the table rows


问:
Android Camera 2 preview size and devices aspect ratio
I'm implementing Camera 2 API in my project. I'm using TextureView and these line of codes to set the camera fullscreen preview size:

```<code>StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];
</code>```

This seems to be the largest preview size that device support. I'm not sure if this size works with all devices and fit its device's aspect ratio without being stretched. Does anyone know?

答:
Change the AutoFitTextureView.java file and set value like below:

```<code>@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);

    if (0 == mRatioWidth || 0 == mRatioHeight) {
        setMeasuredDimension(width, height);
    } else {
        if (width < height * mRatioWidth / mRatioHeight) {
            setMeasuredDimension(width, height);
            Log.d("rlijeolid1",String.valueOf(width)+"\t"+String.valueOf(height));
        } else {
            setMeasuredDimension(width , height);
            Log.d("rlijeolid2",String.valueOf(height * mRatioWidth / mRatioHeight)+"\t"+String.valueOf(height));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm implementing Camera 2 API in my project. I'm using TextureView and these line of codes to set the camera fullscreen preview size:

StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];

This seems to be the largest preview size that device support. I'm not sure if this size works with all devices and fit its device's aspect ratio without being stretched. Does anyone know?

Body:
Change the AutoFitTextureView.java file and set value like below:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);

    if (0 == mRatioWidth || 0 == mRatioHeight) {
        setMeasuredDimension(width, height);
    } else {
        if (width < height * mRatioWidth / mRatioHeight) {
            setMeasuredDimension(width, height);
            Log.d("rlijeolid1",String.valueOf(width)+"\t"+String.valueOf(height));
        } else {
            setMeasuredDimension(width , height);
            Log.d("rlijeolid2",String.valueOf(height * mRatioWidth / mRatioHeight)+"\t"+String.valueOf(height));
        }
    }
}


问:
GWT IntegerBox wrap and events
A subsection of html which gets loaded into a Frame (IframeElement):

```<code><tr>
    <td>Desc</td>
    <td><select id="descfont" class="fontname"></select></td>
    <td><input id="descbold" type="checkbox"></td>
    <td><input id="descitalic" type="checkbox"></td>
    <td><input id="descsize" type="number" class="numberbox"></td>
    <td><canvas id="desccolour" class="colorcanvas"></canvas></td>
</tr>
</code>```

I can wrap select boxes, check boxes, buttons, text boxes and canvases. But I cannot find a way of wrapping the input box with the type as "number".

```<code>final ListBox dfont = ListBox.wrap(doc.getElementById("descfont"));
final SimpleCheckBox dbold = SimpleCheckBox.wrap(doc.getElementById("descbold"));
final SimpleCheckBox ditalic = SimpleCheckBox.wrap(doc.getElementById("descitalic"));
final Canvas dcanvas = Canvas.wrap((CanvasElement)doc.getElementById("desccolour"));
</code>```

And this or similar terms I've tried don't work:

```<code>final ValueBox<Object> title_size = IntegerBox.wrap(doc.getElementById("descsize"),
    IntegerRenderer.instance(), IntegerParser.instance());
</code>```

or

```<code>'something' = ValueBox.wrap(doc.getElementById("descsize"), null, null);
</code>```

Does anyone know how to do this?

As well as that, I can use the onBlur() event on a text box. What events would be required for the IntegerBox?

Many thanks in advance...

EDIT: changed title size to descsize in snippets.

答:
After following the error suggestions from Eclipse I finally managed to get it working and without the need for the onBlur event handler.

```<code>final ValueBox<Integer> title_size = IntegerBox.wrap(doc.getElementById("titlesize"),
    IntegerRenderer.instance(), IntegerParser.instance());

title_size.setSelectionRange(0, 200); // hoping this works now
title_size.setValue(vscroll.desc_size);

title_size.addChangeHandler(new ChangeHandler() {

    @Override
    public void onChange(ChangeEvent event) {
        log.info("New value: " + title_size.getValue());
    }
});
</code>```

Obviously now all I need is to add the validation code and account for erroneous inputs.

Title: GWT IntegerBox wrap and events

Body:
A subsection of html which gets loaded into a Frame (IframeElement):

    Desc
    <select id="descfont" class="fontname"></select>
    <input id="descbold" type="checkbox">
    <input id="descitalic" type="checkbox">
    <input id="descsize" type="number" class="numberbox">
    <canvas id="desccolour" class="colorcanvas"></canvas>

I can wrap select boxes, check boxes, buttons, text boxes and canvases. But I cannot find a way of wrapping the input box with the type as "number".

final ListBox dfont = ListBox.wrap(doc.getElementById("descfont"));
final SimpleCheckBox dbold = SimpleCheckBox.wrap(doc.getElementById("descbold"));
final SimpleCheckBox ditalic = SimpleCheckBox.wrap(doc.getElementById("descitalic"));
final Canvas dcanvas = Canvas.wrap((CanvasElement)doc.getElementById("desccolour"));

And this or similar terms I've tried don't work:

final ValueBox<Object> title_size = IntegerBox.wrap(doc.getElementById("descsize"),
    IntegerRenderer.instance(), IntegerParser.instance());

or

'something' = ValueBox.wrap(doc.getElementById("descsize"), null, null);

Does anyone know how to do this?

As well as that, I can use the onBlur() event on a text box. What events would be required for the IntegerBox?

Many thanks in advance...

EDIT: changed title size to descsize in snippets.

Body:
After following the error suggestions from Eclipse I finally managed to get it working and without the need for the onBlur event handler.

final ValueBox<Integer> title_size = IntegerBox.wrap(doc.getElementById("titlesize"),
    IntegerRenderer.instance(), IntegerParser.instance());

title_size.setSelectionRange(0, 200); // hoping this works now
title_size.setValue(vscroll.desc_size);

title_size.addChangeHandler(new ChangeHandler() {

    @Override
    public void onChange(ChangeEvent event) {
        log.info("New value: " + title_size.getValue());
    }
});

Obviously now all I need is to add the validation code and account for erroneous inputs.


问:
JSON Array with string and boolean
I am creating a xCode/Swift project with .json.

I want to create an array of keys, and also a boolean(true/false) to mark if the key is used or not. Standard boolean value is false. And if the key is used, it updates to true. I am not sure how to do this, but I have tried something like this:

```<code>{
    "aloUrl": "fb://profile/********",
    "imgAD_active": true,
    "keys"{
        "key_red": false // if key "key_red" is used, set to true
        "key_green": false
        "key_black": false
        "key_white": false
        "key_orange": false
        "key_pink": false
    }
}
</code>```

How do I do this?

答:
you can use dictionary contains of String as keys and Any as values

```<code>let dic: [String: Any]
dic["aloUrl"] = "fb://profile/********"
dic["imgAD_active"] = true
dic["keys"] = ["key_green": false, "key_red": false, ...]
</code>```

I also retrieve values as

```<code>let url = dic["aloUrl"] as? String
</code>```

Title: JSON Array with string and boolean

Body:
I am creating a xCode/Swift project with .json.

I want to create an array of keys, and also a boolean(true/false) to mark if the key is used or not. Standard boolean value is false. And if the key is used, it updates to true. I am not sure how to do this, but I have tried something like this:

{
    "aloUrl": "fb://profile/********",
    "imgAD_active": true,
    "keys"{
        "key_red": false // if key "key_red" is used, set to true
        "key_green": false
        "key_black": false
        "key_white": false
        "key_orange": false
        "key_pink": false
    }
}

How do I do this?

Body:
you can use dictionary contains of String as keys and Any as values

let dic: [String: Any]
dic["aloUrl"] = "fb://profile/********"
dic["imgAD_active"] = true
dic["keys"] = ["key_green": false, "key_red": false, ...]

I also retrieve values as

let url = dic["aloUrl"] as? String


问:
how to display a bar chart (jqplot) when pressing a button?
i try to display a bar chart on a pressing on a button but without success , can some one can give me an example ? ( i'm new in java script)
i try that:

```<code>$("#vm_buttons").button();
        $("#vm_buttons").click(function (evt) {
            // increment the value of output
          //  alert ('click');
            bar_chart_add('test_1',[1,3,4],[2,5,6] ,"test",['a','b','c']);

        });
</code>```

bar_chart is function that make  bar chart .

10x,
perry

答:
Give your button an ID. Then, use the click(function()) to achieve the functionality. I used jqplot in the example -

See this -
https://jsfiddle.net/ha3y1omd/

```<code><button type="button" id="btnclick" class="btn btn-primary">Primary</button>

<div class="container" id="chart1">
</div>
</code>```

In your JS file,

```<code> $(document).ready(function(){
    $('#btnclick').click(function(){
       CapacityChart();
    });
  });

function CapacityChart()    {
       var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]);
}
</code>```

Body:
i try to display a bar chart on a pressing on a button but without success , can some one can give me an example ? ( i'm new in java script)
i try that:

$("#vm_buttons").button();
        $("#vm_buttons").click(function (evt) {
            // increment the value of output
          //  alert ('click');
            bar_chart_add('test_1',[1,3,4],[2,5,6] ,"test",['a','b','c']);

        });

bar_chart is function that make  bar chart .

10x,
perry

Body:
Give your button an ID. Then, use the click(function()) to achieve the functionality. I used jqplot in the example -

See this -
https://jsfiddle.net/ha3y1omd/

<button type="button" id="btnclick" class="btn btn-primary">Primary</button>

<div class="container" id="chart1">
</div>

In your JS file,

 $(document).ready(function(){
    $('#btnclick').click(function(){
       CapacityChart();
    });
  });

function CapacityChart()    {
       var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]);
}


问:
How can I clear express session for all users without restarting the application?
I was developing REST services using nodejs express framework and keeping the user specific data in the session with user's id as key to identify user's data.

Here Is the code I am using to store user specific data:

```<code>let session = require("express-session");
let FileStore = require("session-file-store")(session);

//For setting up the data into session
session[userId]={name:xyz, age:22}

//For getting the data
session[userId]
</code>```

I have also configured session with expiry time, which must clear out all the session value.

```<code>  webserver.use(session({
        cookie: {
            maxAge: 60 * 1000 // 24 hours
            // maxAge: 24 * 60 * 60 * 1000 // 24 hours
        },
        key: "sid",
        resave: false,
        saveUninitialized: false,
        secret: "keyboard cat",
        store: new FileStore(storageOptions),
    }));`
</code>```

but the session values seems persisted even after expiry time exceeded. although these are rest services and no cookies are involved in this, I am using user's id instead.

As per my understanding this session should be clear out after expiry time exceeded but it's not.

Question 1 : How can I clear complete session values anytime without restarting the server ?
Question 2 : Why expiry time is not working as per above code ?

Am I doing something wrong ?

Please help

Thanks in advance

答:
I think cookie.maxAge is used to define inactivity time. So the session will be detroyed after 24 hours of inactivity.

If you want to detroy user session, you can use somethink like this :

```<code>req.session.destroy(function (err) {
  if (err) {
    // Handle error
  }
  else {
    // Session destroyed !
  }
});
</code>```

Hope it helps !

Body:
I was developing REST services using nodejs express framework and keeping the user specific data in the session with user's id as key to identify user's data.

Here Is the code I am using to store user specific data:

let session = require("express-session");
let FileStore = require("session-file-store")(session);

//For setting up the data into session
session[userId]={name:xyz, age:22}

//For getting the data
session[userId]

I have also configured session with expiry time, which must clear out all the session value.

  webserver.use(session({
        cookie: {
            maxAge: 60 * 1000 // 24 hours
            // maxAge: 24 * 60 * 60 * 1000 // 24 hours
        },
        key: "sid",
        resave: false,
        saveUninitialized: false,
        secret: "keyboard cat",
        store: new FileStore(storageOptions),
    }));`

but the session values seems persisted even after expiry time exceeded. although these are rest services and no cookies are involved in this, I am using user's id instead.

As per my understanding this session should be clear out after expiry time exceeded but it's not.

Question 1 : How can I clear complete session values anytime without restarting the server ?
Question 2 : Why expiry time is not working as per above code ?

Am I doing something wrong ?

Please help

Thanks in advance

Body:
I think cookie.maxAge is used to define inactivity time. So the session will be detroyed after 24 hours of inactivity.

If you want to detroy user session, you can use somethink like this :

req.session.destroy(function (err) {
  if (err) {
    // Handle error
  }
  else {
    // Session destroyed !
  }
});

Hope it helps !


问:
GCC 6.x warning about lambda visibility
I am building a shared library that contains a bunch of lambdas, and some of those lambdas are created inside other lambdas. But, when I use -fvisibility=hidden and -Wall I get a warning about declarations of something with greater visibility, that I honestly do not understand. I have a minimal example:

```<code>#include <memory>
template<class T>
class MyClass  {
public:
    MyClass() {
#if 0
        auto fn = [this]           { /*Do something useful here*/ };
        auto outer = [this,fn]()   { /*use fn for something here*/ };
#else
        auto outer = [this]()
            {
                auto fn = [this]   { /*Do something useful here */ };
                //use fn for something here
            };
#endif
        /* use outer for something */
    }
};
int main() { MyClass<int> r; }
</code>```

If I compile this I get the following warning:

```<code>% g++    -Wall -fvisibility=hidden -Wno-unused-but-set-variable  -o visibility_test.cpp.o -c visibility_test.cpp
visibility_test.cpp: In instantiation of ‘struct MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>’:
visibility_test.cpp:13:22:   required from ‘MyClass<T>::MyClass()::<lambda()> [with T = int]’
visibility_test.cpp:11:23:   required from ‘struct MyClass<T>::MyClass() [with T = int]::<lambda()>’
visibility_test.cpp:11:14:   required from ‘MyClass<T>::MyClass() [with T = int]’
visibility_test.cpp:22:27:   required from here
visibility_test.cpp:13:32: warning: ‘MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>’ declared with greater visibility than the type of its field ‘MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>::<this capture>’ [-Wattributes]
                 auto fn = [this]   { /*Do something useful here */ };
</code>```

If I change the #if 0 to #if 1, thereby moving the creation of fn to outside the "outer" lambda it all compiles fine.

This warning started appearing when I installed GCC 6 on my Arch box. I get it when compiling with 6.3.1 and 7.1.1.

So, my questions are:

What is this warning trying to tell me?

How do I get rid of the warning without having to violate my code too much (moving the lambdas like in my example is not really an option.)

Update: So, I have accepted that this is a bug in GCC, and I now wanted to get rid of the warning with minimal side effects. So I added "__attribute__ ((visibility ("default")))" to the constructor of MyClass, which appears to work nicely.

答:
Looks like it's a bug in gcc.

There is bug report and there were same warnings earlier without lambdas. You can handle this with using -fvisibility default, or manually setupping visibility to hidden/default by attribute.

Title: GCC 6.x warning about lambda visibility

Body:
I am building a shared library that contains a bunch of lambdas, and some of those lambdas are created inside other lambdas. But, when I use -fvisibility=hidden and -Wall I get a warning about declarations of something with greater visibility, that I honestly do not understand. I have a minimal example:

#include <memory>
template<class T>
class MyClass  {
public:
    MyClass() {
#if 0
        auto fn = [this]           { /*Do something useful here*/ };
        auto outer = [this,fn]()   { /*use fn for something here*/ };
#else
        auto outer = [this]()
            {
                auto fn = [this]   { /*Do something useful here */ };
                //use fn for something here
            };
#endif
        /* use outer for something */
    }
};
int main() { MyClass<int> r; }

If I compile this I get the following warning:

% g++    -Wall -fvisibility=hidden -Wno-unused-but-set-variable  -o visibility_test.cpp.o -c visibility_test.cpp
visibility_test.cpp: In instantiation of ‘struct MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>’:
visibility_test.cpp:13:22:   required from ‘MyClass<T>::MyClass()::<lambda()> [with T = int]’
visibility_test.cpp:11:23:   required from ‘struct MyClass<T>::MyClass() [with T = int]::<lambda()>’
visibility_test.cpp:11:14:   required from ‘MyClass<T>::MyClass() [with T = int]’
visibility_test.cpp:22:27:   required from here
visibility_test.cpp:13:32: warning: ‘MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>’ declared with greater visibility than the type of its field ‘MyClass<T>::MyClass()::<lambda()> [with T = int]::<lambda()>::<this capture>’ [-Wattributes]
                 auto fn = [this]   { /*Do something useful here */ };

If I change the #if 0 to #if 1, thereby moving the creation of fn to outside the "outer" lambda it all compiles fine.

This warning started appearing when I installed GCC 6 on my Arch box. I get it when compiling with 6.3.1 and 7.1.1.

So, my questions are:

What is this warning trying to tell me?

How do I get rid of the warning without having to violate my code too much (moving the lambdas like in my example is not really an option.)

Update: So, I have accepted that this is a bug in GCC, and I now wanted to get rid of the warning with minimal side effects. So I added "__attribute__ ((visibility ("default")))" to the constructor of MyClass, which appears to work nicely.


问:
What are non standard attributes use for?
Today, I was parsing google's HTML and faced with some non standard HTML's attributes. Take a look at this:

As you know, there isn't either jsname or jsdata or .. attributes in HTML. Well I'm just curious, what google use them for?

答:
jsaction attribute is added by Google's jsaction library.
It's source code can be found on project's GitHub page: https://github.com/google/jsaction

I have no idea about the other attributes though.


问:
R - Using glmnet with purrr/tidyr
I am following code from this R Bloggers link in order to run models on groups within my data using tidyr and purrr. However, I would like to use glmnet rather than just lm on my nested data. Unlike lm, glmnet/cv.glmnet takes a model.matrix as the x argument and I need to abstract the formula fed to that model.matrix and that is what is holding me up.

So this works:

```<code>library(purrr)
library(tidyr)
library(dplyr)
library(glmnet)

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., .$mpg ~ .$cyl * .$hp)[,-1],
    y = .$mpg
  )))
mod_test
> mod_test
# A tibble: 2 x 3
     vs               data          cv_mod
  <dbl>             <list>          <list>
1     0 <tibble [18 x 10]> <S3: cv.glmnet>
2     1 <tibble [14 x 10]> <S3: cv.glmnet>
</code>```

But when I try to create the formula for the model.matrix separately, it does not.

```<code>mod_form <- as.formula(".$mpg ~ .$cyl * .$hp")

mod_test2 <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., mod_form)[,-1],
    y = .$mpg
  )))
Error in mutate_impl(.data, dots) : object '.' not found
</code>```

答:
You can use glmnetUtils if you want a formula/data frame interface to glmnet. This makes interfacing with the tidyverse a bit more convenient.</p>

```<code>install.packages("glmnetUtils")

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod=map(data, ~ cv.glmnet(mpg ~ cyl + hp, data=.)))
</code>```

Title: R - Using glmnet with purrr/tidyr

Body:
I am following code from this R Bloggers link in order to run models on groups within my data using tidyr and purrr. However, I would like to use glmnet rather than just lm on my nested data. Unlike lm, glmnet/cv.glmnet takes a model.matrix as the x argument and I need to abstract the formula fed to that model.matrix and that is what is holding me up.

So this works:

library(purrr)
library(tidyr)
library(dplyr)
library(glmnet)

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., .$mpg ~ .$cyl * .$hp)[,-1],
    y = .$mpg
  )))
mod_test
> mod_test
# A tibble: 2 x 3
     vs               data          cv_mod
  <dbl>             <list>          <list>
1     0 <tibble [18 x 10]> <S3: cv.glmnet>
2     1 <tibble [14 x 10]> <S3: cv.glmnet>

But when I try to create the formula for the model.matrix separately, it does not.

mod_form <- as.formula(".$mpg ~ .$cyl * .$hp")

mod_test2 <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., mod_form)[,-1],
    y = .$mpg
  )))
Error in mutate_impl(.data, dots) : object '.' not found

Body:
You can use glmnetUtils if you want a formula/data frame interface to glmnet. This makes interfacing with the tidyverse a bit more convenient.

install.packages("glmnetUtils")

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod=map(data, ~ cv.glmnet(mpg ~ cyl + hp, data=.)))


问:
PHP MVC Globals Variables
I have a little doubt, I understand that using global variables is a bad practice.

I have a small MVC application with php, in which I would like to create a file .. called config.php and inside it, save the global variables that I will use in my classes, example ...

```<code>$config = array ();
$config ['db_host'] = 'localhost';
</code>```

Now, I would like to know what would be the recommended way to include this file in my application .. I have implemented a autoloader, I could include it in this ...

```<code>Class Autoload
{
    public function __construct () {
        global $ config;
        require_once 'config.php';
    }
}
</code>```

But I really do not know if this is a good practice ...

Thank you very much in advance..

答:
Instead of globals you could create a class, like this

```<code>class Autoload {

    public $value1;
    public $value2;
    public static instances = array();

    public static function instantiate($className) {
        if (isset($instances[$className])) {
            return $instances[$className];
        }
        $newInstance = new $className();
        $newInstance->value1 = "foo";
        $newInstance->value2 = "bar";
        return $instances[$className] = $newInstance;
    }
}
</code>```

And you can inherit this class for more specific cases, for instance, different user types.

Title: PHP MVC Globals Variables

Body:
I have a little doubt, I understand that using global variables is a bad practice.

I have a small MVC application with php, in which I would like to create a file .. called config.php and inside it, save the global variables that I will use in my classes, example ...

$config = array ();
$config ['db_host'] = 'localhost';

Now, I would like to know what would be the recommended way to include this file in my application .. I have implemented a autoloader, I could include it in this ...

Class Autoload
{
    public function __construct () {
        global $ config;
        require_once 'config.php';
    }
}

But I really do not know if this is a good practice ...

Thank you very much in advance..

Body:
Instead of globals you could create a class, like this

class Autoload {

    public $value1;
    public $value2;
    public static instances = array();

    public static function instantiate($className) {
        if (isset($instances[$className])) {
            return $instances[$className];
        }
        $newInstance = new $className();
        $newInstance->value1 = "foo";
        $newInstance->value2 = "bar";
        return $instances[$className] = $newInstance;
    }
}

And you can inherit this class for more specific cases, for instance, different user types.


问:
Domain Redirect from domain.com/pathA to domainA.com
I have an IIS web server that is setup to handle all requests to *.myapp.com. We also have clients that have setup a custom domain, e.g. custom.customer.com as a CNAME To customer.myapp.com

I have a requirement to handle the following:

Requests to custom.customer.com/pathA will need to be redirected to a.internal-app.com

Requests to custom.customer.com/pathB will need to be redirected to b.internal-app.com

The problem I have right now is that this can't be done on the DNS level (as it involves paths). Also, whatever the "redirect" is I want the client to see his custom domain at all times. Like he should never see internal-app.com or myapp.com.

Is this possible in any way?

答:
It is possible with reverse proxy.

1) You need to install URL Rewrite and ARR module for IIS

2) Enable ARR. On the Application Request Routing page, select Enable proxy

3) Create rewrite rule

```<code>    <rewrite>
        <rules>
           <rule name="rewrite custom.customer.com/patha" stopProcessing="true">
                <match url="patha" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^custom.customer.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://a.internal-app.com/" />
            </rule>
           <rule name="rewrite custom.customer.com/pathB" stopProcessing="true">
                <match url="pathb" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^custom.customer.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://b.internal-app.com/" />
            </rule>
        </rules>
    </rewrite>
</code>```

P.S. You might have problem with your resources(images,styles,css,js). Because your html might contains absolute paths to resources

You can check this post, when author is creating outbound rule for fixing relative urls https://blogs.iis.net/carlosag/setting-up-a-reverse-proxy-using-iis-url-rewrite-and-arr

Body:
It is possible with reverse proxy.

1) You need to install URL Rewrite and ARR module for IIS

2) Enable ARR. On the Application Request Routing page, select Enable proxy

3) Create rewrite rule

    <rewrite>
        <rules>
           <rule name="rewrite custom.customer.com/patha" stopProcessing="true">
                <match url="patha" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^custom.customer.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://a.internal-app.com/" />
            </rule>
           <rule name="rewrite custom.customer.com/pathB" stopProcessing="true">
                <match url="pathb" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^custom.customer.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://b.internal-app.com/" />
            </rule>
        </rules>
    </rewrite>

P.S. You might have problem with your resources(images,styles,css,js). Because your html might contains absolute paths to resources

You can check this post, when author is creating outbound rule for fixing relative urls https://blogs.iis.net/carlosag/setting-up-a-reverse-proxy-using-iis-url-rewrite-and-arr


问:
Abstracting surounding markup structure

Problem

I have multiple sections that will have the same markup, like this

```<code><div class="A B C">
  <h3 class"D">Section Title 1</h3>

  Some HTML content...
<div>

<div class="A B C">
  <h3 class"D">Section Title 2</h3>

  Some different HTML content...
<div>

<div class="A B C">
  <h3 class"D">Section Title 3</h3>

  Some even different HTML content...
<div>
</code>```

So all the sections share some structure - the surrounding container (
) and heading element (
) - but also have unique content.

Is there a mechanism in Twig to somehow abstract the section creation so that classes A, B, C, D are defined only in 1 place?

Example solution

Ideal solution would be declaring some kind of block-like-macro:

```<code>{% blockLikeMacro section(title) %}
  <div class="A B C">
    <h3 class"D">{{ title }}</h3>
    {% content %}
  <div>
{% endBlockLikeMacto %}
</code>```

And use it like that:

```<code>{% blockLikeMacroUse section("Section Title 1") %}
  Some content..
{% endBlockLikeMacroUse %}

{% blockLikeMacroUse section("Section Title 2") %}
  Some different content..
{% endBlockLikeMacroUse %}

{% blockLikeMacroUse section("Section Title 3") %}
  Some event different content..
{% endBlockLikeMacroUse %}
</code>```

Question

Is such effect (abstract section structure) in any way possible using Twig?

答:
In your case, you can use a loop to iterate over your sections:

```<code>{% for section in sections %}
    <div class="A B C">
        <h3 class"D">{{ section.title }}</h3>
        {{ section.content }}
    <div>
{% endfor %}
</code>```

Twig also does have support for macros: https://twig.sensiolabs.org/doc/2.x/tags/macro.html

Title: Abstracting surounding markup structure

Body:
Problem

I have multiple sections that will have the same markup, like this

Section Title 1

  Some HTML content...

Section Title 2

  Some different HTML content...

Section Title 3

  Some even different HTML content...

So all the sections share some structure - the surrounding container (
) and heading element (
) - but also have unique content.

Is there a mechanism in Twig to somehow abstract the section creation so that classes A, B, C, D are defined only in 1 place?

Example solution

Ideal solution would be declaring some kind of block-like-macro:

{% blockLikeMacro section(title) %}

{{ title }}

    {% content %}

{% endBlockLikeMacto %}

And use it like that:

{% blockLikeMacroUse section("Section Title 1") %}
  Some content..
{% endBlockLikeMacroUse %}

{% blockLikeMacroUse section("Section Title 2") %}
  Some different content..
{% endBlockLikeMacroUse %}

{% blockLikeMacroUse section("Section Title 3") %}
  Some event different content..
{% endBlockLikeMacroUse %}

Question

Is such effect (abstract section structure) in any way possible using Twig?

Body:
In your case, you can use a loop to iterate over your sections:

{% for section in sections %}
    <div class="A B C">
        <h3 class"D">{{ section.title }}</h3>
        {{ section.content }}
    <div>
{% endfor %}

Twig also does have support for macros: https://twig.sensiolabs.org/doc/2.x/tags/macro.html


问:
update an entry in contentful with an reference field
I am working on a project with Contentful, using the contentful-management node module, with Javascript.
I am trying to create an reference in an entry containing a new entry.

I get the following message in the browser console:

```<code>     Uncaught (in promise) Error: {
     "request": {
"url": "https://api.contentful.com:443/spaces/59mi8sr8zemv/entries/2Bxpz2RgA4AQImQOssey8w/published",
"headers": {
  "Accept": "application/json, text/plain, */*",
  "Content-Type": "application/vnd.contentful.management.v1+json",
  "X-Contentful-User-Agent": "contentful-management.js/1.3.1",
  "Authorization": "Bearer <my management-api key>",
  "X-Contentful-Version": 373
  },
   "method": "put",
   "payloadData": null
    },
    "status": 422,
    "statusText": "Unprocessable Entity",
    "requestId": "d00dde60cd564a8db84da90cd671b19f",
    "message": "Validation error",
    "details": {
    "errors": [
    {
    "name": "notResolvable",
    "link": {
      "id": "2Yfc2H8q9OSoOccGcSg4aU",
      "linkType": "Entry",
      "type": "Link"
    },
    "path": [
      "fields",
      "link",
      "en-US",
      7
    ]
  }
]
}
}
 at errorHandler (main-addTrack.bundle.js:3096)
</code>```

When I look in the contentful web app the new entry is there, but saved as a draft. The entry I am trying to add an entry to, says that it needs to be updated.

This is the function i use to create and update the new entry.

```<code>    function publishTrack(){
        //-- Creates the new track in events, with ref to korrekt date
        client.getSpace(<my_spaceId>)
            .then((space) => {
            space.createEntry('events', newTrack)
                .then( event => {

                eventID = event.sys.id;

               (entry) => entry.publish()

                //This function is gets the entry of choosen date
                space.getEntry(dateId)
                    .then((entry) => {

                    //Gets the ID from the newly created event
                    var newId = {sys: {
                        id: eventID,
                        linkType: "Entry",
                        type:"Link"
                    }}

                    //Creates a reference field in dates for show & do
                    entry.fields.link["en-US"].push(newId)

                    //update the event
                    return entry.update()
                    space.getEntry(eventID)
                    .then ((eventID) => entry.publish())

                })
                  space.getEntry(dateId)
                    .then ((entry) => entry.publish());

            })

            publishModal.style.display = 'block';
            publishModal.style.opacity = '1';
            publishModal.style.pointerEvents = 'auto';
            publishModal.style.zIndex = '99999';

        })

    }//end publish track
</code>```

Please apologize for any mistakes, this is my first post on stackowerflow.

答:
Under the hood, you are doing a HTTP PUT request. This means replacing an existing resource with a new one. However, your payload is empty:

"payloadData": null

and you get a user error 4xx (422 in particular) which means that the payload you are sending is not valid. So it means that Contentful does not accept putting that value to null. However, it seems a bit weird, as you are adding newId which is not null.

The resource you are trying to replace with PUT is /fields/link/en-US/7. It might be that some intermediary resource is not present (eg, /fields, /fields/link, or /fields/link/en-US), and PUT on a sub-resource is not handled by Contentful.

Body:
I am working on a project with Contentful, using the contentful-management node module, with Javascript.
I am trying to create an reference in an entry containing a new entry.

I get the following message in the browser console:

     Uncaught (in promise) Error: {
     "request": {
"url": "https://api.contentful.com:443/spaces/59mi8sr8zemv/entries/2Bxpz2RgA4AQImQOssey8w/published",
"headers": {
  "Accept": "application/json, text/plain, */*",
  "Content-Type": "application/vnd.contentful.management.v1+json",
  "X-Contentful-User-Agent": "contentful-management.js/1.3.1",
  "Authorization": "Bearer <my management-api key>",
  "X-Contentful-Version": 373
  },
   "method": "put",
   "payloadData": null
    },
    "status": 422,
    "statusText": "Unprocessable Entity",
    "requestId": "d00dde60cd564a8db84da90cd671b19f",
    "message": "Validation error",
    "details": {
    "errors": [
    {
    "name": "notResolvable",
    "link": {
      "id": "2Yfc2H8q9OSoOccGcSg4aU",
      "linkType": "Entry",
      "type": "Link"
    },
    "path": [
      "fields",
      "link",
      "en-US",
      7
    ]
  }
]
}
}
 at errorHandler (main-addTrack.bundle.js:3096)

When I look in the contentful web app the new entry is there, but saved as a draft. The entry I am trying to add an entry to, says that it needs to be updated.

This is the function i use to create and update the new entry.

    function publishTrack(){
        //-- Creates the new track in events, with ref to korrekt date
        client.getSpace(<my_spaceId>)
            .then((space) => {
            space.createEntry('events', newTrack)
                .then( event => {

                eventID = event.sys.id;

               (entry) => entry.publish()

                //This function is gets the entry of choosen date
                space.getEntry(dateId)
                    .then((entry) => {

                    //Gets the ID from the newly created event
                    var newId = {sys: {
                        id: eventID,
                        linkType: "Entry",
                        type:"Link"
                    }}

                    //Creates a reference field in dates for show & do
                    entry.fields.link["en-US"].push(newId)

                    //update the event
                    return entry.update()
                    space.getEntry(eventID)
                    .then ((eventID) => entry.publish())

                })
                  space.getEntry(dateId)
                    .then ((entry) => entry.publish());

            })

            publishModal.style.display = 'block';
            publishModal.style.opacity = '1';
            publishModal.style.pointerEvents = 'auto';
            publishModal.style.zIndex = '99999';

        })

    }//end publish track

Please apologize for any mistakes, this is my first post on stackowerflow.


问:
ForEach() : Why can't use break/continue inside
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

```<code>lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);
</code>```

Error:

"No enclosing loop out of which to
break or continue"

答:
Because ForEach is a method and not a regular foreach loop. The ForEach method is there for simple tasks, if you need to break or continue just iterate over lstTemp with a regular foreach loop.

Usually, ForEach is implemented like this:

```<code>public static ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
  foreach(var i in input)
    action(i);
}
</code>```

As it is a normal method call, action doesn't know anything about the enclosing foreach, thus you can't break.

Body:
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to
break or continue"

Body:
Because ForEach is a method and not a regular foreach loop. The ForEach method is there for simple tasks, if you need to break or continue just iterate over lstTemp with a regular foreach loop.

Usually, ForEach is implemented like this:

public static ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
  foreach(var i in input)
    action(i);
}

As it is a normal method call, action doesn't know anything about the enclosing foreach, thus you can't break.


问:
Accessing Static variable from one class to another but getting incorrect value
This is my first question on stackoverflow,

I want to access static int variable of one class in another class but when i access this variable in another class it always gives me "zero".

This is First class:

```<code>package kk;

public class ag {
    public static int n=0;

    public static int as()
    {
        return n;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        n=3;
        n=n*5;
        System.out.println(n);
    }

}
</code>```

Here the output is 15 i.e. n=15 here.

Second class:

```<code>package kk;

public class ah extends ag {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //ag aa =new ag();
int k =ag.as();
System.out.println(k);
    }

}
</code>```

In this am trying to access the static variable n from First class but getting 0 as output but i want 15.

答:
You are getting 0 because that is the initial value of n in the first class ag.  n is only changed to 15 when ag's main() method is executed, but you are currently not doing this.

You could call the ag.main() method "manually" as part of the main() method of ah, e.g.:-

```<code>ag.main(null); // <- new code
int k =ag.as();
System.out.println(k);
</code>```

This will set n to 15, but is not the best way to do this.

Body:
This is my first question on stackoverflow,

I want to access static int variable of one class in another class but when i access this variable in another class it always gives me "zero".

This is First class:

package kk;

public class ag {
    public static int n=0;

    public static int as()
    {
        return n;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        n=3;
        n=n*5;
        System.out.println(n);
    }

}

Here the output is 15 i.e. n=15 here.

Second class:

package kk;

public class ah extends ag {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //ag aa =new ag();
int k =ag.as();
System.out.println(k);
    }

}

In this am trying to access the static variable n from First class but getting 0 as output but i want 15.

Body:
You are getting 0 because that is the initial value of n in the first class ag.  n is only changed to 15 when ag's main() method is executed, but you are currently not doing this.

You could call the ag.main() method "manually" as part of the main() method of ah, e.g.:-

ag.main(null); // <- new code
int k =ag.as();
System.out.println(k);

This will set n to 15, but is not the best way to do this.


问:
How to put a service in a component and that is displayed in the html? In angular 2
How to put a service in a component and that is displayed in the html by @Input?

Until the moment I carry this code but I have not received success

This is Service

import {
  Injectable
} from '@angular/core';
import Rx from 'Rx';

@Injectable()
export class TiempoService {

  tiempoTranscurrido: number;

  constructor() {}

  ngOnInit() {

  }
  tiempoTotal() {
    Rx.Observable.interval(1000).subscribe(segundos => {
      this.tiempoTranscurrido = segundos * 1000;
    })
  }
}```
</div>
</div>
</p>

<p>This is component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  TiempoService
} from "app/servicios/tiempo.service"

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  @Input() tiemposervice: TiempoService;
  constructor() {}

  ngOnInit() {

  }

}</code>```

this is html

        Tiempo transcurrido

{{tiempoTranscurrido | date:'mm:ss'}}

```

I would greatly appreciate your help

答:
Your component:

```<code>export class MenuComponent implements OnInit {

  constructor(public tiemposervice: TiempoService) {} //don't forget to add the service to the provider.

}
</code>```

Your html:

```<code><div class="row">
  <div class="small-12 columns">
    <div class="row">
      <div class="small-12 medium-6 columns">
        <span>Tiempo transcurrido</span>
        <h5>{{tiemposervice.tiempoTranscurrido| date:'mm:ss'}}</h5>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
How to put a service in a component and that is displayed in the html by @Input?

Until the moment I carry this code but I have not received success

This is Service

import {
  Injectable
} from '@angular/core';
import Rx from 'Rx';

@Injectable()
export class TiempoService {

  tiempoTranscurrido: number;

  constructor() {}

  ngOnInit() {

  }
  tiempoTotal() {
    Rx.Observable.interval(1000).subscribe(segundos => {
      this.tiempoTranscurrido = segundos * 1000;
    })
  }
}

This is component

import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  TiempoService
} from "app/servicios/tiempo.service"

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  @Input() tiemposervice: TiempoService;
  constructor() {}

  ngOnInit() {

  }

}

this is html

        Tiempo transcurrido

{{tiempoTranscurrido | date:'mm:ss'}}

I would greatly appreciate your help

Body:
Your component:

export class MenuComponent implements OnInit {

  constructor(public tiemposervice: TiempoService) {} //don't forget to add the service to the provider.

}

Your html:

<div class="row">
  <div class="small-12 columns">
    <div class="row">
      <div class="small-12 medium-6 columns">
        <span>Tiempo transcurrido</span>
        <h5>{{tiemposervice.tiempoTranscurrido| date:'mm:ss'}}</h5>
      </div>
    </div>
  </div>
</div>


问:
merge sets' elements with HashMap's key in scala
I hope there is an easy way to solve that
I have two RDDs

```<code>g.vertices
(4,Set(5, 3))
(0,Set(1, 4))
(1,Set(2))
(6,Set())
(3,Set(0))
(5,Set(2))
(2,Set(1))

maps
Map(4 -> Set(5, 3))
Map(0 -> Set(1, 4))
Map(1 -> Set(2))
Map(6 -> Set())
Map(3 -> Set(0))
Map(5 -> Set(2))
Map(2 -> Set(1))
</code>```

How can I do something like this?

```<code>(4,Map(5 -> Set(2), 3 -> Set(0)))
(0,Map(1 -> Set(2), 4 -> Set(5, 3)))
(1,Map(2 -> Set(1)))
(6,Map())
(3,Map(0 -> Set(1, 4)))
(5,Map(2 -> Set(1)))
(2,Map(1 -> Set(2)))
</code>```

I want to combine map's key with elements of set, so I want to change sets' elements (merge them with map's key)

I thought about

```<code>val maps = g.vertices.map { case (id, attr) => HashMap(id -> attr) }

g.mapVertices{case (id, data) => data.map{case vId => maps.
  map { case i if i.keySet.contains(vId) => HashMap(vId -> i.values) } }}
</code>```

but I have an error

org.apache.spark.SparkException: RDD transformations and actions can
  only be invoked by the driver, not inside of other transformations;
  for example, rdd1.map(x => rdd2.values.count() * x) is invalid because
  the values transformation and count action cannot be performed inside
  of the rdd1.map transformation. For more information, see SPARK-5063.

答:
This is a simple use case for join. In the following code, A is the type of the keys in g.vertices, K and V are the key and value types for  maps:

```<code>def joinByKeys[A, K, V](sets: RDD[(A, Set[K])], maps: RDD[Map[K, V]]): RDD[(A, Map[K, V])] = {
  val flattenSets = sets.flatMap(p => p._2.map(_ -> p._1)) // create a pair for each element of vertice's sets
  val flattenMaps = maps.flatMap(identity)                 // create an RDD with all indexed values in Maps
  flattenMaps.join(flattenSets).map{                       // join them by their key
    case (k, (v, a)) => (a, (k, v))                        // reorder to put the vertexId as id
  }.aggregateByKey(Map.empty[K, V])(_ + _, _ ++ _)         // aggregate the maps
</code>```

}

Body:
I hope there is an easy way to solve that
I have two RDDs

g.vertices
(4,Set(5, 3))
(0,Set(1, 4))
(1,Set(2))
(6,Set())
(3,Set(0))
(5,Set(2))
(2,Set(1))

maps
Map(4 -> Set(5, 3))
Map(0 -> Set(1, 4))
Map(1 -> Set(2))
Map(6 -> Set())
Map(3 -> Set(0))
Map(5 -> Set(2))
Map(2 -> Set(1))

How can I do something like this?

(4,Map(5 -> Set(2), 3 -> Set(0)))
(0,Map(1 -> Set(2), 4 -> Set(5, 3)))
(1,Map(2 -> Set(1)))
(6,Map())
(3,Map(0 -> Set(1, 4)))
(5,Map(2 -> Set(1)))
(2,Map(1 -> Set(2)))

I want to combine map's key with elements of set, so I want to change sets' elements (merge them with map's key)

I thought about

val maps = g.vertices.map { case (id, attr) => HashMap(id -> attr) }

g.mapVertices{case (id, data) => data.map{case vId => maps.
  map { case i if i.keySet.contains(vId) => HashMap(vId -> i.values) } }}

but I have an error

org.apache.spark.SparkException: RDD transformations and actions can
  only be invoked by the driver, not inside of other transformations;
  for example, rdd1.map(x => rdd2.values.count() * x) is invalid because
  the values transformation and count action cannot be performed inside
  of the rdd1.map transformation. For more information, see SPARK-5063.

Body:
This is a simple use case for join. In the following code, A is the type of the keys in g.vertices, K and V are the key and value types for  maps:

def joinByKeys[A, K, V](sets: RDD[(A, Set[K])], maps: RDD[Map[K, V]]): RDD[(A, Map[K, V])] = {
  val flattenSets = sets.flatMap(p => p._2.map(_ -> p._1)) // create a pair for each element of vertice's sets
  val flattenMaps = maps.flatMap(identity)                 // create an RDD with all indexed values in Maps
  flattenMaps.join(flattenSets).map{                       // join them by their key
    case (k, (v, a)) => (a, (k, v))                        // reorder to put the vertexId as id
  }.aggregateByKey(Map.empty[K, V])(_ + _, _ ++ _)         // aggregate the maps

}


问:
SQL Server Update Queries Taking Too Long
I have a SQL query that builds analysis tables using SELECT INTO statements from populated staging tables. This part goes pretty smooth, but when I try to append fields to the analysis tables, from each other or from the original staging tables, the UPDATE queries run for HOURS.

I feel this run time is unwarranted because the most records per table is 200K. I have a feeling that this is an issue with my log file management or the fact that I have no indexes on any of these tables. I have been reluctant to build indexes because I know if hastily done, they can actually cause more problems. There are no triggers on any of these tables.

I am trying to find an approach so that this query runs consistently. In the past, it has run under 1 hour (which is still probably too long) but today for instance it has taken 3+ hours.

I've already modified the log file to autogrow by 50% rather than 10%, to have an unlimited MAXSIZE, I've set the DB recovery mode to SIMPLE and I have shrunk the log file manually. None of this is helping.

I know that TABLE SCANS are a source of lag in large queries, so is the solution here to create indexes for all of the fields I use in my LEFT JOINs depicted below? These snippets are exact examples of where the query is lagging. I have transparency into this because I am following the execution of the script in the LIVE QUERY STATISTICS window.

```<code>UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;

-- Link by website2
UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.url2 = b.Website2
WHERE a.[Account ID] IS NULL;
--
UPDATE a
SET a.[SFDC Account Name] = b.[Account Name]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on
a.[Account ID] = b.[Account ID]
WHERE a.[Account ID] IS NOT NULL;

UPDATE a
SET a.ConvertedFlag = b.[Lead ID]
FROM SFAX.dbo.WhoAnalysis1 as a
LEFT JOIN SFAX.dbo.Contacts as b ON a.WhoId = b.[Contact ID];
</code>```

答:
Below has a lot of nonsense work to do - so don't do it.

```<code>UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;
</code>```

If there is no match in b, you will set [a.Account ID] to null. But you are only selecting those rows in a where the column is NULL. SO DON'T DO THAT - your left join is pointless extra work. Change it to an inner join. Will that help significantly? Can't tell without knowing the characteristics of your data.

Body:
I have a SQL query that builds analysis tables using SELECT INTO statements from populated staging tables. This part goes pretty smooth, but when I try to append fields to the analysis tables, from each other or from the original staging tables, the UPDATE queries run for HOURS.

I feel this run time is unwarranted because the most records per table is 200K. I have a feeling that this is an issue with my log file management or the fact that I have no indexes on any of these tables. I have been reluctant to build indexes because I know if hastily done, they can actually cause more problems. There are no triggers on any of these tables.

I am trying to find an approach so that this query runs consistently. In the past, it has run under 1 hour (which is still probably too long) but today for instance it has taken 3+ hours.

I've already modified the log file to autogrow by 50% rather than 10%, to have an unlimited MAXSIZE, I've set the DB recovery mode to SIMPLE and I have shrunk the log file manually. None of this is helping.

I know that TABLE SCANS are a source of lag in large queries, so is the solution here to create indexes for all of the fields I use in my LEFT JOINs depicted below? These snippets are exact examples of where the query is lagging. I have transparency into this because I am following the execution of the script in the LIVE QUERY STATISTICS window.

UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;

-- Link by website2
UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.url2 = b.Website2
WHERE a.[Account ID] IS NULL;
--
UPDATE a
SET a.[SFDC Account Name] = b.[Account Name]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on
a.[Account ID] = b.[Account ID]
WHERE a.[Account ID] IS NOT NULL;

UPDATE a
SET a.ConvertedFlag = b.[Lead ID]
FROM SFAX.dbo.WhoAnalysis1 as a
LEFT JOIN SFAX.dbo.Contacts as b ON a.WhoId = b.[Contact ID];

Body:
Below has a lot of nonsense work to do - so don't do it.

UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;

If there is no match in b, you will set [a.Account ID] to null. But you are only selecting those rows in a where the column is NULL. SO DON'T DO THAT - your left join is pointless extra work. Change it to an inner join. Will that help significantly? Can't tell without knowing the characteristics of your data.


问:
Trying to show images and counting the teachers from each group
In my spare time i'd like to code for fun and helping others. I am new to ionic and angular. I do not use a database just a json object where I get my information from.

So basically I want a page with a ionic card with the studens and the teachers. Like this: https://gyazo.com/61933179c66a1bb815e461f1a158a92c

This is what I have: https://gyazo.com/62123a96be5a2370f4b1300437cff974

With my method it counts every person in the groep. But I want to count per rank.

HTML

```<code><ion-header>

    <ion-navbar color ="primary">
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Amcik</ion-title>
      </ion-navbar>
    </ion-header>

    <ion-content>
      <ion-searchbar>
    </ion-searchbar>
      <ion-grid>
        <ion-row>
          <ion-col col-12 col-md *ngFor="let item of items">
            <ion-card class="groep">
              <ion-item>
                <h2>{{ item.name }}</h2>
                </ion-item>
                <div class="foto"*ngFor="let i of item.items">
                    <img class="pic" src={{i.avatar}}>
                </div>
                <p>{{ item.count }} leerlingen</p>
            </ion-card>
          </ion-col>
        </ion-row>
    </ion-grid>
    </ion-content>
</code>```

TS PAGE

```<code> import { Component } from '@angular/core';

import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-page2',
  templateUrl: 'page2.html'
})

export class Page2 {
items:any;

    constructor(private navCtrl: NavController) {

      this.items = [
      {voornaam: 'Mert', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'teacher'},
      {voornaam: 'Ask Sana', achternaam: 'Benzer', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'teacher'},
      {voornaam: 'Koray', achternaam: 'Avci', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'leerling'},
      {voornaam: 'Recep', achternaam: 'Ivedik', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Gel', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Yarim', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Gonlume', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Huzur', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Ver', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Omrume', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'}
      ];

              let newData = {
                  leerling: [],
                  teacher: []
              }

              for (var i = 0; i < this.items.length; i++) {
                  var element = this.items[i];

                  newData[element.rank].push(element);
              }
      }
}
</code>```

Thanks in advance!

答:
To achieve your request this is the receipe to follow
  so

Sort the data by groep

Iterate over the sorted data and store it in a new array split by the groups.

Within this group we split the teachers and students, each in their own array.

Now we can iterate over the new data for each group and within a group iterate over students and teachers.

See http://plnkr.co/edit/UAjTVO?p=preview

Sorting algorithm from Sort array of objects by single key with date value

```<code>var groupIndex = -1;

// Sort data by groep
items.sort(function (a, b) {
    let keyA = a.groep;
    let keyB = b.groep;
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
});

let previousGroupId = '';

// Iterate over all students
for (var i = 0; i < items.length; i++) {

    var element = items[i];

    // Check if the group already is listed if not create one
    if (element.groep !== previousGroupId) {

        this.groupData.push({
            name: element.groep,
            teachers: [],
            students: []
        });

        previousGroupId = element.groep;
        groupIndex++;
    }

    if (element.rank === 'leerling') {
        this.groupData[groupIndex].students.push(element);
    } else {
        this.groupData[groupIndex].teachers.push(element);
    }

}
</code>```

HTML

```<code><ion-header>

    <ion-navbar color="primary">
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Amcik</ion-title>
    </ion-navbar>
</ion-header>

<ion-content>
    <ion-searchbar>
    </ion-searchbar>
    <ion-grid>
        <ion-row>
            <ion-col col-12 col-md *ngFor="let group of groupData">
                <ion-card class="groep">
                    <ion-item>
                        <h2>{{ group.name }}</h2>

                        <h3>Students ({{group.students.length}})</h3>

                        <ul>
                            <li *ngFor="let student of group.students">
                                <img [src]="student.avatar" /> {{ student.voornaam }}
                            </li>
                        </ul>

                        <h3>Teachers ({{group.teachers.length}})</h3>
                        <ul>
                            <li *ngFor="let teacher of group.teachers">
                                <img [src]="teacher.avatar" /> {{ teacher.voornaam }}
                            </li>
                        </ul>

                    </ion-item>

                </ion-card>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>
</code>```

Body:
In my spare time i'd like to code for fun and helping others. I am new to ionic and angular. I do not use a database just a json object where I get my information from.

So basically I want a page with a ionic card with the studens and the teachers. Like this: https://gyazo.com/61933179c66a1bb815e461f1a158a92c

This is what I have: https://gyazo.com/62123a96be5a2370f4b1300437cff974

With my method it counts every person in the groep. But I want to count per rank.

HTML

<ion-header>

    <ion-navbar color ="primary">
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Amcik</ion-title>
      </ion-navbar>
    </ion-header>

    <ion-content>
      <ion-searchbar>
    </ion-searchbar>
      <ion-grid>
        <ion-row>
          <ion-col col-12 col-md *ngFor="let item of items">
            <ion-card class="groep">
              <ion-item>

{{ item.name }}

                </ion-item>

{{ item.count }} leerlingen

            </ion-card>
          </ion-col>
        </ion-row>
    </ion-grid>
    </ion-content>

TS PAGE

 import { Component } from '@angular/core';

import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-page2',
  templateUrl: 'page2.html'
})

export class Page2 {
items:any;

    constructor(private navCtrl: NavController) {

      this.items = [
      {voornaam: 'Mert', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'teacher'},
      {voornaam: 'Ask Sana', achternaam: 'Benzer', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'teacher'},
      {voornaam: 'Koray', achternaam: 'Avci', avatar: 'http://placehold.it/100', groep: 'Groep 1', rank: 'leerling'},
      {voornaam: 'Recep', achternaam: 'Ivedik', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Gel', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Yarim', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Gonlume', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 3', rank: 'leerling'},
      {voornaam: 'Huzur', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Ver', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'},
      {voornaam: 'Omrume', achternaam: 'Sezen', avatar: 'http://placehold.it/100', groep: 'Groep 2', rank: 'leerling'}
      ];

              let newData = {
                  leerling: [],
                  teacher: []
              }

              for (var i = 0; i < this.items.length; i++) {
                  var element = this.items[i];

                  newData[element.rank].push(element);
              }
      }
}

Thanks in advance!

Body:
To achieve your request this is the receipe to follow
  so

Sort the data by groep

Iterate over the sorted data and store it in a new array split by the groups.

Within this group we split the teachers and students, each in their own array.

Now we can iterate over the new data for each group and within a group iterate over students and teachers.

See http://plnkr.co/edit/UAjTVO?p=preview

Sorting algorithm from Sort array of objects by single key with date value

var groupIndex = -1;

// Sort data by groep
items.sort(function (a, b) {
    let keyA = a.groep;
    let keyB = b.groep;
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
});

let previousGroupId = '';

// Iterate over all students
for (var i = 0; i < items.length; i++) {

    var element = items[i];

    // Check if the group already is listed if not create one
    if (element.groep !== previousGroupId) {

        this.groupData.push({
            name: element.groep,
            teachers: [],
            students: []
        });

        previousGroupId = element.groep;
        groupIndex++;
    }

    if (element.rank === 'leerling') {
        this.groupData[groupIndex].students.push(element);
    } else {
        this.groupData[groupIndex].teachers.push(element);
    }

}

HTML

<ion-header>

    <ion-navbar color="primary">
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>Amcik</ion-title>
    </ion-navbar>
</ion-header>

<ion-content>
    <ion-searchbar>
    </ion-searchbar>
    <ion-grid>
        <ion-row>
            <ion-col col-12 col-md *ngFor="let group of groupData">
                <ion-card class="groep">
                    <ion-item>
                        <h2>{{ group.name }}</h2>

                        <h3>Students ({{group.students.length}})</h3>

                        <ul>
                            <li *ngFor="let student of group.students">
                                <img [src]="student.avatar" /> {{ student.voornaam }}
                            </li>
                        </ul>

                        <h3>Teachers ({{group.teachers.length}})</h3>
                        <ul>
                            <li *ngFor="let teacher of group.teachers">
                                <img [src]="teacher.avatar" /> {{ teacher.voornaam }}
                            </li>
                        </ul>

                    </ion-item>

                </ion-card>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>


问:
How do I detect a failed download in Chrome using SeleniumBasic?
I'm using SeleniumBasic v2.0.9, MS Access 2010, and the Selenium ChromeDriver to automate some file downloads (NB: I need the files from a secured website, I'm not testing my own website).

When I click the "run report" button, a new tab opens in Chrome and it runs a PHP script to generate the report. My code loops looking for the second window to close:

```<code>this.Driver.FindElementByName(DOWNLOAD_LINK_TEXT).Click
While this.Driver.Windows.Count > 1
  DoEvents
Wend
</code>```

The PHP script generates a unique name for the download, but it's not the name I need for the file, so once I'm back to a single window, I loop looking for the existence of default name (it's a formula "known part" & randomValue) before I rename it to what I need.

```<code>downloadedFile = Dir(this.DestinationPath & defaultFileSpec)
While Len(downloadedFile) = 0
  downloadedFile = Dir(this.DestinationPath & defaultFileSpec)
Wend
</code>```

For the first time, I hit an issue where Chrome notified me that the download failed, but there was no error message in VBA, so, of course, the loop above hung.

I don't see any properties within the driver that would indicate the success or failure of the download, so how do I detect that the download has failed, preferably before launching the infinite loop?

答: Just add a timeout to the loop waiting for the file to download so it doesn't try forever.</p>

Body:
I'm using SeleniumBasic v2.0.9, MS Access 2010, and the Selenium ChromeDriver to automate some file downloads (NB: I need the files from a secured website, I'm not testing my own website).

When I click the "run report" button, a new tab opens in Chrome and it runs a PHP script to generate the report. My code loops looking for the second window to close:

this.Driver.FindElementByName(DOWNLOAD_LINK_TEXT).Click
While this.Driver.Windows.Count > 1
  DoEvents
Wend

The PHP script generates a unique name for the download, but it's not the name I need for the file, so once I'm back to a single window, I loop looking for the existence of default name (it's a formula "known part" & randomValue) before I rename it to what I need.

downloadedFile = Dir(this.DestinationPath & defaultFileSpec)
While Len(downloadedFile) = 0
  downloadedFile = Dir(this.DestinationPath & defaultFileSpec)
Wend

For the first time, I hit an issue where Chrome notified me that the download failed, but there was no error message in VBA, so, of course, the loop above hung.

I don't see any properties within the driver that would indicate the success or failure of the download, so how do I detect that the download has failed, preferably before launching the infinite loop?


问:
Can you perform a case-insensitive string comparison in MSBuild?
I have the following code in my MSBuild project file:

```<code><Error Text="Some Text" Condition="'$(StringName)' != 'Test'"/>
</code>```

The string comparison here is case-sensitive, so when $(StringName) is something like 'test', the condition is not met.

How can I change the condition so that 'test' also meets the comparison? Is there any case-insensitive comparison function available in MSBuild?

答:
Use MSBuild property function with a special parameter to perform a case-insensitive string comparison:</p>

```<code><Error Text="Some Text" Condition="!$(StringName.Equals('Test', StringComparison.OrdinalIgnoreCase))"/>
</code>```

Body:
I have the following code in my MSBuild project file:

<Error Text="Some Text" Condition="'$(StringName)' != 'Test'"/>

The string comparison here is case-sensitive, so when $(StringName) is something like 'test', the condition is not met.

How can I change the condition so that 'test' also meets the comparison? Is there any case-insensitive comparison function available in MSBuild?

Body:
Use MSBuild property function with a special parameter to perform a case-insensitive string comparison:

<Error Text="Some Text" Condition="!$(StringName.Equals('Test', StringComparison.OrdinalIgnoreCase))"/>