问:
Why is my code never detecting any contact with my SKPhysicsBody?
The problem I am running in to is that the code I created to detect contact is not working. I wanted it to work when the ball category touched the obstacle category. What is wrong with my code? Thank you so much, any help is appreciated!

Heres where I define the categories:

```<code>let ballCategory : UInt32 = 0x1 << 1
let obstacleCategory : UInt32 = 0x1 << 2
</code>```

Heres where I create the physics aspect of my ball:

```<code>    leftBall.physicsBody = SKPhysicsBody(rectangleOf: leftBall.size)
    leftBall.physicsBody?.categoryBitMask = ballCategory
    leftBall.physicsBody?.contactTestBitMask = obstacleCategory
    leftBall.physicsBody?.affectedByGravity = false
    leftBall.physicsBody?.isDynamic = false
    leftBall.physicsBody?.collisionBitMask = 0
</code>```

Heres where I create the physics aspect of an obstacle:

```<code>    obstacleSquare.physicsBody = SKPhysicsBody(rectangleOf: obstacleSquare.size)
    obstacleSquare.physicsBody?.categoryBitMask = obstacleCategory
    obstacleSquare.physicsBody?.contactTestBitMask = ballCategory
    obstacleSquare.physicsBody?.affectedByGravity = false
    obstacleSquare.physicsBody?.isDynamic = false
    obstacleSquare.physicsBody?.collisionBitMask = 1
</code>```

And heres my collision detection function:

```<code>func didBegin(_ contact: SKPhysicsContact) {

    print("CONTACT")

    if contact.bodyA.categoryBitMask == obstacleCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyB.categoryBitMask == obstacleCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyA.categoryBitMask == ballCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyB.categoryBitMask == ballCategory {

        print("CONTACT")
        gameOver()

    }

}
</code>```

答: Both of your object’s physics bodies have their isDynamic Property set to false.  At least one of them needs to have this property set to true for any contacts to be registered.

Body:
The problem I am running in to is that the code I created to detect contact is not working. I wanted it to work when the ball category touched the obstacle category. What is wrong with my code? Thank you so much, any help is appreciated!

Heres where I define the categories:

let ballCategory : UInt32 = 0x1 << 1
let obstacleCategory : UInt32 = 0x1 << 2

Heres where I create the physics aspect of my ball:

    leftBall.physicsBody = SKPhysicsBody(rectangleOf: leftBall.size)
    leftBall.physicsBody?.categoryBitMask = ballCategory
    leftBall.physicsBody?.contactTestBitMask = obstacleCategory
    leftBall.physicsBody?.affectedByGravity = false
    leftBall.physicsBody?.isDynamic = false
    leftBall.physicsBody?.collisionBitMask = 0

Heres where I create the physics aspect of an obstacle:

    obstacleSquare.physicsBody = SKPhysicsBody(rectangleOf: obstacleSquare.size)
    obstacleSquare.physicsBody?.categoryBitMask = obstacleCategory
    obstacleSquare.physicsBody?.contactTestBitMask = ballCategory
    obstacleSquare.physicsBody?.affectedByGravity = false
    obstacleSquare.physicsBody?.isDynamic = false
    obstacleSquare.physicsBody?.collisionBitMask = 1

And heres my collision detection function:

func didBegin(_ contact: SKPhysicsContact) {

    print("CONTACT")

    if contact.bodyA.categoryBitMask == obstacleCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyB.categoryBitMask == obstacleCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyA.categoryBitMask == ballCategory {

        print("CONTACT")
        gameOver()

    }

    if contact.bodyB.categoryBitMask == ballCategory {

        print("CONTACT")
        gameOver()

    }

}


来源: stackexchange

问:
How to get rid of "RuntimeWarning: invalid value encountered in greater"
This question is very similar to a lot of questions related with the warning RuntimeWarning: invalid value encountered in greater/less/etc

However, I couldn't find a solution for my particular problem, and I think there should be one.

So, I have a numpy.ndarray similar to this one:

```<code>array([[ nan,   1.,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       ...,
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan]])
</code>```

I want to calculate array > 0.5, which gives exactly the result I want, but with the warning for being comparing with nan:

```<code>__main__:1: RuntimeWarning: invalid value encountered in greater
Out[68]:
array([[False,  True, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ...,
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], dtype=bool)
</code>```

I basically want to calculate array > 0.5, but without the warning showing up.

My restrictions:

I do NOT want to just suppress the warning with with np.errstate(invalid='ignore'):

I need to maintain the original array, thus I cannot change it.

I have come up with a simple solution:

Change the nan in the original matrix (array[np.isnan(array)] = -np.inf), recovering it back after I do my comparison (array[array == -np.inf] = np.nan)

But I think it is just a waste of time all these calculations when (I think) it should exist a direct way to do this at once. I have been exploring the numpy.ma module and the numpy.where function, but I couldn't find this "direct" solution which I want.

Any thoughts on this?

答:
You would have that warning whenever an array containing at least one NaN is compared. The solution would be to use masking to compare only the non-NaN elements and we would try to have a generic solution to cover all types of comparisons with the help of comparison based NumPy ufuncs, as shown below -

```<code>def compare_nan_array(func, a, thresh):
    out = ~np.isnan(a)
    out[out] = func(a[out] , thresh)
    return out
</code>```

The idea being :

Get the mask of non-NaNs.

Use that to get the non-NaN values from input array. Then perform the required comparison (greater than, greater than equal to, etc.) to get another mask, which represents the compared mask output for the masked places.

Use this to refine the mask of non-NaNs and this is the final output.

Sample run -

```<code>In [41]: np.random.seed(0)

In [42]: a = np.random.randint(0,9,(4,5)).astype(float)

In [43]: a.ravel()[np.random.choice(a.size, 16, replace=0)] = np.nan

In [44]: a
Out[44]:
array([[ nan,  nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,   4.,   7.],
       [ nan,  nan,  nan,   1.,  nan],
       [ nan,   7.,  nan,  nan,  nan]])

In [45]: a > 5  # Shows warning with the usual comparison
__main__:1: RuntimeWarning: invalid value encountered in greater
Out[45]:
array([[False, False, False, False, False],
       [False, False, False, False,  True],
       [False, False, False, False, False],
       [False,  True, False, False, False]], dtype=bool)

# With suggested masking based method
In [46]: compare_nan_array(np.greater, a, 5)
Out[46]:
array([[False, False, False, False, False],
       [False, False, False, False,  True],
       [False, False, False, False, False],
       [False,  True, False, False, False]], dtype=bool)
</code>```

Let's test out the generic behavior by testing for lesser than 5 -

```<code>In [47]: a < 5
__main__:1: RuntimeWarning: invalid value encountered in less
Out[47]:
array([[False, False, False, False, False],
       [False, False, False,  True, False],
       [False, False, False,  True, False],
       [False, False, False, False, False]], dtype=bool)

In [48]: compare_nan_array(np.less, a, 5)
Out[48]:
array([[False, False, False, False, False],
       [False, False, False,  True, False],
       [False, False, False,  True, False],
       [False, False, False, False, False]], dtype=bool)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This question is very similar to a lot of questions related with the warning RuntimeWarning: invalid value encountered in greater/less/etc

However, I couldn't find a solution for my particular problem, and I think there should be one.

So, I have a numpy.ndarray similar to this one:

array([[ nan,   1.,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       ...,
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan],
       [ nan,  nan,  nan, ...,  nan,  nan,  nan]])

I want to calculate array > 0.5, which gives exactly the result I want, but with the warning for being comparing with nan:

__main__:1: RuntimeWarning: invalid value encountered in greater
Out[68]:
array([[False,  True, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ...,
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], dtype=bool)

I basically want to calculate array > 0.5, but without the warning showing up.

My restrictions:

I do NOT want to just suppress the warning with with np.errstate(invalid='ignore'):

I need to maintain the original array, thus I cannot change it.

I have come up with a simple solution:

Change the nan in the original matrix (array[np.isnan(array)] = -np.inf), recovering it back after I do my comparison (array[array == -np.inf] = np.nan)

But I think it is just a waste of time all these calculations when (I think) it should exist a direct way to do this at once. I have been exploring the numpy.ma module and the numpy.where function, but I couldn't find this "direct" solution which I want.

Any thoughts on this?

Body:
You would have that warning whenever an array containing at least one NaN is compared. The solution would be to use masking to compare only the non-NaN elements and we would try to have a generic solution to cover all types of comparisons with the help of comparison based NumPy ufuncs, as shown below -

def compare_nan_array(func, a, thresh):
    out = ~np.isnan(a)
    out[out] = func(a[out] , thresh)
    return out

The idea being :

Get the mask of non-NaNs.

Use that to get the non-NaN values from input array. Then perform the required comparison (greater than, greater than equal to, etc.) to get another mask, which represents the compared mask output for the masked places.

Use this to refine the mask of non-NaNs and this is the final output.

Sample run -

In [41]: np.random.seed(0)

In [42]: a = np.random.randint(0,9,(4,5)).astype(float)

In [43]: a.ravel()[np.random.choice(a.size, 16, replace=0)] = np.nan

In [44]: a
Out[44]:
array([[ nan,  nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,   4.,   7.],
       [ nan,  nan,  nan,   1.,  nan],
       [ nan,   7.,  nan,  nan,  nan]])

In [45]: a > 5  # Shows warning with the usual comparison
__main__:1: RuntimeWarning: invalid value encountered in greater
Out[45]:
array([[False, False, False, False, False],
       [False, False, False, False,  True],
       [False, False, False, False, False],
       [False,  True, False, False, False]], dtype=bool)

# With suggested masking based method
In [46]: compare_nan_array(np.greater, a, 5)
Out[46]:
array([[False, False, False, False, False],
       [False, False, False, False,  True],
       [False, False, False, False, False],
       [False,  True, False, False, False]], dtype=bool)

Let's test out the generic behavior by testing for lesser than 5 -

In [47]: a < 5
__main__:1: RuntimeWarning: invalid value encountered in less
Out[47]:
array([[False, False, False, False, False],
       [False, False, False,  True, False],
       [False, False, False,  True, False],
       [False, False, False, False, False]], dtype=bool)

In [48]: compare_nan_array(np.less, a, 5)
Out[48]:
array([[False, False, False, False, False],
       [False, False, False,  True, False],
       [False, False, False,  True, False],
       [False, False, False, False, False]], dtype=bool)


问:
How can I build multiple projects in Ant with one build file?
Can I build multiple projects from one build-file. Example:

```<code><project basedir="." default="all" name="app1">
    ...
