问:
Unity3d: rotate camera around center of the screen with middle mouse button pressed
I am working on an RTS game and would like to support the camera to rotate around the current center of the screen on mouse button pressed, just like in any RTS, strategy game.

I tried the MouseOrbitImproved script as shown on the unity wiki (copied below), but it  needs a target object used by the camera to rotate around. My problem is that my target is always the current center of the screen.

Any idea how to achieve this, but only while the middle mouse button is pressed?

```<code>using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

    public Transform target;
    public float distance = 5.0f;
    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = -20f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    private Rigidbody rigidbody;

    float x = 0.0f;
    float y = 0.0f;

    // Use this for initialization
    void Start ()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody != null)
        {
            rigidbody.freezeRotation = true;
        }
    }

    void LateUpdate ()
    {
        if (target)
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

            distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

            RaycastHit hit;
            if (Physics.Linecast (target.position, transform.position, out hit))
            {
                distance -=  hit.distance;
            }
            Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
            Vector3 position = rotation * negDistance + target.position;

            transform.rotation = rotation;
            transform.position = position;
        }
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}
</code>```

答:
In your orbit function, where you determine the object to orbit around, raycast a ray from the center of the screen and orbit around the collision:

```<code>public LayerMask groundLayerMask; // mask to choose orbitable layers

...

Ray screenRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2f, Screen.height/2f, 0f));`

RaycastHit hitInfo;
Physics.Raycast(screenRay, out hitInfo, Mathf.Infinity, groundLayerMask.value);

Vector3 orbitPosition = hitInfo.point;
</code>```

You can check if the middle mouse button is pressed with Input.GetMouseButton(2). Before orbiting, check it and only detect mouse input changes if its held down.

In the MouseOrbitImproved code it might look like this in the LateUpdate method:

```<code>void LateUpdate ()
{
    // Skip mouse input here if middle mouse button is not pressed
    if (Input.GetMouseButton(2))
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
        y = ClampAngle(y, yMinLimit, yMaxLimit);
    }

    Quaternion rotation = Quaternion.Euler(y, x, 0);

    distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

    Ray screenRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2f, Screen.height/2f, 0f));`

    RaycastHit hitInfo;
    Physics.Raycast(screenRay, out hitInfo, Mathf.Infinity, groundLayerMask.value);

    Vector3 orbitPosition = hitInfo.point;

    Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
    Vector3 position = rotation * negDistance + orbitPosition ;

    transform.rotation = rotation;
    transform.position = position;
}
</code>```

In the class fields, get rid of public Transform target; and add public LayerMask groundLayerMask; and set it in the inspector to only collide with whatever layer your ground is.

Body:
I am working on an RTS game and would like to support the camera to rotate around the current center of the screen on mouse button pressed, just like in any RTS, strategy game.

I tried the MouseOrbitImproved script as shown on the unity wiki (copied below), but it  needs a target object used by the camera to rotate around. My problem is that my target is always the current center of the screen.

Any idea how to achieve this, but only while the middle mouse button is pressed?

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

    public Transform target;
    public float distance = 5.0f;
    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = -20f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    private Rigidbody rigidbody;

    float x = 0.0f;
    float y = 0.0f;

    // Use this for initialization
    void Start ()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody != null)
        {
            rigidbody.freezeRotation = true;
        }
    }

    void LateUpdate ()
    {
        if (target)
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

            distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

            RaycastHit hit;
            if (Physics.Linecast (target.position, transform.position, out hit))
            {
                distance -=  hit.distance;
            }
            Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
            Vector3 position = rotation * negDistance + target.position;

            transform.rotation = rotation;
            transform.position = position;
        }
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}

Body:
In your orbit function, where you determine the object to orbit around, raycast a ray from the center of the screen and orbit around the collision:

public LayerMask groundLayerMask; // mask to choose orbitable layers

...

Ray screenRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2f, Screen.height/2f, 0f));`

RaycastHit hitInfo;
Physics.Raycast(screenRay, out hitInfo, Mathf.Infinity, groundLayerMask.value);

Vector3 orbitPosition = hitInfo.point;

You can check if the middle mouse button is pressed with Input.GetMouseButton(2). Before orbiting, check it and only detect mouse input changes if its held down.

In the MouseOrbitImproved code it might look like this in the LateUpdate method:

void LateUpdate ()
{
    // Skip mouse input here if middle mouse button is not pressed
    if (Input.GetMouseButton(2))
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
        y = ClampAngle(y, yMinLimit, yMaxLimit);
    }

    Quaternion rotation = Quaternion.Euler(y, x, 0);

    distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

    Ray screenRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2f, Screen.height/2f, 0f));`

    RaycastHit hitInfo;
    Physics.Raycast(screenRay, out hitInfo, Mathf.Infinity, groundLayerMask.value);

    Vector3 orbitPosition = hitInfo.point;

    Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
    Vector3 position = rotation * negDistance + orbitPosition ;

    transform.rotation = rotation;
    transform.position = position;
}

In the class fields, get rid of public Transform target; and add public LayerMask groundLayerMask; and set it in the inspector to only collide with whatever layer your ground is.


来源: stackexchange

问:
MWS method to get list of offers (including seller IDs)
Is there a method to retrieve the list of current offers (with price) for a specified ASIN if I do not have the product in inventory (I know it is possible to get this information through AnyOfferChangedNotification if I have an active listing for this ASIN)?

Do you know if there is a way to do this with MWS? I could not find one :frowning: Or do you know if there is another third-party API or another way to do this? I looked into Keepa but I need to get an update every time the lowest price changes and Keepa would be too expensive I think.

Thanks a lot for your help!

答:
Does GetCompetitivePricingForASIN not work?  We use a number of these and I can't remember if we had to have the item in stock or not.

But a trick we used to use is to set the inventory = 1 for anything that was out of stock and then after a few minutes (after all the AnyOfferChangedNotifications fired), set the inventory level back to 0.  We used this method as a way to keep our system in sync with the marketplace, even when we were OOS on an item.

ContentLicense: CC BY-SA 4.0


问:
Change xticklabels fontsize of seaborn heatmap
Here is my question:

I plot 7 variable's coefficient using sns.clustermap()

x/y tickslabel seems really small(In my case, s1,s2,... s9)

My attempt

label='big ==> no effect

plt.tick_params(axis='both', which='minor', labelsize=12)  ===> cbar label has changed, but the x/y axes looks the same.

Add

My code:

```<code> ds =  pd.read_csv("xxxx.csv")
 corr = ds.corr().mul(100).astype(int)

 cmap = sns.diverging_palette(h_neg=210, h_pos=350, s=90, l=30, as_cmap=True)

 sns.clustermap(data=corr_s, annot=True, fmt='d',cmap = "Blues",annot_kws={"size": 16},)
</code>```

答:
Or just use the set_xticklabels:

```<code>g = sns.clustermap(data=corr_s, annot=True, fmt='d',cmap = "Blues")
g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xmajorticklabels(), fontsize = 16)
</code>```

To get different colors for the ticklabels:

```<code>import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, corr_s.shape[0]))
for i, ticklabel in enumerate(g.ax_heatmap.xaxis.get_majorticklabels()):
    ticklabel.set_color(colors[i])
</code>```

Body:
Here is my question:

I plot 7 variable's coefficient using sns.clustermap()

x/y tickslabel seems really small(In my case, s1,s2,... s9)

My attempt

label='big ==> no effect

plt.tick_params(axis='both', which='minor', labelsize=12)  ===> cbar label has changed, but the x/y axes looks the same.

Add

My code:

 ds =  pd.read_csv("xxxx.csv")
 corr = ds.corr().mul(100).astype(int)

 cmap = sns.diverging_palette(h_neg=210, h_pos=350, s=90, l=30, as_cmap=True)

 sns.clustermap(data=corr_s, annot=True, fmt='d',cmap = "Blues",annot_kws={"size": 16},)

Body:
Or just use the set_xticklabels:

g = sns.clustermap(data=corr_s, annot=True, fmt='d',cmap = "Blues")
g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xmajorticklabels(), fontsize = 16)

To get different colors for the ticklabels:

import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, corr_s.shape[0]))
for i, ticklabel in enumerate(g.ax_heatmap.xaxis.get_majorticklabels()):
    ticklabel.set_color(colors[i])


问:
CSS - Target background image in DIV
I'd like to target the background-image of a DIV so that I can apply a 'glow' style to it when the DIV is hovered over.

see this fiddle for an exmaple of what my current setup is and how I'm attempting to do it now (albeit, targeting the div and not the image in the div).

Is this possible? If so, how :) ..if not, how might I change my HTML/CSS to give the same visual effect you see in the fiddle but allow the image to have the 'glow' apply to it?

Thanks in advance.

答:
A background image is binary data. You can't manipulate its contents using CSS.

The only way is to, on hover, switch the image to another file that has the glow around the arrow graphic:

```<code>.collapsible {
    background-image: url('/arrow_mini_up.png');
    background-repeat: no-repeat;
    background-position: right;
}

.collapsible:hover {
    background-image: url('/arrow_mini_up_glow.png');
}
</code>```

Even if you use a data URI, it's the same thing: you need to specify one background image for the default state and another for the hover state:

