问:
How to ensure my website loads all resources via https?
URL in question: https://newyorkliquorgiftshop.com/admin/

When you open the above page, you can see in the console that there are lots of error messages saying "...was loaded over HTTPS, but requested an insecure stylesheet.."

This website was working well until all of a sudden this problem shows up. I am not very familiar with https, but I have contacted with Godaddy and the SSL certificate is valid, and there is no obvious problem with "https://newyorkliquorgiftshop.com". And I am stuck here, I've some experiences with HTTPS website before, if the URL of website's homepage is "https", then every resources it loads is via "https" too. I don't know why my website behave differently and I don't know where to start to solve the problem? Any hint is appreciated especially articles about HTTPS that is related to my problem.(I have done a brief research regarding HTTPS but most of the articles I found are about the basic concepts.)

答:
If you have access to the code (not sure what you built the website using), try using https instead of http for the URL's you use to load your style sheets and script files.

For example one of the errors is

```<code>Mixed Content: The page at 'https://newyorkliquorgiftshop.com/admin/' was loaded over HTTPS, but requested an insecure script 'http://www.newyorkliquorgiftshop.com/admin/view/javascript/common.js'. This request has been blocked; the content must be served over HTTPS.
</code>```

You are requesting the .js file using HTTP, try using HTTPS like so:

```<code>https://www.newyorkliquorgiftshop.com/admin/view/javascript/common.js
</code>```

Body:
If you have access to the code (not sure what you built the website using), try using https instead of http for the URL's you use to load your style sheets and script files.

For example one of the errors is

Mixed Content: The page at 'https://newyorkliquorgiftshop.com/admin/' was loaded over HTTPS, but requested an insecure script 'http://www.newyorkliquorgiftshop.com/admin/view/javascript/common.js'. This request has been blocked; the content must be served over HTTPS.

You are requesting the .js file using HTTP, try using HTTPS like so:

https://www.newyorkliquorgiftshop.com/admin/view/javascript/common.js


来源: stackexchange

问:
Why can't I make an int array using 'const int*' same as 'const char*'?
Why can I create a string or array of chars in this way:

```<code>#include <iostream>
int main() {
  const char *string = "Hello, World!";
  std::cout << string[1] << std::endl;
}
</code>```

? and it outputs the second element correctly, while I can't make an array of integer type without the array's subscript notation [ ]? What's the difference between the char's one and this one: const int* intArray={3,54,12,53};.

答:
The "why" is: "Because string literals are special". The string literal is stored in the binary, as a constant part of the program itself, and const char *string = "Hello, World!"; is just treating the literal as an anonymous array stored elsewhere which it then stores a pointer to in string.

There is no equivalent special behavior for other types, but you can get the same basic solution by making a named static constant and using that to initialize the pointer, e.g.

```<code>int main() {
  static const int intstatic[] = {3,54,12,53};
  const int *intptr = intstatic;
  std::cout << intptr[1] << std::endl;
}
</code>```

The effect of the static const array is to allocate the same constant space the string literal would use (though unlike string literals, it's less likely that the compiler will identify duplicate arrays and coalesce the storage), but as a named variable rather than an anonymous one. The string case could be made explicit in the same way:

```<code>int main() {
  static const char hellostatic[] = "Hello, World!";
  const char *string = hellostatic;
  std::cout << string[1] << std::endl;
}
</code>```

but using the literal directly makes things a little cleaner.

ContentLicense: CC BY-SA 3.0

Body:
Why can I create a string or array of chars in this way:

#include <iostream>
int main() {
  const char *string = "Hello, World!";
  std::cout << string[1] << std::endl;
}

? and it outputs the second element correctly, while I can't make an array of integer type without the array's subscript notation [ ]? What's the difference between the char's one and this one: const int* intArray={3,54,12,53};.

Body:
The "why" is: "Because string literals are special". The string literal is stored in the binary, as a constant part of the program itself, and const char *string = "Hello, World!"; is just treating the literal as an anonymous array stored elsewhere which it then stores a pointer to in string.

There is no equivalent special behavior for other types, but you can get the same basic solution by making a named static constant and using that to initialize the pointer, e.g.

int main() {
  static const int intstatic[] = {3,54,12,53};
  const int *intptr = intstatic;
  std::cout << intptr[1] << std::endl;
}

The effect of the static const array is to allocate the same constant space the string literal would use (though unlike string literals, it's less likely that the compiler will identify duplicate arrays and coalesce the storage), but as a named variable rather than an anonymous one. The string case could be made explicit in the same way:

int main() {
  static const char hellostatic[] = "Hello, World!";
  const char *string = hellostatic;
  std::cout << string[1] << std::endl;
}

but using the literal directly makes things a little cleaner.


问:
Background images - even small ones - not displaying on mobile
I've never encountered this one before - my background images are fine on the desktop but completely invisible on mobile. Not even a "bitmappy" version appears, though the space for them is held open, so to speak.

http://www.compassionglobally.org

I've read several similar questions here on StackOverflow but the issue always seems to be the file size (and iOS's enforced limits in that area). But even quite small images - there are four of them down the page - don't show up.

This is a WordPress site, but I feel like that's probably not relevant here... but I guess I should mention that.

Any ideas or suggestions are much appreciated!

答:
To quote Bill the Cat... ACK!!!

I'm still fairly new to the "best practice" site-building method of local development, then uploading to the server. Thought I'd worked out a good system but of course I neglected to check my CSS for local references!

Thank you, I'm sure I will solve this fairly obvious-in-retrospect problem quickly now.


答:
You almost can. There are a couple of things at work.

{1,2,3} and "abc" are not the same thing. In fact, if you wanted to draw a comparison, "abc" should rather be compared to {'a', 'b', 'c', '\0'}. Both of them are valid array initializers:

```<code>char foo[] = "abc";
char bar[] = {'a', 'b', 'c', '\0'};
</code>```

However, only "abc" is also a valid expression to initialize a pointer in C++.

In C (and as an extension in some C++ compilers, including Clang and GCC), you can cast compound literals to an array type, like this:

```<code>static const int* array = (const int[]){1, 2, 3};
</code>```

However, this is almost never correct. It works at the global scope and as a function argument, but if you try to initialize a variable of automatic storage with it (i.e. a variable within a function), you'll get a pointer to a location that is about to expire, so you won't be able to use it for anything useful.

Title: Why can't I make an int array using 'const int*' same as 'const char*'?

Body:
You almost can. There are a couple of things at work.

{1,2,3} and "abc" are not the same thing. In fact, if you wanted to draw a comparison, "abc" should rather be compared to {'a', 'b', 'c', '\0'}. Both of them are valid array initializers:

char foo[] = "abc";
char bar[] = {'a', 'b', 'c', '\0'};

However, only "abc" is also a valid expression to initialize a pointer in C++.

In C (and as an extension in some C++ compilers, including Clang and GCC), you can cast compound literals to an array type, like this:

static const int* array = (const int[]){1, 2, 3};

However, this is almost never correct. It works at the global scope and as a function argument, but if you try to initialize a variable of automatic storage with it (i.e. a variable within a function), you'll get a pointer to a location that is about to expire, so you won't be able to use it for anything useful.


问:
Matplotlib - color under curve based on spectral color
I would like to make a plot of of a spectrum, where the area under the curve will be shaded according the the corresponding color of the light. Much like this plot:

I have tried to emulate this in matplotlib, by using imshow with the spectral colormap to plot the colors, and a white fill_between to cover up the region above the curve. I am fairly happy with the result, except for two things:

1) The colors that I am plotting do not quite align with the visible spectrum. For example I show 700 nm as yellow/orange, when it is red. I am happy with a somewhat stylized representation (for example, I think that the accurate colors shown in the second answer here are boring), but in general, I would like to wavelengths to align with their visible colors.

2) I like how the spectrum above has the regions outside of the visible region colored with alpha<1.0. I am not sure how to achieve this.

Here is what I have so far:

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

fig, axs = plt.subplots(1, 1, figsize=(8,4), tight_layout=True)

wavelengths = np.linspace(200, 1000, 1000)
spectrum = (5 + np.sin(wavelengths*0.1)**2) * np.exp(-0.00002*(wavelengths-600)**2)
plt.plot(wavelengths, spectrum, color='darkred')

y = np.linspace(0, 6, 100)
X,Y = np.meshgrid(wavelengths, y)
X[X<400] = 400
extent=(np.min(wavelengths), np.max(wavelengths), np.min(y), np.max(y))

plt.imshow(X, clim=(350,820),  extent=extent, cmap=plt.get_cmap('spectral'), aspect='auto')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Intensity')

plt.fill_between(wavelengths, spectrum, 8, color='w')
plt.savefig('WavelengthColors.png', dpi=200)

