问:
.cs is a binary file instead of a text file
So, I opened my project in visual studio to find that the code for one of my forms looks like this :

loginForm.cs

```<code>í}ksâH²ö÷ØÿPÑÝ}¢¡w8Ó‹±ÝÍßÆØžw£»cBHh¬Û¨$lvgÿû›Y’¸„AX¥¶÷œi„*Ÿ|²²²nYå’Ô(”àÿê7R¹]j¶+ÕbS’
¥Z»T"}ª¸še’¡å»óÙ¡ä7Ë¹g®Œ—?[S?Õjú2¡ƒKŸ¤rQ*–>§éê§J¹Q®V«ˆeã>]SÊŒþ¼±Tx×Àb”Œ-æª_Kµz©ô|½t´‘fÊ®åü³ÞlÔ óŸŽéPöt÷;9ö[3G„ÊŽ>%º5bí¿ÿíoþGNøEÍÔ\~‡€øŽK
ÁßZaÊÍÒa
Û   raÏVe—¢Î@a*J¥XæPyUÿþLiš9´¶-ê³®
bÈºn)däAYŒ˜–Ù¶å¸T-F«€š*!›U0çƒµgÖh„°=FÊÌ%¶ìŽÛðQgôï)v3¦d`9òGÐ†í·ÞÙ€ùÈ¦ªS•¦äÎ»–“zÙ=Ð§&ëÚ¿¡Š3©|˜òˆ:iÕõ‡š.y€ê‡ºU5ê¦åLÛ¤ÛþvåX#G6ŽeWþæ×ÓoüÝé+Û¡²zeY:yÐLÕz`}WVî{†AU
Œ¾k˜Ø'â:^ZÚ>•5§¯Œ©êéÔùN®Ír4*9€º«DC« 2xª -¦T(z¹_=êÑâÄ0@½K€hë½¿Ì€J ²µÉÖ¿ù@Ü©MAKC€N4Dô Ð| šKß¨6£¥ƒ(±yh%n¯ºgÖ|…IõÃjìÌ2G72»ßVoKÏGk`ìI}sGÒÊ®2æŽ‹—Eè£By8ÀÀ‹1y ó–*õb¯éHc.…F›b
</code>```

Visual studio is saying that loginForm.cs is a binary file instead of a text file.

If anyone could help me in recovering the original code, that would be great!

答:
Do you know what might have corrupted or overwritten the file?

If you don't have a version to revert to in your source control system, there may be a previous version still in your file system, or you may have some luck with other file editors or decompiling, depending on how complex the file was.

Here is article that suggests several approaches for recovering corrupted cs source files in Visual Studio:

https://www.samnoble.co.uk/2014/11/30/visual-studio-crashes-and-a-corrupted-cs-file/

Body:
So, I opened my project in visual studio to find that the code for one of my forms looks like this :

loginForm.cs

í}ksâH²ö÷ØÿPÑÝ}¢¡w8Ó‹±ÝÍßÆØžw£»cBHh¬Û¨$lvgÿû›Y’¸„AX¥¶÷œi„*Ÿ|²²²nYå’Ô(”àÿê7R¹]j¶+ÕbS’
¥Z»T"}ª¸še’¡å»óÙ¡ä7Ë¹g®Œ—?[S?Õjú2¡ƒKŸ¤rQ*–>§éê§J¹Q®V«ˆeã>]SÊŒþ¼±Tx×Àb”Œ-æª_Kµz©ô|½t´‘fÊ®åü³ÞlÔ óŸŽéPöt÷;9ö[3G„ÊŽ>%º5bí¿ÿíoþGNøEÍÔ\~‡€øŽK
ÁßZaÊÍÒa
Û   raÏVe—¢Î@a*J¥XæPyUÿþLiš9´¶-ê³®
bÈºn)däAYŒ˜–Ù¶å¸T-F«€š*!›U0çƒµgÖh„°=FÊÌ%¶ìŽÛðQgôï)v3¦d`9òGÐ†í·ÞÙ€ùÈ¦ªS•¦äÎ»–“zÙ=Ð§&ëÚ¿¡Š3©|˜òˆ:iÕõ‡š.y€ê‡ºU5ê¦åLÛ¤ÛþvåX#G6ŽeWþæ×ÓoüÝé+Û¡²zeY:yÐLÕz`}WVî{†AU
Œ¾k˜Ø'â:^ZÚ>•5§¯Œ©êéÔùN®Ír4*9€º«DC« 2xª -¦T(z¹_=êÑâÄ0@½K€hë½¿Ì€J ²µÉÖ¿ù@Ü©MAKC€N4Dô Ð| šKß¨6£¥ƒ(±yh%n¯ºgÖ|…IõÃjìÌ2G72»ßVoKÏGk`ìI}sGÒÊ®2æŽ‹—Eè£By8ÀÀ‹1y ó–*õb¯éHc.…F›b

Visual studio is saying that loginForm.cs is a binary file instead of a text file.

If anyone could help me in recovering the original code, that would be great!


来源: stackexchange

问:
How to extract a segment of audio file using python?
I am trying to extract a single heartbeat from a .wav file of 20-30 second recorded heartbeat audio.Every heartbeat starts with a high-intensity sound (peak) called "lub" and then another heartbeat repeats from the next peak.

Like what libraries to use, any algorithms already available, tutorials available, etc.

答:
Use standard library wave module to load audio. Then convert data into numpy array and then use peak detection algorithm from scipy or some of scikits.

Some code:

```<code>import wave
wf = wave.open("file.wav", "r")
fs = wf.getframerate()
nc = wf.getnchannels()
sw = wf.getsampwidth()
nf = wf.getnframes()
data = wf.readframes(nf)
wf.close()

import numpy as np
dt = {1: np.int8, 2: np.int16, 4: np.int32}
a = np.fromstring(data, dtype=dt[sw])
</code>```

And now you perform peak detection on array a. You can use for example an algorithm from scikits talkbox (here is a copy-paste of the function):