```<code>.collapsible {
    background-image: url('data:image/png;base64,A0Giftt6...');
    background-repeat: no-repeat;
    background-position: right;
}

.collapsible:hover {
    background-image: url('data:image/png;base64,n4x71Al4...');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: CSS - Target background image in DIV

Body:
A background image is binary data. You can't manipulate its contents using CSS.

The only way is to, on hover, switch the image to another file that has the glow around the arrow graphic:

.collapsible {
    background-image: url('/arrow_mini_up.png');
    background-repeat: no-repeat;
    background-position: right;
}

.collapsible:hover {
    background-image: url('/arrow_mini_up_glow.png');
}

Even if you use a data URI, it's the same thing: you need to specify one background image for the default state and another for the hover state:

.collapsible {
    background-image: url('data:image/png;base64,A0Giftt6...');
    background-repeat: no-repeat;
    background-position: right;
}

.collapsible:hover {
    background-image: url('data:image/png;base64,n4x71Al4...');
}


问:
How to structure Angular 7 app with multiple modules
Please refer the picture attached to understand the project structure. This is a very common angular project structure with different modules protected by AuthGuard and a shared module which will have all core features to be used across all protected modules.

Our application is becoming too large and as per our requirements users cannot access features present in all module. I do feel that there is no need to load all modules (they are developed to be using lazy loading).

I am thinking to provide a middleware page which will contain tiles (Module-1, Module-2 and so on based on permissions) and clicking on the tile will load the angular app with only selected and shared module.

Is there a provision like this in angular 7?

Thank You for your help.

答:
Angular v7 has support for mono repo architecture. You can make libraries and share them in projects.

Please find the link below for reference:
  https://github.com/ShubhenduVaid/angularCLI-monorepo

Another way to approach this is with NX workspace which is build over angular cli.

Please find the link below for reference:
  https://github.com/nrwl/nx


问:
Run the same codes with data and variable names changed in R
I need to run very similar codes for 3 different dataset. My current codes look like this:

```<code>## data a
a_dat2 <- merge(a_dat, zip, by = "zip", all.x = T)
a_dat2 <- a_dat2 %>%
group_by(zip) %>%
summarize(dist_a_min = min(dist))
## data b
b_dat2 <- merge(b_dat, zip, by = "zip", all.x = T)
    b_dat2 <- b_dat2 %>%
     group_by(zip) %>%
summarize(dist_b_min = min(dist))
## data c
c_dat2 <- merge(c_dat, zip, by = "zip", all.x = T)
    c_dat2 <- c_dat2 %>%
     group_by(zip) %>%
summarize(dist_c_min = min(dist))
</code>```

The codes for the 3 dataset are same except that the name of the data varies: a_dat, b_dat, c_dat. The variable name dist varies too: dist_a_min, dist_b_min, dist_c_min. What function/loop can be used to shorten the codes so that I don't need to copy and paste for each dataset separately?

答:
An option would be to place the elements in a list with mget, loop through the list with imap, join (?left_join) with 'zip' dataset, grouped by 'zip' and get the min of 'dist' while creating the column name based on the identifier name substring

```<code>library(tidyverse)
mget(ls(pattern = "_dat2$")) %>%
        imap(~ left_join(.x, zip, by = 'zip') %>%
             group_by(zip) %>%
             summarise((! str_c('dist_', substr(.y, 1, 1), '_min')  :=  min(dist)))
</code>```

Or another option is to create a function for repeated tasks

```<code>joinSumm <- function(dat, groupName, colName, data2) {
    groupName <- enquo(groupName)
    colName <- enquo(colName)
    nm1 <- str_c('dist_', str_sub(rlang::as_name(enquo(dat)), 1, 1), '_min')
    dat %>%
       left_join(data2, by = rlang::as_name(groupName)) %>%
        group_by(!! groupName) %>%
        summarise((!! nm1) := min(!! colName))

  }
joinSumm(a_dat2, zip, dist, zip)
joinSumm(b_dat2, zip, dist, zip)
</code>```

A reproducible example with built-in dataset iris (without the join part)

```<code>list(a_dat = iris, b_dat = iris, c_dat = iris) %>%
      imap(~ .x %>%
            group_by(Species) %>%
            summarise(!! str_c('dist_', substr(.y, 1, 1), '_min') := min(Sepal.Length)))
#$a_dat
# A tibble: 3 x 2
#  Species    dist_a_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9

#$b_dat
# A tibble: 3 x 2
#  Species    dist_b_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9

$c_dat
# A tibble: 3 x 2
#  Species    dist_c_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9
</code>```

Body:
I need to run very similar codes for 3 different dataset. My current codes look like this:

## data a
a_dat2 <- merge(a_dat, zip, by = "zip", all.x = T)
a_dat2 <- a_dat2 %>%
group_by(zip) %>%
summarize(dist_a_min = min(dist))
## data b
b_dat2 <- merge(b_dat, zip, by = "zip", all.x = T)
    b_dat2 <- b_dat2 %>%
     group_by(zip) %>%
summarize(dist_b_min = min(dist))
## data c
c_dat2 <- merge(c_dat, zip, by = "zip", all.x = T)
    c_dat2 <- c_dat2 %>%
     group_by(zip) %>%
summarize(dist_c_min = min(dist))

The codes for the 3 dataset are same except that the name of the data varies: a_dat, b_dat, c_dat. The variable name dist varies too: dist_a_min, dist_b_min, dist_c_min. What function/loop can be used to shorten the codes so that I don't need to copy and paste for each dataset separately?

Body:
An option would be to place the elements in a list with mget, loop through the list with imap, join (?left_join) with 'zip' dataset, grouped by 'zip' and get the min of 'dist' while creating the column name based on the identifier name substring

library(tidyverse)
mget(ls(pattern = "_dat2$")) %>%
        imap(~ left_join(.x, zip, by = 'zip') %>%
             group_by(zip) %>%
             summarise((! str_c('dist_', substr(.y, 1, 1), '_min')  :=  min(dist)))

Or another option is to create a function for repeated tasks

joinSumm <- function(dat, groupName, colName, data2) {
    groupName <- enquo(groupName)
    colName <- enquo(colName)
    nm1 <- str_c('dist_', str_sub(rlang::as_name(enquo(dat)), 1, 1), '_min')
    dat %>%
       left_join(data2, by = rlang::as_name(groupName)) %>%
        group_by(!! groupName) %>%
        summarise((!! nm1) := min(!! colName))

  }
joinSumm(a_dat2, zip, dist, zip)
joinSumm(b_dat2, zip, dist, zip)

A reproducible example with built-in dataset iris (without the join part)

list(a_dat = iris, b_dat = iris, c_dat = iris) %>%
      imap(~ .x %>%
            group_by(Species) %>%
            summarise(!! str_c('dist_', substr(.y, 1, 1), '_min') := min(Sepal.Length)))
#$a_dat
# A tibble: 3 x 2
#  Species    dist_a_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9

#$b_dat
# A tibble: 3 x 2
#  Species    dist_b_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9

$c_dat
# A tibble: 3 x 2
#  Species    dist_c_min
#  <fct>           <dbl>
#1 setosa            4.3
#2 versicolor        4.9
#3 virginica         4.9


问:
Problems making an awk between range of columns
I have a file called sds

```<code>$head sds
2557 386 fs://name/user/hive/ware/doc1/do_fact/date=20190313/fact=6
2593 393 fs://name/user/hive/ware/toc1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/user/hive/ware/dac2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/user/hive/ware/tec2/do_des/mes=25
340  332 fs://name/user/hive/ware/dc1/venta/year=2018/month=12
</code>```

I want delete /user/hive/ware and replace $7 ~ /_1$ for 1and other $7 for 2 using awk.

The code that I used was:

```<code>awk -F"/" '{ if ($7 ~ /_1$/)
print $1"//"$3"/1/"$7-$NF
else
print $1"//"$3"/2/"$7-$NF}' sds
</code>```

but the result is bad.

I would like and output like:

```<code>2557 386 fs://name/1/do_fact/date=20190313/fact=6
2593 393 fs://name/1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/2/do_des/mes=25
340  332 fs://name/1/venta/year=2018/month=12
</code>```

答:
with sed

```<code>$ sed -E 's_/user/hive/ware/[^/]+(.)/_/\1/_' file

2557 386 fs://name/1/do_fact/date=20190313/fact=6
2593 393 fs://name/1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/2/do_des/mes=25
340  332 fs://name/1/venta/year=2018/month=12
</code>```

it's not really a conditional replacement.

Body:
I have a file called sds

$head sds
2557 386 fs://name/user/hive/ware/doc1/do_fact/date=20190313/fact=6
2593 393 fs://name/user/hive/ware/toc1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/user/hive/ware/dac2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/user/hive/ware/tec2/do_des/mes=25
340  332 fs://name/user/hive/ware/dc1/venta/year=2018/month=12

I want delete /user/hive/ware and replace $7 ~ /_1$ for 1and other $7 for 2 using awk.

The code that I used was:

awk -F"/" '{ if ($7 ~ /_1$/)
print $1"//"$3"/1/"$7-$NF
else
print $1"//"$3"/2/"$7-$NF}' sds

but the result is bad.

I would like and output like:

2557 386 fs://name/1/do_fact/date=20190313/fact=6
2593 393 fs://name/1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/2/do_des/mes=25
340  332 fs://name/1/venta/year=2018/month=12

Body:
with sed

$ sed -E 's_/user/hive/ware/[^/]+(.)/_/\1/_' file

2557 386 fs://name/1/do_fact/date=20190313/fact=6
2593 393 fs://name/1/do_gas/idi_centr=6372/mes=20
2594 343 fs://name/2/do_gas2/idi_centr=6354/mes=21
349  307 fs://name/2/do_des/mes=25
340  332 fs://name/1/venta/year=2018/month=12

it's not really a conditional replacement.


问:
Is there a way to select an array without specifying it
I want to get a number from an array, without having to do a lot of if statements.</p>

```<code>double[] PVC_A1_Cu = new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d};
double[] PVC_A2_Cu = new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d};
double[] PVC_B1_Cu = new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d};
double[] PVC_B2_Cu = new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d};