plt.show()
</code>```

答:
First of all you would need a function that takes the wavelength as input and returns an RGB color. Such a function can be found here. One may adapt it to also return an alpha value, which is smaller 1 outside the range of visible colors.

This function can be used to make create a colormap. Using a decent normalization allows to have the range of wavelengths mapped to the range between 0 and 1, such that this colormap may be used in an imshow plot.

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

def wavelength_to_rgb(wavelength, gamma=0.8):
    ''' taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
    This converts a given wavelength of light to an
    approximate RGB color value. The wavelength must be given
    in nanometers in the range from 380 nm through 750 nm
    (789 THz through 400 THz).

    Based on code by Dan Bruton
    http://www.physics.sfasu.edu/astro/color/spectra.html
    Additionally alpha value set to 0.5 outside range
    '''
    wavelength = float(wavelength)
    if wavelength >= 380 and wavelength <= 750:
        A = 1.
    else:
        A=0.5
    if wavelength < 380:
        wavelength = 380.
    if wavelength >750:
        wavelength = 750.
    if wavelength >= 380 and wavelength <= 440:
        attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380)
        R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma
        G = 0.0
        B = (1.0 * attenuation) ** gamma
    elif wavelength >= 440 and wavelength <= 490:
        R = 0.0
        G = ((wavelength - 440) / (490 - 440)) ** gamma
        B = 1.0
    elif wavelength >= 490 and wavelength <= 510:
        R = 0.0
        G = 1.0
        B = (-(wavelength - 510) / (510 - 490)) ** gamma
    elif wavelength >= 510 and wavelength <= 580:
        R = ((wavelength - 510) / (580 - 510)) ** gamma
        G = 1.0
        B = 0.0
    elif wavelength >= 580 and wavelength <= 645:
        R = 1.0
        G = (-(wavelength - 645) / (645 - 580)) ** gamma
        B = 0.0
    elif wavelength >= 645 and wavelength <= 750:
        attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645)
        R = (1.0 * attenuation) ** gamma
        G = 0.0
        B = 0.0
    else:
        R = 0.0
        G = 0.0
        B = 0.0
    return (R,G,B,A)

clim=(350,780)
norm = plt.Normalize(*clim)
wl = np.arange(clim[0],clim[1]+1,2)
colorlist = list(zip(norm(wl),[wavelength_to_rgb(w) for w in wl]))
spectralmap = matplotlib.colors.LinearSegmentedColormap.from_list("spectrum", colorlist)

fig, axs = plt.subplots(1, 1, figsize=(8,4), tight_layout=True)

wavelengths = np.linspace(200, 1000, 1000)
spectrum = (5 + np.sin(wavelengths*0.1)**2) * np.exp(-0.00002*(wavelengths-600)**2)
plt.plot(wavelengths, spectrum, color='darkred')

y = np.linspace(0, 6, 100)
X,Y = np.meshgrid(wavelengths, y)

extent=(np.min(wavelengths), np.max(wavelengths), np.min(y), np.max(y))

plt.imshow(X, clim=clim,  extent=extent, cmap=spectralmap, aspect='auto')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Intensity')

plt.fill_between(wavelengths, spectrum, 8, color='w')
plt.savefig('WavelengthColors.png', dpi=200)

plt.show()
</code>```

Body:
I would like to make a plot of of a spectrum, where the area under the curve will be shaded according the the corresponding color of the light. Much like this plot:

I have tried to emulate this in matplotlib, by using imshow with the spectral colormap to plot the colors, and a white fill_between to cover up the region above the curve. I am fairly happy with the result, except for two things:

1) The colors that I am plotting do not quite align with the visible spectrum. For example I show 700 nm as yellow/orange, when it is red. I am happy with a somewhat stylized representation (for example, I think that the accurate colors shown in the second answer here are boring), but in general, I would like to wavelengths to align with their visible colors.

2) I like how the spectrum above has the regions outside of the visible region colored with alpha<1.0. I am not sure how to achieve this.

Here is what I have so far:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 1, figsize=(8,4), tight_layout=True)

wavelengths = np.linspace(200, 1000, 1000)
spectrum = (5 + np.sin(wavelengths*0.1)**2) * np.exp(-0.00002*(wavelengths-600)**2)
plt.plot(wavelengths, spectrum, color='darkred')

y = np.linspace(0, 6, 100)
X,Y = np.meshgrid(wavelengths, y)
X[X<400] = 400
extent=(np.min(wavelengths), np.max(wavelengths), np.min(y), np.max(y))

plt.imshow(X, clim=(350,820),  extent=extent, cmap=plt.get_cmap('spectral'), aspect='auto')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Intensity')

plt.fill_between(wavelengths, spectrum, 8, color='w')
plt.savefig('WavelengthColors.png', dpi=200)

plt.show()

Body:
First of all you would need a function that takes the wavelength as input and returns an RGB color. Such a function can be found here. One may adapt it to also return an alpha value, which is smaller 1 outside the range of visible colors.

This function can be used to make create a colormap. Using a decent normalization allows to have the range of wavelengths mapped to the range between 0 and 1, such that this colormap may be used in an imshow plot.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

def wavelength_to_rgb(wavelength, gamma=0.8):
    ''' taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
    This converts a given wavelength of light to an
    approximate RGB color value. The wavelength must be given
    in nanometers in the range from 380 nm through 750 nm
    (789 THz through 400 THz).

    Based on code by Dan Bruton
    http://www.physics.sfasu.edu/astro/color/spectra.html
    Additionally alpha value set to 0.5 outside range
    '''
    wavelength = float(wavelength)
    if wavelength >= 380 and wavelength <= 750:
        A = 1.
    else:
        A=0.5
    if wavelength < 380:
        wavelength = 380.
    if wavelength >750:
        wavelength = 750.
    if wavelength >= 380 and wavelength <= 440:
        attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380)
        R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma
        G = 0.0
        B = (1.0 * attenuation) ** gamma
    elif wavelength >= 440 and wavelength <= 490:
        R = 0.0
        G = ((wavelength - 440) / (490 - 440)) ** gamma
        B = 1.0
    elif wavelength >= 490 and wavelength <= 510:
        R = 0.0
        G = 1.0
        B = (-(wavelength - 510) / (510 - 490)) ** gamma
    elif wavelength >= 510 and wavelength <= 580:
        R = ((wavelength - 510) / (580 - 510)) ** gamma
        G = 1.0
        B = 0.0
    elif wavelength >= 580 and wavelength <= 645:
        R = 1.0
        G = (-(wavelength - 645) / (645 - 580)) ** gamma
        B = 0.0
    elif wavelength >= 645 and wavelength <= 750:
        attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645)
        R = (1.0 * attenuation) ** gamma
        G = 0.0
        B = 0.0
    else:
        R = 0.0
        G = 0.0
        B = 0.0
    return (R,G,B,A)

clim=(350,780)
norm = plt.Normalize(*clim)
wl = np.arange(clim[0],clim[1]+1,2)
colorlist = list(zip(norm(wl),[wavelength_to_rgb(w) for w in wl]))
spectralmap = matplotlib.colors.LinearSegmentedColormap.from_list("spectrum", colorlist)

fig, axs = plt.subplots(1, 1, figsize=(8,4), tight_layout=True)

wavelengths = np.linspace(200, 1000, 1000)
spectrum = (5 + np.sin(wavelengths*0.1)**2) * np.exp(-0.00002*(wavelengths-600)**2)
plt.plot(wavelengths, spectrum, color='darkred')

y = np.linspace(0, 6, 100)
X,Y = np.meshgrid(wavelengths, y)

extent=(np.min(wavelengths), np.max(wavelengths), np.min(y), np.max(y))

plt.imshow(X, clim=clim,  extent=extent, cmap=spectralmap, aspect='auto')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Intensity')

plt.fill_between(wavelengths, spectrum, 8, color='w')
plt.savefig('WavelengthColors.png', dpi=200)

plt.show()

ContentLicense: CC BY-SA 4.0


问:
Generate a unique id
I am a student at university and our task is to create a search engine. I am having difficulty generating a unique id to assign to each url when added into the frontier. I have attempted using the SHA-256 hashing algorithm as well as Guid. Here is the code that i used to implement the guid:</p>

```<code>public string generateID(string url_add)
{
    long i = 1;

    foreach (byte b in Guid.NewGuid().ToByteArray())
    {
        i *= ((int)b + 1);
    }

    string number = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000);

    return number;
}
</code>```

答:
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"

```<code>StringBuilder builder = new StringBuilder();
Enumerable
   .Range(65, 26)
    .Select(e => ((char)e).ToString())
    .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
    .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
    .OrderBy(e => Guid.NewGuid())
    .Take(11)
    .ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
</code>```

It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.

0.001% duplicates in 100 million.

Title: Generate a unique id

Body:
I am a student at university and our task is to create a search engine. I am having difficulty generating a unique id to assign to each url when added into the frontier. I have attempted using the SHA-256 hashing algorithm as well as Guid. Here is the code that i used to implement the guid:

public string generateID(string url_add)
{
    long i = 1;

    foreach (byte b in Guid.NewGuid().ToByteArray())
    {
        i *= ((int)b + 1);
    }

    string number = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000);

    return number;
}

Body:
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"

StringBuilder builder = new StringBuilder();
Enumerable
   .Range(65, 26)
    .Select(e => ((char)e).ToString())
    .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
    .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
    .OrderBy(e => Guid.NewGuid())
    .Take(11)
    .ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();