```<code>

def findpeaks (x, neighbours=50):
    """
    Peak seeking algorithm from scikits talkbox.
    Returns indexes of peaks in the x curve.
    """
    peaks = []
    nx = x.size

    assert 2 * neighbours + 1 <= nx

    if nx == 1:
        return [0]
    elif nx == 2:
        if x[0] > x[1]:
            peaks.append(0)
        else:
            peaks.append(1)
        return peaks

    # Handle points which have less than neighs samples on their left
    for i in xrange(neighbours):
        cur = x[i]
        m = x[i+1]
        # look at the left of the current position
        for j in xrange(i):
            if m < x[j]:
                m = x[j]
        # look at the right of the current position
        for j in xrange(i+1, i+neighbours):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    # Handle points which have at least neighs samples on both their left
    # and right
    for i in xrange(neighbours, nx - neighbours):
        cur = x[i]
        m = x[i+1]
        # look at the left
        for j in xrange(i - neighbours, i):
            if m < x[j]:
                m = x[j]
        # look at the right
        for j in xrange(i+1, i+neighbours):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    # Handle points which have less than neighs samples on their right
    for i in xrange(nx - neighbours, nx):
        cur = x[i]
        m = x[i-1]
        # look at the left
        for j in xrange(i - neighbours, i):
            if m < x[j]:
                m = x[j]

        # look at the right
        for j in xrange(i+1, nx):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    return peaks

peaks = findpeaks(a)
# And now you get the segment of a signal by slicing it:
# For example (assuming you checked what peaks you want and if they were found at all):
s = a[peaks[0]:peaks[1]] # Let say you want first two peaks regardless the sign

# As you can see, this concrete algo is not strictly numpy dependant. You just have to change line nx = x.size into nx = len(x) to avoid it completely.
# So you can "throw" numpy away by loading wave data into a list like this:

import struct
dt = {1: "c", 2: "h", 4: "l"}
a = struct.unpack("<"+dt[sw], data)
# And then you use a as demonstrated above i.e. as an array. But numpy will give you more flexibility, speed and options to work on.

</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use standard library wave module to load audio. Then convert data into numpy array and then use peak detection algorithm from scipy or some of scikits.

Some code:

import wave
wf = wave.open("file.wav", "r")
fs = wf.getframerate()
nc = wf.getnchannels()
sw = wf.getsampwidth()
nf = wf.getnframes()
data = wf.readframes(nf)
wf.close()

import numpy as np
dt = {1: np.int8, 2: np.int16, 4: np.int32}
a = np.fromstring(data, dtype=dt[sw])

And now you perform peak detection on array a. You can use for example an algorithm from scikits talkbox (here is a copy-paste of the function):

def findpeaks (x, neighbours=50):
    """
    Peak seeking algorithm from scikits talkbox.
    Returns indexes of peaks in the x curve.
    """
    peaks = []
    nx = x.size

    assert 2 * neighbours + 1 <= nx

    if nx == 1:
        return [0]
    elif nx == 2:
        if x[0] > x[1]:
            peaks.append(0)
        else:
            peaks.append(1)
        return peaks

    # Handle points which have less than neighs samples on their left
    for i in xrange(neighbours):
        cur = x[i]
        m = x[i+1]
        # look at the left of the current position
        for j in xrange(i):
            if m < x[j]:
                m = x[j]
        # look at the right of the current position
        for j in xrange(i+1, i+neighbours):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    # Handle points which have at least neighs samples on both their left
    # and right
    for i in xrange(neighbours, nx - neighbours):
        cur = x[i]
        m = x[i+1]
        # look at the left
        for j in xrange(i - neighbours, i):
            if m < x[j]:
                m = x[j]
        # look at the right
        for j in xrange(i+1, i+neighbours):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    # Handle points which have less than neighs samples on their right
    for i in xrange(nx - neighbours, nx):
        cur = x[i]
        m = x[i-1]
        # look at the left
        for j in xrange(i - neighbours, i):
            if m < x[j]:
                m = x[j]

        # look at the right
        for j in xrange(i+1, nx):
            if m < x[j]:
                m = x[j]

        if cur > m:
            peaks.append(i)
            #assert(pkcnt <= (nx / neighbours + 1))

    return peaks

peaks = findpeaks(a)
# And now you get the segment of a signal by slicing it:
# For example (assuming you checked what peaks you want and if they were found at all):
s = a[peaks[0]:peaks[1]] # Let say you want first two peaks regardless the sign

# As you can see, this concrete algo is not strictly numpy dependant. You just have to change line nx = x.size into nx = len(x) to avoid it completely.
# So you can "throw" numpy away by loading wave data into a list like this:

import struct
dt = {1: "c", 2: "h", 4: "l"}
a = struct.unpack("<"+dt[sw], data)
# And then you use a as demonstrated above i.e. as an array. But numpy will give you more flexibility, speed and options to work on.


问:
Very basic MurmurHash questions: variable descriptions for len, key in C++ implementation
I'm trying to adapt MurmurHash into a program built for a class, but I can't seem to find explicit confirmation about what the variables represent.

I'm using the following as reference:

```<code>unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed )
{
    // 'm' and 'r' are mixing constants generated offline.
    // They're not really 'magic', they just happen to work well.

    const unsigned int m = 0x5bd1e995;
    const int r = 24;

    // Initialize the hash to a 'random' value

    unsigned int h = seed ^ len;

    // Mix 4 bytes at a time into the hash

    const unsigned char * data = (const unsigned char *)key;

    while(len >= 4)
    {
        unsigned int k = *(unsigned int *)data;

        k *= m;
        k ^= k >> r;
        k *= m;

        h *= m;
        h ^= k;

        data += 4;
        len -= 4;
    }

    // Handle the last few bytes of the input array

    switch(len)
    {
    case 3: h ^= data[2] << 16;
    case 2: h ^= data[1] << 8;
    case 1: h ^= data[0];
            h *= m;
    };

    // Do a few final mixes of the hash to ensure the last few
    // bytes are well-incorporated.

    h ^= h >> 13;
    h *= m;
    h ^= h >> 15;

    return h;
}
</code>```

As I understand it, hash functions will take some value and puts it into a hash table. Is "len" the size of the hash table and "key" the value to be hashed?

答:
Here's what they represent:

```<code>unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed )
</code>```

key - Points to an array of bytes that you want to generate a hash value for

len - the number of bytes that key points to (or at least, the number of bytes you want included in the input from which the hash value is computed)

seed - pick whatever value you want for this; you'll get different hash codes for a given input if you use different seed values.  If in doubt, just always pass in zero.

Returns a hash value computed from the passed-in bytes.  You'll always get the same hash value back for the same byte-sequence (assuming you also passed in the same seed value), but the returned hash value will vary considerably for different byte-sequences (i.e. even a small difference in the input bytes will probably result in a very different returned hash-value)

As I understand it, hash functions will take some value and puts it
  into a hash table. Is "len" the size of the hash table and "key" the
  value to be hashed?

That's incorrect.  MurmurHash2() merely computes a hash-code, and so MurmurHash2() could be useful as part of a hash table implementation, but it does not itself implement a hash table.

Body:
I'm trying to adapt MurmurHash into a program built for a class, but I can't seem to find explicit confirmation about what the variables represent.

I'm using the following as reference:

unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed )
{
    // 'm' and 'r' are mixing constants generated offline.
    // They're not really 'magic', they just happen to work well.

    const unsigned int m = 0x5bd1e995;
    const int r = 24;

    // Initialize the hash to a 'random' value

    unsigned int h = seed ^ len;

    // Mix 4 bytes at a time into the hash

    const unsigned char * data = (const unsigned char *)key;

    while(len >= 4)
    {
        unsigned int k = *(unsigned int *)data;

        k *= m;
        k ^= k >> r;
        k *= m;

        h *= m;
        h ^= k;

        data += 4;
        len -= 4;
    }

    // Handle the last few bytes of the input array

    switch(len)
    {
    case 3: h ^= data[2] << 16;
    case 2: h ^= data[1] << 8;
    case 1: h ^= data[0];
            h *= m;
    };

    // Do a few final mixes of the hash to ensure the last few
    // bytes are well-incorporated.

    h ^= h >> 13;
    h *= m;
    h ^= h >> 15;

    return h;
}

As I understand it, hash functions will take some value and puts it into a hash table. Is "len" the size of the hash table and "key" the value to be hashed?

Body:
Here's what they represent:

unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed )

key - Points to an array of bytes that you want to generate a hash value for

len - the number of bytes that key points to (or at least, the number of bytes you want included in the input from which the hash value is computed)

seed - pick whatever value you want for this; you'll get different hash codes for a given input if you use different seed values.  If in doubt, just always pass in zero.

Returns a hash value computed from the passed-in bytes.  You'll always get the same hash value back for the same byte-sequence (assuming you also passed in the same seed value), but the returned hash value will vary considerably for different byte-sequences (i.e. even a small difference in the input bytes will probably result in a very different returned hash-value)

As I understand it, hash functions will take some value and puts it
  into a hash table. Is "len" the size of the hash table and "key" the
  value to be hashed?

That's incorrect.  MurmurHash2() merely computes a hash-code, and so MurmurHash2() could be useful as part of a hash table implementation, but it does not itself implement a hash table.


问:
how to display table view cells whenever we need to click on one cell
i am writing one app in that app i have to display tableview with two cells.while the first cell touched by the user then it have to show some other cells within the view (i cant use navigation here) and also second cell also visible..can any one tell me the suggestion for this.
thank you all.</p>

答:
define a data-object e.g. NSMutableDictionary

always readout the data from this object (for count and also for the values you want to show)

in the case the user clicks the defined cell. you'll flush the MutableDirectory and add new data.

Reload the TableViewController [tableviewController.tableview reloadData];

thats it
cheers Simon

ContentLicense: CC BY-SA 2.5


问:
Determining If the Cell Contents are Equal in Excel
I am trying to see if the numerical values in two cells are equivalent.

My problem is that one cell is text formatted and the number has one decimal precision and the other numerical format with 7 decimals precision.

I want to see if they are both equal to one decimal precision and I can't figure out how to do it.

So, the values in my cells look like this:

```<code>numerical         text
  5.6%             5.6%