String Kappe = SpinLederKapp.getSelectedItem().toString();   // This would return "PVC"
String LederMat = SpinLederMat.getSelectedItem().toString(); // This would return "A1"
String InsMet = SpinInsMet.getSelectedItem().toString();     //This would return  "Cu"

Integer Tverrsnitt = SpinTverrsnitt.getSelectedItemPosition();  //This would return in this case   "2"

String Codetest = Kappe + "_" + InsMet + "_"+LederMat;  //this would put it together like "PVC_A1_Cu"

Double Test3 = Codetest[Tverrsnitt];  //And here is were my knowledge ends...
//This does not work ^

//What i want it to do:
Double Test1 = PVC_A1_Cu[2];
</code>```

Body:
I want to get a number from an array, without having to do a lot of if statements.

double[] PVC_A1_Cu = new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d};
double[] PVC_A2_Cu = new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d};
double[] PVC_B1_Cu = new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d};
double[] PVC_B2_Cu = new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d};

String Kappe = SpinLederKapp.getSelectedItem().toString();   // This would return "PVC"
String LederMat = SpinLederMat.getSelectedItem().toString(); // This would return "A1"
String InsMet = SpinInsMet.getSelectedItem().toString();     //This would return  "Cu"

Integer Tverrsnitt = SpinTverrsnitt.getSelectedItemPosition();  //This would return in this case   "2"

String Codetest = Kappe + "_" + InsMet + "_"+LederMat;  //this would put it together like "PVC_A1_Cu"

Double Test3 = Codetest[Tverrsnitt];  //And here is were my knowledge ends...
//This does not work ^

//What i want it to do:
Double Test1 = PVC_A1_Cu[2];

Body:
Put the arrays in a Map (probably once and then keep it at the class level):

Map<String, double[]> map = new HashMap<>();
map.put("PVC_A1_Cu", new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d});
map.put("PVC_A2_Cu", new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d});
map.put("PVC_B1_Cu", new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d});
map.put("PVC_B2_Cu", new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d});

and then use it with your Codetest string:

double Test3 = map.get(Codetest)[Tverrsnitt];

Note that I ued double, not Double, since the arrays are of primitive doubles, not Double instances.


问:
avoid sorting in X axis in matplotlib and plot common X axis with multiple y axis
I wish to clarify two queries in this post.

I have a pandas df like below picture.

1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.

example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.

```<code>plt.plot(df.col_0, df.col_1)
</code>```

What will be best way to avoid sorting X axis values. ?

2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.

答:
I don't understand what you mean by they get sorted - does it not plot 112, 0.90178 and connect it to 110.89899, 0.90779, etc?

To share the X axis but have 2 Y axes that certain sets are plotted on, use twinx

```<code>fig, ax1 = plt.subplots()
ax1.plot(df.col_0, df.col_1)
ax2 = ax1.twinx()
ax2.plot(df.col_0, df.col_2)
</code>```

re: how to plot in the order you want

I believe your intention is to actually plot these values vs. time or index. To that end, I suggest:

```<code>fig, ax1 = plt.subplots()
ax1.plot(df['Time'], df.col_0) # or df.index, df.col_0
ax2 = ax1.twinx()
ax2.plot(df['Time'], df.col_1)
</code>```

Body:
I wish to clarify two queries in this post.

I have a pandas df like below picture.

1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.

example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.

plt.plot(df.col_0, df.col_1)

What will be best way to avoid sorting X axis values. ?

2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.

Body:
I don't understand what you mean by they get sorted - does it not plot 112, 0.90178 and connect it to 110.89899, 0.90779, etc?

To share the X axis but have 2 Y axes that certain sets are plotted on, use twinx

fig, ax1 = plt.subplots()
ax1.plot(df.col_0, df.col_1)
ax2 = ax1.twinx()
ax2.plot(df.col_0, df.col_2)

re: how to plot in the order you want

I believe your intention is to actually plot these values vs. time or index. To that end, I suggest:

fig, ax1 = plt.subplots()
ax1.plot(df['Time'], df.col_0) # or df.index, df.col_0
ax2 = ax1.twinx()
ax2.plot(df['Time'], df.col_1)


问:
Multiple distinct Content-Disposition headers received from server in Jasperreports
I'm trying to set content-disposition header in response of servlet, but i get this error in browser. What should i do?

Duplicate headers received from server

The response from the server
contained duplicate headers. This problem is generally the result of a
misconfigured website or proxy. Only the website or proxy
administrator can fix this issue.

Error 349 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION): Multiple
distinct Content-Disposition headers received. This is disallowed to
protect against HTTP response splitting attacks.

Here my servlet controller:

```<code>@RequestMapping("/**/paymentOrderReport.pdf")
public class PaymentOrderReportViewController extends org.springframework.web.servlet.mvc.AbstractController {

    private PaymentDao paymentDao;
    private JasperPdfView pdfView;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=" + "report.pdf");

        PaymentOrderEntity paymentOrderEntity = null;
        String traceCode = request.getParameter(ParamConstants.TRACE_CODE);

        if (traceCode != null) {
            PaymentSheetRequestEntity payRequestEntity = paymentDao.loadByUniqueProperty(PaymentSheetRequestEntity.PROP_TRACE_CODE,
                    traceCode);
            if (payRequestEntity != null) {
                paymentOrderEntity = payRequestEntity.getPaymentOrder();
            }
        }

        if (paymentOrderEntity != null) {
            List<PaymentOrderEntity> result = new ArrayList<PaymentOrderEntity>();
            result.add(paymentOrderEntity);
            JRDataSource jrDataSource = new JRBeanCollectionDataSource(result);

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("reportData", jrDataSource);

            return new ModelAndView(pdfView, model);
        }
        return null;
    }

    public void setPaymentDao(PaymentDao paymentDao) {
        this.paymentDao = paymentDao;
    }

    public void setPdfView(JasperPdfView pdfView) {
        this.pdfView = pdfView;
    }
}
</code>```

And JasperPdfView Class:

```<code>public class JasperPdfView extends AbstractJasperReportsView {

    @Override
    protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response) throws Exception {
        JRPdfExporter jrPdfExporter = new JRPdfExporter();
        if (getConvertedExporterParameters() != null) {
            jrPdfExporter.setParameters(getConvertedExporterParameters());
        }
        jrPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, populatedReport);
        jrPdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        jrPdfExporter.exportReport();
    }

}
</code>```

答:
Incorrect:

```<code>response.setHeader("Content-Disposition","attachment;filename="+filename+);
</code>```

Correct:

```<code>response.setHeader("Content-Disposition","attachment;filename=\""+filename+"\"");
</code>```

Body:
I'm trying to set content-disposition header in response of servlet, but i get this error in browser. What should i do?

Duplicate headers received from server

The response from the server
contained duplicate headers. This problem is generally the result of a
misconfigured website or proxy. Only the website or proxy
administrator can fix this issue.

Error 349 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION): Multiple
distinct Content-Disposition headers received. This is disallowed to
protect against HTTP response splitting attacks.

Here my servlet controller:

@RequestMapping("/**/paymentOrderReport.pdf")
public class PaymentOrderReportViewController extends org.springframework.web.servlet.mvc.AbstractController {

    private PaymentDao paymentDao;
    private JasperPdfView pdfView;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=" + "report.pdf");

        PaymentOrderEntity paymentOrderEntity = null;
        String traceCode = request.getParameter(ParamConstants.TRACE_CODE);

        if (traceCode != null) {
            PaymentSheetRequestEntity payRequestEntity = paymentDao.loadByUniqueProperty(PaymentSheetRequestEntity.PROP_TRACE_CODE,
                    traceCode);
            if (payRequestEntity != null) {
                paymentOrderEntity = payRequestEntity.getPaymentOrder();
            }
        }

        if (paymentOrderEntity != null) {
            List<PaymentOrderEntity> result = new ArrayList<PaymentOrderEntity>();
            result.add(paymentOrderEntity);
            JRDataSource jrDataSource = new JRBeanCollectionDataSource(result);

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("reportData", jrDataSource);

            return new ModelAndView(pdfView, model);
        }
        return null;
    }

    public void setPaymentDao(PaymentDao paymentDao) {
        this.paymentDao = paymentDao;
    }

    public void setPdfView(JasperPdfView pdfView) {
        this.pdfView = pdfView;
    }
}

And JasperPdfView Class:

public class JasperPdfView extends AbstractJasperReportsView {

    @Override
    protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response) throws Exception {
        JRPdfExporter jrPdfExporter = new JRPdfExporter();
        if (getConvertedExporterParameters() != null) {
            jrPdfExporter.setParameters(getConvertedExporterParameters());
        }
        jrPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, populatedReport);
        jrPdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        jrPdfExporter.exportReport();
    }

}

Body:
Incorrect:

response.setHeader("Content-Disposition","attachment;filename="+filename+);

Correct:

response.setHeader("Content-Disposition","attachment;filename=\""+filename+"\"");


问:
N1QL query to join document, with the latest child (on basis of creationDateTime) in couchbase
N1QL  query to get the latest document having same other property in a join result of two different documents in couchbase

I have a bucket called "prices", with two different types of documents "intent" and "request"

```<code>  "intent"  (id = "intent1")
  {
  "locationDSL": "some_location"
  "product": "some_product1"
  }
  "intent"  (id = "intent2")
  {
  "locationDSL": "some_location2"
  "product": "some_product2"
  }
  "request"  (id = "request1")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-04-01",
  "status" : "success"
  }
  "request"  (id = "request2")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-05-01"
   "status" : "failed"
  }
  "request"  (id = "request3")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-06-01",
 "status" : "failed"
  }
  "request"  (id = "request4")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-07-01",
  "status" : "success"
  }