It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.

0.001% duplicates in 100 million.


问:
Passing a changed varriable that creates a split in the string from incomming parameter-Python
I have created a working version of the assignment. I am not asking for anyone to do my assignment as it already creates the correct output.

However, there is most certainly a better way. I am just wondering what that is. The code is broken into two files (driver and runner) and is ran through a .bat.
First part is unchangeable.

```<code>import Proj07Runner

str = 'The lazy brown fox'
index = 6
myList = Proj07Runner.run(str,index)
print(str)
for item in str:
    print(item)
</code>```

And the second:

```<code>import sys
import os
def run(str,index):

    print (str)
    print (index)
    print (str)
    mylist = (str)
    mylist = mylist[:6]
    print (mylist)
    mylist = (str)
    mylist = mylist[6:]
    print(mylist)
    sys.exit()

    print (mylist)
    return(str,index)
</code>```

The required output is

```<code>The lazy brown fox
6
The lazy brown fox
The la
azy brown fox
</code>```

Overall, how am I able to return the string on two lines following the instructors code instead of instantiating it in my portion?

答:
If I understand this correctly, you're supposed to return a string that prints on two lines, split at the indicated index position.  If so, then simply do that much: return a string composed of

The first 6 characters (taking the index of 6 from your example)

a newline character

The rest of the string

In short:

```<code>def run(str,index):
    return str[:index] + '\n' + str[index:]
</code>```

Is that what you needed?

Body:
I have created a working version of the assignment. I am not asking for anyone to do my assignment as it already creates the correct output.

However, there is most certainly a better way. I am just wondering what that is. The code is broken into two files (driver and runner) and is ran through a .bat.
First part is unchangeable.

import Proj07Runner

str = 'The lazy brown fox'
index = 6
myList = Proj07Runner.run(str,index)
print(str)
for item in str:
    print(item)

And the second:

import sys
import os
def run(str,index):

    print (str)
    print (index)
    print (str)
    mylist = (str)
    mylist = mylist[:6]
    print (mylist)
    mylist = (str)
    mylist = mylist[6:]
    print(mylist)
    sys.exit()

    print (mylist)
    return(str,index)

The required output is

The lazy brown fox
6
The lazy brown fox
The la
azy brown fox

Overall, how am I able to return the string on two lines following the instructors code instead of instantiating it in my portion?

Body:
If I understand this correctly, you're supposed to return a string that prints on two lines, split at the indicated index position.  If so, then simply do that much: return a string composed of

The first 6 characters (taking the index of 6 from your example)

a newline character

The rest of the string

In short:

def run(str,index):
    return str[:index] + '\n' + str[index:]

Is that what you needed?


问:
Reading strings and primitive data types from a file and creating objects
I'm reading from a file and using a scanner to read the inputs but am having difficulty understanding how to apply next() and nextLine() to assign data from the text to variables to be sent to my rectangle class constructor for printing these objects to the console. I get parsing the input (nextInt...etc.), but when strings and primitive data mix on the same line on multiple lines of a scanner read text file how do you handle this? Do I create multiple scanner loops for ints and String(s) to loop through it all to ensure the read data gets assigned to the array elements correctly?

TLDR: How do I read multiple strings and primitives from one .txt file, populate that data into my class fields to then create an array of objects and print *'s to the console to symbolize my created "rectangular" objects from said .txt file?

答:
Check out this related question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

I honestly didn't understand your explanation of the text input, but it might be because the Scanner#nextInt method does not consume the last newline ('\n') character. If that's the case, a workaround is to call another nextLine() to consume it.

Also, Scanner#next do ignore whitespaces, but it doesn't ignore primitives, such as booleans or integers, as they are valid tokens.


问:
Passing value from HTML form to php variable
I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far: </p>

```<code><form method="post" action="a34.php">
 <select name="category">
  <option value="6008">15</option>
  <option value="6018">25</option>
  <option value="6034">30</option>
  <option value="6038">40</option>

$V=$_POST['category'];

$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
 ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";
</code>```

答:
Okay, try the following.

The JS file detects when the user clicks an option and sends out an ajax request to the updateRow.php file with the $_POST variable of val.

updateRow.php takes the $_POST variable and casts it into an integer. The query is then updated with that variable. Process the query, then echo, print, etc. the data in the desired HTML format. Otherwise, the data echo 'failure'.

The output that is echoed, printed, etc is then sent back to the JS file under the variable data. If the data equals 'failure', then an error message is outputted. Otherwise, it inserts the HTML in the #row element.

```<code>// ------ Your JS file ---------

$(function() {
  $row = $("#row");

  $("#update-row").on("change", function() {
    var val = $("select option:selected", this).val();
    $.post('updateRow.php', {
      val: val
    }, function(data) {
      if (data == 'failure') {
        $row.text("Sorry, the row does not exist");
      } else {
        $row.html(data);
      }
    });
  });
});
</code>```

```<code>//------- updateRow.php ---------
//Make sure path/to/updateRow.php in the JS file is updated to here

$V = (int) $_POST['val'];

$getrow = "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID =" . $V;

if ( QUERY_IS_SUCCESSFUL() ) {
  echo 'The <b>HTML</b> you want to display the data in';
} else {
  echo 'failure';
}
</code>```

<form method="post" action="a34.php" id="update-row">
  <select name="category">
    <option value="6008">15</option>
    <option value="6018">25</option>
    <option value="6034">30</option>
    <option value="6038">40</option>
    </select>
</form>