</project>

<project basedir="." default="all" name="app2">
    ...
</project>
</code>```

Currently I type ant -f build1.xml compile and it builds my application and I have to use two separate build files. Is there some way to get it running in a way that i have both the projects defined a common build-file and I can type something like ant app1 compile or ant app2 compile?

Here's what my build-file looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="azebooster" default="dist" basedir=".">

    <!-- Globals -->
    <property name="src" location="src/com/aelitis"/>
    <property name="build" location="build/azebooster"/>
    <property name="jar" location="jar/azebooster"/>
    <property name="resources" location="res/azebooster"/>

    <!-- Paths -->
    <path id="classpath">
        <fileset dir="." includes="**/*.jar"/>
    </path>

    <!-- Start it -->
    <target name="init">
      <tstamp/>
      <mkdir dir="${build}"/>
      <mkdir dir="${jar}"/>
    </target>

    <!-- Build it -->
    <target name="compile" depends="init" description="compile the source" >
        <javac srcdir="${src}" destdir="${build}">
            <classpath>
                <path refid="classpath"/>
            </classpath>
        </javac>
    </target>

    <!-- Jar it -->
    <target name="jar" depends="compile">
        <jar destfile="${jar}/${ant.project.name}.jar">
            <fileset dir="${build}"/>
            <fileset dir="${resources}" />
        </jar>
    </target>

    <!-- Clean it -->
    <target name="clean" description="clean up" >
        <tstamp/>
        <delete dir="${build}"/>
        <delete dir="${jar}"/>
    </target>

</project>
</code>```

Thank you.

答:
Yes you can create a default.build file (in this way you don't need to specify the file, because it's used by default). On it you can create the following targets:

```<code><target name="all" depends="app1, app2" />

<target name="app1">
    <ant antfile=<app1file> target="compile" />
</target>

<target name="app2">
    <ant antfile=<app2file> target="compile" />
</target>
</code>```

On this way you can use both ant file from one unique file.

And you can do all in only one file, if you replace the app1 and app2 targets, with the needed targets to compile them that you have in the separate files.

EDITED:

You have different ways to include both of them in only one file, maybe the easiest one is include a suffix for each project on each target. And you can call the specific project target or the target for both.

I put you an example with the compile target (and for init target too).

You can use compile for compile both projects (I call the other project other), and compileazeboster to compile the azeboster project.

You can search the common things to avoid the innecesary duplicated code (common paths, targets and so on)

```<code><property name="srcazebooster" location="src/com/aelitis"/>
<property name="buildazebooster" location="build/azebooster"/>
<property name="jarazebooster" location="jar/azebooster"/>
<property name="srcother" location="src/other"/>
<property name="buildother" location="build/other"/>
<property name="jarother" location="jar/other"/>

<!-- Start it -->
<target name="init" depends="initazebooster, initother"/>

<!-- Build it -->
<target name="compile" depends="compileazebooster, compileother" description="compile the source for all" />

<!-- Start azebooster-->
<target name="initazebooster">
    <tstamp/>
    <mkdir dir="${buildazebooster}"/>
    <mkdir dir="${jarazebooster}"/>
</target>

<!-- Build azeboster-->
<target name="compileazebooster" depends="initazebooster" description="compile the source for azebooster" >
    <javac srcdir="${srcazebooster}" destdir="${buildazebooster}">
        <classpath>
            <path refid="classpath"/>
        </classpath>
    </javac>
</target>

<!-- Start other-->
<target name="initother">
    <tstamp/>
    <mkdir dir="${buildotherr}"/>
    <mkdir dir="${jarother}"/>
</target>

<!-- Build other-->
<target name="compileother" depends="initother" description="compile the source for other" >
    <javac srcdir="${srcother}" destdir="${buildother}">
        <classpath>
            <path refid="classpath"/>
        </classpath>
    </javac>
</target>
</code>```

Body:
Can I build multiple projects from one build-file. Example:

<project basedir="." default="all" name="app1">
    ...
</project>

<project basedir="." default="all" name="app2">
    ...
</project>

Currently I type ant -f build1.xml compile and it builds my application and I have to use two separate build files. Is there some way to get it running in a way that i have both the projects defined a common build-file and I can type something like ant app1 compile or ant app2 compile?

Here's what my build-file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<project name="azebooster" default="dist" basedir=".">

    <property name="src" location="src/com/aelitis"/>
    <property name="build" location="build/azebooster"/>
    <property name="jar" location="jar/azebooster"/>
    <property name="resources" location="res/azebooster"/>

    <path id="classpath">
        <fileset dir="." includes="**/*.jar"/>
    </path>

    <target name="init">
      <tstamp/>
      <mkdir dir="${build}"/>
      <mkdir dir="${jar}"/>
    </target>

    <target name="compile" depends="init" description="compile the source" >
        <javac srcdir="${src}" destdir="${build}">
            <classpath>
                <path refid="classpath"/>
            </classpath>
        </javac>
    </target>

    <target name="jar" depends="compile">
        <jar destfile="${jar}/${ant.project.name}.jar">
            <fileset dir="${build}"/>
            <fileset dir="${resources}" />
        </jar>
    </target>

    <target name="clean" description="clean up" >
        <tstamp/>
        <delete dir="${build}"/>
        <delete dir="${jar}"/>
    </target>

</project>

Thank you.

Body:
Yes you can create a default.build file (in this way you don't need to specify the file, because it's used by default). On it you can create the following targets:

<target name="all" depends="app1, app2" />

<target name="app1">
    <ant antfile=<app1file> target="compile" />
</target>

<target name="app2">
    <ant antfile=<app2file> target="compile" />
</target>

On this way you can use both ant file from one unique file.

And you can do all in only one file, if you replace the app1 and app2 targets, with the needed targets to compile them that you have in the separate files.

EDITED:

You have different ways to include both of them in only one file, maybe the easiest one is include a suffix for each project on each target. And you can call the specific project target or the target for both.

I put you an example with the compile target (and for init target too).

You can use compile for compile both projects (I call the other project other), and compileazeboster to compile the azeboster project.

You can search the common things to avoid the innecesary duplicated code (common paths, targets and so on)

<property name="srcazebooster" location="src/com/aelitis"/>
<property name="buildazebooster" location="build/azebooster"/>
<property name="jarazebooster" location="jar/azebooster"/>
<property name="srcother" location="src/other"/>
<property name="buildother" location="build/other"/>
<property name="jarother" location="jar/other"/>

<!-- Start it -->
<target name="init" depends="initazebooster, initother"/>

<!-- Build it -->
<target name="compile" depends="compileazebooster, compileother" description="compile the source for all" />

<!-- Start azebooster-->
<target name="initazebooster">
    <tstamp/>
    <mkdir dir="${buildazebooster}"/>
    <mkdir dir="${jarazebooster}"/>
</target>

<!-- Build azeboster-->
<target name="compileazebooster" depends="initazebooster" description="compile the source for azebooster" >
    <javac srcdir="${srcazebooster}" destdir="${buildazebooster}">
        <classpath>
            <path refid="classpath"/>
        </classpath>
    </javac>
</target>

<!-- Start other-->
<target name="initother">
    <tstamp/>
    <mkdir dir="${buildotherr}"/>
    <mkdir dir="${jarother}"/>
</target>

<!-- Build other-->
<target name="compileother" depends="initother" description="compile the source for other" >
    <javac srcdir="${srcother}" destdir="${buildother}">
        <classpath>
            <path refid="classpath"/>
        </classpath>
    </javac>
</target>


问:
How is protobuf 3 singular different than optional
Looking at the proto3 reference:

https://developers.google.com/protocol-buffers/docs/proto3#simple

It says this about singular:

```<code>singular: a well-formed message can have zero or one of this field (but not more than one).
</code>```

It's not clear to me how this is different than optional. Is singular just an explicit way of stating that something is optional (which is now implicit for proto3)? Or is there something else this does that I'm missing?

Thanks.

答:
Optional is proto2 syntax. Singular is proto3 syntax.

In proto3, singular is the default rule. As today the documentation needs to be improved, and there's an open issue: google/protobuf#3457.

See also google/protobuf#2497 why messge type remove 'required,optional'?, and also haberman's comment on GoogleCloudPlatform/google-cloud-python#1402:

I think the question is: what are you trying to do? Why is it relevant
  to you whether a field is set or not and what do you intend to do with
  this information?

In proto3, field presence for scalar fields simply doesn't exist. Your
  mental model for proto3 should be that it's a C++ or Go struct. For
  integers and strings, there is no such thing as being set or not, it
  always has a value. For submessages, it's a pointer to the submessage
  instance which can be NULL, that's why you can test presence for it.

Body:
Looking at the proto3 reference:

https://developers.google.com/protocol-buffers/docs/proto3#simple

It says this about singular:

singular: a well-formed message can have zero or one of this field (but not more than one).

It's not clear to me how this is different than optional. Is singular just an explicit way of stating that something is optional (which is now implicit for proto3)? Or is there something else this does that I'm missing?

Thanks.


问:
Non-recursive depth first search algorithm
I am looking for a non-recursive depth first search algorithm for a non-binary tree. Any help is very much appreciated.</p>

答:
```<code>Stack<Node> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
    Node node = stack.pop();
    System.out.print(node.getData() + " ");

    Node right = node.getRight();
    if (right != null) {
        stack.push(right);
    }

    Node left = node.getLeft();
    if (left != null) {
        stack.push(left);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0


问:
Testing array elements vs multiple criteria
I am trying to create a method complex_check(n), which will do the following:

Create an array of integers ascending from 0 to n

Check each element of that array against complex criteria.

For example, I have an array from 0..n, and I want to know which elements of the array are both evenly divisible by 3 and not divisible by 4. I can index through to check for single criteria like odd?, etc., but is there a compact way to check each integer against multiple criteria?

答:
One of the things Ruby is very good at is processing through lists and other regular data structures. The Enumerable extensions common to many things including Array allow you to quickly filter, split, chunk, and otherwise completely rework the data you're dealing with. Often a few quick alterations can do the job.

In this case select can be used to filter out undesirable values from your potential candidates in the range 0 to n:

```<code> def complex_check(n)
   (0..n).select do |v|
      v % 3 == 0 and v % 4 != 0
   end
 end