</code>```

so I have 2 requests("request1" and "request2") for "intent1" and 2 requests("request3" and "request4") for intent2,

I need to join "intent1" and "intent2" with latest requests (request having latest createdDateTime) i.e  "request2" and "request4" respectively, and also able filter on some fields of latest child document of matching "intentId", so if query for "status" = "success", then it should only return (intentId2 , request4) and not (intent1,request1), since in the latest child "request2" doesn't match with the condition

i am able to join  the documents , but the join is not with latest requests but all requests matching intent.id.

This question is similar to
[Filter documents using n1ql
,but I need a join of all the fields in two documents, rather than single field or attributes

答:
Based on your query try the following. The subquery uses covering index and only fetch the latest document in parent query</p>

```<code>CREATE INDEX ix1 ON pricescmd(intentId, status, createdDateTime DESC);
SELECT intents, request
FROM (SELECT mx.*
      FROM pricescmd
      WHERE intentId IS NOT NULL
      GROUP BY intentId, status
      mx = MAX([createdDateTime, {META().id, intentId, status} ])[1] )  AS d
LET request = (SELECT RAW request FROM pricescmd AS request USE KEYS d.id)[0],
    intents = (SELECT RAW intent FROM pricescmd AS intent USE KEYS d.intentId)[0];
</code>```

Body:
N1QL  query to get the latest document having same other property in a join result of two different documents in couchbase

I have a bucket called "prices", with two different types of documents "intent" and "request"

  "intent"  (id = "intent1")
  {
  "locationDSL": "some_location"
  "product": "some_product1"
  }
  "intent"  (id = "intent2")
  {
  "locationDSL": "some_location2"
  "product": "some_product2"
  }
  "request"  (id = "request1")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-04-01",
  "status" : "success"
  }
  "request"  (id = "request2")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-05-01"
   "status" : "failed"
  }
  "request"  (id = "request3")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-06-01",
 "status" : "failed"
  }
  "request"  (id = "request4")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-07-01",
  "status" : "success"
  }

so I have 2 requests("request1" and "request2") for "intent1" and 2 requests("request3" and "request4") for intent2,

I need to join "intent1" and "intent2" with latest requests (request having latest createdDateTime) i.e  "request2" and "request4" respectively, and also able filter on some fields of latest child document of matching "intentId", so if query for "status" = "success", then it should only return (intentId2 , request4) and not (intent1,request1), since in the latest child "request2" doesn't match with the condition

i am able to join  the documents , but the join is not with latest requests but all requests matching intent.id.

This question is similar to
[Filter documents using n1ql
,but I need a join of all the fields in two documents, rather than single field or attributes

Body:
Based on your query try the following. The subquery uses covering index and only fetch the latest document in parent query

CREATE INDEX ix1 ON pricescmd(intentId, status, createdDateTime DESC);
SELECT intents, request
FROM (SELECT mx.*
      FROM pricescmd
      WHERE intentId IS NOT NULL
      GROUP BY intentId, status
      mx = MAX([createdDateTime, {META().id, intentId, status} ])[1] )  AS d
LET request = (SELECT RAW request FROM pricescmd AS request USE KEYS d.id)[0],
    intents = (SELECT RAW intent FROM pricescmd AS intent USE KEYS d.intentId)[0];


问:
Fmincon in matlab running out of memory
I am using Matlab's fmincon to optimize an objective function which is the l2 norm between 2 vectors. There is also an inequality constraint which is another l2 norm between the vector to be optimized and some other constance vector. So basically the number of parameters is the size of this vector which I am trying to minimize in an l2 sense.

|| M*s - s ||_2 s.t. ||s-t||_2 < epsilon

M is a constant matrix, t is a constant vectors and epsilon is a constant.

So now the problem for me is that s is huge. It can have from anywhere 400 to 20000 variables. Now fmincon runs out of memory when internally trying to store matrices. Is there a way to solve this problem ?

Thanks !

答:
when you run fmincon, you should consider adding a set of options. look at optimset,
so do :

```<code>OPTI = optimset('MaxIter',1000)
</code>```

or checkout all the optimization options.

then

```<code>get_val = fmincon(... , OPTI)
</code>```

if that doesn't work you should post your code

Title: Fmincon in matlab running out of memory

Body:
when you run fmincon, you should consider adding a set of options. look at optimset,
so do :

OPTI = optimset('MaxIter',1000)

or checkout all the optimization options.

then

get_val = fmincon(... , OPTI)

if that doesn't work you should post your code


问:
Windows Registry Key Check Fails in C#
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }
```

I expect the result to be true but it returns false.

答:
I fixed it. It was basically the architecture messing things up.

Old Code:

bool checkIfJavaInstalled()
{
    string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
    return installed;
}
```

<p>New code:</p>

<pre class="lang-cs prettyprint-override"><code>bool checkIfJavaInstalled()
{
    var regview = Microsoft.Win32.RegistryView.Registry64;
    if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))
    {
        regview = Microsoft.Win32.RegistryView.Registry32;
    }
    string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    bool installed = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, regview).OpenSubKey(JavaKey) != null;
    return installed;
}
</code>```

Title: Windows Registry Key Check Fails in C#

Body:
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }

I expect the result to be true but it returns false.

Body:
I fixed it. It was basically the architecture messing things up.

Old Code:

bool checkIfJavaInstalled()
{
    string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
    return installed;
}

New code:

bool checkIfJavaInstalled()
{
    var regview = Microsoft.Win32.RegistryView.Registry64;
    if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))
    {
        regview = Microsoft.Win32.RegistryView.Registry32;
    }
    string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    bool installed = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, regview).OpenSubKey(JavaKey) != null;
    return installed;
}


问:
How to make an AJAX call before blueimp uploader starts a multi-file upload
When multiple files are dropped onto a dropzone, I need to do a one-time server-side preparation before the individual files are uploaded.

Ideally, the uploader would have a multi-file-init callback that would allow me to make an ajax call to my server (where the preparation is done) and begin uploading of the individual files only when the preparation call returns.

Is there any way to achieve this end?

Currently, my server-side (php) code that is run for each uploaded file checks to see if the preparation has been done, and runs the preparation function if needed. But due to the uploader's asynchronously sending multiple files, a race-condition occurs and the prepartion function sometimes gets called multiple times.

答:
I was able to solve my problem by following advice from barmar and adding a button to initiate uploads.

I found specific instructions here: https://stackoverflow.com/a/38236305/671669

I now include this code in the initialization of the blueimp jQuery-File-Upload plugin:

```<code>add: function (e, data) {
    // enable the upload button
    $("#fileupload-start-button").prop('disabled', false);

    // wait for button click to process
    $("#fileupload-start-button").on('xyzUploadTrigger', function (e) {
        data.submit();
    });
},
</code>```

And my binding to the "Start Upload" button looks like this:

```<code>$("#fileupload-start-button").on('click', function (e) {
    $(this).prop('disabled', true)
    e.preventDefault();

    // prepare server-side for upload of resources
    axios.post('/resources/initResourceCollectionForUploader',
        {
            'params': params,
        })
        .then(function (response) {
            // hide the upload button and trigger it
            $("#fileupload-controls-container").addClass('d-none');
            $("#fileupload-start-button").trigger('xyzUploadTrigger');
        })
        .catch(function (error) {
            console.log(error);
        });
});
</code>```

Body:
I was able to solve my problem by following advice from barmar and adding a button to initiate uploads.

I found specific instructions here: https://stackoverflow.com/a/38236305/671669

I now include this code in the initialization of the blueimp jQuery-File-Upload plugin:

add: function (e, data) {
    // enable the upload button
    $("#fileupload-start-button").prop('disabled', false);

    // wait for button click to process
    $("#fileupload-start-button").on('xyzUploadTrigger', function (e) {
        data.submit();
    });
},

And my binding to the "Start Upload" button looks like this:

$("#fileupload-start-button").on('click', function (e) {
    $(this).prop('disabled', true)
    e.preventDefault();

    // prepare server-side for upload of resources
    axios.post('/resources/initResourceCollectionForUploader',
        {
            'params': params,
        })
        .then(function (response) {
            // hide the upload button and trigger it
            $("#fileupload-controls-container").addClass('d-none');
            $("#fileupload-start-button").trigger('xyzUploadTrigger');
        })
        .catch(function (error) {
            console.log(error);
        });
});


问:
How to split each digit of a number into different rows
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9
```

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

答:
Using Nae's and Raymond's answers

To split a fixed-length number into separated rows

```<code>SELECT
   SUBSTR(1234567890123, range10, 1)