```

Body:
I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far:

<form method="post" action="a34.php">
 <select name="category">
  <option value="6008">15</option>
  <option value="6018">25</option>
  <option value="6034">30</option>
  <option value="6038">40</option>

$V=$_POST['category'];

$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
 ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";

Body:
Okay, try the following.

The JS file detects when the user clicks an option and sends out an ajax request to the updateRow.php file with the $_POST variable of val.

updateRow.php takes the $_POST variable and casts it into an integer. The query is then updated with that variable. Process the query, then echo, print, etc. the data in the desired HTML format. Otherwise, the data echo 'failure'.

The output that is echoed, printed, etc is then sent back to the JS file under the variable data. If the data equals 'failure', then an error message is outputted. Otherwise, it inserts the HTML in the #row element.

// ------ Your JS file ---------

$(function() {
  $row = $("#row");

  $("#update-row").on("change", function() {
    var val = $("select option:selected", this).val();
    $.post('updateRow.php', {
      val: val
    }, function(data) {
      if (data == 'failure') {
        $row.text("Sorry, the row does not exist");
      } else {
        $row.html(data);
      }
    });
  });
});

//------- updateRow.php ---------
//Make sure path/to/updateRow.php in the JS file is updated to here

$V = (int) $_POST['val'];

$getrow = "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID =" . $V;

if ( QUERY_IS_SUCCESSFUL() ) {
  echo 'The <b>HTML</b> you want to display the data in';
} else {
  echo 'failure';
}

<!----- HTML file ---->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="path/to/js/file.js"></script>

<form method="post" action="a34.php" id="update-row">
  <select name="category">
    <option value="6008">15</option>
    <option value="6018">25</option>
    <option value="6034">30</option>
    <option value="6038">40</option>
    </select>
</form>

<div id="row"></div>


问:
I can't transform numeric numbers into time
Here's the structure of the data

What I want to do is to change the form of Time into POSIXct.

Here's what I have tried.

```<code>a <- as.POSIXct(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- as.POSIXlt(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- strptime(power_consumption$Time, "%H:%M:%S")
head(a)
[1] NA                        "2017-07-07 17:24:00 CST" "2017-07-07 17:25:00 CST" "2017-07-07 17:26:00 CST" "2017-07-07 17:27:00 CST"
[6] "2017-07-07 17:28:00 CST"
</code>```

I don't think the result is right, for the struction of Time has time only.

What should I do to transform Time into %H:%M:%S? Thanks

答: @Ryan You need to reload the data frame from the source and set each column to the correct data type. Everything inpower_consumption should be a double except the date and time. You will be unable to do any serious processing, because all the data is represented as factors.

Body:
Here's the structure of the data

What I want to do is to change the form of Time into POSIXct.

Here's what I have tried.

a <- as.POSIXct(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- as.POSIXlt(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- strptime(power_consumption$Time, "%H:%M:%S")
head(a)
[1] NA                        "2017-07-07 17:24:00 CST" "2017-07-07 17:25:00 CST" "2017-07-07 17:26:00 CST" "2017-07-07 17:27:00 CST"
[6] "2017-07-07 17:28:00 CST"

I don't think the result is right, for the struction of Time has time only.

What should I do to transform Time into %H:%M:%S? Thanks


问:
How to do sequence comparison in idiomatic Scala
Input:

```<code>target: ["a", "b", "c", "d"]

sequence1: ["b", "c"]
sequence2: ["c", "b"]
</code>```

Desired behavior

```<code>sequence1 matches with target because "b", "c" matches with a sub sequence of the target

sequence2 does not match with target
</code>```

I can write this in Python or Java with a for loop pretty easily. What is the idiomatic way to write this in scala

答:
I think containsSlice() is what you're after.

```<code>scala> List("a","b","c","d").containsSlice(List("b","c"))
res0: Boolean = true

scala> List("a","b","c","d").containsSlice(List("c","b"))
res1: Boolean = false
</code>```

Body:
Input:

target: ["a", "b", "c", "d"]

sequence1: ["b", "c"]
sequence2: ["c", "b"]

Desired behavior

sequence1 matches with target because "b", "c" matches with a sub sequence of the target

sequence2 does not match with target

I can write this in Python or Java with a for loop pretty easily. What is the idiomatic way to write this in scala

Body:
I think containsSlice() is what you're after.

scala> List("a","b","c","d").containsSlice(List("b","c"))
res0: Boolean = true

scala> List("a","b","c","d").containsSlice(List("c","b"))
res1: Boolean = false


问:
Get mysql database schema
Is it possible to get the full structure of a mySQL database in json or xml format?

what I'm looking for is a way to get the schema (stored data doesn't matter) to use it to create a backend/crud for the application.

答:
This is not a fully comprehensive answer to the question, as it doesn't return a json. But it's a simple class that gives all relevant info about a table as an object. This could easily be transformed to return a json.

The class relies on having passed a db object that implements a rawQuery method, as PHP-Mysqli-Database-Class does. But you could easily rewrite the method extractTableInfo if you need.

```<code><?php
Class dbHelper {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function extractTableInfo($tableName) {
        $result = $this->db->rawQuery("DESCRIBE `".$tableName."`");

        $tableInfo = array();
        foreach ($result as $key => $value) {
            $info = new \stdClass();
            $info->name = $value['Field'];
            $info->type = $this->_getColumnType($value['Type']);
            $info->length = $this->_getLength($value['Type']);
            $info->hasNull = $this->_getNull($value['Null']);
            $info->default = $this->_getDefault($value['Default']);
            $tableInfo[] = $info;
        }
        return $tableInfo;
    }

    public function getIndexes($tableName) {
        $result = $this->db->rawQuery("SHOW INDEX FROM `".$tableName."`");
        return $result;
    }

    private function _getLength($info) {
        $pattern = '/\({1}([\d\W]*)\){1}/';
        preg_match($pattern, $info, $matches);
        return isset($matches[1]) ? $matches[1] : NULL;
    }

    private function _getColumnType($info) {
        $pattern = '/([\w]*)(\([\d\W]*\))*/';
        preg_match($pattern, $info, $matches);
        return isset($matches[1]) ? $matches[1] : NULL;
    }

    private function _getNull($info) {
        if($info==='NO') {
            return false;
        } else {
            return true;
        }
    }

    private function _getDefault($info) {
        if($info>='') {
            return $info;
        } else {
            return NULL;
        }
    }

}
</code>```

Usage:

```<code>$db = YOUR DATABASE OBJECT/CLASS;
$dbHelper = new dbHelper($db);
$tableName = "test";
$tableInfo = $dbHelper->extractTableInfo($tableName);
echo json_encode($tableInfo);
</code>```

To get a list of all tables in a database you'll need:

```<code>SHOW TABLES [in dbname]
</code>```

or follow this question

Still, there are many alternatives with different benefits/outputs:

using mysql workbench

using phpmyadmin

using command line mysqldump -u root -p --no-data dbname > schema.sql

Title: Get mysql database schema

Body:
This is not a fully comprehensive answer to the question, as it doesn't return a json. But it's a simple class that gives all relevant info about a table as an object. This could easily be transformed to return a json.

The class relies on having passed a db object that implements a rawQuery method, as PHP-Mysqli-Database-Class does. But you could easily rewrite the method extractTableInfo if you need.

<?php
Class dbHelper {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function extractTableInfo($tableName) {
        $result = $this->db->rawQuery("DESCRIBE `".$tableName."`");

        $tableInfo = array();
        foreach ($result as $key => $value) {
            $info = new \stdClass();
            $info->name = $value['Field'];
            $info->type = $this->_getColumnType($value['Type']);
            $info->length = $this->_getLength($value['Type']);
            $info->hasNull = $this->_getNull($value['Null']);
            $info->default = $this->_getDefault($value['Default']);
            $tableInfo[] = $info;
        }
        return $tableInfo;
    }

    public function getIndexes($tableName) {
        $result = $this->db->rawQuery("SHOW INDEX FROM `".$tableName."`");
        return $result;
    }

    private function _getLength($info) {
        $pattern = '/\({1}([\d\W]*)\){1}/';
        preg_match($pattern, $info, $matches);
        return isset($matches[1]) ? $matches[1] : NULL;
    }

    private function _getColumnType($info) {
        $pattern = '/([\w]*)(\([\d\W]*\))*/';
        preg_match($pattern, $info, $matches);
        return isset($matches[1]) ? $matches[1] : NULL;
    }

    private function _getNull($info) {
        if($info==='NO') {
            return false;
        } else {
            return true;
        }
    }

    private function _getDefault($info) {
        if($info>='') {
            return $info;
        } else {
            return NULL;
        }
    }

}

Usage:

$db = YOUR DATABASE OBJECT/CLASS;
$dbHelper = new dbHelper($db);
$tableName = "test";
$tableInfo = $dbHelper->extractTableInfo($tableName);
echo json_encode($tableInfo);

To get a list of all tables in a database you'll need:

SHOW TABLES [in dbname]

or follow this question

Still, there are many alternatives with different benefits/outputs:

using mysql workbench

using phpmyadmin

using command line mysqldump -u root -p --no-data dbname > schema.sql


问:
Trouble with application function vs if code
Why this code not work. Anybody can help with simple code? I write the code like this:</p>

```<code>Private sub cmbStart_click()
Dim bro as application
Dim bre as integer
Dim bru as control

For bre = 1 to 42
Set bru = controls("cmb" &  bre).caption
Set bro = application.worksheetfunction.vlookup(bre, sheets("keg").range("c2:f300"),4,0)
  If bro = "es" then
    Controls("cmb" & bre).backcolor = rgb(255,0,0)
  Else
  Controls("cmb" & bre).backcolor = rgb(255,0,0)
 End if
Next bre
End sub
</code>```

答:
Vlookup() doesn't return an application so declaring bro to be an Application is pointless.

Simply

```<code>Dim bro As Variant
'...
bro = Application.Worksheetfunction.Vlookup(bre, sheets("keg").Range("c2:f300"),4,0)
</code>```

Similarly, there is no reason to declare bru to be a control. The caption is simply a String.

Thus:

```<code>Dim bru As String
'...
bru = controls("cmb" &  bre).caption
</code>```

VBA is mostly an imperative language which uses objects. You seem to be trying to make everything an object.

I am not in a position to test the code, but the above makes more sense as VBA.

If this doesn't fix the problem, you need to say a bit more about how the code doesn't work. Simply reporting that it doesn't work isn't very helpful.

Body:
Why this code not work. Anybody can help with simple code? I write the code like this:

Private sub cmbStart_click()
Dim bro as application
Dim bre as integer
Dim bru as control

For bre = 1 to 42
Set bru = controls("cmb" &  bre).caption
Set bro = application.worksheetfunction.vlookup(bre, sheets("keg").range("c2:f300"),4,0)
  If bro = "es" then
    Controls("cmb" & bre).backcolor = rgb(255,0,0)
  Else
  Controls("cmb" & bre).backcolor = rgb(255,0,0)
 End if
Next bre
End sub

Body:
Vlookup() doesn't return an application so declaring bro to be an Application is pointless.

Simply

Dim bro As Variant
'...
bro = Application.Worksheetfunction.Vlookup(bre, sheets("keg").Range("c2:f300"),4,0)

Similarly, there is no reason to declare bru to be a control. The caption is simply a String.

Thus:

Dim bru As String
'...
bru = controls("cmb" &  bre).caption

VBA is mostly an imperative language which uses objects. You seem to be trying to make everything an object.

I am not in a position to test the code, but the above makes more sense as VBA.

If this doesn't fix the problem, you need to say a bit more about how the code doesn't work. Simply reporting that it doesn't work isn't very helpful.


问:
Reliable way to detect if the firmware is UEFI or BIOS from a Windows kernel driver
Is there any reliable way to detect if the firmware is BIOS or UEFI from a Windows kernel driver in runtime without access to the disk?</p>

答:
Try ExGetFirmwareEnvironmentVariable function.  Call this function with empty variable name and dummy GUID to determine if Windows was installed using BIOS or UEFI.  For more details, see the followings as stated in the documentation.

Firmware environment variables are not supported on a legacy BIOS-based platform. Calls to ExGetFirmwareEnvironmentVariable always fail on a legacy BIOS-based platform; they also fail if Windows was installed using the legacy BIOS on a platform that supports both legacy BIOS and UEFI. To identify these conditions, call the function with a dummy VariableName string (for example, an empty string) and a dummy GUID such as

"{00000000-0000-0000-0000-000000000000}"

for the VendorGuid parameter. On a legacy BIOS-based platform, or on a platform that supports both legacy BIOS and UEFI but in which Windows was installed using the legacy BIOS, the function will fail with STATUS_NOT_IMPLEMENTED. On a UEFI-based platform, the function will fail with an error specific to the firmware, such as STATUS_VARIABLE_NOT_FOUND, to indicate that the dummy GUID namespace does not exist.


问:
Creating a shell command line application with Python and Click
I'm using click (http://click.pocoo.org/3/) to create a command line application, but I don't know how to create a shell for this application.

Suppose I'm writing a program called test and I have commands called subtest1 and subtest2

I was able to make it work from terminal like:

```<code>$ test subtest1
$ test subtest2
</code>```

But what I was thinking about is a shell, so I could do:

```<code>$ test
>> subtest1
>> subtest2
</code>```

Is this possible with click?

答:
I know this is super old, but I've been working on fpbhb's solution to support options as well. I'm sure this could use some more work, but here is a basic example of how it could be done:</p>

```<code>import click
import cmd
import sys

from click import BaseCommand, UsageError

class REPL(cmd.Cmd):
    def __init__(self, ctx):
        cmd.Cmd.__init__(self)
        self.ctx = ctx

    def default(self, line):
        subcommand = line.split()[0]
        args = line.split()[1:]

        subcommand = cli.commands.get(subcommand)
        if subcommand:
            try:
                subcommand.parse_args(self.ctx, args)
                self.ctx.forward(subcommand)
            except UsageError as e:
                print(e.format_message())
        else:
            return cmd.Cmd.default(self, line)

@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        repl = REPL(ctx)
        repl.cmdloop()

@cli.command()
@click.option('--foo', required=True)
def a(foo):
    print("a")
    print(foo)
    return 'banana'

@cli.command()
@click.option('--foo', required=True)
def b(foo):
    print("b")
    print(foo)

if __name__ == "__main__":
    cli()
</code>```

Body:
I'm using click (http://click.pocoo.org/3/) to create a command line application, but I don't know how to create a shell for this application.

Suppose I'm writing a program called test and I have commands called subtest1 and subtest2

I was able to make it work from terminal like:

$ test subtest1
$ test subtest2

But what I was thinking about is a shell, so I could do:

$ test
>> subtest1
>> subtest2

Is this possible with click?

Body:
I know this is super old, but I've been working on fpbhb's solution to support options as well. I'm sure this could use some more work, but here is a basic example of how it could be done:

import click
import cmd
import sys

from click import BaseCommand, UsageError

class REPL(cmd.Cmd):
    def __init__(self, ctx):
        cmd.Cmd.__init__(self)
        self.ctx = ctx

    def default(self, line):
        subcommand = line.split()[0]
        args = line.split()[1:]

        subcommand = cli.commands.get(subcommand)
        if subcommand:
            try:
                subcommand.parse_args(self.ctx, args)
                self.ctx.forward(subcommand)
            except UsageError as e:
                print(e.format_message())
        else:
            return cmd.Cmd.default(self, line)

@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        repl = REPL(ctx)
        repl.cmdloop()

@cli.command()
@click.option('--foo', required=True)
def a(foo):
    print("a")
    print(foo)
    return 'banana'

@cli.command()
@click.option('--foo', required=True)
def b(foo):
    print("b")
    print(foo)

if __name__ == "__main__":
    cli()


问:
Changing Laravel 5.4 password encryption and table column names
I am trying to integrate the auth in laravel 5.4 within an existing database where the user and password fields have other names (memberid, passwordnew_enc). With the bellow changes and forcing the create function in RegisterController to use MD5 I managed to make the registration work. It also logins fine after registration. However the actual login form returns:

These credentials do not match our records.

So far I have changed the User.php

```<code>public function getAuthPassword()
{
    return $this->passwordnew_enc;
}
</code>```

and

```<code>public function setPasswordAttribute($value)
{
    $this->attributes['password'] = md5($value);
}
</code>```

Also on LoginController.php

```<code>public function username()
{
    return 'memberid';
}
</code>```

Did I miss something ?

I only need to change the two column names to fit and the password encryption from bcrypt to md5

答:
upful's code worked for me (in Laravel 5.4)

But I needed to add:

```<code>use Illuminate\Contracts\Auth\Authenticatable as UserContract;
</code>```

in the CustomUserProvider class.

Body:
I am trying to integrate the auth in laravel 5.4 within an existing database where the user and password fields have other names (memberid, passwordnew_enc). With the bellow changes and forcing the create function in RegisterController to use MD5 I managed to make the registration work. It also logins fine after registration. However the actual login form returns:

These credentials do not match our records.

So far I have changed the User.php

public function getAuthPassword()
{
    return $this->passwordnew_enc;
}

and

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = md5($value);
}

Also on LoginController.php

public function username()
{
    return 'memberid';
}

Did I miss something ?

I only need to change the two column names to fit and the password encryption from bcrypt to md5

Body:
upful's code worked for me (in Laravel 5.4)

But I needed to add:

use Illuminate\Contracts\Auth\Authenticatable as UserContract;

in the CustomUserProvider class.


问:
Keras: Feeding in part of previous layer to next layer, in CNN

I am trying to feed in the individual kernel outputs of the previous layer to a new conv filter, to get the next layer. To do that, I tried passing each of the kernel outputs through a Conv2D, by calling them by their index. The function I used is:

def modification(weights_path=None, classes=2):

    ###########
    ## Input ##
    ###########

    ### 224x224x3 sized RGB Input
    inputs = Input(shape=(224,224,3))

    #################################
    ## Conv2D Layer with 5 kernels ##
    #################################

    k = 5
    x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
    y = np.empty(k, dtype=object)
    for i in range(0,k):
        y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
    y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
    out = Activation('relu')(y)
    print ('Output shape is, ' +str(out.get_shape()))

    ### Maxpooling(2,2) with a stride of (2,2)
    out = MaxPooling2D((2,2), strides=(2,2), data_format='channels_last')(out)

    ############################################
    ## Top layer, with fully connected layers ##
    ############################################

    out = Flatten(name='flatten')(out)
    out = Dense(4096, activation='relu', name='fc1')(out)
    out = Dropout(0.5)(out)
    out = Dense(4096, activation='relu', name='fc2')(out)
    out = Dropout(0.5)(out)
    out = Dense(classes, activation='softmax', name='predictions')(out)

    if weights_path:
        model.load_weights(weights_path)

    model = Model(inputs, out, name='modification')

    return model
```

<p>But this is not working, and is throwing the following error:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "sim-conn-edit.py", line 137, in <module>
    model = modification()
  File "sim-conn-edit.py", line 38, in modification
    y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 511, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 408, in assert_input_compatibil
ity
    if K.ndim(x) != spec.ndim:
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 437, in ndim
    dims = x.get_shape()._dims
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
</code>```

I fed in layer x[i] as [ x[i] ] to meet the dimention requirements of a Conv2D layer. Any help with solving this problem will be deeply appreciated!

答:
After posting this and this questions in StackOverflow, and some personal exploring, I came up with a solution. One can possibly do this with Lambda layers; by calling a Lambda layer to extract a sub part of the previous layer. For example, if the Lambda function is defined as,

```<code>def layer_slice(x,i):
    return x[:,:,:,i:i+1]
</code>```

and then, called as,

```<code>k = 5
x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
y = np.empty(k, dtype=object)
for i in range(0,k):
    y[i] = Lambda(layer_slice, arguments={'i':i})(x)
    y[i] = Conv2D(1,(3,3), data_format='channels_last', padding='same')(y[i])
y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
out = Activation('relu')(y)
print ('Output shape is, ' +str(out.get_shape()))
</code>```

it should effectively feed in individual kernel outputs to a new Conv2D layer. The layer shapes and corresponding number of trainable parameters being obtained from model.summary() matches the expectation. Thanks to Daniel for pointing out that Lambda layers cannot have trainable weights.

Body:
I am trying to feed in the individual kernel outputs of the previous layer to a new conv filter, to get the next layer. To do that, I tried passing each of the kernel outputs through a Conv2D, by calling them by their index. The function I used is:

def modification(weights_path=None, classes=2):

    ###########
    ## Input ##
    ###########

    ### 224x224x3 sized RGB Input
    inputs = Input(shape=(224,224,3))

    #################################
    ## Conv2D Layer with 5 kernels ##
    #################################

    k = 5
    x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
    y = np.empty(k, dtype=object)
    for i in range(0,k):
        y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
    y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
    out = Activation('relu')(y)
    print ('Output shape is, ' +str(out.get_shape()))

    ### Maxpooling(2,2) with a stride of (2,2)
    out = MaxPooling2D((2,2), strides=(2,2), data_format='channels_last')(out)

    ############################################
    ## Top layer, with fully connected layers ##
    ############################################

    out = Flatten(name='flatten')(out)
    out = Dense(4096, activation='relu', name='fc1')(out)
    out = Dropout(0.5)(out)
    out = Dense(4096, activation='relu', name='fc2')(out)
    out = Dropout(0.5)(out)
    out = Dense(classes, activation='softmax', name='predictions')(out)

    if weights_path:
        model.load_weights(weights_path)

    model = Model(inputs, out, name='modification')

    return model

But this is not working, and is throwing the following error:

Traceback (most recent call last):
  File "sim-conn-edit.py", line 137, in <module>
    model = modification()
  File "sim-conn-edit.py", line 38, in modification
    y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 511, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 408, in assert_input_compatibil
ity
    if K.ndim(x) != spec.ndim:
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 437, in ndim
    dims = x.get_shape()._dims
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

I fed in layer x[i] as [ x[i] ] to meet the dimention requirements of a Conv2D layer. Any help with solving this problem will be deeply appreciated!

Body:
After posting this and this questions in StackOverflow, and some personal exploring, I came up with a solution. One can possibly do this with Lambda layers; by calling a Lambda layer to extract a sub part of the previous layer. For example, if the Lambda function is defined as,

def layer_slice(x,i):
    return x[:,:,:,i:i+1]

and then, called as,

k = 5
x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
y = np.empty(k, dtype=object)
for i in range(0,k):
    y[i] = Lambda(layer_slice, arguments={'i':i})(x)
    y[i] = Conv2D(1,(3,3), data_format='channels_last', padding='same')(y[i])
y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
out = Activation('relu')(y)
print ('Output shape is, ' +str(out.get_shape()))

it should effectively feed in individual kernel outputs to a new Conv2D layer. The layer shapes and corresponding number of trainable parameters being obtained from model.summary() matches the expectation. Thanks to Daniel for pointing out that Lambda layers cannot have trainable weights.


问:
Pandas Extract Number from String
Given the following data frame:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['1a',np.nan,'10a','100b','0b'],
                   })
df

    A
0   1a
1   NaN
2   10a
3   100b
4   0b
</code>```

I'd like to extract the numbers from each cell (where they exist).
The desired result is:

```<code>    A
0   1
1   NaN
2   10
3   100
4   0
</code>```

I know it can be done with str.extract, but I'm not sure how.

答:
To answer @Steven G 's question in the comment above, this should work:</p>

```<code>df.A.str.extract('(^\d*)')
</code>```

Title: Pandas Extract Number from String

Body:
Given the following data frame:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['1a',np.nan,'10a','100b','0b'],
                   })