</code>```

The key here is using select where any block that returns a logically true value will be a signal to include the element, and otherwise to exclude it. The opposite of this is reject which works on the same principle, just with inverted logic.

You could also pass these filters in dynamically:

```<code>def complex_check(n, *tests)
  tests.each_with_object((0..n).to_a) do |test, a|
    a.select!(&test)
  end
end
</code>```

Where your test code ends up looking like this:

```<code>complex_check(
  50,
  -> (v) { v % 3 == 0 },
  -> (v) { v % 4 != 0 }
)
</code>```

Then you can plug in tests using lambdas which are little reusable blocks.

Body:
One of the things Ruby is very good at is processing through lists and other regular data structures. The Enumerable extensions common to many things including Array allow you to quickly filter, split, chunk, and otherwise completely rework the data you're dealing with. Often a few quick alterations can do the job.

In this case select can be used to filter out undesirable values from your potential candidates in the range 0 to n:

 def complex_check(n)
   (0..n).select do |v|
      v % 3 == 0 and v % 4 != 0
   end
 end

The key here is using select where any block that returns a logically true value will be a signal to include the element, and otherwise to exclude it. The opposite of this is reject which works on the same principle, just with inverted logic.

You could also pass these filters in dynamically:

def complex_check(n, *tests)
  tests.each_with_object((0..n).to_a) do |test, a|
    a.select!(&test)
  end
end

Where your test code ends up looking like this:

complex_check(
  50,
  -> (v) { v % 3 == 0 },
  -> (v) { v % 4 != 0 }
)

Then you can plug in tests using lambdas which are little reusable blocks.


问:
How to use powershell to return all exchange distribution groups for a user
I'm trying to pull a list of Office365 distribution groups for a specific user using powershell.  The following works when I type out (or paste)the captured $DN for the user, but if I capture the $DN and use it as a variable, I cannot get the correct results.

This works:

```<code>$mailbox=get-Mailbox user@domain.com
$DN=$mailbox.DistinguishedName
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "CN=Lastname\, First M,OU=domain.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR02A003,DC=prod,DC=outlook,DC=com"}
</code>```

These do not:

```<code>$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like $DN}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like '$DN'}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "$DN"}
</code>```

Can anybody tell me how to get a variable for $DN to work in the script?

答:
Avshalom thanks for this awesome script.

I have added this to clean up the results.  Just replace "Domain" with your company's domain.

```<code>| Select-Object Name, @{label='PrimarySmtpAddress';expression={$_.PrimarySmtpAddress -replace '@domain.com'}}
</code>```

Note: the -filter {Members...} may be broken in the get-distributiongroup command.  Doesn't seem to accept Members as a filterable property.  :(

Body:
I'm trying to pull a list of Office365 distribution groups for a specific user using powershell.  The following works when I type out (or paste)the captured $DN for the user, but if I capture the $DN and use it as a variable, I cannot get the correct results.

This works:

$mailbox=get-Mailbox user@domain.com
$DN=$mailbox.DistinguishedName
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "CN=Lastname\, First M,OU=domain.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR02A003,DC=prod,DC=outlook,DC=com"}

These do not:

$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like $DN}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like '$DN'}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "$DN"}

Can anybody tell me how to get a variable for $DN to work in the script?

Body:
Avshalom thanks for this awesome script.

I have added this to clean up the results.  Just replace "Domain" with your company's domain.

| Select-Object Name, @{label='PrimarySmtpAddress';expression={$_.PrimarySmtpAddress -replace '@domain.com'}}

Note: the -filter {Members...} may be broken in the get-distributiongroup command.  Doesn't seem to accept Members as a filterable property.  :(


问:
submitting form to controller@store
laravel 5.5

 voyager 1.0

i'm trying to submit a form to a controller with :

```<code><form class="" action="FeedController@store" method="post">
    <div class="mui-textfield mui-textfield--float-label">
        <input id="title" type="text"  name="title" value="" required autofocus>
        <label for="title" class="col-md-4 control-label">title</label>
    </div>
    <div class="mui-textfield mui-textfield--float-label">
        <textarea id="description" type="textarea"  name="description" value="" required autofocus></textarea>
        <label for="description" class="col-md-4 control-label">description</label>
    </div>
    <input class="mui-btn btn-primary pull-right " type="submit" name="" value="submit">