FROM (
  SELECT 1 range10
  UNION SELECT 2
  UNION SELECT 3
  UNION SELECT 4
  UNION SELECT 5
  UNION SELECT 6
  UNION SELECT 7
  UNION SELECT 8
  UNION SELECT 9
  UNION SELECT 10
  UNION SELECT 11
  UNION SELECT 12
  UNION SELECT 13
) A
</code>```

For a variable-length number of characters, see Nae's answer

The whole RUC's validation made into a function

CREATE FUNCTION `validate_ruc`(`ruc` BIGINT) RETURNS binary(1)
BEGIN
DECLARE isValid BINARY;

IF LENGTH(ruc) != 11 THEN RETURN FALSE; END IF;

SELECT
  ((11 - (sum % 11)) % 10) = (ruc % 10)
INTO isValid
FROM (
  SELECT
     SUM( SUBSTR(ruc, range10, 1) * (SUBSTR(5432765432, range10, 1)) ) AS sum
  FROM (
    SELECT 1 range10
    UNION SELECT 2
    UNION SELECT 3
    UNION SELECT 4
    UNION SELECT 5
    UNION SELECT 6
    UNION SELECT 7
    UNION SELECT 8
    UNION SELECT 9
    UNION SELECT 10
  ) A
) B;

RETURN isValid;

END
```

Body:
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

Body:
Using Nae's and Raymond's answers

To split a fixed-length number into separated rows

SELECT
   SUBSTR(1234567890123, range10, 1)
FROM (
  SELECT 1 range10
  UNION SELECT 2
  UNION SELECT 3
  UNION SELECT 4
  UNION SELECT 5
  UNION SELECT 6
  UNION SELECT 7
  UNION SELECT 8
  UNION SELECT 9
  UNION SELECT 10
  UNION SELECT 11
  UNION SELECT 12
  UNION SELECT 13
) A

For a variable-length number of characters, see Nae's answer

The whole RUC's validation made into a function

CREATE FUNCTION `validate_ruc`(`ruc` BIGINT) RETURNS binary(1)
BEGIN
DECLARE isValid BINARY;

IF LENGTH(ruc) != 11 THEN RETURN FALSE; END IF;

SELECT
  ((11 - (sum % 11)) % 10) = (ruc % 10)
INTO isValid
FROM (
  SELECT
     SUM( SUBSTR(ruc, range10, 1) * (SUBSTR(5432765432, range10, 1)) ) AS sum
  FROM (
    SELECT 1 range10
    UNION SELECT 2
    UNION SELECT 3
    UNION SELECT 4
    UNION SELECT 5
    UNION SELECT 6
    UNION SELECT 7
    UNION SELECT 8
    UNION SELECT 9
    UNION SELECT 10
  ) A
) B;

RETURN isValid;

END


问:
dplyr filter() with SQL-like %wildcard%
Suppose I have the following data:

```<code>foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

> foo
   Company    Metric
1 company1 10.539970
2      foo  9.487823
3     test  9.663994
4     food  9.499327
</code>```

Why does the following code return 0 results (instead of the second and fourth rows)?

```<code>library(dplyr)
library(data.table)

foo %>% dplyr::filter(Company %like% "%foo%")
</code>```

I'm trying to use the SQL-equivalent wildcard filter on a particular input string to dplyr::filter, using the %like% operator from the data.table package.

What am I doing wrong?

答:
First convert that variable into same case for all records

```<code>foo$Company <- toupper(foo$Company)
</code>```

then apply filter

```<code>foo <- foo[Company %like% 'foo']
</code>```

This will give the subset where Company could be:

```<code>WESTFOO FIRST NATION-LGS,
SPRINGER EUFOO OIL CO,
US FOO,
CITIFOO NA
</code>```

Title: dplyr filter() with SQL-like %wildcard%

Body:
Suppose I have the following data:

foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

> foo
   Company    Metric
1 company1 10.539970
2      foo  9.487823
3     test  9.663994
4     food  9.499327

Why does the following code return 0 results (instead of the second and fourth rows)?

library(dplyr)
library(data.table)

foo %>% dplyr::filter(Company %like% "%foo%")

I'm trying to use the SQL-equivalent wildcard filter on a particular input string to dplyr::filter, using the %like% operator from the data.table package.

What am I doing wrong?

Body:
First convert that variable into same case for all records

foo$Company <- toupper(foo$Company)

then apply filter

foo <- foo[Company %like% 'foo']

This will give the subset where Company could be:

WESTFOO FIRST NATION-LGS,
SPRINGER EUFOO OIL CO,
US FOO,
CITIFOO NA


问:
PHPMailer : SMTP host connection error on Godaddy

Mailer Error: SMTP Error: Could not connect to SMTP host.;

this error is generating when i run this code in godaddy.

```<code><?php
require("PHPMailer_5.2.0/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host     = "smtpout.secureserver.net"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username@domain.com"; // SMTP username
$mail->Password = "******"; // SMTP password
$mail->From     = "username@domain.com";
$mail->FromName = "User";
$mail->AddAddress("Sendto@gmail.com"); // name is optional
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body    = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if (!$mail->Send()) {
    echo "Message could not be sent. <p>";
    echo "Mailer Error: " . $mail->ErrorInfo;
    exit;
}
echo "Message has been sent";
?>
</code>```

答:
i solved this using localhost as smtp server, port 25,  no ssl and no  authentication.
I'm using wordpress, with divi theme on a godaddy server.</p>

Body:
Mailer Error: SMTP Error: Could not connect to SMTP host.;

this error is generating when i run this code in godaddy.

<?php
require("PHPMailer_5.2.0/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host     = "smtpout.secureserver.net"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username@domain.com"; // SMTP username
$mail->Password = "******"; // SMTP password
$mail->From     = "username@domain.com";
$mail->FromName = "User";
$mail->AddAddress("Sendto@gmail.com"); // name is optional
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body    = "This is the HTML message body in bold!";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if (!$mail->Send()) {
    echo "Message could not be sent.
";
    echo "Mailer Error: " . $mail->ErrorInfo;
    exit;
}
echo "Message has been sent";
?>


问:
How to reset a RXJS scan operator based on another Observable
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

```<code>const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};
</code>```

答:
Found a working solution: I check the current offset by using withLatestFrom before the scan operator and reset the accumulator if needed based on this value.

Stackblitz demo

Body:
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};


问:
How to get "Quantity Sold" from eBay website into excel using VBA?
I am trying to get item sold quantity (live) from eBay into excel using VBA?
This is what I found on stackoverflow so far.
But I don't get any results
I would appreciate any help
Thanks</p>

```<code>Option Explicit
Sub readData()

Dim XMLPage As New MSXML2.XMLHTTP60
Dim html As New MSHTML.HTMLDocument
Dim profile As IHTMLElement6

XMLPage.Open "GET", "https://www.ebay.com/itm/VIRGINIA-CAVALIERS-FINAL-FOUR-National-FREAKIN-Champions-T-Shirt-Gildan/352639122861", False
XMLPage.send

If XMLPage.Status <> 200 Then MsgBox XMLPage.statusText
html.body.innerHTML = XMLPage.responseText

 For Each profile In html.getElementsByTagName("span")(0).Children
 Debug.Print profile.getElementsByClassName("vi-txt-underline")(0)

Next

End Sub
</code>```

答:
Using the class is fine. There is only 1 match on the page so no need to grab multiple collections and loop. Simply use querySelector to return first match.

```<code>Public Sub GetNumberSold()
    Dim html As HTMLDocument

    Set html = New HTMLDocument

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.ebay.com/itm/VIRGINIA-CAVALIERS-FINAL-FOUR-National-FREAKIN-Champions-T-Shirt-Gildan/352639122861", False
        .send
        html.body.innerHTML = .responseText
    End With

    MsgBox html.querySelector(".vi-txt-underline").innerText
    Debug.Print Replace$(html.querySelector(".vi-txt-underline").innerText," sold",vbNullString)
    Debug.Print split(html.querySelector(".vi-txt-underline").innerText,chr$(32))(0)

End Sub
</code>```

Body:
I am trying to get item sold quantity (live) from eBay into excel using VBA?
This is what I found on stackoverflow so far.
But I don't get any results
I would appreciate any help
Thanks

Option Explicit
Sub readData()

Dim XMLPage As New MSXML2.XMLHTTP60
Dim html As New MSHTML.HTMLDocument
Dim profile As IHTMLElement6

XMLPage.Open "GET", "https://www.ebay.com/itm/VIRGINIA-CAVALIERS-FINAL-FOUR-National-FREAKIN-Champions-T-Shirt-Gildan/352639122861", False
XMLPage.send

If XMLPage.Status <> 200 Then MsgBox XMLPage.statusText
html.body.innerHTML = XMLPage.responseText

 For Each profile In html.getElementsByTagName("span")(0).Children
 Debug.Print profile.getElementsByClassName("vi-txt-underline")(0)

Next

End Sub

Body:
Using the class is fine. There is only 1 match on the page so no need to grab multiple collections and loop. Simply use querySelector to return first match.

Public Sub GetNumberSold()
    Dim html As HTMLDocument

    Set html = New HTMLDocument

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.ebay.com/itm/VIRGINIA-CAVALIERS-FINAL-FOUR-National-FREAKIN-Champions-T-Shirt-Gildan/352639122861", False
        .send
        html.body.innerHTML = .responseText
    End With

    MsgBox html.querySelector(".vi-txt-underline").innerText
    Debug.Print Replace$(html.querySelector(".vi-txt-underline").innerText," sold",vbNullString)
    Debug.Print split(html.querySelector(".vi-txt-underline").innerText,chr$(32))(0)

End Sub


问:
Where is PIP installed by default with Python 3.7 for Mac?
I am new to Python and looking to use to to create some cool solutions. The documentation says that pip is included by default with Python 3.4+ and I've just installed version 3.7.3 but cannot located pip as I was attempting to use it to install the Requests package for API calls.