df

    A
0   1a
1   NaN
2   10a
3   100b
4   0b

I'd like to extract the numbers from each cell (where they exist).
The desired result is:

    A
0   1
1   NaN
2   10
3   100
4   0

I know it can be done with str.extract, but I'm not sure how.

Body:
To answer @Steven G 's question in the comment above, this should work:

df.A.str.extract('(^\d*)')


问:
Why don't my images load in Vue.js 2?
I'm trying to get my images to load via a relative path in Vue.js 2 but something seems off. I'm just getting my feet wet with regard to Vue and would appreciate any pointers. Said images are in the /src/assets/imgs directory.

Below are the relevant code snippets for the component in question.

```<code><template>
  <section class="container sources">
        <h2>{{ heading }}</h2>
        <div class="columns">
            <div class="column" v-for="source in sources">
                <figure :title="source">
                    <img :src="imgPath + source + '.png'" :alt="source + ' logo'">
                    <figcaption>{{ source }}</figcaption>
                </figure>
            </div>
        </div>
    </section>
</template>

<script>
export default {
   name: 'sources',
   data () {
      return {
          heading: 'News Sources',
          imgPath: 'src/assets/imgs/',
          sources: [
            'al-jazeera-english', 'associated-press', 'bbc-news', 'bbc-sport', 'business-insider', 'cnn',
            'daily-mail', 'entertainment-weekly', 'espn', 'financial-times', 'fox-sports', 'hackernews',
            'ign','independent', 'mtv-news', 'national-geographic', 'new-scientist', 'reuters', 'techcrunch', 'the-economist', 'the-guardian-uk', 'the-huffington-post', 'the-new-york-times',
                'the-washington-post'
           ]
      }
   }
}
</script>
</code>```