</code>```

But the real values are:

```<code>numerical        text
5.56650625%       5.6%
</code>```

How can I test do this?

Thanks in advance.

答:
To avoid any floating point imprecision I suggest comparing Text to Text so if the Numeric version is in A1, in say A4:

```<code>=TEXT(ROUND(A1*100,1),"General")&"%"
</code>```

With the Text version in B1:

```<code>=B1=A4
</code>```

returns TRUE.

Working on the Text version to try to bring it 'into line' with the other is pointless because it simply does not have all the decimal places that the Number format version has.

Body:
I am trying to see if the numerical values in two cells are equivalent.

My problem is that one cell is text formatted and the number has one decimal precision and the other numerical format with 7 decimals precision.

I want to see if they are both equal to one decimal precision and I can't figure out how to do it.

So, the values in my cells look like this:

numerical         text
  5.6%             5.6%

But the real values are:

numerical        text
5.56650625%       5.6%

How can I test do this?

Thanks in advance.

Body:
To avoid any floating point imprecision I suggest comparing Text to Text so if the Numeric version is in A1, in say A4:

=TEXT(ROUND(A1*100,1),"General")&"%"

With the Text version in B1:

=B1=A4

returns TRUE.

Working on the Text version to try to bring it 'into line' with the other is pointless because it simply does not have all the decimal places that the Number format version has.


问:
add shinyBS popover on disabled button
I haven't found any information in documentation of shinyBS and on the google/SO about how to use trigger = 'manual' on, for example, addPopover of shinyBS. I thought this would be the way to add a tooltip to a disabled button. (I dont want to do it with div'ving the button and giving title to div.
Also would be nice if someone has a way to add tooltips reactively to shiny apps

答:
Since shosaco's solution didnt work for me, I got it to work this way:</p>

```<code>if (input$disable) {
  addCssClass("buttonId", "disabled")
  bsTooltip("buttonId", "This button is currently disabled.")
} else {
  bsTooltip("buttonId", "")
  removeCssClass("buttonId", "disabled")
}
observeEvent(input$buttonId, {
    if (!input$disable) {
      output$text <- renderText("Bla")
    } else {
      output$text <- renderText(NULL)
    }
</code>```

Title: add shinyBS popover on disabled button

Body:
Since shosaco's solution didnt work for me, I got it to work this way:

if (input$disable) {
  addCssClass("buttonId", "disabled")
  bsTooltip("buttonId", "This button is currently disabled.")
} else {
  bsTooltip("buttonId", "")
  removeCssClass("buttonId", "disabled")
}
observeEvent(input$buttonId, {
    if (!input$disable) {
      output$text <- renderText("Bla")
    } else {
      output$text <- renderText(NULL)
    }


问:
One line solution for editing a numpy array of counts? (python)
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])
</code>```

I want to get back an array like so:

```<code>[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]
</code>```

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1
</code>```

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

```<code>cumulative[:, :, a[:, :]-1] +=1
</code>```

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

答:
It's technically not a one-liner, but if you ignore PEP 8's maximum line length then you can whittle it down to two lines.

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

out = np.zeros((a.shape[0], 1 + a.max() - a.min(), a.shape[1]), dtype=np.int8)
out[np.repeat(np.arange(a.shape[0]), a.shape[1]), np.subtract(
    a, a.min())[:].flatten(), np.tile(np.arange(a.shape[1]), a.shape[0])] = 1
print(out)
</code>```

Which outputs;

```<code>[[[1 0 0]
  [0 1 0]
  [0 0 1]]

 [[0 0 1]
  [0 1 0]
  [1 0 0]]

 [[0 1 0]
  [1 0 0]
  [0 0 1]]

 [[1 0 0]
  [1 0 0]
  [1 0 0]]]
</code>```

This is perhaps not the most gainly nor graceful solution, and unfortunately does not scale to n dimensions, but hopefully this (almost one-liner) is sufficiently vectorised for you.

It's quite hefty so I'll briefly run through how this works.

The output array is created full of zeros by default, with the total lengths of the 'one-hot vectors' equal to the range of the input array (I assumed this is what you wanted given that there was no row for the value zero given in your example).

np.tile and np.repeat are used with np.arange to produce the first and last index arrays, that is the indices of each element in a.

Fancy indicing is used to fill set the indices of a matching number to 1.

Body:
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

I want to get back an array like so:

[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

cumulative[:, :, a[:, :]-1] +=1

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

Body:
It's technically not a one-liner, but if you ignore PEP 8's maximum line length then you can whittle it down to two lines.

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

out = np.zeros((a.shape[0], 1 + a.max() - a.min(), a.shape[1]), dtype=np.int8)
out[np.repeat(np.arange(a.shape[0]), a.shape[1]), np.subtract(
    a, a.min())[:].flatten(), np.tile(np.arange(a.shape[1]), a.shape[0])] = 1
print(out)

Which outputs;

[[[1 0 0]
  [0 1 0]
  [0 0 1]]

 [[0 0 1]
  [0 1 0]
  [1 0 0]]

 [[0 1 0]
  [1 0 0]
  [0 0 1]]

 [[1 0 0]
  [1 0 0]
  [1 0 0]]]

This is perhaps not the most gainly nor graceful solution, and unfortunately does not scale to n dimensions, but hopefully this (almost one-liner) is sufficiently vectorised for you.

It's quite hefty so I'll briefly run through how this works.

The output array is created full of zeros by default, with the total lengths of the 'one-hot vectors' equal to the range of the input array (I assumed this is what you wanted given that there was no row for the value zero given in your example).

np.tile and np.repeat are used with np.arange to produce the first and last index arrays, that is the indices of each element in a.

Fancy indicing is used to fill set the indices of a matching number to 1.


问:
Is there a cleaner way to print this list of dictionaries?
Is there a cleaner print statement for this, other than what I have?

```<code>weather = [{
    'day_1': ['Overcast', 87, 20, 'Saturday', 'Chamblee'],
    'day_2': ['Rain', 80, 25, 'Sunday', 'Marietta'],
    'day_3': ['Sunny', 90, 30, 'Monday', 'Atlanta']
}]

for item in weather:
    print(item['day_1'][3], 'in',
          item['day_1'][4],
          'looks like',
          item['day_1'][0],
          'with a high of',
          item['day_1'][1],
          'and a',
          item['day_1'][2],
          '% chance of rain.')
</code>```

I need to run this sentence for each Day key.

答:
Use string formatting:

```<code>print(
    '{3} in {4} looks like {0} with a high of '
    '{1} and a {2}% chance of rain'.format(*item['day_1']))
</code>```

The placeholder numbering references the positions of the item['day_1'] sequences.

Body:
Is there a cleaner print statement for this, other than what I have?

weather = [{
    'day_1': ['Overcast', 87, 20, 'Saturday', 'Chamblee'],
    'day_2': ['Rain', 80, 25, 'Sunday', 'Marietta'],
    'day_3': ['Sunny', 90, 30, 'Monday', 'Atlanta']
}]

for item in weather:
    print(item['day_1'][3], 'in',
          item['day_1'][4],
          'looks like',
          item['day_1'][0],
          'with a high of',
          item['day_1'][1],
          'and a',
          item['day_1'][2],
          '% chance of rain.')

I need to run this sentence for each Day key.

Body:
Use string formatting:

print(
    '{3} in {4} looks like {0} with a high of '
    '{1} and a {2}% chance of rain'.format(*item['day_1']))

The placeholder numbering references the positions of the item['day_1'] sequences.


问:
react-native 0.46 link command quits after prompt?
After updating from 0.45 to 0.46, the react-native link command no longer seems to do anything in my project. I even tried re-creating a new app from scratch and found the same issue. Reproduced on Mac, and Windows 10 Ubuntu Bash.

I get the prompt asking the usual question, but it seems to exit without any error message right after. Using node 6.10.1 and npm 4.5.0.

答:
This was a confirmed bug in 0.46 that was fixed in 0.46.1:
https://twitter.com/grabbou/status/883358932907024386

It was caused by an inadvertent upgrade of the inquirer package, whose prompt function signature changed between versions (from a callback to a Promise):
https://github.com/facebook/react-native/commit/352c3d97b3017ab91cfca15a8d54fb753edc7ed5


问:
Opening a named pipe in low integrity level
I'm working on an application which is made of two modules. These modules communicate through named pipes in the following environment:

Windows 7 Home Premium x64

Visual Studio 2008

C# / .Net 3.5

The server runs with administrator rights (high integrity level). The client runs in low integrity level. So that the client can connect to the server, I need to create the pipe in low integrity level. I manage to do this only when the server runs in medium integrity level.

I tested the following setups :

server : high, client : low => access refused

server : high, client : medium => access refused

server : high, client : high => OK

server : medium, client : low => OK

server : medium, client : medium => OK

server : low, client : low => OK

Setup #4 shows that the named pipe gets created with different integrity level than the one of the process, which is good. However, the setup I am interested in is the first one.

I have a sample which makes it easy to test. If the connection is successful, the clients writes "Connected" and the server writes "Received connection". If the connection fails, the client writes "Failed" and the server stays on "Waiting".

Here is how I execute the client program (for the server, simply replace NamePipeClient with NamedPipeServer):

medium integrity level:

open the command prompt

icacls NamedPipeClient.exe /setintegritylevel Medium

NamedPipeClient.exe

low integrity level:

open the command prompt

icacls NamedPipeClient.exe /setintegritylevel Low

NamedPipeClient.exe

high integrity level:

open the command prompt in admin mode

icacls NamedPipeClient.exe /setintegritylevel High

NamedPipeClient.exe

Any help will be greatly appreciated!

Server code

Program.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.IO.Pipes;

namespace NamedPipeServer
{
    class Program
    {
        static void Main(string[] args)
        {
            SafePipeHandle handle = LowIntegrityPipeFactory.CreateLowIntegrityNamedPipe("NamedPipe/Test");
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeDirection.InOut, true, false, handle);
            pipeServer.BeginWaitForConnection(HandleConnection, pipeServer);

            Console.WriteLine("Waiting...");
            Console.ReadLine();
        }

        private static void HandleConnection(IAsyncResult ar)
        {
            Console.WriteLine("Received connection");
        }
    }
}
</code>```

LowIntegrityPipeFactory.cs

```<code>using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO.Pipes;
using System.ComponentModel;
using System.IO;
using System.Security.Principal;
using System.Security.AccessControl;

namespace NamedPipeServer
{
    static class LowIntegrityPipeFactory
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode,
            int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout,
            SECURITY_ATTRIBUTES securityAttributes);

        [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = false)]
        private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
            [In] string StringSecurityDescriptor,
            [In] uint StringSDRevision,
            [Out] out IntPtr SecurityDescriptor,
            [Out] out int SecurityDescriptorSize
        );

        [StructLayout(LayoutKind.Sequential)]
        private struct SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr lpSecurityDescriptor;
            public int bInheritHandle;
        }

        private const string LOW_INTEGRITY_SSL_SACL = "S:(ML;;NW;;;LW)";

        public static SafePipeHandle CreateLowIntegrityNamedPipe(string pipeName)
        {
            // convert the security descriptor
            IntPtr securityDescriptorPtr = IntPtr.Zero;
            int securityDescriptorSize = 0;
            bool result = ConvertStringSecurityDescriptorToSecurityDescriptor(
                LOW_INTEGRITY_SSL_SACL, 1, out securityDescriptorPtr, out securityDescriptorSize);
            if (!result)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES();
            securityAttributes.nLength = Marshal.SizeOf(securityAttributes);
            securityAttributes.bInheritHandle = 1;
            securityAttributes.lpSecurityDescriptor = securityDescriptorPtr;

            SafePipeHandle handle = CreateNamedPipe(@"\\.\pipe\" + pipeName,
                PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                0, 0, PipeAccessRights.ReadWrite, securityAttributes);
            if (handle.IsInvalid)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            return handle;
        }

        private static SafePipeHandle CreateNamedPipe(string fullPipeName, PipeDirection direction,
            int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options,
            int inBufferSize, int outBufferSize, PipeAccessRights rights, SECURITY_ATTRIBUTES secAttrs)
        {
            int openMode = (int)direction | (int)options;
            int pipeMode = 0;
            if (maxNumberOfServerInstances == -1)
                maxNumberOfServerInstances = 0xff;

            SafePipeHandle handle = CreateNamedPipe(fullPipeName, openMode, pipeMode,
                maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);
            if (handle.IsInvalid)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            return handle;
        }

    }
}
</code>```

Client code

Program.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;

namespace NamedPipeClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var pipeClient = new NamedPipeClientStream(".", "NamedPipe/Test",
                    PipeDirection.InOut,
                    PipeOptions.None);
                pipeClient.Connect(100);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: " + ex);
                return;
            }

            Console.WriteLine("Connected");
            Console.ReadLine();
        }
    }
}
</code>```