</form>
</code>```

within FeedController:

```<code>/**
*@param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){

    $data = ReportDatum::create([
        'owner_id' => auth()->id(),
        'title' => request('title'),
        'description' => request('description')
    ]);
    return test;
}
</code>```

and in the routes:

```<code>Route::resource('feed', 'FeedController');
</code>```

(and/or depending on what I'm trying)

```<code> Route::post('store', 'FeedController@store');
</code>```

what I'm i missing to correctly submit the form?

  I'm not using laravelCollective forms

答:
You're missing the csrf_field(). Try adding it after the <form> tag.

Ref: https://laravel.com/docs/5.5/csrf

Title: submitting form to controller@store

Body:
laravel 5.5

 voyager 1.0

i'm trying to submit a form to a controller with :

<form class="" action="FeedController@store" method="post">

        <input id="title" type="text"  name="title" value="" required autofocus>
        title

        <textarea id="description" type="textarea"  name="description" value="" required autofocus></textarea>
        description

    <input class="mui-btn btn-primary pull-right " type="submit" name="" value="submit">
</form>

within FeedController:

/**
*@param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){

    $data = ReportDatum::create([
        'owner_id' => auth()->id(),
        'title' => request('title'),
        'description' => request('description')
    ]);
    return test;
}

and in the routes:

Route::resource('feed', 'FeedController');

(and/or depending on what I'm trying)

 Route::post('store', 'FeedController@store');

what I'm i missing to correctly submit the form?

  I'm not using laravelCollective forms


问:
check for the last space in a string?
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

```<code>finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr
</code>```

What I want to get is:

```<code>Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.
</code>```

However, this is the traceback I get, what am I doing wrong?

```<code>Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range
</code>```

答:
Since knowing where to break your line depends on how long a word is, you won't be able to do this by treating T as just a sequence of characters unless you want to backtrack (what if you're halfway through a word and you run out of space?).

I would instead split up T into a list of words and then just run through them:

```<code>lines = []
line = ''

for word in T.split(' '):
    if len(word) + len(line) <= L:
        # we can add the word onto the end of the current line
    else:
        # the word flows past the end of the current line, start a new one
</code>```

Note that your expected output doesn't wrap on column 30, it looks to wrap on column 25. Otherwise, line 3 would be 26 characters long and contain:

```<code>prosuere, risus non mollis
</code>```

An alternative solution would be to find the breaking point by using the limit arguments to str.rfind and just iteratively breaking down text using that:

```<code>while T:
    # If T is already short, we don't have to worry about breaking it up
    if len(T) <= L:
        line = T
        T = ''
    else:
        # Find the rightmost space in the T that occurs before column L
        furthest_space = T.rindex(' ', 0, L)

        # Now you can figure out the next line from the position of the
        # furthest space and cut that part off of your T
        ...

    print(line)
</code>```

Title: check for the last space in a string?

Body:
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr

What I want to get is:

Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.

However, this is the traceback I get, what am I doing wrong?

Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range

Body:
Since knowing where to break your line depends on how long a word is, you won't be able to do this by treating T as just a sequence of characters unless you want to backtrack (what if you're halfway through a word and you run out of space?).

I would instead split up T into a list of words and then just run through them:

lines = []
line = ''

for word in T.split(' '):
    if len(word) + len(line) <= L:
        # we can add the word onto the end of the current line
    else:
        # the word flows past the end of the current line, start a new one

Note that your expected output doesn't wrap on column 30, it looks to wrap on column 25. Otherwise, line 3 would be 26 characters long and contain:

prosuere, risus non mollis

An alternative solution would be to find the breaking point by using the limit arguments to str.rfind and just iteratively breaking down text using that:

while T:
    # If T is already short, we don't have to worry about breaking it up
    if len(T) <= L:
        line = T
        T = ''
    else:
        # Find the rightmost space in the T that occurs before column L
        furthest_space = T.rindex(' ', 0, L)

        # Now you can figure out the next line from the position of the
        # furthest space and cut that part off of your T
        ...

    print(line)


问:
DevPay and Mfa are mutually exclusive authorization methods
I'm trying to add MFA-deletion to my S3 bucket with the AWS-cli with the following command:

```<code>aws s3api put-bucket-versioning --bucket <my-bucket-name> --versioning-configuration '{"MFADelete":"Enabled","Status":"Enabled"}' --mfa 'arn:aws:iam::<code-found-at-iam-page>:mfa/root-account-mfa-device <my-google-authenticator-code>'
</code>```

but the response I get is this:

An error occurred (InvalidRequest) when calling the
  PutBucketVersioning operation: DevPay and Mfa are mutually exclusive
  authorization methods.

which makes no sense as I have never used DevPay. My security group for the instance has S3FullAccess enabled so that shouldn't be a problem either.

Any suggestions on what the problem might be would be appreciated.

答:
I submitted a case to AWS and they answer with this:

That error response typically gets returned when the API cannot
  perform the MFA Delete task due to the request being made with
  non-root credentials. The only way to turn on MFA Delete is to use the
  credentials from the root user of the account

Simple solution!

Body:
I'm trying to add MFA-deletion to my S3 bucket with the AWS-cli with the following command:

aws s3api put-bucket-versioning --bucket <my-bucket-name> --versioning-configuration '{"MFADelete":"Enabled","Status":"Enabled"}' --mfa 'arn:aws:iam:::mfa/root-account-mfa-device <my-google-authenticator-code>'

but the response I get is this:

An error occurred (InvalidRequest) when calling the
  PutBucketVersioning operation: DevPay and Mfa are mutually exclusive
  authorization methods.

which makes no sense as I have never used DevPay. My security group for the instance has S3FullAccess enabled so that shouldn't be a problem either.

Any suggestions on what the problem might be would be appreciated.


问:
Incorrect stacktrace by rethrow
I rethrow an exception with "throw;", but the stacktrace is incorrect:

```<code>static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}
</code>```

The right stacktrace should be:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12
</code>```

But I get:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15
</code>```

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

答:
There is a duplicate question here.

As I understand it - throw; is compiled into 'rethrow' MSIL instruction and it modifies the last frame of the stack-trace.

I would expect it to keep the original stack-trace and add the line where it has been re-thrown, but apparently there can only be one stack frame per method call.

Conclusion: avoid using throw; and wrap your exception in a new one on re-throwing - it's not ugly, it's best practice.

Title: Incorrect stacktrace by rethrow

Body:
I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}

The right stacktrace should be:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

ContentLicense: CC BY-SA 2.5


问:
How do I assign a conditional variable without mutation?
I am adhering to strict functional programming principles with no mutation.

How can I write something like the below code in a way that doesn't mutate the greeting variable, and without returning it within each if block?

```<code>const greet = (name, time) => {
  let greeting = 'Morning';

  if(time >= 12) {
    greeting = 'Afternoon';
  }
  if(time >= 17) {
    greeting = 'Evening';
  }

  return `Good ${greeting} ${name}!`;
};
</code>```

If it was just two conditions I would do the following, but it won't work when there are 3 conditions:

```<code>const greeting = time > 12 ? 'Afternoon' : 'Morning'
</code>```

答:
To be clear you are not doing any mutation, you are using let instead of const. Why it is not a mutation - because string is immutable in javascript. So your question is more - "How assign conditional value to const".

To be clear I don't see anything wrong with doing let here and such behavior. Until this not goes outside the function scope it is just fine to mutate it (I am talking more about general approach, for example with objects).

Immutability rule should be used for structures declared outside the scope of the function. What directly means that you should never mutate function input and never touch what not belongs to you.

To the point, my answer is - leave it as it is, for me it is much more clear than ternary operator with many conditions.

Body:
I am adhering to strict functional programming principles with no mutation.

How can I write something like the below code in a way that doesn't mutate the greeting variable, and without returning it within each if block?

const greet = (name, time) => {
  let greeting = 'Morning';

  if(time >= 12) {
    greeting = 'Afternoon';
  }
  if(time >= 17) {
    greeting = 'Evening';
  }

  return `Good ${greeting} ${name}!`;
};

If it was just two conditions I would do the following, but it won't work when there are 3 conditions:

const greeting = time > 12 ? 'Afternoon' : 'Morning'


问:
InvalidUseOfMatchersException: not using any raw values
I don't know what's causing this issue, but it throws an InvalidUseOfMatchersException.

```<code>This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.
</code>```

The code that causes the exception is below.

```<code>when(EventHandlingForFileUpload.onUploadEvent(any(CustomBatchFile.class))).thenReturn(SomeCustomEvents);
</code>```

答:
I was also not using any raw values but got "InvalidUseOfMatchersException"

I had something like

```<code>when(service.getResolver(eq(document.getId()), anyString())).thenReturn(aResolver);
</code>```

and it was throwing the exception. "document" is a mock

After I changed it to ...

```<code>when(service.getResolver(eq(docId), anyString())).thenReturn(aResolver);
</code>```

... it worked (i.e. I moved out the method call getId())

Body:
I don't know what's causing this issue, but it throws an InvalidUseOfMatchersException.

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

The code that causes the exception is below.

when(EventHandlingForFileUpload.onUploadEvent(any(CustomBatchFile.class))).thenReturn(SomeCustomEvents);

Body:
I was also not using any raw values but got "InvalidUseOfMatchersException"

I had something like

when(service.getResolver(eq(document.getId()), anyString())).thenReturn(aResolver);

and it was throwing the exception. "document" is a mock

After I changed it to ...

when(service.getResolver(eq(docId), anyString())).thenReturn(aResolver);

... it worked (i.e. I moved out the method call getId())


问:
Trying to profile CodeIgniter Application but can't get report
I have tried to include $this->output->enable_profiler(true); in my controller as per the official documentation. I've added the line of code under parent::__construct(); in my constructor, but the webpage doesn't load.

UPDATED

This is withing my constructor:

```<code>parent::__construct();
        $this->output->enable_profiler(true);
        $sections = array(
            'config' => FALSE,
            'queries' => TRUE,
            'post' => FALSE,
            'memory_usage' => TRUE,
            'get' => FALSE,
            'benchmarks' => TRUE,
            'controller_info' => FALSE,
            'url_string' => FALSE,
        );
        $this->output->set_profiler_sections($sections);
</code>```

答:
It might just be a copy/paste error but you have

```<code>$this-output-set_profiler_sections($sections);
</code>```

When you should have:

```<code>$this->output->set_profiler_sections($sections);
</code>```

Body:
I have tried to include $this->output->enable_profiler(true); in my controller as per the official documentation. I've added the line of code under parent::__construct(); in my constructor, but the webpage doesn't load.

UPDATED

This is withing my constructor:

parent::__construct();
        $this->output->enable_profiler(true);
        $sections = array(
            'config' => FALSE,
            'queries' => TRUE,
            'post' => FALSE,
            'memory_usage' => TRUE,
            'get' => FALSE,
            'benchmarks' => TRUE,
            'controller_info' => FALSE,
            'url_string' => FALSE,
        );
        $this->output->set_profiler_sections($sections);

Body:
It might just be a copy/paste error but you have

$this-output-set_profiler_sections($sections);

When you should have:

$this->output->set_profiler_sections($sections);


问:
Convert json to html table output in javascript/JQuery
I get the JSON output on the UI using the below function

```<code>$("#idvar").click(function(){
  var d1 = document.getElementById("dText");
  var d2 = document.getElementById("dJson");
  var mytext = d1.textContent;
  alert(mytext);
  $.post(
    url,
    {doc: mytext},
    function(data) {
      console.log(Object.keys(data).length);
      d2.textContent = data;
    }
  );
});
</code>```

where d1 is the displaying the uploaded input document, d2 for the output generated from processing the document on a model.  Currently, I am getting json format.  I tried to implement the codes in these posts (Parsing JSON objects for HTML table, Convert json data to a html table), but I get [object, Object] in the text area.  Is there a way to convert the json to table.

In the URL text area i get

```<code> [{"tag":"a1","relevance":0.5},
  {"tag":"a2","relevance":0.3},
  {"tag":"c3","relevance":0.2},{"tag":"d3,
   ...
</code>```

Instead, I was hoping to get

enter image description here

答:
You should traverse the data and print it in table format. First, make sure the element with id dJson is a
 element. Then, you can change your success callback to something like:

```<code>function(data) {
  console.log(Object.keys(data).length);
  var html = '<tr><th>Tag</th><th>Relevance</th></tr>';
  for(var i=0; i<data.length; i++){
    html +=
      '<tr>' +
        '<td>' +
          data[i].tag +
        '</td>' +
        '<td>' +
          data[i].relevance +
        '</td>' +
      '</tr>'
    ;
  }
  d2.innerHTML = html;
}
</code>```

Here you have a working example (without the $.post call): https://jsfiddle.net/cLbqmwa4/

Body:
I get the JSON output on the UI using the below function

$("#idvar").click(function(){
  var d1 = document.getElementById("dText");
  var d2 = document.getElementById("dJson");
  var mytext = d1.textContent;
  alert(mytext);
  $.post(
    url,
    {doc: mytext},
    function(data) {
      console.log(Object.keys(data).length);
      d2.textContent = data;
    }
  );
});

where d1 is the displaying the uploaded input document, d2 for the output generated from processing the document on a model.  Currently, I am getting json format.  I tried to implement the codes in these posts (Parsing JSON objects for HTML table, Convert json data to a html table), but I get [object, Object] in the text area.  Is there a way to convert the json to table.

In the URL text area i get

 [{"tag":"a1","relevance":0.5},
  {"tag":"a2","relevance":0.3},
  {"tag":"c3","relevance":0.2},{"tag":"d3,
   ...

Instead, I was hoping to get

enter image description here

Body:
You should traverse the data and print it in table format. First, make sure the element with id dJson is a <table> element. Then, you can change your success callback to something like:

function(data) {
  console.log(Object.keys(data).length);
  var html = '<tr><th>Tag</th><th>Relevance</th></tr>';
  for(var i=0; i<data.length; i++){
    html +=
      '<tr>' +
        '<td>' +
          data[i].tag +
        '</td>' +
        '<td>' +
          data[i].relevance +
        '</td>' +
      '</tr>'
    ;
  }
  d2.innerHTML = html;
}

Here you have a working example (without the $.post call): https://jsfiddle.net/cLbqmwa4/


答: Same error here. I've commented the line \Greazy\Http\Middleware\VerifyCsrfToken::class which stays in app/Http/Kernel.php and the post method worked in Postman, however it does not work when invoked on the form.

Title: submitting form to controller@store


问:
aws-sdk-go s3 move directory between bucket
I would like to know how can I move a directory inside the same bucket.
I didn't had any problem to move one specific file inside the same bucket with CopyObject but not a directory

This is the error I have after running the code below.

Unable to copy item from bucket "bucketName" to bucket "bucketName", NoSuchKey: The specified key does not exist.

dir := "newPlace/directory"
source := bucket + "/directory"

// Copy the item
_, err = svc.CopyObject(&s3.CopyObjectInput{Bucket: aws.String(bucket), CopySource: aws.String(source), Key: aws.String(dir)})
if err != nil {
    exitErrorf("Unable to copy item from bucket %q to bucket %q, %v", bucket, bucket, err)
}

//Wait to see if the item got copied
err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(dir)})
if err != nil {
    exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v", bucket, item, bucket, err)
}

fmt.Printf("Item %q successfully copied from bucket %q to bucket %q\n", item, bucket, bucket)
```

My last solution was to COPY + DELETE each file from my directory but I am surprised that they didn't implement a move directory in the SDK and the mv is also available in the aws-cli-s3

Thanks in advance,

答: The SDK does have support for batch operation. This should allow you to use the batch download iterator and write your own iterator for upload</p>

Body:
I would like to know how can I move a directory inside the same bucket.
I didn't had any problem to move one specific file inside the same bucket with CopyObject but not a directory

This is the error I have after running the code below.

Unable to copy item from bucket "bucketName" to bucket "bucketName", NoSuchKey: The specified key does not exist.

dir := "newPlace/directory"
source := bucket + "/directory"

// Copy the item
_, err = svc.CopyObject(&s3.CopyObjectInput{Bucket: aws.String(bucket), CopySource: aws.String(source), Key: aws.String(dir)})
if err != nil {
    exitErrorf("Unable to copy item from bucket %q to bucket %q, %v", bucket, bucket, err)
}

//Wait to see if the item got copied
err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(dir)})
if err != nil {
    exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v", bucket, item, bucket, err)
}

fmt.Printf("Item %q successfully copied from bucket %q to bucket %q\n", item, bucket, bucket)

My last solution was to COPY + DELETE each file from my directory but I am surprised that they didn't implement a move directory in the SDK and the mv is also available in the aws-cli-s3

Thanks in advance,


问:
Notification (FCM) function events
I'm using Firebase for sending notifications to my app users from the console. Every time I send a notification, I want to store the data in the realtime-database and also I want to log who sent the notification from the console.
So far, the only viable way I found to get the publish notification event is:

```<code>exports.news2db = functions.pubsub.topic('news').onPublish(event => {
    ...
});
</code>```

However, this only applies when I send a notification to a specific topic. I would like to get an event that is triggered every time ANY notification is sent to the console, not only topics. By this, I mean notifications sent to all app users, to single users, etc.. Is there any way to do that?

The second problem I have is to figure out which user configured and sent the notification to the console so I can log that info. What's the best attempt to do this?

```<code>admin.auth(). ???
</code>```

答: I was wrong about pubsub events.. they are not for notifications. So yeah, there is no way to get an event when a notification is sent from the console.</p>

Title: Notification (FCM) function events

Body:
I'm using Firebase for sending notifications to my app users from the console. Every time I send a notification, I want to store the data in the realtime-database and also I want to log who sent the notification from the console.
So far, the only viable way I found to get the publish notification event is:

exports.news2db = functions.pubsub.topic('news').onPublish(event => {
    ...
});

However, this only applies when I send a notification to a specific topic. I would like to get an event that is triggered every time ANY notification is sent to the console, not only topics. By this, I mean notifications sent to all app users, to single users, etc.. Is there any way to do that?

The second problem I have is to figure out which user configured and sent the notification to the console so I can log that info. What's the best attempt to do this?

admin.auth(). ???


问:
Cross-validation in LightGBM
How are we supposed to use the dictionary output from lightgbm.cv to improve our predictions?

Here's an example - we train our cv model using the code below:

```<code>cv_mod = lgb.cv(params,
                d_train,
                500,
                nfold = 10,
                early_stopping_rounds = 25,
                stratified = True)
</code>```

How can we use the parameters found from the best iteration of the above code to predict an output? In this case, cv_mod has no "predict" method like lightgbm.train, and the dictionary output from lightgbm.cvthrows an error when used in lightgbm.train.predict(..., pred_parameters = cv_mod).

Am I missing an important transformation step?

答:
You should use CV for parameter optimization.

If your model performs well on all folds use these parameters to train on the whole training set.
Then evaluate that model on the external test set.

Title: Cross-validation in LightGBM

Body:
How are we supposed to use the dictionary output from lightgbm.cv to improve our predictions?

Here's an example - we train our cv model using the code below:

cv_mod = lgb.cv(params,
                d_train,
                500,
                nfold = 10,
                early_stopping_rounds = 25,
                stratified = True)

How can we use the parameters found from the best iteration of the above code to predict an output? In this case, cv_mod has no "predict" method like lightgbm.train, and the dictionary output from lightgbm.cvthrows an error when used in lightgbm.train.predict(..., pred_parameters = cv_mod).

Am I missing an important transformation step?


问:
Convert monitor resolution to rows and cols?
Convert monitor resolution to rows and cols . </p>

<p>The follow code is what i have thus far </p>

```<code>python << EOF
import subprocess
import sys
results = subprocess.Popen(['xrandr'],stdout=subprocess.PIPE).communicate()[0].split("current")[1].split(",")[0]
width = results.split("x")[0].strip()
height = results.split("x")[1].strip()
print width + "x" + height

row = width
col = height
sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=row, cols=col))

print """
      TEST
      """
EOF
</code>```

答:
Since you're using the dtterm window manipulation controls (see XTerm Control Sequences), the terminal may implement the corresponding reports.  This section has the information:

```<code>CSI Ps ; Ps ; Ps t
          Window manipulation (from dtterm, as well as extensions).
          These controls may be disabled using the allowWindowOps
          resource.  Valid values for the first (and any additional
          parameters) are:
</code>```

This is relevant:

```<code>        Ps = 1 4  -> Report xterm window in pixels.
      Result is CSI  4  ;  height ;  width t
</code>```

That is, you could obtain the size of the window in pixels using that control sequence, and from knowing the window's rows/columns, you could compute the font-size.  Given that information (and the monitor's size), you can determine the number of character rows and columns which would fit.

Body:
Convert monitor resolution to rows and cols .

The follow code is what i have thus far

python << EOF
import subprocess
import sys
results = subprocess.Popen(['xrandr'],stdout=subprocess.PIPE).communicate()[0].split("current")[1].split(",")[0]
width = results.split("x")[0].strip()
height = results.split("x")[1].strip()
print width + "x" + height

row = width
col = height
sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=row, cols=col))

print """
      TEST
      """
EOF

Body:
Since you're using the dtterm window manipulation controls (see XTerm Control Sequences), the terminal may implement the corresponding reports.  This section has the information:

CSI Ps ; Ps ; Ps t
          Window manipulation (from dtterm, as well as extensions).
          These controls may be disabled using the allowWindowOps
          resource.  Valid values for the first (and any additional
          parameters) are:

This is relevant:

        Ps = 1 4  -> Report xterm window in pixels.
      Result is CSI  4  ;  height ;  width t

That is, you could obtain the size of the window in pixels using that control sequence, and from knowing the window's rows/columns, you could compute the font-size.  Given that information (and the monitor's size), you can determine the number of character rows and columns which would fit.


问:
Accents with python
I would like to know how to keep the accents in python, and if we could explain to myself a little about how it works, I spend hours searching. I still do not understand anything x)

Example 1:

```<code>text = "Danay Suarèz hablé"
print(text)
</code>```

output:

```<code>Danay Suar▒z habl▒
</code>```

Example 2:

```<code>print(text.encode('utf-8'))
</code>```

output:

```<code> b'Danay Suar\xc3\xa8z habl\xc3\xa9'
</code>```

I would like just output: Danay Suarèz hablé

答:
Try This :

```<code>import sys
def sys_out(out_data):
    try:
        print(out_data)  # or change this line to sys.stdout.write(out_data)
    except UnicodeEncodeError:
        if sys.version_info >= (3,):
            print(out_data.encode('utf8').decode(sys.stdout.encoding))
        else:
            print(out_data.encode('utf8'))

sys_out("Danay Suarèz hablé")
</code>```

NOTE : but generally, It depends on your text viewer.... whether it supports other encodings ( such as utf-8 ) or not.

Good Luck ...

Title: Accents with python

Body:
I would like to know how to keep the accents in python, and if we could explain to myself a little about how it works, I spend hours searching. I still do not understand anything x)

Example 1:

text = "Danay Suarèz hablé"
print(text)

output:

Danay Suar▒z habl▒

Example 2:

print(text.encode('utf-8'))

output:

 b'Danay Suar\xc3\xa8z habl\xc3\xa9'

I would like just output: Danay Suarèz hablé

Body:
Try This :

import sys
def sys_out(out_data):
    try:
        print(out_data)  # or change this line to sys.stdout.write(out_data)
    except UnicodeEncodeError:
        if sys.version_info >= (3,):
            print(out_data.encode('utf8').decode(sys.stdout.encoding))
        else:
            print(out_data.encode('utf8'))

sys_out("Danay Suarèz hablé")

NOTE : but generally, It depends on your text viewer.... whether it supports other encodings ( such as utf-8 ) or not.

Good Luck ...


问:
Taking Screenshot using Selenium 3.6 - Java - Webdriver
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
</code>```

Unfortunately the "copyFile" gives the following error:

```<code>The method copyFile(File, File) is undefined for the type FileUtils
</code>```

I have also imported all the required packages.

Can anyone help me to take screenshot?

答:
Try

```<code>String capture = "window.png";

    try {

        Thread.sleep(3000);

        byte screenshot[] = (byte[])((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);

    FileOutputStream fos = new FileOutputStream(capture);
                fos.write(screenshot);

        }catch (Exception){ }
</code>```

This works for me correct .

Body:
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Unfortunately the "copyFile" gives the following error:

The method copyFile(File, File) is undefined for the type FileUtils

I have also imported all the required packages.

Can anyone help me to take screenshot?

Body:
Try

String capture = "window.png";

    try {

        Thread.sleep(3000);

        byte screenshot[] = (byte[])((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);

    FileOutputStream fos = new FileOutputStream(capture);
                fos.write(screenshot);

        }catch (Exception){ }

This works for me correct .


问:
Awkward spacing between 2 column list items
I have a list of ingredients in a two-column layout, using flex-box. When an ingredient is long enough to cause the text to break to a second line, it causes awkward vertical spacing between the list items in the adjacent column. Before using flex-box, I tried using making the list items inline-blocks and floated them.

Here's what it looks like on my website:

Here's what my code looks like:

.field-items {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.field-item {
  width: 50%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field-items">
  <div class="field-item even">
    8 ounces sugar snap peas, stringed </div>
  <div class="field-item odd">
    12 grape tomatoes, halved </div>
  <div class="field-item even">2 tablespoons sliced almonds</div>
  <div class="field-item odd">2 tablespoons extra-virgin olive, walnut, or almond oil</div>
  <div class="field-item even">
    2 tablespoons fruity vinegar, such as raspberry or pomegranate </div>
  <div class="field-item odd">
    ¼ teaspoon salt </div>
  <div class="field-item even">
    1/8 teaspoon freshly ground pepper </div>
  <div class="field-item odd">
    4 cups packed mixed baby lettuce </div>
  <div class="field-item even">
    ¼ cup snipped fresh chives (½-inch pieces) </div>
  <div class="field-item odd">
    ¼ cup chopped fresh tarragon </div>
</div></code>```

See it in action: https://jsfiddle.net/4t4pd3tt/2/

My goal is to have even spacing between all of the list elements. I'm sure this question has already been answered before, but I wasn't able to find what I was looking for in my initial search.

答:
I've been in a similar position where I tried to do this with flex. I spent a long, long time on it and eventually found out that there is no nice way of doing it. My suggestion would be to go back to the trusty (read: awkward and annoying) float.

You just need to clean up your CSS a little and you can float the odd elements to the left and the even elements to the right (or the other way, if you so wish, but that would be kinda stupid, so I wouldn't advise doing that.

```<code>.field-item {
  width: 50%;
}

.field-item.odd {
  float: left;
}

.field-item.even {
  float: right;
}
</code>```

For this, you can remove all the rules from .field-items in your CSS.

An obvious issue here is that you need to continue to add odd and even classes to the div tags, which could easily cause a bug if you do it wrong.

I hope this helps!

EDIT

As Jonathan Nicol pointed out, you can also use nth-child(odd|even) to achieve the same thing, without the need for specific classes (rendering my note above redundant.

```<code>.field-item {
  width: 50%;
}

.field-item:nth-child(odd) {
  float: left;
}

.field-item:nth-child(even) {
  float: right;
}
</code>```

Body:
I have a list of ingredients in a two-column layout, using flex-box. When an ingredient is long enough to cause the text to break to a second line, it causes awkward vertical spacing between the list items in the adjacent column. Before using flex-box, I tried using making the list items inline-blocks and floated them.

Here's what it looks like on my website:

Here's what my code looks like:

.field-items {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.field-item {
  width: 50%;
  float: left;
}

    8 ounces sugar snap peas, stringed

    12 grape tomatoes, halved

2 tablespoons sliced almonds

2 tablespoons extra-virgin olive, walnut, or almond oil

    2 tablespoons fruity vinegar, such as raspberry or pomegranate

    ¼ teaspoon salt

    1/8 teaspoon freshly ground pepper

    4 cups packed mixed baby lettuce

    ¼ cup snipped fresh chives (½-inch pieces)

    ¼ cup chopped fresh tarragon

See it in action: https://jsfiddle.net/4t4pd3tt/2/

My goal is to have even spacing between all of the list elements. I'm sure this question has already been answered before, but I wasn't able to find what I was looking for in my initial search.

Body:
I've been in a similar position where I tried to do this with flex. I spent a long, long time on it and eventually found out that there is no nice way of doing it. My suggestion would be to go back to the trusty (read: awkward and annoying) float.

You just need to clean up your CSS a little and you can float the odd elements to the left and the even elements to the right (or the other way, if you so wish, but that would be kinda stupid, so I wouldn't advise doing that.

.field-item {
  width: 50%;
}

.field-item.odd {
  float: left;
}

.field-item.even {
  float: right;
}

For this, you can remove all the rules from .field-items in your CSS.

An obvious issue here is that you need to continue to add odd and even classes to the div tags, which could easily cause a bug if you do it wrong.

I hope this helps!

EDIT

As Jonathan Nicol pointed out, you can also use nth-child(odd|even) to achieve the same thing, without the need for specific classes (rendering my note above redundant.

.field-item {
  width: 50%;
}

.field-item:nth-child(odd) {
  float: left;
}

.field-item:nth-child(even) {
  float: right;
}


问:
How to use type check Loopback / Fireloop PersistedModel
I'm using Fireloop with Loopback 3 and wanting to know how best to create typesafe hooks and remote methods using type checked PersistedModel and Validatable methods.  I'd like to change the type of the constructor from ...

constructor(public model: any) { }

to ...

constructor(public model: SomeType) { }

I'd like to make PersistedModel calls like

```<code>this.model.count().then((n) => ...);
</code>```

OR Validatable calls like:

```<code>model.validatesLengthOf('code', {
    min: 6, max: 12, message: { min: 'too short',  max: 'too long'}
});
</code>```

The Fireloop examples like the one below only use any as type of this.model.
The firestarter model samples and Fireloop documentation were also of no use here.

I know that there is a type called ModelConstructor declared in the fireloop source tree under core/index.d.ts. This interface looks correct because it implements all the PersistedModel and Validatable methods but where is it published in npmjs? Is it already part of the Fireloop server SDK or do I need to npm install it? No idea.

```<code>import { Model } from '@mean-expert/model';

/**
 * @module Account
 * @description
 * Write a useful Account Model description.
 * Register hooks and remote methods within the
 * Model Decorator
 **/