Edit: Added a screenshot of my project's (simple) file tree upon request. Said images are in the 'imgs' folder, of course.

答:
Assuming you're using the webpack template from vue-cli, you can simply use a relative path for static assets.

```<code><img :src="'./assets/imgs/' + source + '.png'"
</code>```

Alternatively, put your images in the static directory and reference them with an absolute path, ie

```<code><img :src="'/static/imgs/' + source + '.png'"
</code>```

Title: Why don't my images load in Vue.js 2?

Body:
I'm trying to get my images to load via a relative path in Vue.js 2 but something seems off. I'm just getting my feet wet with regard to Vue and would appreciate any pointers. Said images are in the /src/assets/imgs directory.

Below are the relevant code snippets for the component in question.

<template>

{{ heading }}

{{ source }}

</template>

Edit: Added a screenshot of my project's (simple) file tree upon request. Said images are in the 'imgs' folder, of course.

Body:
Assuming you're using the webpack template from vue-cli, you can simply use a relative path for static assets.

<img :src="'./assets/imgs/' + source + '.png'"

Alternatively, put your images in the static directory and reference them with an absolute path, ie

<img :src="'/static/imgs/' + source + '.png'"


问:
Converting byte array to string and printing out to console
```
public void parse_table(BinaryReader inFile)
{
    byte[] idstring = inFile.ReadBytes(6);
    Console.WriteLine(Convert.ToString(idstring));
}
```

It is a simple snippet: read the first 6 bytes of the file and convert that to a string.

However the console shows System.Byte[].

Maybe I'm using the wrong class for conversion. What should I be using? It will eventually be parsing filenames encoded in UTF-8, and I'm planning to use the same method to read all filenames.

答:
I've used this simple code in my codebase:

```<code>static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}
</code>```

To use:

```<code>Console.WriteLine(ToReadableByteArray(bytes));
</code>```

Body:
public void parse_table(BinaryReader inFile)
{
    byte[] idstring = inFile.ReadBytes(6);
    Console.WriteLine(Convert.ToString(idstring));
}

It is a simple snippet: read the first 6 bytes of the file and convert that to a string.

However the console shows System.Byte[].

Maybe I'm using the wrong class for conversion. What should I be using? It will eventually be parsing filenames encoded in UTF-8, and I'm planning to use the same method to read all filenames.

Body:
I've used this simple code in my codebase:

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

To use:

Console.WriteLine(ToReadableByteArray(bytes));


问:
Cannot prevent my service from registering with Eureka
I have a Spring Boot application with the following config:

```<code>eureka:
  client:
    enabled: true
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://somehost:9999/eureka/
  registration:
    enabled: false
</code>```

My service makes use of Eureka to discover external services, but I don't want it to register with Eureka. Despite the above config I still see the following in my logs, which is odd:

```<code>DiscoveryClient - Not registering with Eureka server per configuration
...
EurekaServiceRegistry - Registering application foo with eureka with status UP
</code>```

The first log line makes sense - it's what I want. However, the second log line doesn't make sense given the config. Am I missing a setting?

答:
You didn't missing anything and your configuration is right. The second log just says that what happened in your local process.

The all periodic tasks that are related to actual registration process (ex heartbeat, instance info replication) with Eureka server are not scheduled by your configuration. So registration with Eureka server will not happen.

Body:
I have a Spring Boot application with the following config:

eureka:
  client:
    enabled: true
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://somehost:9999/eureka/
  registration:
    enabled: false

My service makes use of Eureka to discover external services, but I don't want it to register with Eureka. Despite the above config I still see the following in my logs, which is odd:

DiscoveryClient - Not registering with Eureka server per configuration
...
EurekaServiceRegistry - Registering application foo with eureka with status UP

The first log line makes sense - it's what I want. However, the second log line doesn't make sense given the config. Am I missing a setting?


问:
Custom UIbutton inside a nested UICollectionView cell does not get fired
I have a main UICollectionView which contains a custom header and a custom cell. Inside the custom cell I have another UICollectionView with a custom cell in which there are three buttons (inside a stackView) that has added target as a selector function to it for .touchUpInside but when I touch the button it does not fire the selector function at all. didSelectItemAt function gets called on parent UICollectionView but not the nested one. If I comment out the parent didSelectItemAt nothing is called.

I have also set the nested collectionView delegate. Any idea what I should do to make it work would be much appreciated.