答:
Your code for setting the mandatory integrity label on the pipe achieves this successfully. However, because your security descriptor doesn't define a DACL, your pipe is being created with the default one.

It is the DACL which is causing the low integrity client to fail when trying to connect to the pipe created by your high integrity server.

You need to fix the DACL in the server before opening the listener. Rather than trying to construct the full descriptor using P/Invoke code before creating the pipe, which is pretty hard to get right, I'd suggest leveraging the System.IO.Pipes classes to do it in managed code as a separate step after the pipe is created, like this:

```<code>    // Fix up the DACL on the pipe before opening the listener instance
    // This won't disturb the SACL containing the mandatory integrity label
    NamedPipeServerStream handleForSecurity = null;
    try
    {
        handleForSecurity = new NamedPipeServerStream("NamedPipe/Test", PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null, System.IO.HandleInheritability.None, PipeAccessRights.ChangePermissions);
        PipeSecurity ps = handleForSecurity.GetAccessControl();
        PipeAccessRule aceClients = new PipeAccessRule(
            new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), // or some other group defining the allowed clients
            PipeAccessRights.ReadWrite,
            AccessControlType.Allow);
        PipeAccessRule aceOwner = new PipeAccessRule(
            WindowsIdentity.GetCurrent().Owner,
            PipeAccessRights.FullControl,
            AccessControlType.Allow);
        ps.AddAccessRule(aceClients);
        ps.AddAccessRule(aceOwner);
        handleForSecurity.SetAccessControl(ps);
    }
    finally
    {
        if (null != handleForSecurity) handleForSecurity.Close();
        handleForSecurity = null;
    }
</code>```

This works for me, with the rest of your code unchanged.

Body:
I'm working on an application which is made of two modules. These modules communicate through named pipes in the following environment:

Windows 7 Home Premium x64

Visual Studio 2008

C# / .Net 3.5

The server runs with administrator rights (high integrity level). The client runs in low integrity level. So that the client can connect to the server, I need to create the pipe in low integrity level. I manage to do this only when the server runs in medium integrity level.

I tested the following setups :

server : high, client : low => access refused

server : high, client : medium => access refused

server : high, client : high => OK

server : medium, client : low => OK

server : medium, client : medium => OK

server : low, client : low => OK

Setup #4 shows that the named pipe gets created with different integrity level than the one of the process, which is good. However, the setup I am interested in is the first one.

I have a sample which makes it easy to test. If the connection is successful, the clients writes "Connected" and the server writes "Received connection". If the connection fails, the client writes "Failed" and the server stays on "Waiting".

Here is how I execute the client program (for the server, simply replace NamePipeClient with NamedPipeServer):

medium integrity level:

open the command prompt

icacls NamedPipeClient.exe /setintegritylevel Medium

NamedPipeClient.exe

low integrity level:

open the command prompt

icacls NamedPipeClient.exe /setintegritylevel Low

NamedPipeClient.exe

high integrity level:

open the command prompt in admin mode

icacls NamedPipeClient.exe /setintegritylevel High

NamedPipeClient.exe

Any help will be greatly appreciated!

Server code

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.IO.Pipes;

namespace NamedPipeServer
{
    class Program
    {
        static void Main(string[] args)
        {
            SafePipeHandle handle = LowIntegrityPipeFactory.CreateLowIntegrityNamedPipe("NamedPipe/Test");
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeDirection.InOut, true, false, handle);
            pipeServer.BeginWaitForConnection(HandleConnection, pipeServer);

            Console.WriteLine("Waiting...");
            Console.ReadLine();
        }

        private static void HandleConnection(IAsyncResult ar)
        {
            Console.WriteLine("Received connection");
        }
    }
}

LowIntegrityPipeFactory.cs

using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO.Pipes;
using System.ComponentModel;
using System.IO;
using System.Security.Principal;
using System.Security.AccessControl;

namespace NamedPipeServer
{
    static class LowIntegrityPipeFactory
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode,
            int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout,
            SECURITY_ATTRIBUTES securityAttributes);

        [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = false)]
        private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
            [In] string StringSecurityDescriptor,
            [In] uint StringSDRevision,
            [Out] out IntPtr SecurityDescriptor,
            [Out] out int SecurityDescriptorSize
        );

        [StructLayout(LayoutKind.Sequential)]
        private struct SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr lpSecurityDescriptor;
            public int bInheritHandle;
        }

        private const string LOW_INTEGRITY_SSL_SACL = "S:(ML;;NW;;;LW)";

        public static SafePipeHandle CreateLowIntegrityNamedPipe(string pipeName)
        {
            // convert the security descriptor
            IntPtr securityDescriptorPtr = IntPtr.Zero;
            int securityDescriptorSize = 0;
            bool result = ConvertStringSecurityDescriptorToSecurityDescriptor(
                LOW_INTEGRITY_SSL_SACL, 1, out securityDescriptorPtr, out securityDescriptorSize);
            if (!result)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES();
            securityAttributes.nLength = Marshal.SizeOf(securityAttributes);
            securityAttributes.bInheritHandle = 1;
            securityAttributes.lpSecurityDescriptor = securityDescriptorPtr;

            SafePipeHandle handle = CreateNamedPipe(@"\\.\pipe\" + pipeName,
                PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                0, 0, PipeAccessRights.ReadWrite, securityAttributes);
            if (handle.IsInvalid)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            return handle;
        }

        private static SafePipeHandle CreateNamedPipe(string fullPipeName, PipeDirection direction,
            int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options,
            int inBufferSize, int outBufferSize, PipeAccessRights rights, SECURITY_ATTRIBUTES secAttrs)
        {
            int openMode = (int)direction | (int)options;
            int pipeMode = 0;
            if (maxNumberOfServerInstances == -1)
                maxNumberOfServerInstances = 0xff;

            SafePipeHandle handle = CreateNamedPipe(fullPipeName, openMode, pipeMode,
                maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);
            if (handle.IsInvalid)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            return handle;
        }

    }
}

Client code

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;

namespace NamedPipeClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var pipeClient = new NamedPipeClientStream(".", "NamedPipe/Test",
                    PipeDirection.InOut,
                    PipeOptions.None);
                pipeClient.Connect(100);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: " + ex);
                return;
            }

            Console.WriteLine("Connected");
            Console.ReadLine();
        }
    }
}

Body:
Your code for setting the mandatory integrity label on the pipe achieves this successfully. However, because your security descriptor doesn't define a DACL, your pipe is being created with the default one.

It is the DACL which is causing the low integrity client to fail when trying to connect to the pipe created by your high integrity server.

You need to fix the DACL in the server before opening the listener. Rather than trying to construct the full descriptor using P/Invoke code before creating the pipe, which is pretty hard to get right, I'd suggest leveraging the System.IO.Pipes classes to do it in managed code as a separate step after the pipe is created, like this:

    // Fix up the DACL on the pipe before opening the listener instance
    // This won't disturb the SACL containing the mandatory integrity label
    NamedPipeServerStream handleForSecurity = null;
    try
    {
        handleForSecurity = new NamedPipeServerStream("NamedPipe/Test", PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null, System.IO.HandleInheritability.None, PipeAccessRights.ChangePermissions);
        PipeSecurity ps = handleForSecurity.GetAccessControl();
        PipeAccessRule aceClients = new PipeAccessRule(
            new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), // or some other group defining the allowed clients
            PipeAccessRights.ReadWrite,
            AccessControlType.Allow);
        PipeAccessRule aceOwner = new PipeAccessRule(
            WindowsIdentity.GetCurrent().Owner,
            PipeAccessRights.FullControl,
            AccessControlType.Allow);
        ps.AddAccessRule(aceClients);
        ps.AddAccessRule(aceOwner);
        handleForSecurity.SetAccessControl(ps);
    }
    finally
    {
        if (null != handleForSecurity) handleForSecurity.Close();
        handleForSecurity = null;
    }

This works for me, with the rest of your code unchanged.


答:
The cleanest way is probably to use a separate function, and string formatting.</p>

```<code>def print_weather(info):
    text = "{day}"
           " in {place}"
           " looks like {weather}"
           " with a high of {high}"
           " and a {rain}% of rain"

    text = text.format(day = info[3],
                       place = info[4],
                       weather = info[0],
                       high = info[1],
                       rain = info[2])

    print(text)
</code>```

Title: Is there a cleaner way to print this list of dictionaries?

Body:
The cleanest way is probably to use a separate function, and string formatting.

def print_weather(info):
    text = "{day}"
           " in {place}"
           " looks like {weather}"
           " with a high of {high}"
           " and a {rain}% of rain"

    text = text.format(day = info[3],
                       place = info[4],
                       weather = info[0],
                       high = info[1],
                       rain = info[2])

    print(text)


问:
How to set custom separator between items of ListView
Is there a way to use custom delegate as a separator between every two consecutive items of ListView just like header and footer properties?

Body:
I just added:

Text {
    text: "____________________________________________"
    color: "black"
}

To the end of my Item.


问:
quilt patch with a new file
I'm trying to create a new quilt patch with only one file added. Unfortunately the file seems to be ignored.

I did quilt new some_patch and quilt add some_file. I can see the file in quilt files then, but when I refresh, I get back:

```<code>Nothing in patch some_patch
</code>```