```<code>$ python3 --version
Python 3.7.3
$ pip --version
-bash: pip: command not found
</code>```

So I can see in fact that version 3.7.3 of Python is installed, yet pip isn't? I checked both Library/Python/3.7/bin/ and Library/Python/3.7/lib/python/site-packages/ and do not see any reference to pip.

The documentation states that you can use a curl command to get pip and then install it. I am new to the terminal and have never used a curl command. Also, I've read you want to keep your Python3 stuff away from the system Python version, so would I use the following?

```<code>$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3 get-pip.py
</code>```

答: You need to signal that you are using Python 3 with python3 -m pip ..... otherwise it takes the default Python 2

Body:
I am new to Python and looking to use to to create some cool solutions. The documentation says that pip is included by default with Python 3.4+ and I've just installed version 3.7.3 but cannot located pip as I was attempting to use it to install the Requests package for API calls.

$ python3 --version
Python 3.7.3
$ pip --version
-bash: pip: command not found

So I can see in fact that version 3.7.3 of Python is installed, yet pip isn't? I checked both Library/Python/3.7/bin/ and Library/Python/3.7/lib/python/site-packages/ and do not see any reference to pip.

The documentation states that you can use a curl command to get pip and then install it. I am new to the terminal and have never used a curl command. Also, I've read you want to keep your Python3 stuff away from the system Python version, so would I use the following?

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3 get-pip.py


问:
Advanced table-layout to CSS
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

```<code>     padding-left: 200000px;
     margin-left: -200000px;
</code>```

To fake the expansion to the left?

答:
Ideally here you would want a fluid width. See: http://jsfiddle.net/cbNvn/1/

```<code><div id="left">Left</div>
<div id="center">Center</div>
<div id="right">Right</div>
</code>```

```<code>
div {
    float: left;
}

#left {
    width: 25%;
    text-align: right;
}

#center {
    width: 50%;
}

#right {
    width: 25%;
}
</code>```

Expanding the page would expand the left column and the background image can repeat. The linked images can lay over the background as they do currently. The text-align:right attribute will keep the linked images on the right.

Title: Advanced table-layout to CSS

Body:
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

     padding-left: 200000px;
     margin-left: -200000px;

To fake the expansion to the left?

Body:
Ideally here you would want a fluid width. See: http://jsfiddle.net/cbNvn/1/

<div id="left">Left</div>
<div id="center">Center</div>
<div id="right">Right</div>

div {
    float: left;
}

#left {
    width: 25%;
    text-align: right;
}

#center {
    width: 50%;
}

#right {
    width: 25%;
}

Expanding the page would expand the left column and the background image can repeat. The linked images can lay over the background as they do currently. The text-align:right attribute will keep the linked images on the right.


问:
How to update Salesforce through NetSuite?
How would you go about updating Salesforce with NetSuite data?
I know that you would need to use Suitescript 2.0 and some sort of token authentication.</p>

答:
I have a suitescript 2.0 user event script that does just this, It makes a connection to salesforce and updates netsuite customer fields to salesforce accounts.

The script will update three custom fields on the salesforce account: NSID, sync, syntime.

```<code>/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */

define(['N/https', 'N/search', 'N/record'],

function (https, search, record)
{
    _HTTPS = https;
    _SEARCH = search;
    _RECORD = record;

    //handle after submition of customer on create and edit
    function afterSubmit(context)
    {
        var body;
        var NSID;
        var sfEntityID;
        var sync;
        var syncTime;
        var accountURL;
        var response;
        var recordData = {};

        //If customer is getting deleted reflect that to SF
        if(context.type === "delete")
            NSID = 'deleted';
        else
            NSID = context.newRecord.id;

        //get the SF account ID
        sfEntityID = context.newRecord.getValue({fieldId:"custentity_sf_account_id"});
        if (sfEntityID == undefined || sfEntityID == "") //If there is no SFID stop
        {
            log.debug("afterSubmit","No sfEntityID on customer with NSID: " + NSID);
            return;
        }

        var date = new Date();
        var month = date.getUTCMonth() + 1; // jan = 0
        if (month < 10)
        {
            month = "0" + month;
        }
        syncTime = date.getUTCFullYear() + '-' + month + '-' + date.getUTCDate() + 'T' + date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds() + '.000Z';

        //login to SF (loginSalesforceNLAP controls sandbox/production login)
        body = loginSalesforceNLAP();

        //check if I got an access token back
        if(body.access_token == undefined || body.access_token == "")
        {
            log.debug('afterSubmit','could not get SF access token');
            return;
        }

        //set fields that will be updated on SF account
        recordData.Netsuite_Internal_ID__c = NSID;
        recordData.Sync__c = true;
        recordData.Synced_Time__c = syncTime;
        recordData = JSON.stringify(recordData);

        //send update request
        response = _HTTPS.post({
            url: (getURL(body) + "/sobjects/Account/" + sfEntityID + "?_HttpMethod=PATCH"),
            body: recordData,
            headers: {"Authorization": "OAuth " + body.access_token,"Content-Type": "application/json"}
        });

        log.debug("response",response);

        //log an error if it occurred
        if(response.code != 204)
        {
            log.debug("afterSubmit","Could not update sf Account: " + sfEntityID + ' NSID: ' + NSID);
            return;
        }

        //success message
        log.debug("afterSubmit","successfully updated sf Account: " + sfEntityID + ' NSID: ' + NSID);
        return;
    }

    return {afterSubmit: afterSubmit};

});

//get max SF version for SF update request
function getURL(body)
{
    var max
    var arr
    var header = {"Authorization": "OAuth " + body.access_token  };
    var recordData = {};
    var url = body.instance_url + "/services/data/";

    response = _HTTPS.get({
                url: url,
                body: recordData,
                headers: header
            });

    if(response.code == 200 || response.code == 204)
    {
        arr = JSON.parse(response.body)
        for(var i = 0; i < arr.length; i++)
        {
            //find max version
            if(!max || parseInt(arr[i]["version"]) > parseInt(max["version"]))
                max = arr[i];
        }
        return body.instance_url + max.url;
    }
    else
        return "";
}

//Connect to Salesforce instance and obtain the Access Token used for subsequent Salesforce calls this session
function loginSalesforceNLAP()
{

    //production
    var clientID = "3MVG9QDx8IX8nP5SpP0endmsendmeMepopopBvuB074i_7h7fakehoB0hnnhK7FyfTUgxH2234vR6QPoVXpDE";
    var clientSecret = "1231232320412308455";
    var securityToken = "N0bx9dI321F732aO12iC33gm6";
    var username = "sflogin@login.com";
    var password = "password";
    var loginURL = "https://login.salesforce.com/services/oauth2/token";

    var header = [];
    header['Content-Type'] = 'application/json;charset=UTF-8';
    var recordData = {};
    var url = loginURL + "?grant_type=password&client_id=" + clientID + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password + securityToken;

    try
    {
        response = _HTTPS.post({
                url: url,
                body: recordData,
                headers: header
            });
        response = JSON.parse(JSON.stringify(response));
        if (response.code == 200 || response.code == 204)
            return JSON.parse(response.body); //return body
    }
    catch (er02)
    {
        log.error('ERROR:loginSalesforceNLAP', er02);
    }
    return "";
}
</code>```

In order to get clientID, clientSecret, and the security token follow these steps: https://developer.salesforce.com/forums/?id=906F0000000AfcgIAC

Body:
I have a suitescript 2.0 user event script that does just this, It makes a connection to salesforce and updates netsuite customer fields to salesforce accounts.

The script will update three custom fields on the salesforce account: NSID, sync, syntime.

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */

define(['N/https', 'N/search', 'N/record'],

function (https, search, record)
{
    _HTTPS = https;
    _SEARCH = search;
    _RECORD = record;

    //handle after submition of customer on create and edit
    function afterSubmit(context)
    {
        var body;
        var NSID;
        var sfEntityID;
        var sync;
        var syncTime;
        var accountURL;
        var response;
        var recordData = {};

        //If customer is getting deleted reflect that to SF
        if(context.type === "delete")
            NSID = 'deleted';
        else
            NSID = context.newRecord.id;

        //get the SF account ID
        sfEntityID = context.newRecord.getValue({fieldId:"custentity_sf_account_id"});
        if (sfEntityID == undefined || sfEntityID == "") //If there is no SFID stop
        {
            log.debug("afterSubmit","No sfEntityID on customer with NSID: " + NSID);
            return;
        }

        var date = new Date();
        var month = date.getUTCMonth() + 1; // jan = 0
        if (month < 10)
        {
            month = "0" + month;
        }
        syncTime = date.getUTCFullYear() + '-' + month + '-' + date.getUTCDate() + 'T' + date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds() + '.000Z';

        //login to SF (loginSalesforceNLAP controls sandbox/production login)
        body = loginSalesforceNLAP();

        //check if I got an access token back
        if(body.access_token == undefined || body.access_token == "")
        {
            log.debug('afterSubmit','could not get SF access token');
            return;
        }

        //set fields that will be updated on SF account
        recordData.Netsuite_Internal_ID__c = NSID;
        recordData.Sync__c = true;
        recordData.Synced_Time__c = syncTime;
        recordData = JSON.stringify(recordData);

        //send update request
        response = _HTTPS.post({
            url: (getURL(body) + "/sobjects/Account/" + sfEntityID + "?_HttpMethod=PATCH"),
            body: recordData,
            headers: {"Authorization": "OAuth " + body.access_token,"Content-Type": "application/json"}
        });

        log.debug("response",response);

        //log an error if it occurred
        if(response.code != 204)
        {
            log.debug("afterSubmit","Could not update sf Account: " + sfEntityID + ' NSID: ' + NSID);
            return;
        }

        //success message
        log.debug("afterSubmit","successfully updated sf Account: " + sfEntityID + ' NSID: ' + NSID);
        return;
    }

    return {afterSubmit: afterSubmit};

});