(I don't use storyboard)

答: Try to disable your parent collection view's .delaysContentTouches, and if that doesn't work, try to override hitTest all the way down at your button's view level hierarchy and see if the touch reaches it.


问:
What is the difference between aws IoT 'device' and 'thingShadow' classes?
I have an app that subscribes and publishes to topics on aws IoT. I am wondering what the difference between the two classes "device" and "thingShadow" are. This library gives examples of both and they both seem to have similar functionalities.</p>

答:
The device class is used to subscribe to and publish messages on MQTT topics for telemetry and messaging purposes.

The thingShadow class is a wrapper around the device class, which provides additional methods such as .register, .update or delete which are designed to interact with a device shadow. This class also emits specific events associated with a shadow lifecycle such as status, delta or foreignStateChange.

[...] the thingShadow class allows devices to update, be notified of changes to, get the current state of, or delete Thing Shadows from AWS IoT.

So basically, if you're using device shadows use the thingShadow class, otherwise you can use the device class.

EDIT:

To expand a bit more on the basic principles of AWS IoT, you have two communication scheme between devices:

Since AWS IoT implements a standard MQTT interface, you can use topics to communicate with your devices using a pattern called publish-subscribe. Your apps can subscribe to a topic and wait for a device to publish a message on it. Similarly, your app can publish a message on a device topic and have the device receive it.

AWS IoT implements a second communication interface called the device shadow, which allows you to address a device even when it is disconnected, and keep a synchronized state between your app and the device itself. The AWS documentation explains it in clear terms.

A thing shadow (sometimes referred to as a device shadow) is a JSON
  document that is used to store and retrieve current state information
  for a thing (device, app, and so on). The Thing Shadows service
  maintains a thing shadow for each thing you connect to AWS IoT. You
  can use thing shadows to get and set the state of a thing over MQTT or
  HTTP, regardless of whether the thing is connected to the Internet.
  Each thing shadow is uniquely identified by its name.

The two interfaces can be addressed in the SDK using the device class for subscribing and publishing on MQTT topics, and the thing shadow class to retrieve, update or delete a device thing shadow document.


问:
How to recursively delete an entire directory with PowerShell 2.0?
What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7.

I have learned from several sources that the most obvious command, Remove-Item $targetDir -Recurse -Force, does not work correctly. This includes a statement in the PowerShell V2 online help (found using Get-Help Remove-Item -Examples) that states:

...Because the Recurse parameter in this cmdlet is faulty, the command uses the Get-Childitem cmdlet to get the desired files, and it uses the pipeline operator to pass them to the Remove-Item cmdlet...

I have seen various examples that use Get-ChildItem and pipe it to Remove-Item, but the examples usually remove some set of files based on a filter, not the entire directory.

I am looking for the cleanest way to blow out an entire directory, files and child directories, without generating any user warning messages using the least amount of code. A one-liner would be nice if it is easy to understand.

答:
Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors.  Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors.  I do not know why this happens, though some insight may be gained from this StackOverflow posting.

I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays.  The following runs well for me:

```<code># First remove any files in the folder tree
Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force

# Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }

# Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
Remove-Item -LiteralPath $FolderToDelete -Recurse -Force

# Finally, give Windows some time to finish deleting the folder (try not to hurl)
Start-Sleep -Seconds 4
</code>```

A Microsoft TechNet article Using Calculated Properties in PowerShell was helpful to me in getting a list of sub-folders sorted by depth.

Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (i.e. using ping as shown below).

```<code>DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
RD /S /Q "C:\Some\Folder\to\Delete" > nul
if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul
</code>```

Body:
Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors.  Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors.  I do not know why this happens, though some insight may be gained from this StackOverflow posting.

I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays.  The following runs well for me:

# First remove any files in the folder tree
Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force

# Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }

# Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
Remove-Item -LiteralPath $FolderToDelete -Recurse -Force

# Finally, give Windows some time to finish deleting the folder (try not to hurl)
Start-Sleep -Seconds 4

A Microsoft TechNet article Using Calculated Properties in PowerShell was helpful to me in getting a list of sub-folders sorted by depth.

Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (i.e. using ping as shown below).

DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
RD /S /Q "C:\Some\Folder\to\Delete" > nul
if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul


问:
Where is “Jenkins URL” configuration stored?
I'm trying to set up a non-default URL as part of a puppet script that installs Jenkins. I know how to edit the value via the web UI but I can't seem to find where the value is actually stored. I've looked through the jenkins_home folder and apache and have yet to find it.</p>

答: I'm on Jenkins 2.68 and it's stored at jenkins.model.JenkinsLocationConfiguration.xml under the Jenkins home folder.


问:
Which to use? Delegate vs. keyPathObserver - UIViewController With Two UIScrollViews
Before I get too far in to implementing this, I wanted to know what the optimal way to implement doing things with regards to contentOffest as the UIScrollView gets moved.

NOTE: Asking this from having read that having more than one object calling a delegate method can be problematic

1) Adding observers to each of the views' contentOffset keyPaths

2) Making my class a UIScrollViewDelegate and using scrollViewDidScroll

```<code>class MyAwesomeVC: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollViewA: UIScrollView!
@IBOutlet weak var scrollViewB: UIScrollView!
private var observerContext = 0

...

     override func viewDidLoad() {
         super.viewDidLoad()

         scrollViewA.delegate = self
         scrollViewB.delegate = self

         scrollViewA.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
         scrollViewB.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // check which scrollview if possible then do all the things

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

                 // check which scrollview if possible then do all the things

    }

    ...
    deinit {
        scrollViewA.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewB.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewA = nil
        scrollViewB = nil
    }

}
</code>```

答: I'd say the cleanest way to do this is to just assign yourself as the scroll view delegate and override the function scrollViewDidScroll like you have, and print(scrollView.contentOffset) in the function, and do whatever you need with it. If you need to check if you're scrolling down, you can attach a property to your class that saves your last contentOffset and simply compare it to the current one.

Body:
Before I get too far in to implementing this, I wanted to know what the optimal way to implement doing things with regards to contentOffest as the UIScrollView gets moved.

NOTE: Asking this from having read that having more than one object calling a delegate method can be problematic

1) Adding observers to each of the views' contentOffset keyPaths

2) Making my class a UIScrollViewDelegate and using scrollViewDidScroll

class MyAwesomeVC: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollViewA: UIScrollView!
@IBOutlet weak var scrollViewB: UIScrollView!
private var observerContext = 0

...

     override func viewDidLoad() {
         super.viewDidLoad()

         scrollViewA.delegate = self
         scrollViewB.delegate = self

         scrollViewA.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
         scrollViewB.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // check which scrollview if possible then do all the things

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

                 // check which scrollview if possible then do all the things

    }

    ...
    deinit {
        scrollViewA.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewB.removeObserver(self, forKeyPath: "contentOffset", context: &observerContext)
        scrollViewA = nil
        scrollViewB = nil
    }

}


问:
Flatten an arbitrarily nested list with recursion
I have a question about recursion.

```<code>def f6(lst):
result = []
if type(lst[0]) == list:
    return f6(lst[0])
else:
    result.append(lst[0])

    if lst[1]:
        return f6(lst[1])

    else:
        return result
</code>```