After I pop some_patch, the added file is not removed and nothing is actually saved into the patch (patch file is not created).

What am I doing wrong here?

答: You have to add the file to quilt first, before writing it. So that quilt can track the difference. If you add it after writing it, there is no change after that.</p>

Title: quilt patch with a new file

Body:
I'm trying to create a new quilt patch with only one file added. Unfortunately the file seems to be ignored.

I did quilt new some_patch and quilt add some_file. I can see the file in quilt files then, but when I refresh, I get back:

Nothing in patch some_patch

After I pop some_patch, the added file is not removed and nothing is actually saved into the patch (patch file is not created).

What am I doing wrong here?


答:
Your best and fastest way would be to sort the values either in ascending or descending order.

```<code>leftTable = leftTable.sort_values('Depth')
rightTable = rightTable.sort_values('Merge')
#reindex the data
leftTable = leftTable.reset_index(drop=True)
rightTable = rightTable.reset_index(drop=True)
</code>```

Now go for the merge with the index as parameter.

```<code>Table = leftTable.join(rightTable, how = "outer")
</code>```

The other alternative would be to go for an iteration method which will not only be time consuming but might also cause data loss.
If this was an ascending sorted datframe for left table(data modified for ease).

```<code>index Date_Time Depth
6659 4/25/2017 1:26 20
6660 4/25/2017 1:26 21
6661 4/25/2017 1:26 23
6662 4/25/2017 1:26 24
6663 4/25/2017 1:26 27
6664 4/25/2017 1:26 28
</code>```

And if this was an ascending sorted array for Right Table (Data Modified for ease)

```<code>index MeasuredDepth Inclination
16 1844 12
17 1939 20
18 2034 21
19 2128 23
20 2223 24
21 2317 27
</code>```

They are both of equal sizes. If we used a function to measure the difference between the Depth values of each row in both tables then clearly the row with Depth 12 on the Right Table will not be appended anywhere as the criterion set is "Minimum Distance"

If you are fine with the loss of data then you can try iterating over each row and finding the best match.

Title: Python Pandas Calc Column

Body:
I have two Pandas dataframes and I am trying to join the right table on the left table where Inclination closest matches the Left tables 'Depth' from the Right Tables 'MeasuredDepth'?

Example left table  (main table)

index     Date_Time         Depth
6659    4/25/2017 1:26       2073.02
6660    4/25/2017 1:26       2073.287
6661    4/25/2017 1:26       2073.916
6662    4/25/2017 1:26       2074.64
6663    4/25/2017 1:26       2075.335
6664    4/25/2017 1:26       2076.044

Example Right table (Reference table)

index   MeasuredDepth   Inclination
16      1844           1.42
17      1939           1.69
18      2034           1.43
19      2128           1.39
20      2223           1.12
21      2317           1.22
22      2412           1.1
23      2600           0.56
24      2695           1.97

Example Result Table

index   DATETIME        Depth        Inclination
6659    4/25/2017 1:26      2073.02          1.43
6660    4/25/2017 1:26      2073.287         1.43
6661    4/25/2017 1:26      2073.916         1.43
...
26704   5/3/2017 23:23      2625.316         0.56
26705   5/3/2017 23:23      2626.143         0.56
26706   5/3/2017 23:24       2627.08         0.56
26707   5/3/2017 23:24      2628.056         0.56

Any help would be appreciated!

Body:
Your best and fastest way would be to sort the values either in ascending or descending order.

leftTable = leftTable.sort_values('Depth')
rightTable = rightTable.sort_values('Merge')
#reindex the data
leftTable = leftTable.reset_index(drop=True)
rightTable = rightTable.reset_index(drop=True)

Now go for the merge with the index as parameter.

Table = leftTable.join(rightTable, how = "outer")

The other alternative would be to go for an iteration method which will not only be time consuming but might also cause data loss.
If this was an ascending sorted datframe for left table(data modified for ease).

index Date_Time Depth
6659 4/25/2017 1:26 20
6660 4/25/2017 1:26 21
6661 4/25/2017 1:26 23
6662 4/25/2017 1:26 24
6663 4/25/2017 1:26 27
6664 4/25/2017 1:26 28

And if this was an ascending sorted array for Right Table (Data Modified for ease)

index MeasuredDepth Inclination
16 1844 12
17 1939 20
18 2034 21
19 2128 23
20 2223 24
21 2317 27

They are both of equal sizes. If we used a function to measure the difference between the Depth values of each row in both tables then clearly the row with Depth 12 on the Right Table will not be appended anywhere as the criterion set is "Minimum Distance"

If you are fine with the loss of data then you can try iterating over each row and finding the best match.


问:
In clause in linq expression
i am developing a online test application where have two tables category and subCategory from which i want to select some questions with the help of category and subcategory. something like ( question where category ID in (1) and subcategoryID in (1,2,3,4)

I am getting list of subcategory that is going to pass in query

```<code>int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains("here all value in Subcategory"))
                      .Take(NoOfQuestions);
</code>```

or something like subcategoryID.contains("some value in array of integer")

can i get some help from anybody?

答:
You could use Contains as per https://blogs.msdn.microsoft.com/alexj/2009/03/25/tip-8-how-to-write-where-in-style-queries-using-linq-to-entities/ and Linq to Entities - SQL "IN" clause .

```<code>int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains(x.subcategoryID))
                      .Take(NoOfQuestions);
</code>```

This will generate an IN statement behind the scenes. You will want to ensure that the array is relatively small so you don't exhaust the SQL Server parameter limit.

Title: In clause in linq expression

Body:
i am developing a online test application where have two tables category and subCategory from which i want to select some questions with the help of category and subcategory. something like ( question where category ID in (1) and subcategoryID in (1,2,3,4)

I am getting list of subcategory that is going to pass in query

int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains("here all value in Subcategory"))
                      .Take(NoOfQuestions);

or something like subcategoryID.contains("some value in array of integer")

can i get some help from anybody?

Body:
You could use Contains as per https://blogs.msdn.microsoft.com/alexj/2009/03/25/tip-8-how-to-write-where-in-style-queries-using-linq-to-entities/ and Linq to Entities - SQL "IN" clause .

int[] subCategoryForQuestions=new int[]{1,2,3,4};

var TestDataList = coreDbContext.SolutionMasters
                       .Where(x => x.CategoryID == categoryID
                                   && x.DifficultyId == questionLevel
                                   && subCategoryForQuestions.Contains(x.subcategoryID))
                      .Take(NoOfQuestions);

This will generate an IN statement behind the scenes. You will want to ensure that the array is relatively small so you don't exhaust the SQL Server parameter limit.


问:
angular : How to export a service from a npm package
I have a service in my Angular 2 package I want to put on NPM with theses lines :

```<code>public showModal: Subject<any> = new Subject<any>();
public $showModal = this.showModal.asObservable();

public closeModal: Subject<any> = new Subject<any>();
public $closeModal = this.closeModal.asObservable();

public configModal: Subject<any> = new Subject<any>();
public $configModal = this.configModal.asObservable();
</code>```

Subject variables are used like this : myService.configModal(new ModalConfig());
Observables are used with a subscribe to update my component data, show it or hide it.

Here is my index.ts who export my class :

```<code>import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {ModalComponent} from "./lib/modal.component";
import {ModalService} from "./lib/modal.service";
@NgModule({
    imports: [CommonModule],
    declarations: [ModalComponent],
    providers: [ModalService],
    exports: [ModalComponent],
//  bootstrap: [ModalComponent]
})
export class ModalModule {}
</code>```

How can I access to ModalService in another app ? I want my service to be a singleton too, So I can't export it and provide the service in my component

答:
Some days later, I found the solution to my problem.  I just have to add an export statement :</p>

```<code>import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {ModalComponent} from "./lib/modal.component";
import {ModalService} from "./lib/modal.service";

export {ModalService} from "./lib/modal.service";

@NgModule({
    imports: [CommonModule],
    declarations: [ModalComponent],
    providers: [ModalService],
    exports: [ModalComponent],
//  bootstrap: [ModalComponent]
})
export class ModalModule {}
</code>```

Body:
I have a service in my Angular 2 package I want to put on NPM with theses lines :

public showModal: Subject<any> = new Subject<any>();
public $showModal = this.showModal.asObservable();

public closeModal: Subject<any> = new Subject<any>();
public $closeModal = this.closeModal.asObservable();

public configModal: Subject<any> = new Subject<any>();
public $configModal = this.configModal.asObservable();

Subject variables are used like this : myService.configModal(new ModalConfig());
Observables are used with a subscribe to update my component data, show it or hide it.

Here is my index.ts who export my class :

import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {ModalComponent} from "./lib/modal.component";
import {ModalService} from "./lib/modal.service";
@NgModule({
    imports: [CommonModule],
    declarations: [ModalComponent],
    providers: [ModalService],
    exports: [ModalComponent],
//  bootstrap: [ModalComponent]
})
export class ModalModule {}

How can I access to ModalService in another app ? I want my service to be a singleton too, So I can't export it and provide the service in my component

Body:
Some days later, I found the solution to my problem.  I just have to add an export statement :

import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {ModalComponent} from "./lib/modal.component";
import {ModalService} from "./lib/modal.service";

export {ModalService} from "./lib/modal.service";

@NgModule({
    imports: [CommonModule],
    declarations: [ModalComponent],
    providers: [ModalService],
    exports: [ModalComponent],
//  bootstrap: [ModalComponent]
})
export class ModalModule {}


问:
@PropertySource java.io.FileNotFoundException
I am testing Spring's @Conditional in which I load the bean depending on the value present in the .properties file. So I created a .properties file in src/main/resources/application-config.properties and I have the configuration class as:

```<code>@Configuration
@PropertySource(value = {"classpath:application-config.properties"}, ignoreResourceNotFound = false)
@ComponentScan(basePackages = {"com.app.test"})
public class ApplicationContextConfig {...}
</code>```

I have 2 Condition implementations as below:

```<code>public class ConditionalBeanOne implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String name= conditionContext.getEnvironment().getProperty("condition.name");
        return name.equalsIgnoreCase("condition_one");
    }
}

public class ConditionalBeanTwo implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String name= conditionContext.getEnvironment().getProperty("condition.name");
        return name.equalsIgnoreCase("condition_two");
    }
}
</code>```

I have respective POJO classes as:

```<code>@Component
@Conditional(value = ConditionalBeanOne.class)
public class BeanOne implements ServiceBean {}

@Component
@Conditional(value = ConditionalBeanTwo.class)
public class BeanTwo implements ServiceBean {}
</code>```

When I run the application, I get following exception:
Caused by: java.io.FileNotFoundException: class path resource [application-config.properties] cannot be opened because it does not exist

I am running this through main method as following:

```<code>public class ConditionalMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
        .....
    }
}
</code>```

答:
I couldn't reproduce your problem so I created a complete working example based on your use case, which is also available on my GitHub. I noticed that your conditions are really the same, only the values are different, so you don't really need to duplicate the code there. Other than that, it's pretty much what you did.

I'd say that you're reinventing the wheel here. Spring Boot already has a ConditionalOnProperty which does this.

Application.java:

```<code>public class Application {
    public static void main(String[] args) {
        try (AnnotationConfigApplicationContext applicationContext =
                     new AnnotationConfigApplicationContext(ApplicationConfig.class)) {

            ApplicationConfig.GreeterService greeterService =
                    applicationContext.getBean(ApplicationConfig.GreeterService.class);

            String actual = greeterService.greeting();

            System.out.printf("Greeting: %s.\n", actual);
        }
    }
}
</code>```

ApplicationConfig.java:

```<code>@Configuration
// The / doesn't matter, but I prefer being explicit
@PropertySource("classpath:/application.properties")
@ComponentScan
public class ApplicationConfig {

    @FunctionalInterface
    public static interface GreeterService {
        String greeting();
    }

    @Bean
    @ConditionalOnProperty("hello")
    public GreeterService helloService() {
        return () -> "hello";
    }

    @Bean
    @ConditionalOnProperty("hi")
    public GreeterService hiService() {
        return () -> "hi";
    }
}
</code>```

ConditionalOnProperty.java:

```<code>@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
    String value() default "";
}
</code>```

OnPropertyCondition.java:

```<code>public class OnPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Map<String, Object> attributes = annotatedTypeMetadata
                .getAnnotationAttributes(ConditionalOnProperty.class.getName());
        String value = (String) attributes.get("value");

        String name = conditionContext.getEnvironment().getProperty("greeting");

        return !isEmpty(name) && name.equalsIgnoreCase(value);
    }
}
</code>```

application.properties:

```<code>greeting=hello
</code>```

Run normally:

Output:

Greeting: hello.

Run with -Dgreeting=hi:

Output:

Greeting: hi.

Body:
I am testing Spring's @Conditional in which I load the bean depending on the value present in the .properties file. So I created a .properties file in src/main/resources/application-config.properties and I have the configuration class as:

@Configuration
@PropertySource(value = {"classpath:application-config.properties"}, ignoreResourceNotFound = false)
@ComponentScan(basePackages = {"com.app.test"})
public class ApplicationContextConfig {...}

I have 2 Condition implementations as below:

public class ConditionalBeanOne implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String name= conditionContext.getEnvironment().getProperty("condition.name");
        return name.equalsIgnoreCase("condition_one");
    }
}