@Model({
  hooks: {
    beforeSave: { name: 'before save', type: 'operation' }
  },
  remotes: {
    myRemote: {
      returns: { arg: 'result', type: 'array' },
      http: { path: '/my-remote', verb: 'get' }
    }
  }
})

class Account {
  // LoopBack model instance is injected in constructor
  constructor(public model: any) { }

  // Example Operation Hook
  beforeSave(ctx: any, next: Function): void {
    console.log('Account: Before Save', ctx.instance);
    next();
  }
  // Example Remote Method
  myRemote(next: Function): void {
    this.model.find(next);
  }
}

module.exports = Account;
</code>```

Finially, I've also attempted to use the Loopback 3 Typescript definitions but hit more problems as the PersistedModel methods here are all declared as static so fail type checks and return Promise<T> | void. The later means you’re forced to type cast the result back to just Promise<T> so it seems like the type def authors have never actually used  them. Is this a bug or am I missing something?  Can't find any working examples to prove otherwise.

This is the server side API pain. Client side REST API for Fireloop is also undocumented (lots of example for Real-time API) but none for the REST api it's also supposed to include (just mentioned once in one issue). Would be nice to find it can all be type checked by Typescript.

答:
I found that ModelConstructor validation methods were missing arguments like { message: 'my error message' } and methods like exists() returned Promise<any> instead of Promise<boolean>.

The type definitions in Loopback 3 Type definitions were more complete but were unusable unless fixed as described above.

In the end I used ..

```<code># Used modified type defs from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/loopback/index.d.ts