I want to make one dimensional list from multidimensional list input.
For example, when I put ["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']]
,I want to take ["baa",4,True,10, 5,1,2,'moo','chirp']

But it gives me index out of range error at if lst[1]:

Can't I use lst[1] as True/False condition?
I appreciate your help.

答:
You're not taking care of conditions where a list can have an arbitrary number of elements and nested lists in any order. You'll need to initialise a results list, and then run a loop across each element to and check if the element is an instance of list (this is cleaner than type(x) == list) and if it is, make a recursive call, and extend the results list. Otherwise, append that element to results.

```<code>def f6(lst):
    result = []
    for i in lst:
        if not isinstance(i, list):
            result.append(i)
        else:
            result.extend(f6(i))

    return result
</code>```

Calling this with f6(["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']]) produces:

```<code>['baa', 4, True, 10, 5, 1, 2, 'moo', 'chirp']
</code>```

Body:
I have a question about recursion.

def f6(lst):
result = []
if type(lst[0]) == list:
    return f6(lst[0])
else:
    result.append(lst[0])

    if lst[1]:
        return f6(lst[1])

    else:
        return result

I want to make one dimensional list from multidimensional list input.
For example, when I put ["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']]
,I want to take ["baa",4,True,10, 5,1,2,'moo','chirp']

But it gives me index out of range error at if lst[1]:

Can't I use lst[1] as True/False condition?
I appreciate your help.

Body:
You're not taking care of conditions where a list can have an arbitrary number of elements and nested lists in any order. You'll need to initialise a results list, and then run a loop across each element to and check if the element is an instance of list (this is cleaner than type(x) == list) and if it is, make a recursive call, and extend the results list. Otherwise, append that element to results.

def f6(lst):
    result = []
    for i in lst:
        if not isinstance(i, list):
            result.append(i)
        else:
            result.extend(f6(i))

    return result

Calling this with f6(["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']]) produces:

['baa', 4, True, 10, 5, 1, 2, 'moo', 'chirp']


问:
AWS Console > switch to user
How would you switch to a user in the AWS console?

I've set up an IAM policy for a user and I'd like to test whether they're working or not.

I've tried switching roles http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html

using the account id from the User ARN (e.g.

```<code>arn:aws:iam::<account id>:user/<username>
</code>```

in

```<code>https://signin.aws.amazon.com/switchrole
</code>```

using:

```<code>Account: <account id>
Role: test_user
Display Name: Test User
</code>```

then clicking Switch Role but I get:

```<code>Could not switch roles using the provided information. Please check your settings and try again. If you continue to have problems, contact your administrator.
</code>```

Note: I am an Admin with full access.

答:
You cannot use the Switch Role functionality to switch to a User.

You have two options:

Login as the User you wish to test, or

Create a Role with the same permissions, switch to the Role, then test

The easiest is to simply login as the user you wish to test. However, this can be a poor security practice because you are using another person's account and any actions you perform would be recorded against that user in Amazon CloudTrail (audit trail).

Alternatively, you could create a new IAM Role and assign exactly the same permissions to that Role. You would also need to assign a Trust Policy to the role to permit it to be used by you (your IAM User). You can then switch to that role in the console. This will work, unless you have any policies that specifically reference the User you wish to test (which will not recognise your Role permissions).

Title: AWS Console > switch to user

Body:
How would you switch to a user in the AWS console?

I've set up an IAM policy for a user and I'd like to test whether they're working or not.

I've tried switching roles http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html

using the account id from the User ARN (e.g.

arn:aws:iam::<account id>:user/<username>

in

https://signin.aws.amazon.com/switchrole

using:

Account: <account id>
Role: test_user
Display Name: Test User

then clicking Switch Role but I get:

Could not switch roles using the provided information. Please check your settings and try again. If you continue to have problems, contact your administrator.

Note: I am an Admin with full access.


问:
When using cocoapods, what is the best way to change the PRODUCT_NAME?
I created an app with name "ABC". Months later I decided to change the name to "ABCD". I believe the way I changed it, was in my Podfile, I changed target "ABC" do to target "ABCD" do. However, I recall going through quite a few issues/errors afterward in my workspace that caused a lot of stress. It was so long ago that I can't quite recall though.

Now I'm ready to submit, and I want to change the name one last time. I've changed the name in iTunes Connect, but now I want to change my PRODUCT_NAME, and my bundle identifier to match.

What is the best way to do this? Should I change the target fields in my Podfile? Or should I leave them, and just change something else in Xcode? Or do I need to change both or more than one thing?

答:
I've been scouting the internet to no avail looking for an answer to this. While editing the podfile and running pod install again fixes the renaming problem, in my case it broke my application as those pods had evolved while my app had stayed the same.
If you have concerns about backwards compatibility and don't want to reinstall your dependencies I suggest you do as I did and edit directly the .xcworkspace and .xcodeproj files using a text editor.</p>


问:
Make tracking codes disappear from URL bar
I'm using tracking codes to know where do the visitors of my website come from.

Example:

Facebook "Use App" button http://www.example.com/?fb_useapp=1

An emailing campaign : http://www.example.com/?mailingjuly2017=1

etc.

But then this is what gets displayed in the browser:

This is not very user-friendly: the users shouldn't see this information. How to get this parameter hidden on browser? (but still present in the server logs, that's where I'll do my analysis!)

Shoud I do it from JS or PHP, or even in an .htaccess RewriteRule?

PS: instead of using parameters ?param=1, I could also use a different approach and have a RewriteRule redirect example.com/mailingjuly2017/ to example.com.

答:
If you just want to remove the appearance of the parameters in the address bar without the need to refresh the page, you can try the following JS:

```<code>if (history.pushState && window.location.href.includes('?')) {
    history.pushState({}, null, window.location.origin);
}
</code>```

This will remove the parameters in url address bar and should not affect server-side logs.  Note that it will also remove them in the history so if the user clicks the back button and then forward, the page will be loaded without the parameters.  See MDN for details and browser compatibility.

Body:
If you just want to remove the appearance of the parameters in the address bar without the need to refresh the page, you can try the following JS:

if (history.pushState && window.location.href.includes('?')) {
    history.pushState({}, null, window.location.origin);
}

This will remove the parameters in url address bar and should not affect server-side logs.  Note that it will also remove them in the history so if the user clicks the back button and then forward, the page will be loaded without the parameters.  See MDN for details and browser compatibility.


问:
Why does swift substring with range require a special type of Range
Consider this function to build a string of random characters:

```<code>func makeToken(length: Int) -> String {
    let chars: String = "abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    var result: String = ""
    for _ in 0..<length {
        let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
        let idxEnd = idx + 1
        let range: Range = idx..<idxEnd
        let char = chars.substring(with: range)
        result += char
    }
    return result
}
</code>```

This throws an error on the substring method:

```<code>Cannot convert value of type 'Range<Int>' to expected argument
type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')
</code>```

I'm confused why I can't simply provide a Range with 2 integers, and why it's making me go the roundabout way of making a Range<String.Index>.

So I have to change the Range creation to this very over-complicated way:

```<code>let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
let start = chars.index(chars.startIndex, offsetBy: idx)
let end = chars.index(chars.startIndex, offsetBy: idx + 1)
let range: Range = start..<end
</code>```

Why isn't it good enough for Swift for me to simply create a range with 2 integers and the half-open range operator? (..<)

Quite the contrast to "swift", in javascript I can simply do chars.substr(idx, 1)

答:
I suggest converting your String to [Character] so that you can index it easily with Int:

```<code>func makeToken(length: Int) -> String {
    let chars = Array("abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)

    var result = ""
    for _ in 0..<length {
        let idx = Int(arc4random_uniform(UInt32(chars.count)))
        result += String(chars[idx])
    }
    return result
}
</code>```

Body:
Consider this function to build a string of random characters:

func makeToken(length: Int) -> String {
    let chars: String = "abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    var result: String = ""
    for _ in 0..<length {
        let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
        let idxEnd = idx + 1
        let range: Range = idx..<idxEnd
        let char = chars.substring(with: range)
        result += char
    }
    return result
}

This throws an error on the substring method:

Cannot convert value of type 'Range<Int>' to expected argument
type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')

I'm confused why I can't simply provide a Range with 2 integers, and why it's making me go the roundabout way of making a Range<String.Index>.

So I have to change the Range creation to this very over-complicated way:

let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
let start = chars.index(chars.startIndex, offsetBy: idx)
let end = chars.index(chars.startIndex, offsetBy: idx + 1)
let range: Range = start..<end

Why isn't it good enough for Swift for me to simply create a range with 2 integers and the half-open range operator? (..<)

Quite the contrast to "swift", in javascript I can simply do chars.substr(idx, 1)

Body:
I suggest converting your String to [Character] so that you can index it easily with Int:

func makeToken(length: Int) -> String {
    let chars = Array("abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)

    var result = ""
    for _ in 0..<length {
        let idx = Int(arc4random_uniform(UInt32(chars.count)))
        result += String(chars[idx])
    }
    return result
}


问:
Can't form a chain between two views/widgets in Android Studio
When I'm using the layout editor in Android Studio and I try to make a chain (bidirectional constraint) between a EditText View and a Button View using the constraint anchors, it doesn't make the chain.

It only makes a constraint if I try to constrain one View to the other.

I am trying to chain the right side of the EditText to the left side of the Button.

This is what my Layout Editor looks like:

答:
I disobeyed the tutorial by turning on Autoconnect (because I was trying everything).

I selected both widgets, then selected Center Horizontally. The chain was created, I turned Autoconnect back off, then continued the tutorial.


问:
Export always encrypted data from Azure SQL
Here are the environment details:

I've one Azure SQL Databases V12 and another local DB SQL Server 2016. I've enabled Always Encrypted on a table in the first DB - DB1.  The same table structure is also created and i need to migrate the encrypted data from first DB to second DB.

When I try to export data from DB1 to DB2 I am getting error

"Creating destination for Encrypted source is not supported".

The error is because the CMK and CEK that were used to encrypt DB 1 is in Azure-Key-vault.
The export tool never gave an option to access key-vault.

How do I  migrate the data from DB1 to DB2?

答:
@G_Tania: which import/export tool, are you trying to use? I understand, you want to use a local certificate in your target database (not the column master key stored in Azure Key Vault), correct? Do you also want to replace the column encryption key (CEK), or do you want to keep the original CEK?

In general, there are two kinds of out-of-the-box tools that support migrating databases using Always Encrypted, each of which supports different scenarios:

Bacpac-based tools – please, see https://learn.microsoft.com/en-us/azure/sql-database/sql-database-export. Such tools generate a bacpac file that contains encrypted data and original key metadata. The data remains encrypted throughout the migration process and when you import the file to your target server, the key metadata will point to the original keys (the master key in Azure Key Vault, in your case). If you want to use different keys in the target database, you still can use bacpac-based tools, but after importing the database, you will need to rotate your keys. Please, see https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/overview-of-key-management-for-always-encrypted.

SSIS-based tools, such as the Import/Export Wizard that ships with SSMS: https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/start-the-sql-server-import-and-export-wizard. These tools are useful if you want to migrate the data and replace the keys in one step. The process for migrating and encrypting data using the I/E Wizard is described here: https://blogs.msdn.microsoft.com/sqlsecurity/2015/07/28/encrypting-existing-data-with-always-encrypted/. The process for re-encrypting the data will be similar – you need to make sure that Always Encrypted is enabled for both the source and the target connection. In addition, since your master key is stored in Azure Key Vault, you need to use the ODBC 13.1 driver (at least for your source database connection). Unlike ADO.NET, ODBC allows you to specify Key Vault credentials in the connection string. Please, see “Using the Azure Key Vault Provider” in https://learn.microsoft.com/en-us/sql/connect/odbc/using-always-encrypted-with-the-odbc-driver.