public class ConditionalBeanTwo implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String name= conditionContext.getEnvironment().getProperty("condition.name");
        return name.equalsIgnoreCase("condition_two");
    }
}

I have respective POJO classes as:

@Component
@Conditional(value = ConditionalBeanOne.class)
public class BeanOne implements ServiceBean {}

@Component
@Conditional(value = ConditionalBeanTwo.class)
public class BeanTwo implements ServiceBean {}

When I run the application, I get following exception:
Caused by: java.io.FileNotFoundException: class path resource [application-config.properties] cannot be opened because it does not exist

I am running this through main method as following:

public class ConditionalMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
        .....
    }
}

Body:
I couldn't reproduce your problem so I created a complete working example based on your use case, which is also available on my GitHub. I noticed that your conditions are really the same, only the values are different, so you don't really need to duplicate the code there. Other than that, it's pretty much what you did.

I'd say that you're reinventing the wheel here. Spring Boot already has a ConditionalOnProperty which does this.

Application.java:

public class Application {
    public static void main(String[] args) {
        try (AnnotationConfigApplicationContext applicationContext =
                     new AnnotationConfigApplicationContext(ApplicationConfig.class)) {

            ApplicationConfig.GreeterService greeterService =
                    applicationContext.getBean(ApplicationConfig.GreeterService.class);

            String actual = greeterService.greeting();

            System.out.printf("Greeting: %s.\n", actual);
        }
    }
}

ApplicationConfig.java:

@Configuration
// The / doesn't matter, but I prefer being explicit
@PropertySource("classpath:/application.properties")
@ComponentScan
public class ApplicationConfig {

    @FunctionalInterface
    public static interface GreeterService {
        String greeting();
    }

    @Bean
    @ConditionalOnProperty("hello")
    public GreeterService helloService() {
        return () -> "hello";
    }

    @Bean
    @ConditionalOnProperty("hi")
    public GreeterService hiService() {
        return () -> "hi";
    }
}

ConditionalOnProperty.java:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
    String value() default "";
}

OnPropertyCondition.java:

public class OnPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Map<String, Object> attributes = annotatedTypeMetadata
                .getAnnotationAttributes(ConditionalOnProperty.class.getName());
        String value = (String) attributes.get("value");

        String name = conditionContext.getEnvironment().getProperty("greeting");

        return !isEmpty(name) && name.equalsIgnoreCase(value);
    }
}

application.properties:

greeting=hello

Run normally:

Output:

Greeting: hello.

Run with -Dgreeting=hi:

Output:

Greeting: hi.


问:
ASP.NET BoilerPlate: .Net core template - app service error
I am in the process of moving my app code from the .Net5 MVC/JQuery ASPNETZERO template to the new .Net core 1.1 MVC/JQuery template.
So far I have copied over my first few custom entities. Created a EF migration and applied the changes to my DB.
I then started building the first app service for one of my entities. I am copying over the code from my existing MVC template that is working without any issues.

```<code>      public async Task<PagedResultDto<ListValuesListDto>> GetListValues(GetListValuesInput input)
    {
        var query = from lv in _listvaluesRepository2.GetAll()
                    select new ListValuesListDto
                    {
                        Id = lv.Id,
                         ListName = lv.ListName,
                         ListText = lv.ListText
                    };
        query = query.WhereIf(!input.Filter.IsNullOrWhiteSpace(), lv => lv.ListName.Contains(input.Filter) || lv.ListText.Contains(input.Filter));
        var resultCount = await query.CountAsync();
        var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
        return new PagedResultDto<ListValuesListDto>(resultCount, results);
    }
</code>```

The method above is from my MVC template. When I place this into the .Net core solution, I keep getting the following build error.

CS0411    The type arguments for method 'Enumerable.OrderBy(IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly

The error is pointing to the "OrderBy" on this line of code:

```<code>      var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
</code>```

I am still very much learning the ABP template and EF. I cannot for the life of me figure out why the same code in the .Net core template does not work?

Any help that anyone can provide would be much appreciated!

答:
I just solved my own issue. I had to add the using statement for System.Linq.Dynamic.Core

Hope it helps someone else! :-)

Body:
I am in the process of moving my app code from the .Net5 MVC/JQuery ASPNETZERO template to the new .Net core 1.1 MVC/JQuery template.
So far I have copied over my first few custom entities. Created a EF migration and applied the changes to my DB.
I then started building the first app service for one of my entities. I am copying over the code from my existing MVC template that is working without any issues.

      public async Task<PagedResultDto<ListValuesListDto>> GetListValues(GetListValuesInput input)
    {
        var query = from lv in _listvaluesRepository2.GetAll()
                    select new ListValuesListDto
                    {
                        Id = lv.Id,
                         ListName = lv.ListName,
                         ListText = lv.ListText
                    };
        query = query.WhereIf(!input.Filter.IsNullOrWhiteSpace(), lv => lv.ListName.Contains(input.Filter) || lv.ListText.Contains(input.Filter));
        var resultCount = await query.CountAsync();
        var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
        return new PagedResultDto<ListValuesListDto>(resultCount, results);
    }

The method above is from my MVC template. When I place this into the .Net core solution, I keep getting the following build error.

CS0411    The type arguments for method 'Enumerable.OrderBy(IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly

The error is pointing to the "OrderBy" on this line of code:

      var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();

I am still very much learning the ABP template and EF. I cannot for the life of me figure out why the same code in the .Net core template does not work?

Any help that anyone can provide would be much appreciated!


问:
Displaying navigation properties in ngx-datatable
I have a table like this that displays data including several navigation properties :