//get max SF version for SF update request
function getURL(body)
{
    var max
    var arr
    var header = {"Authorization": "OAuth " + body.access_token  };
    var recordData = {};
    var url = body.instance_url + "/services/data/";

    response = _HTTPS.get({
                url: url,
                body: recordData,
                headers: header
            });

    if(response.code == 200 || response.code == 204)
    {
        arr = JSON.parse(response.body)
        for(var i = 0; i < arr.length; i++)
        {
            //find max version
            if(!max || parseInt(arr[i]["version"]) > parseInt(max["version"]))
                max = arr[i];
        }
        return body.instance_url + max.url;
    }
    else
        return "";
}

//Connect to Salesforce instance and obtain the Access Token used for subsequent Salesforce calls this session
function loginSalesforceNLAP()
{

    //production
    var clientID = "3MVG9QDx8IX8nP5SpP0endmsendmeMepopopBvuB074i_7h7fakehoB0hnnhK7FyfTUgxH2234vR6QPoVXpDE";
    var clientSecret = "1231232320412308455";
    var securityToken = "N0bx9dI321F732aO12iC33gm6";
    var username = "sflogin@login.com";
    var password = "password";
    var loginURL = "https://login.salesforce.com/services/oauth2/token";

    var header = [];
    header['Content-Type'] = 'application/json;charset=UTF-8';
    var recordData = {};
    var url = loginURL + "?grant_type=password&client_id=" + clientID + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password + securityToken;

    try
    {
        response = _HTTPS.post({
                url: url,
                body: recordData,
                headers: header
            });
        response = JSON.parse(JSON.stringify(response));
        if (response.code == 200 || response.code == 204)
            return JSON.parse(response.body); //return body
    }
    catch (er02)
    {
        log.error('ERROR:loginSalesforceNLAP', er02);
    }
    return "";
}

In order to get clientID, clientSecret, and the security token follow these steps: https://developer.salesforce.com/forums/?id=906F0000000AfcgIAC


问:
How to auto-reload code loaded by load magic in Jupyter notebook?
Jupyter Notebook has a %load magic that can load code into a cell of a notebook.

%load start.py
```

<p>This line loads the content of <code>start.py</code> into the current cell. The magic is automatically commented out after execution.</p>

<pre class="lang-py prettyprint-override"><code># %load start.py
import numpy as np
import pandas as pd
</code>```

Jupyter Notebook also has a %autoreload extension that can reload modules before executing code.

%load_ext autoreload
%autoreload 2
from utils import load_data
```

<p>If there is a change in the <code>load_data</code> function, this extension can detect and auto-reload the new function before execution.</p>

<p>Is there a way to combine the functionality of these two? In other words, if the content of <code>start.py</code> change, how can I automatically detect the change and reload it into the cell before running code?</p>

<p>For example, if the content of <code>start.py</code> is now</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
</code>```

I would like the cell to be reloaded to become:

# %load start.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```

答:
I think you're trying to mix things beyond the point they were intended.

If you want a hack, as you mention you could import a function from within start.py, then %autoreload will give you the functionality you want. You could then mix with this if you wanted to see the contents of the .py file:

```<code>with open("start.py") as f:
    print(f.read())
</code>```

You could then easily copy and paste into a cell if needed.

Body:
Jupyter Notebook has a %load magic that can load code into a cell of a notebook.

%load start.py

This line loads the content of start.py into the current cell. The magic is automatically commented out after execution.

# %load start.py
import numpy as np
import pandas as pd

Jupyter Notebook also has a %autoreload extension that can reload modules before executing code.

%load_ext autoreload
%autoreload 2
from utils import load_data

If there is a change in the load_data function, this extension can detect and auto-reload the new function before execution.

Is there a way to combine the functionality of these two? In other words, if the content of start.py change, how can I automatically detect the change and reload it into the cell before running code?

For example, if the content of start.py is now

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

I would like the cell to be reloaded to become:

# %load start.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Body:
I think you're trying to mix things beyond the point they were intended.

If you want a hack, as you mention you could import a function from within start.py, then %autoreload will give you the functionality you want. You could then mix with this if you wanted to see the contents of the .py file:

with open("start.py") as f:
    print(f.read())

You could then easily copy and paste into a cell if needed.


问:
How to get the html document contained inside an HTML tag using selenium in python
I want to get the source code of HTML document which is inside an HTML tag which is generated after some JavaScript and store it in a variable. Here, the HTML tag is  and it contains a variable kind of something that looks like #document and when I expand this, I get an HTML document which looks something like <!DOCTYPE html> ...

To summarize:

```<code><iframe src="https://www.XXXXXX.com/" allow="autoplay; fullscreen" frameborder="no" scrolling="no" allowfullscreen="yes" style="width: 100%; height: 100%;">
    #document
        <!DOCTYPE html>
        <html>...</html>  // a whole new HTML document
</iframe>
</code>```

I want to store all the content of this HTML document as a string in python

What I have done:

```<code>driver.find_element_by_xpath('/path/to/iframe/tag').get_attribute('innerHTML')
</code>```

but, this just returns an empty string. Also, I have checked if it is working with BeautifulSoup

```<code>html = driver.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(html, 'html5lib')
print(soup.prettify())
</code>```

but, this also isn't working

NOTE: I run these test only after the script is executed, also, I guess the problem seems to be with the #document thing

Body:
I want to get the source code of HTML document which is inside an HTML tag which is generated after some JavaScript and store it in a variable. Here, the HTML tag is  and it contains a variable kind of something that looks like #document and when I expand this, I get an HTML document which looks something like <!DOCTYPE html> ...

To summarize:

    #document
        <!DOCTYPE html>
        ...  // a whole new HTML document

I want to store all the content of this HTML document as a string in python

What I have done:

driver.find_element_by_xpath('/path/to/iframe/tag').get_attribute('innerHTML')

but, this just returns an empty string. Also, I have checked if it is working with BeautifulSoup

html = driver.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(html, 'html5lib')
print(soup.prettify())

but, this also isn't working

NOTE: I run these test only after the script is executed, also, I guess the problem seems to be with the #document thing

Body: Why would you want a HTML document in an html document? I do think this isn't possible, but you could try putting an HTLM document on a different site and than by using <iframe src="www.html-content.com"></iframe>


问:
Spring boot - Server did not recognize the value of HTTP Header SOAPAction
I want to consume soap service using jaxb.
The generated request from jaxb is

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
      <ns2:Add xmlns:ns2="http://tempuri.org/">
         <ns2:intA>10</ns2:intA><ns2:intB>20</ns2:intB>
      </ns2:Add>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

But the response is a soap exception as stated in the title.

```<code>Caused by: org.springframework.ws.soap.client.SoapFaultClientException: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .
   at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
</code>```

Below is my soap config code. Source example: https://howtodoinjava.com/spring-boot/spring-soap-client-webservicetemplate/

```<code>    public class ConsumeSoapApplication {
            public static String wsdlurl = "http://www.dneonline.com/calculator.asmx?wsdl";
            public static void main(String[] args) {
                try {
                    JAXBContext.newInstance(com.dxc.service.soap.service.calc.ObjectFactory.class.getPackage().getName(),
                            com.dxc.service.soap.service.calc.ObjectFactory.class.getClassLoader());
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                SpringApplication.run(ConsumeSoapApplication.class, args);
            }

            @Bean
            CommandLineRunner lookup(SoapConnector soapConnector) {
                return args -> {
                    Integer a = 10;
                    Integer b = 20;
                    if(args.length>0){
                        a = Integer.parseInt(args[0]);
                        b = Integer.parseInt(args[1]);
                    }

                    Add add = new Add();
                    add.setIntA(a);
                    add.setIntB(b);
                    AddResponse addRes = (AddResponse) soapConnector.callWebService(wsdlurl, add);
                    System.out.println("Got Response As below ========= : ");
                    System.out.println("Added result : "+addRes.getAddResult());
                };
            }
        }

@Configuration
public class SoapConfig {
    @Bean
        public Jaxb2Marshaller marshaller() {
            try {
                JAXBContext jb = JAXBContext.newInstance(com.dxc.service.soap.service.calc.ObjectFactory.class.getPackage().getName(),
                        com.dxc.service.soap.service.calc.ObjectFactory.class.getClassLoader());
                //Jaxb2Marshaller marshaller = (Jaxb2Marshaller) jb.createMarshaller();
                Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
                marshaller.setPackagesToScan("com.dxc.service.soap.service.calc");
                //marshaller.setContextPath("com.dxc.service.soap.calc");
                return marshaller;
            } catch (JAXBException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Bean
        public SoapConnector soapConnector(Jaxb2Marshaller marshaller) {
            SoapConnector client = new SoapConnector();
            client.setDefaultUri("http://www.dneonline.com/calculator.asmx");
            client.setMarshaller(marshaller);
            client.setUnmarshaller(marshaller);
            return client;
        }
</code>```

Please help me. Thanks.

答:
The issue you're facing is that the web service at http://www.dneonline.com/calculator.asmx expects a SOAPAction header. And since you're not providing one the service have no idea how to route the request.