import { Validatable } from '../types/validatable';
 # Fixed static methods and return types.
import { PersistedModel } from '../types/loopback';

constructor(public MyModel: Validatable | PersistedModel) {
  let Model = MyModel as Validatable;
  Model.validatesLengthOf('code', {
    min: 6,
    max: 80,
    message: { min: 'too short',  max: 'too long' } });
  Model.validatesFormatOf('email',
    { with: this.reEmail,
      message: 'invalid email address',
      allowNull: false });
  Model.validatesInclusionOf('role', {
    in: RoleNames,
    message: 'is not valid'
  });
}
</code>```

And in later methods ..

```<code>let Model = this.MyModel as PersistedModel;

// knows that isFound is boolean
Model.exists(code).then(isFound => { ... });
</code>```

Body:
I'm using Fireloop with Loopback 3 and wanting to know how best to create typesafe hooks and remote methods using type checked PersistedModel and Validatable methods.  I'd like to change the type of the constructor from ...

constructor(public model: any) { }

to ...

constructor(public model: SomeType) { }

I'd like to make PersistedModel calls like

this.model.count().then((n) => ...);

OR Validatable calls like:

model.validatesLengthOf('code', {
    min: 6, max: 12, message: { min: 'too short',  max: 'too long'}
});

The Fireloop examples like the one below only use any as type of this.model.
The firestarter model samples and Fireloop documentation were also of no use here.

I know that there is a type called ModelConstructor declared in the fireloop source tree under core/index.d.ts. This interface looks correct because it implements all the PersistedModel and Validatable methods but where is it published in npmjs? Is it already part of the Fireloop server SDK or do I need to npm install it? No idea.

import { Model } from '@mean-expert/model';

/**
 * @module Account
 * @description
 * Write a useful Account Model description.
 * Register hooks and remote methods within the
 * Model Decorator
 **/
@Model({
  hooks: {
    beforeSave: { name: 'before save', type: 'operation' }
  },
  remotes: {
    myRemote: {
      returns: { arg: 'result', type: 'array' },
      http: { path: '/my-remote', verb: 'get' }
    }
  }
})

class Account {
  // LoopBack model instance is injected in constructor
  constructor(public model: any) { }

  // Example Operation Hook
  beforeSave(ctx: any, next: Function): void {
    console.log('Account: Before Save', ctx.instance);
    next();
  }
  // Example Remote Method
  myRemote(next: Function): void {
    this.model.find(next);
  }
}

module.exports = Account;

Finially, I've also attempted to use the Loopback 3 Typescript definitions but hit more problems as the PersistedModel methods here are all declared as static so fail type checks and return Promise<T> | void. The later means you’re forced to type cast the result back to just Promise<T> so it seems like the type def authors have never actually used  them. Is this a bug or am I missing something?  Can't find any working examples to prove otherwise.

This is the server side API pain. Client side REST API for Fireloop is also undocumented (lots of example for Real-time API) but none for the REST api it's also supposed to include (just mentioned once in one issue). Would be nice to find it can all be type checked by Typescript.

Body:
I found that ModelConstructor validation methods were missing arguments like { message: 'my error message' } and methods like exists() returned Promise<any> instead of Promise<boolean>.

The type definitions in Loopback 3 Type definitions were more complete but were unusable unless fixed as described above.

In the end I used ..

# Used modified type defs from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/loopback/index.d.ts

import { Validatable } from '../types/validatable';
 # Fixed static methods and return types.
import { PersistedModel } from '../types/loopback';

constructor(public MyModel: Validatable | PersistedModel) {
  let Model = MyModel as Validatable;
  Model.validatesLengthOf('code', {
    min: 6,
    max: 80,
    message: { min: 'too short',  max: 'too long' } });
  Model.validatesFormatOf('email',
    { with: this.reEmail,
      message: 'invalid email address',
      allowNull: false });
  Model.validatesInclusionOf('role', {
    in: RoleNames,
    message: 'is not valid'
  });
}

And in later methods ..

let Model = this.MyModel as PersistedModel;

// knows that isFound is boolean
Model.exists(code).then(isFound => { ... });


答: so you want [[a[1][0]],[a[2][0]]? Well, for one, I'd figure out another way of writing your arrays to make them easier to parse (visually and mechanically.) But, in response to your question, I'd use a list comprehension. [a[i][0] for i in [1,2]] would work, I believe.

Title: selecting specific part of array

Body:
Lets say I have an array

a = [[[1, 2], [3, 4]],
     [[5, 6], [7, 8]],
     [[9, 10], [11, 12]],
     [[13, 14], [15, 16]],
     [[17, 18], [19, 20]]]

At the end I would like an array

b = [[[5, 6]],[[9, 10]]]

I thought that

b = a[1:3][0:1]

would work. But from that i get

b=[[[5, 6], [7, 8]]]


问:
Firebird - database file shutdown error message
I have a problem with my Firebird database. The primary key of one of the tables is referenced by another table that was actually dropped earlier. So this reference from a non-existent table was causing errors when I try to make any changes in the table data.

So I did a backup and restore and the bad reference was gone but now when I try to connect to my database more than once at the same time I get the following error:

database [file path] shutdown

How can I solve this?

答:
use online

```<code>gfix  -user "SYSDBA" -password "masterkey"  -online DATA.FDB
</code>```

after database is used retry

```<code>gfix  -user "SYSDBA" -password "masterkey"   -shut -force 0 DATA.FDB
</code>```

Body:
use online

gfix  -user "SYSDBA" -password "masterkey"  -online DATA.FDB

after database is used retry

gfix  -user "SYSDBA" -password "masterkey"   -shut -force 0 DATA.FDB


问:
Passing List of records with jQuery
I've a situation where I want to pass list of records via Ajax/JQuery.

```<code>public JsonResult GetListOfRecords()
{
   return Json(_repository.GetAllRecords());
}
</code>```

when I call this action method with jQuery, it doesn't work:

```<code>$.getJSON('GetAllRecords', function(data){ // data is IQueryable<T> or IEnumerabel<T>
$.each(data, function(d) {
    $('#somewhere').html(d.Title); //d is SomeModelType and Title is property of that type
});
});
</code>```

Note: GetAllRecords method returns IQueryable.... I also tested IEnumerable

However, if pass ArrayList type, it seems to be work (but not fulfill my need):

```<code>public JsonResult GetAllRecords()
{
  var list = new ArrayList();
  foreach(var item in _repository.GetAllRecords())
  {
    list.Add(item.Title);
  }
  return Json(list);
}
</code>```

it just displays title...

My Question is that "I want to pass IQueryable or IEnumerable through ajax."

答:
This doesn't seem to be the case. The following works perfectly fine with an IEnumerable<T> and an anonymous type:

```<code>public ActionResult GetListOfRecords()
{
    return Json(
        Enumerable.Range(1, 3).Select(i => new
        {
            Id = i,
            Title = "title " + i
        }),
        JsonRequestBehavior.AllowGet
    );
}
</code>```

and to invoke:

```<code>$.getJSON('<%= Url.Action("GetListOfRecords") %>', { }, function(records) {
    $.each(records, function(index, record) {
        alert(record.Id + ' ' + record.Title);
    });
});
</code>```

Also notice the slight subtility in the $.each() function.

In your case you have:

```<code>$.each(data, function(d) { ...
</code>```

In my case I have:

```<code>$.each(data, function(index, d) { ...
</code>```

The first parameter of the callback is the index, not the value.

Title: Passing List of records with jQuery

Body:
I've a situation where I want to pass list of records via Ajax/JQuery.

public JsonResult GetListOfRecords()
{
   return Json(_repository.GetAllRecords());
}

when I call this action method with jQuery, it doesn't work:

$.getJSON('GetAllRecords', function(data){ // data is IQueryable<T> or IEnumerabel<T>
$.each(data, function(d) {
    $('#somewhere').html(d.Title); //d is SomeModelType and Title is property of that type
});
});

Note: GetAllRecords method returns IQueryable.... I also tested IEnumerable

However, if pass ArrayList type, it seems to be work (but not fulfill my need):

public JsonResult GetAllRecords()
{
  var list = new ArrayList();
  foreach(var item in _repository.GetAllRecords())
  {
    list.Add(item.Title);
  }
  return Json(list);
}

it just displays title...

My Question is that "I want to pass IQueryable or IEnumerable through ajax."

Body:
This doesn't seem to be the case. The following works perfectly fine with an IEnumerable<T> and an anonymous type:

public ActionResult GetListOfRecords()
{
    return Json(
        Enumerable.Range(1, 3).Select(i => new
        {
            Id = i,
            Title = "title " + i
        }),
        JsonRequestBehavior.AllowGet
    );
}

and to invoke:

$.getJSON('<%= Url.Action("GetListOfRecords") %>', { }, function(records) {
    $.each(records, function(index, record) {
        alert(record.Id + ' ' + record.Title);
    });
});

Also notice the slight subtility in the $.each() function.

In your case you have:

$.each(data, function(d) { ...

In my case I have:

$.each(data, function(index, d) { ...

The first parameter of the callback is the index, not the value.


问:
Connecting to Sybase using sqsh
I am new to sybase.  I am trying to connect to the database using sqsh.

```<code>sqsh -Ddatabasename -Hservername -Uusername
or
sqsh -D databasename -H servername -U username
</code>```

I get the following error.  server name not found in configuration file.  unknown host machine name.
I am trying to connect using the command line.  Wouldn't that bypass a config file.

答: Don’t use the hostname. Use -S for the servername , which must be defined in the interfaces file (or sql.ini file). You can leave the database name out.</p>

Title: Connecting to Sybase using sqsh

Body:
I am new to sybase.  I am trying to connect to the database using sqsh.

sqsh -Ddatabasename -Hservername -Uusername
or
sqsh -D databasename -H servername -U username

I get the following error.  server name not found in configuration file.  unknown host machine name.
I am trying to connect using the command line.  Wouldn't that bypass a config file.


问:
Cassandra CQLSH OperationTimedOut error=Client request timeout. See Session.execute[_async](timeout)
I want to transfer data from one Cassandra cluster (reached via 192.168.0.200) to another Cassandra cluster (reached via 127.0.0.1). The data is 523 rows but each row is about 1 MB. I am using the COPY FROM and COPY TO command. I get the following error when I issue the COPY TO command:

```<code>Error for (8948428671687021382, 9075041744804640605):
OperationTimedOut - errors={
'192.168.0.200': 'Client request timeout. See Session.execute[_async](timeout)'},
last_host=192.168.0.200 (will try again later attempt 1 of 5).
</code>```

I tried to change the ~/.cassandra/cqlshrc file to:

```<code>[connection]
client_timeout = 5000
</code>```

But this hasn't helped.

答:
You may want to increment the request timeout (default: 10 seconds), not the connect timeout.

Try:

```<code>cqlsh --request-timeout=6000
</code>```

or add:

```<code>[connection]
request_timeout = 6000
</code>```

to your ~/.cassandra/cqlshrc file.

Body:
I want to transfer data from one Cassandra cluster (reached via 192.168.0.200) to another Cassandra cluster (reached via 127.0.0.1). The data is 523 rows but each row is about 1 MB. I am using the COPY FROM and COPY TO command. I get the following error when I issue the COPY TO command:

Error for (8948428671687021382, 9075041744804640605):
OperationTimedOut - errors={
'192.168.0.200': 'Client request timeout. See Session.execute[_async](timeout)'},
last_host=192.168.0.200 (will try again later attempt 1 of 5).

I tried to change the ~/.cassandra/cqlshrc file to:

[connection]
client_timeout = 5000

But this hasn't helped.

Body:
You may want to increment the request timeout (default: 10 seconds), not the connect timeout.

Try:

cqlsh --request-timeout=6000

or add:

[connection]
request_timeout = 6000

to your ~/.cassandra/cqlshrc file.


Title: selecting specific part of array

Body:
>>> b = [[a[1][0],a[2][0]]]
>>> print(b)
[[[5, 6], [9, 10]]]


问:
adding a colon after every two letters in an alphanumeric string in shell
So i have an alphanumeric string 10006cc2190ab011 i am trying to add a colon after every two letters in this alphanumeric string.

```<code>this is the string : 10006cc2190ab011
i want it be - 10:00:6c:c2:19:0a:b0:11
</code>```

Thanks in advance.

答:
A sed solution:

```<code>$ echo 10006cc2190ab011 | sed 's/../&:/g; s/:$//'
10:00:6c:c2:19:0a:b0:11
</code>```

Replaces each non-overlapping pair of characters with the same pair plus :. In the end removes the trailing : (if input text had even length).

Body:
So i have an alphanumeric string 10006cc2190ab011 i am trying to add a colon after every two letters in this alphanumeric string.

this is the string : 10006cc2190ab011
i want it be - 10:00:6c:c2:19:0a:b0:11

Thanks in advance.

Body:
A sed solution:

$ echo 10006cc2190ab011 | sed 's/../&:/g; s/:$//'
10:00:6c:c2:19:0a:b0:11

Replaces each non-overlapping pair of characters with the same pair plus :. In the end removes the trailing : (if input text had even length).


问:
What's wrong with the prime number generator?
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.</p>

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

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}
</code>```

答: Don't do integer division instead do modulus and check whether the remainder is 0.</p>

Body:
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.

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

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}


问:
Creating git repository from several repositories locally
I have the following directory structure:

Parent/ contains
  Child1/
  Child2/
  ...
  ChildN/

Each of the Child directories is its own git repository with commit histories, etc. I have realized that it would make more sense to make Parent a git repository with the children as subrepositories (presumably using git-subtree or something). This is because the child directories are all components of the same project.

I have looked at various answers, but they all involve pushing/pulling from some remote repo, whereas everything is local to my machine in this case (and I would like to keep it that way--plus, I don't know how to work with remotes).

So my question is: how to I create the Parent repository in such a way that the children are part of it but retain their individual histories and  without reference to any remote repository?

Reason this is different from the proposed duplicate:
The link about remote repos being on a local hard drive is helpful and definitely makes the other answers on SO more accessible. I just tried the procedure in the linked question on merging two repositories, and it almost does the job but is laborious and labor-prone in my case. In that question, two repositories are to be merged to create a third repository, whereas in my case, a number of repositories need to become the directories of a new repository.

To use the proposed duplicate answer, I would have to make a copy of Parent, say Parent_copy, then delete everything from Parent, create the Parent .git directory, then merge in the Child directories one at a time. In the process, the contents of each Child would be either copied from Parent_copy/Child into Parent or ignored (based on a .gitignore file). Then I could recreate e.g. Parent/Child1 as an empty directory, move the files from Parent, and copy the ignored files from Parent_copy/Child1. So it would work, but is a bit laborious and error-prone. I wonder is there is a more efficient way, ideally treating the Child directories in place?

答:
Use git submodules and as a submodule url use local repo path.

E.g. to add submodule to parent repository use git submodule add /path/to/some/submodule1.git

Please remember that your existing sub repository should be outside parent repository. Apropriate reference will be copied to parent repo when you call git submodule add ...


问:
How to scroll a modal window in Capybara
I'm testing with Selenium WebDriver, RSpec and Capybara.

I let the program successfully fill in some fields in a modal window. Now I want to click on a button that is at the bottom of this modal window. At the first glance, I cannot see this button, so Capybara needs to scroll down in the modal window.

The two relevant code snippets of the webpage:

```<code><div class = “modal”> </div>
   <button class=”btn …..”> TextOnButton ::after </button>
</code>```

I tried:

```<code>within('.modal') do
      find('.btn', text: ‘TextOnButton').scrollIntoView(true)
end
</code>```

but received the error message.

Unable to find visible css ".btn" with text "TextOnButton"

I tried:

```<code>within('.modal’) do
       page.execute_script 'window.scrollBy(0,100)'
end
</code>```

but then he scrolls the main window but not the modal window.

答:
Assuming your HTML snippet is incorrect and the button element is actually contained in the modal (as in your text description), then you can try something like</p>

```<code>within('.modal') do
  btn = find(:button, 'TextOnButton', visible: :all)
  execute_script('arguments[0].scrollIntoView(true)', btn)
  btn.click
end
</code>```

Body:
I'm testing with Selenium WebDriver, RSpec and Capybara.

I let the program successfully fill in some fields in a modal window. Now I want to click on a button that is at the bottom of this modal window. At the first glance, I cannot see this button, so Capybara needs to scroll down in the modal window.

The two relevant code snippets of the webpage:

   <button class=”btn …..”> TextOnButton ::after </button>

I tried:

within('.modal') do
      find('.btn', text: ‘TextOnButton').scrollIntoView(true)
end

but received the error message.

Unable to find visible css ".btn" with text "TextOnButton"

I tried:

within('.modal’) do
       page.execute_script 'window.scrollBy(0,100)'
end

but then he scrolls the main window but not the modal window.

Body:
Assuming your HTML snippet is incorrect and the button element is actually contained in the modal (as in your text description), then you can try something like

within('.modal') do
  btn = find(:button, 'TextOnButton', visible: :all)
  execute_script('arguments[0].scrollIntoView(true)', btn)
  btn.click
end


问:
`body` parameter is absent in AWS Lambda Authorizer `event` object
The event object is missing body and isBase64Encoded properties. But they should be there according to the docs The full structure is the following:

```<code>{
    "type": "REQUEST",
    "methodArn": "arn:aws:execute-api:us-west-2:*******:*******/development/POST/auth/login",
    "resource": "/{proxy+}",
    "path": "/auth/login",
    "httpMethod": "ANY",
    "headers": {
       .....
    },
    "queryStringParameters": {
        "test": "123"
    },
    "pathParameters": {
        "proxy": "auth/login"
    },
    "stageVariables": {
        "lambdaVersion": "development"
    },
    "requestContext": {
        "path": "/development/auth/login",
        "accountId": "*****",
        "resourceId": "f8wvnk",
        "stage": "development",
        "requestId": "****",
        "identity": {
            ....
        },
        "resourcePath": "/{proxy+}",
        "httpMethod": "POST",
        "apiId": "********"
    }
}
</code>```

Does anyone have the similar issue?

答:
In custom authorizer request type there is no body in the passed event to the authorizer. According to the documentation:

For a custom authorizer of the REQUEST type, API Gateway passes the required request parameters to the authorizer Lambda function as part of the event object. The affected request parameters include headers, path parameters, query string parameters, stage variables, and some of request context variables.

NO Body is there!

Body:
The event object is missing body and isBase64Encoded properties. But they should be there according to the docs The full structure is the following:

{
    "type": "REQUEST",
    "methodArn": "arn:aws:execute-api:us-west-2:*******:*******/development/POST/auth/login",
    "resource": "/{proxy+}",
    "path": "/auth/login",
    "httpMethod": "ANY",
    "headers": {
       .....
    },
    "queryStringParameters": {
        "test": "123"
    },
    "pathParameters": {
        "proxy": "auth/login"
    },
    "stageVariables": {
        "lambdaVersion": "development"
    },
    "requestContext": {
        "path": "/development/auth/login",
        "accountId": "*****",
        "resourceId": "f8wvnk",
        "stage": "development",
        "requestId": "****",
        "identity": {
            ....
        },
        "resourcePath": "/{proxy+}",
        "httpMethod": "POST",
        "apiId": "********"
    }
}

Does anyone have the similar issue?


问:
Testing array elements vs multiple criteria
I am trying to create a method complex_check(n), which will do the following:

Create an array of integers ascending from 0 to n

Check each element of that array against complex criteria.

For example, I have an array from 0..n, and I want to know which elements of the array are both evenly divisible by 3 and not divisible by 4. I can index through to check for single criteria like odd?, etc., but is there a compact way to check each integer against multiple criteria?

答:
create an array of integers ascending from 0 to n

Don't do this if you don't have to, which is almost never.
Use a Range or an Enumerator. They are real easy:

```<code>0.upto(n).select do |i|  #0.upto(n) results in a Enumerator
  #complex criteria
end

#or

def complex_check(n)
  0.step(n,3).reject{|n| (n%4).zero?}  #0.step(n,3) is an Enumerator
end

p complex_check(15) #= [3, 6, 9, 15]
</code>```

Body:
create an array of integers ascending from 0 to n

Don't do this if you don't have to, which is almost never.
Use a Range or an Enumerator. They are real easy:

0.upto(n).select do |i|  #0.upto(n) results in a Enumerator
  #complex criteria
end

#or

def complex_check(n)
  0.step(n,3).reject{|n| (n%4).zero?}  #0.step(n,3) is an Enumerator
end

p complex_check(15) #= [3, 6, 9, 15]


问:
jest spies on component functionality
I create a jest spy to test my component function with expecting the function will be called. However, it seems not to be called.

This is my test:

```<code>  import React from 'react';
  import { shallow, mount } from 'enzyme';
  import SideNavBar from '../SideNavBar';
  test('Should call mock function when clicking NavBar button', () => {
    const openNavSpy = jest.fn();
    const wrapper = shallow(<SideNavBar openNav={openNavSpy} />);
    wrapper.find('i').simulate('click');
    expect(openNavSpy).toHaveBeenCalledTimes(1);
  });
</code>```

This is my some related code from SideNavBar:

```<code>openNav = () => {
    if (this.mySidenav) {
      this.mySidenav.style.width = '360px';
    }
  };
....
 <i className="fa fa-bars" aria-hidden="true" onClick={this.openNav} />
</code>```

答:
this.openNav is referencing the classes openNav and not the spy prop that you pass in through SideBarNav from your test.

```<code>test('Should call mock function when clicking NavBar button', () => {
    const wrapper = shallow(<SideNavBar />);
    const openNavSpy = jest.fn();

    wrapper.instance().openNav = openNavSpy;

    wrapper.find('i').simulate('click');

    expect(openNavSpy).toHaveBeenCalledTimes(1);
});
</code>```

Instead of testing that openNav was called why don't you test that mySideNav's width was set instead.
This would be better because we actually don't care that openNav was called on click we only care that the width was set on click.

```<code>test('Should set the side nav width to 360px', () => {
    const wrapper = shallow(<SideNavBar />);

    wrapper.find('i').simulate('click');

    const sideNav = wrapper.instance().mySidenav;

    expect(sideNav.style.width).toBe('360px');
});
</code>```

Title: jest spies on component functionality

Body:
I create a jest spy to test my component function with expecting the function will be called. However, it seems not to be called.

This is my test:

  import React from 'react';
  import { shallow, mount } from 'enzyme';
  import SideNavBar from '../SideNavBar';
  test('Should call mock function when clicking NavBar button', () => {
    const openNavSpy = jest.fn();
    const wrapper = shallow(<SideNavBar openNav={openNavSpy} />);
    wrapper.find('i').simulate('click');
    expect(openNavSpy).toHaveBeenCalledTimes(1);
  });

This is my some related code from SideNavBar:

openNav = () => {
    if (this.mySidenav) {
      this.mySidenav.style.width = '360px';
    }
  };
....

Body:
this.openNav is referencing the classes openNav and not the spy prop that you pass in through SideBarNav from your test.

test('Should call mock function when clicking NavBar button', () => {
    const wrapper = shallow(<SideNavBar />);
    const openNavSpy = jest.fn();

    wrapper.instance().openNav = openNavSpy;

    wrapper.find('i').simulate('click');

    expect(openNavSpy).toHaveBeenCalledTimes(1);
});

Instead of testing that openNav was called why don't you test that mySideNav's width was set instead.
This would be better because we actually don't care that openNav was called on click we only care that the width was set on click.

test('Should set the side nav width to 360px', () => {
    const wrapper = shallow(<SideNavBar />);

    wrapper.find('i').simulate('click');

    const sideNav = wrapper.instance().mySidenav;

    expect(sideNav.style.width).toBe('360px');
});