```<code><table class="table afcstandings">
        <thead>
            <tr>
                <th>team</th>
                <th>coach</th>
                <th>w</th>
                <th>l</th>
                <th>t</th>
                <th>fa</th>
                <th>agst</th>
                <th>diff</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let standing of standingsAFCEast">
                <!-- property binding rather than interpolation-->
                <td>{{ standing.team.teamName }}</td>
                <td>{{ standing.team.coach.coachName }}</td>
                <td>{{ standing.won }}</td>
                <td>{{ standing.lost }}</td>
                <td>{{ standing.tied }}</td>
                <td>{{ standing.pointsFor }}</td>
                <td>{{ standing.pointsAgainst }}</td>
                <td>{{ standing.pointsDifference }}</td>
            </tr>
        </tbody>
    </table>
</code>```

Here is the data structure that is being read :

```<code> [{"team":{"teamId":22,"teamName":"Carolina Panthers","coach":{"coachId":61,"coachName":"J Smith"},"division":{"divisionId":2,"divisionName":"NFC West"},"headerImage":"","logoImage":"","hex":"","r":null,"g":null,"b":null},"won":2,"lost":1,"tied":0,"pointsFor":82,"pointsAgainst":62,"pointsDifference":20}]
</code>```

My question is, how do I display this data using ngx-datatable?  I have tested with 3 fields, teamName, coachName and won, and am able to display the won field, but not the others, as I am not sure how to drill down into the team object or the coach object.

```<code><ngx-datatable class="ngx-datatable" [rows]="standingsAFCEast">
    <ngx-datatable-column name="team.teamName" [width]="300"></ngx-datatable-column>
    <ngx-datatable-column name="team.coach.coachName"></ngx-datatable-column>
    <ngx-datatable-column name="won"></ngx-datatable-column>
</ngx-datatable>
</code>```

Any advice would be really appreciated!

答:
After looking at the basic examples, I made this work (Plunker here):

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
      <ngx-datatable
        [rows]="rows"
        [columns]="columns"
        [columnMode]="'force'"
        [headerHeight]="50"
        [footerHeight]="50"
        [rowHeight]="'auto'"
        [reorderable]="reorderable">
      </ngx-datatable>
    </div>
  `
})
export class AppComponent {

  standingsAFCEast = [{
    "team":{
      "teamId":22,
      "teamName":"Carolina Panthers",
      "coach":{
        "coachId":61,
        "coachName":"J Smith"
      },
      "division":{
        "divisionId":2,
        "divisionName":"NFC West"
      },
      "headerImage":"",
      "logoImage":"",
      "hex":"",
      "r":null,
      "g":null,
      "b":null
    },
    "won":2,
    "lost":1,
    "tied":0,
    "pointsFor":82,
    "pointsAgainst":62,
    "pointsDifference":20
  }]

  get rows () {
    return this.standingsAFCEast.map(standing => ({
      team: standing.team.teamName,
      coach: standing.team.coach.coachName,
      w: standing.won,
      l: standing.lost,
      t: standing.tied,
      fa: standing.pointsFor,
      agst: standing.pointsAgainst,
      diff: standing.pointsDifference
    }))

  }
  // columns = [{name:'team'}, {name:'coach'}, {name:'w'}, {name:'l'}, {name:'t'}, {name:'fa'}, {name:'agst'}, {name:'diff'}]
  columns = Object.keys(this.rows[0]).map(val => ({name: val}))
}
</code>```

Let me know if this helps!

Body:
I have a table like this that displays data including several navigation properties :

                team
                coach
                w
                l
                t
                fa
                agst
                diff

                {{ standing.team.teamName }}
                {{ standing.team.coach.coachName }}
                {{ standing.won }}
                {{ standing.lost }}
                {{ standing.tied }}
                {{ standing.pointsFor }}
                {{ standing.pointsAgainst }}
                {{ standing.pointsDifference }}

Here is the data structure that is being read :

 [{"team":{"teamId":22,"teamName":"Carolina Panthers","coach":{"coachId":61,"coachName":"J Smith"},"division":{"divisionId":2,"divisionName":"NFC West"},"headerImage":"","logoImage":"","hex":"","r":null,"g":null,"b":null},"won":2,"lost":1,"tied":0,"pointsFor":82,"pointsAgainst":62,"pointsDifference":20}]

My question is, how do I display this data using ngx-datatable?  I have tested with 3 fields, teamName, coachName and won, and am able to display the won field, but not the others, as I am not sure how to drill down into the team object or the coach object.

<ngx-datatable class="ngx-datatable" [rows]="standingsAFCEast">
    <ngx-datatable-column name="team.teamName" [width]="300"></ngx-datatable-column>
    <ngx-datatable-column name="team.coach.coachName"></ngx-datatable-column>
    <ngx-datatable-column name="won"></ngx-datatable-column>
</ngx-datatable>

Any advice would be really appreciated!

Body:
After looking at the basic examples, I made this work (Plunker here):

@Component({
  selector: 'my-app',
  template: `
    <div>
      <ngx-datatable
        [rows]="rows"
        [columns]="columns"
        [columnMode]="'force'"
        [headerHeight]="50"
        [footerHeight]="50"
        [rowHeight]="'auto'"
        [reorderable]="reorderable">
      </ngx-datatable>
    </div>
  `
})
export class AppComponent {

  standingsAFCEast = [{
    "team":{
      "teamId":22,
      "teamName":"Carolina Panthers",
      "coach":{
        "coachId":61,
        "coachName":"J Smith"
      },
      "division":{
        "divisionId":2,
        "divisionName":"NFC West"
      },
      "headerImage":"",
      "logoImage":"",
      "hex":"",
      "r":null,
      "g":null,
      "b":null
    },
    "won":2,
    "lost":1,
    "tied":0,
    "pointsFor":82,
    "pointsAgainst":62,
    "pointsDifference":20
  }]

  get rows () {
    return this.standingsAFCEast.map(standing => ({
      team: standing.team.teamName,
      coach: standing.team.coach.coachName,
      w: standing.won,
      l: standing.lost,
      t: standing.tied,
      fa: standing.pointsFor,
      agst: standing.pointsAgainst,
      diff: standing.pointsDifference
    }))

  }
  // columns = [{name:'team'}, {name:'coach'}, {name:'w'}, {name:'l'}, {name:'t'}, {name:'fa'}, {name:'agst'}, {name:'diff'}]
  columns = Object.keys(this.rows[0]).map(val => ({name: val}))
}

Let me know if this helps!


问:
How do I import files in Python?
I'm trying to use pytest to check a function—here is my code:

```<code># src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1
</code>```

How do I require in my src file so that I can test it with pytest? I have tried a few things:

```<code>1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')
</code>```

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

答:
First, you must check that src/ and tests/ are in the same directory, I checked the function importing return_self in return_self_test.py and this is how:

Testpy search for files with test_[prefix] so I recommend changing return_self_test.py to test_return_self.py

```<code># src/return_self.py
def return_self(n):
    return n

# tests/test_return_self.py
import return_self

def test_1():
    value = return_self.return_self(1)
    assert value == 1
</code>```

Finally, test in cmd (in the correct path) or Pycharm terminal with the following command:
py.test -v and voila! It's done (:

Title: How do I import files in Python?

Body:
I'm trying to use pytest to check a function—here is my code:

# src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1

How do I require in my src file so that I can test it with pytest? I have tried a few things:

1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

Body:
First, you must check that src/ and tests/ are in the same directory, I checked the function importing return_self in return_self_test.py and this is how:

Testpy search for files with test_[prefix] so I recommend changing return_self_test.py to test_return_self.py

# src/return_self.py
def return_self(n):
    return n

# tests/test_return_self.py
import return_self

def test_1():
    value = return_self.return_self(1)
    assert value == 1

Finally, test in cmd (in the correct path) or Pycharm terminal with the following command:
py.test -v and voila! It's done (:


答:
If you organize your data a little bit better, you can use str.format() with named fields, like {location}, which makes your code much more readable:

```<code>weather = [
    {'forecast': 'Overcast', 'high': 87, 'rain': 20, 'day': 'Saturday', 'location': 'Chamblee'},
    {'forecast': 'Rain', 'high': 80, 'rain': 25, 'day': 'Sunday', 'location': 'Marietta'},
    {'forecast': 'Sunny', 'high': 90, 'rain': 30, 'day': 'Monday', 'location': 'Atlanta'}
]

for item in weather:
    print("{day} in {location} looks like {forecast} with "
          "high of {high} and a {rain}% chance of rain.".format(**item))
</code>```

Produces:

```<code>Saturday in Chamblee looks like Overcast with high of 87 and a 20% chance of rain.
Sunday in Marietta looks like Rain with high of 80 and a 25% chance of rain.
Monday in Atlanta looks like Sunny with high of 90 and a 30% chance of rain.
</code>```

Body:
Is there a cleaner print statement for this, other than what I have?

weather = [{
    'day_1': ['Overcast', 87, 20, 'Saturday', 'Chamblee'],
    'day_2': ['Rain', 80, 25, 'Sunday', 'Marietta'],
    'day_3': ['Sunny', 90, 30, 'Monday', 'Atlanta']
}]

for item in weather:
    print(item['day_1'][3], 'in',
          item['day_1'][4],
          'looks like',
          item['day_1'][0],
          'with a high of',
          item['day_1'][1],
          'and a',
          item['day_1'][2],
          '% chance of rain.')

I need to run this sentence for each Day key.

Body:
If you organize your data a little bit better, you can use str.format() with named fields, like {location}, which makes your code much more readable:

weather = [
    {'forecast': 'Overcast', 'high': 87, 'rain': 20, 'day': 'Saturday', 'location': 'Chamblee'},
    {'forecast': 'Rain', 'high': 80, 'rain': 25, 'day': 'Sunday', 'location': 'Marietta'},
    {'forecast': 'Sunny', 'high': 90, 'rain': 30, 'day': 'Monday', 'location': 'Atlanta'}
]