The tutorial you're following doesn't require the SOAPAction header to do the routing.

If you take a look at how the Add operation is specified in the the WSDL, you'll find the expected value of the SOAPAction header there. Same for all the other operations the service provides.

```<code><wsdl:operation name="Add">
  <soap:operation soapAction="http://tempuri.org/Add" style="document" />
  <wsdl:input>
    <soap:body use="literal" />
  </wsdl:input>
  <wsdl:output>
    <soap:body use="literal" />
  </wsdl:output>
</wsdl:operation>
</code>```

Assuming that your SoapConnector class is identical to the one in the tutorial you can remove the String url as input to the callWebservice method since that is already set via the client.setDefaultUri("http://www.dneonline.com/calculator.asmx"); in the SoapConnector bean. Instead, add String soapAction as an input parameter, giving you the following

```<code>public class SOAPConnector extends WebServiceGatewaySupport {

    public Object callWebService(Object request, String soapAction){
        return getWebServiceTemplate().marshalSendAndReceive(url, new SoapActionCallback(soapAction));
    }
}
</code>```

Then, remove the wsdlurl as input to soapConnector.callWebService (it was wrong anyway) and add the soapHeader value for the operation you want to use instead, leaving you with this

```<code>@Bean
CommandLineRunner lookup(SoapConnector soapConnector) {
    return args -> {
        Integer a = 10;
        Integer b = 20;
        if(args.length>0){
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
        }

        Add add = new Add();
        add.setIntA(a);
        add.setIntB(b);
        AddResponse addRes = (AddResponse) soapConnector.callWebService(add, "http://tempuri.org/Add");
        System.out.println("Got Response As below ========= : ");
        System.out.println("Added result : "+addRes.getAddResult());
    };
}
</code>```

Of course, if you want to use other operations besides Add you'll have to tweak this solution to make it generic.

Body:
I want to consume soap service using jaxb.
The generated request from jaxb is

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
      <ns2:Add xmlns:ns2="http://tempuri.org/">
         <ns2:intA>10</ns2:intA><ns2:intB>20</ns2:intB>
      </ns2:Add>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

But the response is a soap exception as stated in the title.

Caused by: org.springframework.ws.soap.client.SoapFaultClientException: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .
   at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)

Below is my soap config code. Source example: https://howtodoinjava.com/spring-boot/spring-soap-client-webservicetemplate/

    public class ConsumeSoapApplication {
            public static String wsdlurl = "http://www.dneonline.com/calculator.asmx?wsdl";
            public static void main(String[] args) {
                try {
                    JAXBContext.newInstance(com.dxc.service.soap.service.calc.ObjectFactory.class.getPackage().getName(),
                            com.dxc.service.soap.service.calc.ObjectFactory.class.getClassLoader());
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                SpringApplication.run(ConsumeSoapApplication.class, args);
            }

            @Bean
            CommandLineRunner lookup(SoapConnector soapConnector) {
                return args -> {
                    Integer a = 10;
                    Integer b = 20;
                    if(args.length>0){
                        a = Integer.parseInt(args[0]);
                        b = Integer.parseInt(args[1]);
                    }

                    Add add = new Add();
                    add.setIntA(a);
                    add.setIntB(b);
                    AddResponse addRes = (AddResponse) soapConnector.callWebService(wsdlurl, add);
                    System.out.println("Got Response As below ========= : ");
                    System.out.println("Added result : "+addRes.getAddResult());
                };
            }
        }

@Configuration
public class SoapConfig {
    @Bean
        public Jaxb2Marshaller marshaller() {
            try {
                JAXBContext jb = JAXBContext.newInstance(com.dxc.service.soap.service.calc.ObjectFactory.class.getPackage().getName(),
                        com.dxc.service.soap.service.calc.ObjectFactory.class.getClassLoader());
                //Jaxb2Marshaller marshaller = (Jaxb2Marshaller) jb.createMarshaller();
                Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
                marshaller.setPackagesToScan("com.dxc.service.soap.service.calc");
                //marshaller.setContextPath("com.dxc.service.soap.calc");
                return marshaller;
            } catch (JAXBException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Bean
        public SoapConnector soapConnector(Jaxb2Marshaller marshaller) {
            SoapConnector client = new SoapConnector();
            client.setDefaultUri("http://www.dneonline.com/calculator.asmx");
            client.setMarshaller(marshaller);
            client.setUnmarshaller(marshaller);
            return client;
        }

Please help me. Thanks.

Body:
The issue you're facing is that the web service at http://www.dneonline.com/calculator.asmx expects a SOAPAction header. And since you're not providing one the service have no idea how to route the request.

The tutorial you're following doesn't require the SOAPAction header to do the routing.

If you take a look at how the Add operation is specified in the the WSDL, you'll find the expected value of the SOAPAction header there. Same for all the other operations the service provides.

<wsdl:operation name="Add">
  <soap:operation soapAction="http://tempuri.org/Add" style="document" />
  <wsdl:input>
    <soap:body use="literal" />
  </wsdl:input>
  <wsdl:output>
    <soap:body use="literal" />
  </wsdl:output>
</wsdl:operation>

Assuming that your SoapConnector class is identical to the one in the tutorial you can remove the String url as input to the callWebservice method since that is already set via the client.setDefaultUri("http://www.dneonline.com/calculator.asmx"); in the SoapConnector bean. Instead, add String soapAction as an input parameter, giving you the following

public class SOAPConnector extends WebServiceGatewaySupport {

    public Object callWebService(Object request, String soapAction){
        return getWebServiceTemplate().marshalSendAndReceive(url, new SoapActionCallback(soapAction));
    }
}

Then, remove the wsdlurl as input to soapConnector.callWebService (it was wrong anyway) and add the soapHeader value for the operation you want to use instead, leaving you with this

@Bean
CommandLineRunner lookup(SoapConnector soapConnector) {
    return args -> {
        Integer a = 10;
        Integer b = 20;
        if(args.length>0){
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
        }

        Add add = new Add();
        add.setIntA(a);
        add.setIntB(b);
        AddResponse addRes = (AddResponse) soapConnector.callWebService(add, "http://tempuri.org/Add");
        System.out.println("Got Response As below ========= : ");
        System.out.println("Added result : "+addRes.getAddResult());
    };
}

Of course, if you want to use other operations besides Add you'll have to tweak this solution to make it generic.


问:
Send an email using mailKit in MVC 5
I am trying to find a basic step-by-step tutorial to send an email in ASP.NET using mailKit but every tutorial talks about ASP.NET Core.

Can anyone point me to right direction? What should I use to send emails in MVC 5 and link a step-by-step tutorial?

I do not want to use smtpClient class as it is obsolete now.

答: The code to send email using MailKit is the same in both ASP.NET MVC 5 and ASP.NET Core.</p>

Title: Send an email using mailKit in MVC 5


问:
Showing image binary data using javascript
I am trying to get the image stored in db as json and diplay  the image using javascipt. but not able to view the image. i tried fire bug to view the html code img src is showing null.

here is my php code to get the data from db table:

```<code><?php
header('Content-type: application/json');

include 'connect.php';

$b_id=$_GET['b_id'];
$c_id=$_GET['c_id'];

$sql_select=mysql_query("SELECT * FROM business_directory WHERE business_category_id=$b_id") or die(mysql_error());

$records = array();

if(mysql_num_rows($sql_select)>0){

while($row=mysql_fetch_array($sql_select)){
    $records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}else{

    echo 'data not selected';
}
?>
</code>```

Here is javascript code:

```<code>function get_business(){

$.ajax({
        url:'http://localhost/ajax_practice/php/get_business.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,

        success:function(data){
            $.each(data, function(i,item){
                var output="";
                    $(".gallery").append(output);

                        output+="<li>";

                        output+="<a href='category.html?b_id="+item.id+"' data-transition='slide' rel='external'>";
                        output+="<img src='"+item.business_icon+"'/>";
                        output+="<span>"+item.business_name+"</span";
                        output+="</a>";
                        output+="</li>";
                    $(".gallery").append(output);

            });
        }
    });
</code>```

}

Can onyone help me that how can i get the data from database and show it using javascript.

答:
You can use </p>

```<code>output +="<img style='width: 30px; width:50px;' src='data:image/png;base64,"+item.business_icon+"' />";
</code>```

Body:
I am trying to get the image stored in db as json and diplay  the image using javascipt. but not able to view the image. i tried fire bug to view the html code img src is showing null.

here is my php code to get the data from db table:

<?php
header('Content-type: application/json');

include 'connect.php';

$b_id=$_GET['b_id'];
$c_id=$_GET['c_id'];

$sql_select=mysql_query("SELECT * FROM business_directory WHERE business_category_id=$b_id") or die(mysql_error());

$records = array();

if(mysql_num_rows($sql_select)>0){

while($row=mysql_fetch_array($sql_select)){
    $records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}else{

    echo 'data not selected';
}
?>

Here is javascript code:

function get_business(){

$.ajax({
        url:'http://localhost/ajax_practice/php/get_business.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,

        success:function(data){
            $.each(data, function(i,item){
                var output="";
                    $(".gallery").append(output);

                        output+="
";

                        output+="";
                        output+="";
                        output+=""+item.business_name+"</span";
                        output+="";
                        output+="
";
                    $(".gallery").append(output);

            });
        }
    });

}

Can onyone help me that how can i get the data from database and show it using javascript.

Body:
You can use

output +="<img style='width: 30px; width:50px;' src='data:image/png;base64,"+item.business_icon+"' />";