for item in weather:
    print("{day} in {location} looks like {forecast} with "
          "high of {high} and a {rain}% chance of rain.".format(**item))

Produces:

Saturday in Chamblee looks like Overcast with high of 87 and a 20% chance of rain.
Sunday in Marietta looks like Rain with high of 80 and a 25% chance of rain.
Monday in Atlanta looks like Sunny with high of 90 and a 30% chance of rain.


问:
How to add a routing module to an existing module in angular CLI version 1.1.1?
I have created a module in using angular CLI and forget to add --routing while it's creation, now i want to add a routing module to it.

ng init --routing won't help in angular CLI version 1.1.1

答:
That's not a problem at all.

Just add the routing manually.

All that the --routing flag does, in addition to adding <router-outlet></router-outlet> in app.component.html, is add q RouterModule.forRoot() call in a separate module called AppRoutingModule, and include that module in the imports of AppModule.

So, in app.module.ts, it adds AppRoutingModule to the imports of your AppModule.

The AppRoutingModule is defined as app-routing.module.ts, which is created from this template.

It's very small that I'll copy it here:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    children: []
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

The {path: '', children:[]} is just a placeholder that you are expected to replace (I know because I added it to the source code). It just makes sure the router doesn't complain about the <router-outlet> when you don't have any routes.

So, back to the question, what should you do? Either copy the file to your project, to look just like the original CLI, and add AppRoutingModule to your AppModule's imports...

Or just add RouterModule.forRoot([/* routes here */]) to your AppModule's imports instead. It'll still work, with built-in support for lazy loading and everything else working just fine.

P.S.

Remember that to add child routes, you can always generate more modules with routing ng generate module Foo --routing regardless of whether you used the --routing flag with ng new or not. No configuration or any magic to worry about.

Body:
That's not a problem at all.

Just add the routing manually.

All that the --routing flag does, in addition to adding <router-outlet></router-outlet> in app.component.html, is add q RouterModule.forRoot() call in a separate module called AppRoutingModule, and include that module in the imports of AppModule.

So, in app.module.ts, it adds AppRoutingModule to the imports of your AppModule.

The AppRoutingModule is defined as app-routing.module.ts, which is created from this template.

It's very small that I'll copy it here:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    children: []
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The {path: '', children:[]} is just a placeholder that you are expected to replace (I know because I added it to the source code). It just makes sure the router doesn't complain about the <router-outlet> when you don't have any routes.

So, back to the question, what should you do? Either copy the file to your project, to look just like the original CLI, and add AppRoutingModule to your AppModule's imports...

Or just add RouterModule.forRoot([/* routes here */]) to your AppModule's imports instead. It'll still work, with built-in support for lazy loading and everything else working just fine.

P.S.

Remember that to add child routes, you can always generate more modules with routing ng generate module Foo --routing regardless of whether you used the --routing flag with ng new or not. No configuration or any magic to worry about.

ContentLicense: CC BY-SA 4.0


问:
Adding Google Custom Search to AMP site
I have my Google Custom Search Engine (GCSE) code:

```<code><script>
  (function() {
    var cx = '008589157460623253837:mhsjluzrngo';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
</code>```

However my Accelerated Mobile Pages (AMP) site does not allow me to add JavaScript to it, and I don't see any AMP components that allow for embedding GCSE into an AMP site.

How can I get GCSE on my site without breaking AMP compliance?

Thanks

答: You can try putting that code in a separate page then including that page in your AMP via the amp-iframe component. You will also have to abide by the constraints described here: https://www.ampproject.org/docs/reference/components/amp-iframe

Title: Adding Google Custom Search to AMP site

Body:
I have my Google Custom Search Engine (GCSE) code:

However my Accelerated Mobile Pages (AMP) site does not allow me to add JavaScript to it, and I don't see any AMP components that allow for embedding GCSE into an AMP site.

How can I get GCSE on my site without breaking AMP compliance?

Thanks


问:
How to call reloaddata() from another class?
I have two classes NSViewController, which contains a NSTableView, and a NSPageController, which can be used to add data to the table view. How can I call reloadData() from NSPageController to update the table view of NSViewController?

Update:

I already tried to solve this with a delegate and I already have done this in Objective-C, but with swift I feel completely lost.

My PageController needs to notify the ViewController, that the tableView has to be updated. So I added this code to my PageController

```<code>protocol PageControllerDelegate {
    func updateTableView()
}
</code>```

and

```<code>weak var delegate: PageControllerDelegate?
</code>```

To my ViewController which hold the table view I added the following lines:

```<code>class ViewController: NSViewController, PageControllerDelegate {
...
</code>```

and

```<code>func updateTableView() {
        self.tableView.reloadData()
}
</code>```

Xcode gives me the following errors:

'weak' may only be applied to class and class-bound protocol types, not 'PageControllerDelegate'

Property 'delegate' with type 'PageControllerDelegate?' cannot override a property with type 'NSPageControllerDelegate?' (aka 'Optional')

答:
I can give you only a generic answer.

First of all, you need a contact for your view controllers. Like NSTableViewController or something that you defined (a Protocol).

Example, when you using a table view controller:

```<code>(viewController as? NSTableViewController)?.tableView.reloadData()
</code>```

And an example, when you using a view controller with an contract:

The contact:

```<code>protocol HasTableView {
    var tableView: NSTableView? { get }
}
</code>```

The view controller conforming to the contract:

```<code>class ExampleViewController: NSViewController, HasTableView {
    var tableView: NSTableView? { return myTableView }
    ...
}
</code>```

And your reload data call:

```<code>(viewController as? HasTableView)?.tableView?.reloadData()
</code>```

Hope it’s helps.

Body:
I have two classes NSViewController, which contains a NSTableView, and a NSPageController, which can be used to add data to the table view. How can I call reloadData() from NSPageController to update the table view of NSViewController?

Update:

I already tried to solve this with a delegate and I already have done this in Objective-C, but with swift I feel completely lost.

My PageController needs to notify the ViewController, that the tableView has to be updated. So I added this code to my PageController

protocol PageControllerDelegate {
    func updateTableView()
}

and

weak var delegate: PageControllerDelegate?

To my ViewController which hold the table view I added the following lines:

class ViewController: NSViewController, PageControllerDelegate {
...

and

func updateTableView() {
        self.tableView.reloadData()
}

Xcode gives me the following errors:

'weak' may only be applied to class and class-bound protocol types, not 'PageControllerDelegate'

Property 'delegate' with type 'PageControllerDelegate?' cannot override a property with type 'NSPageControllerDelegate?' (aka 'Optional')

Body:
I can give you only a generic answer.

First of all, you need a contact for your view controllers. Like NSTableViewController or something that you defined (a Protocol).

Example, when you using a table view controller:

(viewController as? NSTableViewController)?.tableView.reloadData()

And an example, when you using a view controller with an contract:

The contact:

protocol HasTableView {
    var tableView: NSTableView? { get }
}

The view controller conforming to the contract:

class ExampleViewController: NSViewController, HasTableView {
    var tableView: NSTableView? { return myTableView }
    ...
}

And your reload data call:

(viewController as? HasTableView)?.tableView?.reloadData()

Hope it’s helps.


问:
How can I make this javascript stop when the last slide is shown
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }
</code>```

HTML code:

```<code><div class="links-to-wbp">
                    <div class="slide">
                        <a href="/physics/index.html"><img class="wbp" alt="thumb1" src="img/thumb1.png"/></a><a href="/francais/index.html"><img class="wbp" alt="thumb2" src="img/thumb2.png"/></a><a href="/strict/index.html"><img class="wbp" alt="thumb3" src="img/thumb3.png"/></a></div>
                <div class="slide">
                        <img class="wbp" alt="thumb4" src="img/thumb4.png"/><img class="wbp" alt="thumb5" src="img/thumb5.png"/><img class="wbp" alt="thumb6" src="img/thumb6.png"/></div>
                <div class="slide">
                        <img class="wbp" alt="thumb7" src="img/thumb7.png"/><img class="wbp" alt="thumb8" src="img/thumb8.png"/><img class="wbp" alt="thumb9" src="img/thumb9.png"/></div>
                     <div onclick="plusDivs(-1)" class="button previous_button"><</div>
                    <div onclick="plusDivs(+1)" class="button next_button">></div>
                </div>
</code>```

答:
I want to make this javascript stop when the last slide is shown, so
  that the next button won't work.

For that you can add a new if statement to your showDivs function

```<code>if (n > x.length) {slideIndex = x.length}
</code>```

so your showDivs function should look like this now:

```<code>function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n > x.length) {slideIndex = x.length}
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }
</code>```

but same with the previous button when the first slide is shown. For
  the previous button, when I press it and the slider is at the first
  slide I want it to stay to the current slide.

This should be already working because thats the purpose of the following statemnt in your showDiv function:

if (n < 1) {slideIndex = 1;}

Body:
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }

HTML code:

<

>

Body:
I want to make this javascript stop when the last slide is shown, so
  that the next button won't work.

For that you can add a new if statement to your showDivs function

if (n > x.length) {slideIndex = x.length}

so your showDivs function should look like this now:

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n > x.length) {slideIndex = x.length}
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }

but same with the previous button when the first slide is shown. For
  the previous button, when I press it and the slider is at the first
  slide I want it to stay to the current slide.

This should be already working because thats the purpose of the following statemnt in your showDiv function:

if (n < 1) {slideIndex = 1;}