问:
Remove two columns at once in a matrix with array_splice()
I'm trying to get the correct result for deleted columns and rows in a matrix, but whenever I remove the first column specified in the $columnsToRemove array, the array shifts, and I end up deleting the wrong column. in the following example, how would I delete both the 0th and the 2nd column in each submatrix in one go?

```<code>$matrix = [
    [1,0,0,2],
    [0,5,0,1],
    [0,0,3,5]
];

$rowsToDelete = [1];

$columnsToDelete = [0, 2];

function constructSubmatrix($matrix, $rowsToDelete, $columnsToDelete) {
    foreach($rowsToDelete as $row){
        array_splice($matrix, $row, 1);
    }
    foreach($columnsToDelete as $column){
        for($i = 0; $i < count($matrix); $i++){
            array_splice($matrix[$i], $column, 1);
        }
    }
    return $matrix;
}
</code>```

The return value should be: [[0,2],[0,5]]

But I keep getting: [[0,0],[0,3]]

答:
Because if you're deleting multiple rows or multiple columns, then deleting the lowest column in that list will mean that the higher column numbers aren't correct any more.

e.g. with $columnsToDelete = [0, 2]; once you've deleted column 0, then column 2 has become column 1, but your'e still trying to delete column 2

You need to delete in reverse order to avoid this; so use rsort() your $rowsToDelete and $columnsToDelete before doing the deletion.

```<code>function constructSubmatrix($matrix, $rowsToDelete, $columnsToDelete) {
    rsort($rowsToDelete);
    foreach($rowsToDelete as $row){
        array_splice($matrix, $row, 1);
    }
    rsort($columnsToDelete);
    foreach($columnsToDelete as $column){
        for($i = 0; $i < count($matrix); $i++){
            array_splice($matrix[$i], $column, 1);
        }
    }
    return $matrix;
}
</code>```

Body:
I'm trying to get the correct result for deleted columns and rows in a matrix, but whenever I remove the first column specified in the $columnsToRemove array, the array shifts, and I end up deleting the wrong column. in the following example, how would I delete both the 0th and the 2nd column in each submatrix in one go?

$matrix = [
    [1,0,0,2],
    [0,5,0,1],
    [0,0,3,5]
];

$rowsToDelete = [1];

$columnsToDelete = [0, 2];

function constructSubmatrix($matrix, $rowsToDelete, $columnsToDelete) {
    foreach($rowsToDelete as $row){
        array_splice($matrix, $row, 1);
    }
    foreach($columnsToDelete as $column){
        for($i = 0; $i < count($matrix); $i++){
            array_splice($matrix[$i], $column, 1);
        }
    }
    return $matrix;
}

The return value should be: [[0,2],[0,5]]

But I keep getting: [[0,0],[0,3]]

Body:
Because if you're deleting multiple rows or multiple columns, then deleting the lowest column in that list will mean that the higher column numbers aren't correct any more.

e.g. with $columnsToDelete = [0, 2]; once you've deleted column 0, then column 2 has become column 1, but your'e still trying to delete column 2

You need to delete in reverse order to avoid this; so use rsort() your $rowsToDelete and $columnsToDelete before doing the deletion.

function constructSubmatrix($matrix, $rowsToDelete, $columnsToDelete) {
    rsort($rowsToDelete);
    foreach($rowsToDelete as $row){
        array_splice($matrix, $row, 1);
    }
    rsort($columnsToDelete);
    foreach($columnsToDelete as $column){
        for($i = 0; $i < count($matrix); $i++){
            array_splice($matrix[$i], $column, 1);
        }
    }
    return $matrix;
}


来源: stackexchange

问:
How Do I Follow A T-SQL Transaction?
Are there any programs that will allow you to follow a sql transaction through to it's end?  For instance, say I've inherited a rather complex sql database with a data dictionary.  The data dictionary is pretty good, but not as good as say, SQL Doc.  I've taken a look at Red Gate's Dependency Tracker and, while that does a very good job of putting things together (triggers, stored procedures, tables, views, etc.), it still does nothing for following a transaction through it's various tracks.

What I'd like is software that will allow me to enter a transaction and based on everything in my db, tree it out visually to let me see what's happening during the transaction.  Does that make sense or do I need to elaborate?

Edited to elaborate:  While the answers below were very good, it's not exactly what I'm looking for.  The front end of the sql database was built with PowerBuilder.  I can use SqlSpy during frontend data input and that helps to follow transactions through, but it's all the t-sql and as you can imagine, reams of output.  I'm looking for something that would do the same thing, but lay it out visually with the ability to tree out the detail if I wanted to.

答: If you open a connection in Visual Studio, you can run sprocs and queries in debug mode.  i.e. you can go step by step over a query with intellisense and see the values in the variables.</p>

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

Title: How Do I Follow A T-SQL Transaction?

LastEditorDisplayName: Cade Roux

OwnerDisplayName: mson


问:
Set application pool with MSDeploy and TFS 2010
I'm trying to deploy website with MSDeploy and team build using some of this ...

```<code>/p:DeployOnBuild
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=InProc
/p:MSDeployServiceURL=localhost
/p:DeployIISAppPath="Default Web Site"
</code>```

Is there a way to set this website in custom application pool?

答: Part of the trick is with /p:IncludeAppPool=true.  That changes the deploy script to enable AppPoolExtension. But I haven't figured out how best to actually set the app pool yet.  :)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to deploy website with MSDeploy and team build using some of this ...

/p:DeployOnBuild
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=InProc
/p:MSDeployServiceURL=localhost
/p:DeployIISAppPath="Default Web Site"

Is there a way to set this website in custom application pool?


问:
Merge two data frames based on common column values in Pandas
How to get merged data frame from two data frames having common column value such that only those rows make merged data frame having common value in a particular column.

I have 5000 rows of df1 as format : -

```<code>    director_name   actor_1_name    actor_2_name    actor_3_name    movie_title
0   James Cameron   CCH Pounder Joel David Moore    Wes Studi     Avatar
1   Gore Verbinski  Johnny Depp Orlando Bloom   Jack Davenport   Pirates
    of the Caribbean: At World's End
2   Sam Mendes   Christoph Waltz    Rory Kinnear    Stephanie Sigman Spectre
</code>```

and 10000 rows of df2 as

```<code>movieId                   genres                        movie_title
    1       Adventure|Animation|Children|Comedy|Fantasy   Toy Story
    2       Adventure|Children|Fantasy                    Jumanji
    3       Comedy|Romance                             Grumpier Old Men
    4       Comedy|Drama|Romance                      Waiting to Exhale
</code>```

A common column 'movie_title' have common values and based on them, I want to get all rows where 'movie_title' is same. Other rows to be deleted.

Any help/suggestion would be appreciated.

Note:  I already tried

```<code>pd.merge(dfinal, df1, on='movie_title')
</code>```

and output comes like one row

```<code>director_name   actor_1_name    actor_2_name    actor_3_name    movie_title movieId title   genres
</code>```

and on how ="outer"/"left", "right", I tried all and didn't get any row after dropping NaN although many common coloumn do exist.

答:
We can merge two Data frames in several ways. Most common way in python is using merge operation in Pandas.

```<code>import pandas
dfinal = df1.merge(df2, on="movie_title", how = 'inner')
</code>```

For merging based on columns of different dataframe, you may specify left and right common column names specially in case of ambiguity of two different names of same column, lets say - 'movie_title' as 'movie_name'.

```<code>dfinal = df1.merge(df2, how='inner', left_on='movie_title', right_on='movie_name')
</code>```

If you want to be even more specific, you may read the documentation of pandas merge operation.

Body:
How to get merged data frame from two data frames having common column value such that only those rows make merged data frame having common value in a particular column.

I have 5000 rows of df1 as format : -

    director_name   actor_1_name    actor_2_name    actor_3_name    movie_title
0   James Cameron   CCH Pounder Joel David Moore    Wes Studi     Avatar
1   Gore Verbinski  Johnny Depp Orlando Bloom   Jack Davenport   Pirates
    of the Caribbean: At World's End
2   Sam Mendes   Christoph Waltz    Rory Kinnear    Stephanie Sigman Spectre

and 10000 rows of df2 as

movieId                   genres                        movie_title
    1       Adventure|Animation|Children|Comedy|Fantasy   Toy Story
    2       Adventure|Children|Fantasy                    Jumanji
    3       Comedy|Romance                             Grumpier Old Men
    4       Comedy|Drama|Romance                      Waiting to Exhale

A common column 'movie_title' have common values and based on them, I want to get all rows where 'movie_title' is same. Other rows to be deleted.

Any help/suggestion would be appreciated.

Note:  I already tried

pd.merge(dfinal, df1, on='movie_title')

and output comes like one row

director_name   actor_1_name    actor_2_name    actor_3_name    movie_title movieId title   genres

and on how ="outer"/"left", "right", I tried all and didn't get any row after dropping NaN although many common coloumn do exist.

Body:
We can merge two Data frames in several ways. Most common way in python is using merge operation in Pandas.

import pandas
dfinal = df1.merge(df2, on="movie_title", how = 'inner')

For merging based on columns of different dataframe, you may specify left and right common column names specially in case of ambiguity of two different names of same column, lets say - 'movie_title' as 'movie_name'.

dfinal = df1.merge(df2, how='inner', left_on='movie_title', right_on='movie_name')

If you want to be even more specific, you may read the documentation of pandas merge operation.

ContentLicense: CC BY-SA 4.0


问:
no known conversion 'float (MyClass::*)' to 'float (*)'
I am supposed to write a program which has to generate a triangle function, calculate the derivative using forward and backward divided differences and differentiate the triangle function.
So, I wrote some code and have only one problem:

include\MyClass.h|12|note:   no known conversion for argument 1 from 'float (MyClass::)(int, float, float)' to 'float ()(int, float, float)'|

My code:

main.cpp

```<code>#include <iostream>
#include "MyClass.h"
using namespace std;

int main()
{
    MyClass object (3,4,2,0.1);

    for (float i=object.x; i<2.5; i+=0.01)
    {
        cout << object.Triangle(10, 3.14, i) << " ";
    }

    cout << "////////////////////";

    for (float i=object.x; i<2.5; i+=0.01)
    {
        cout << object.Derivative(&object.Triangle, i, object.con) << " ";
    }
}
</code>```

MyClass.h

```<code>#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
    public:
        MyClass();
        MyClass(int k_max, float omega, float x, float con);
        ~MyClass();
        float Triangle (int k_max, float omega, float x);
        float Derivative (float (*w) (int k_max, float omega, float x), float var, float con);
        float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con);
        int k_max;
        float omega, x, result, con;
};

#endif // MYCLASS_H
</code>```

MyClass.cpp

```<code>#include "MyClass.h"

MyClass::MyClass() {}
MyClass::~MyClass() {}

MyClass(int K_max, float Omega, float X, float Con)
{
    k_max=K_max;
    omega=Omega;
    x=X;
    con=Con;
}

///////////////////////////////////////////////

float Triangle (int k_max, float omega, float x)
    {
        result=0;

        for int (i=0; i<=k_max; i++)
        {
            result += ( 8*pow(-1, i)*(sin((2*i+1)*omega*x ) / ( pow(2*i+1, 2) * pow(M_PI, 2) )
        }
        return result;
    }

///////////////////////////////////////////////

float Derivative (float (*w) (int k_max, float omega, float x), float var, float con)
    {
        float result = (w(10, 3.14, var+con) - w(10, 3.14, var))/var;
        return result;
    }

///////////////////////////////////////////////

float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con)
    {
        float result=(w(10, 3.14, var)-w(10, 3.14, var-con))/2*var;
        return result;
    }
</code>```

I would really appreciate your help, thanks!

EDIT:
I've got this program working, but it's recommended to use a class and required to use a pointer to the function. That's my non object-oriented code:
https://ideone.com/mtPLAo

答:
You have several errors of syntactical nature in your code.

In MyClass.h, change into

```<code>float Derivative (float *w, int k_max, float omega, float x, float var, float con);
float DerivativeCntr (float *w, int k_max, float omega, float x, float var, float con);
</code>```

In MyClass.cpp, all member functions should be prefixed by MyClass:: and also the same for the constructor that takes arguments.

Body:
I am supposed to write a program which has to generate a triangle function, calculate the derivative using forward and backward divided differences and differentiate the triangle function.
So, I wrote some code and have only one problem:

include\MyClass.h|12|note:   no known conversion for argument 1 from 'float (MyClass::)(int, float, float)' to 'float ()(int, float, float)'|

My code:

main.cpp

#include <iostream>
#include "MyClass.h"
using namespace std;

int main()
{
    MyClass object (3,4,2,0.1);

    for (float i=object.x; i<2.5; i+=0.01)
    {
        cout << object.Triangle(10, 3.14, i) << " ";
    }

    cout << "////////////////////";

    for (float i=object.x; i<2.5; i+=0.01)
    {
        cout << object.Derivative(&object.Triangle, i, object.con) << " ";
    }
}

MyClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
    public:
        MyClass();
        MyClass(int k_max, float omega, float x, float con);
        ~MyClass();
        float Triangle (int k_max, float omega, float x);
        float Derivative (float (*w) (int k_max, float omega, float x), float var, float con);
        float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con);
        int k_max;
        float omega, x, result, con;
};

#endif // MYCLASS_H

MyClass.cpp

#include "MyClass.h"

MyClass::MyClass() {}
MyClass::~MyClass() {}

MyClass(int K_max, float Omega, float X, float Con)
{
    k_max=K_max;
    omega=Omega;
    x=X;
    con=Con;
}

///////////////////////////////////////////////

float Triangle (int k_max, float omega, float x)
    {
        result=0;

        for int (i=0; i<=k_max; i++)
        {
            result += ( 8*pow(-1, i)*(sin((2*i+1)*omega*x ) / ( pow(2*i+1, 2) * pow(M_PI, 2) )
        }
        return result;
    }

///////////////////////////////////////////////

float Derivative (float (*w) (int k_max, float omega, float x), float var, float con)
    {
        float result = (w(10, 3.14, var+con) - w(10, 3.14, var))/var;
        return result;
    }

///////////////////////////////////////////////

float DerivativeCntr (float (*w) (int k_max, float omega, float x), float var, float con)
    {
        float result=(w(10, 3.14, var)-w(10, 3.14, var-con))/2*var;
        return result;
    }

I would really appreciate your help, thanks!

EDIT:
I've got this program working, but it's recommended to use a class and required to use a pointer to the function. That's my non object-oriented code:
https://ideone.com/mtPLAo

Body:
You have several errors of syntactical nature in your code.

In MyClass.h, change into

float Derivative (float *w, int k_max, float omega, float x, float var, float con);
float DerivativeCntr (float *w, int k_max, float omega, float x, float var, float con);

In MyClass.cpp, all member functions should be prefixed by MyClass:: and also the same for the constructor that takes arguments.


问:
A "catch-all" for SFINAE functions?
I am trying to make a typed compare function that do some customized comparison for different types.

```<code> #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}
</code>```

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

答:
The problem with the code in your question is that when the floating point typedCompare() is SFINAE enabled, collide with the general version because the compiler can't prefer one version over the other.

To solve this problem, I suggest you another way, based on template partial specialization (available only with structs and classes, so need a helper struct)

If you define an helper struct as follows

```<code>template <typename T, typename = void>
struct typedCompareHelper
 {
   static constexpr bool func (T const & lhs, T const & rhs)
    { return lhs == rhs; } // default case, use ==
 };

template <typename T>
struct typedCompareHelper<T,
   typename std::enable_if<std::is_floating_point<T>::value>::type>
 {
   static constexpr bool func (T const & lhs, T const & rhs)
    { return (lhs - rhs) < 1e-10; }
 };
</code>```

you avoid the ambiguity problem because the typedCompareHelper specialization in more specialized of the generic one.

You can simply add more specializations for different special cases making only attention in avoiding collisions (different specializations of the same level that apply over the same type).

Your typedCompare() become simply

```<code>template <typename T>
bool typedCompare (T const & lhs, T const & rhs)
 { return typedCompareHelper<T>::func(lhs, rhs); }
</code>```

Title: A "catch-all" for SFINAE functions?

Body:
I am trying to make a typed compare function that do some customized comparison for different types.

 #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

Body:
The problem with the code in your question is that when the floating point typedCompare() is SFINAE enabled, collide with the general version because the compiler can't prefer one version over the other.

To solve this problem, I suggest you another way, based on template partial specialization (available only with structs and classes, so need a helper struct)

If you define an helper struct as follows

template <typename T, typename = void>
struct typedCompareHelper
 {
   static constexpr bool func (T const & lhs, T const & rhs)
    { return lhs == rhs; } // default case, use ==
 };

template <typename T>
struct typedCompareHelper<T,
   typename std::enable_if<std::is_floating_point<T>::value>::type>
 {
   static constexpr bool func (T const & lhs, T const & rhs)
    { return (lhs - rhs) < 1e-10; }
 };

you avoid the ambiguity problem because the typedCompareHelper specialization in more specialized of the generic one.

You can simply add more specializations for different special cases making only attention in avoiding collisions (different specializations of the same level that apply over the same type).

Your typedCompare() become simply

template <typename T>
bool typedCompare (T const & lhs, T const & rhs)
 { return typedCompareHelper<T>::func(lhs, rhs); }


问:
Element Push without closing tag JSX
I want to execute the below recursive function, the problem is ul Since when the function is called I'm pushing a ul tag and at the end of forEach I'm closing it. Incase if I change outputArray.push(
) with the closing
 then it works fine, but that won't serve my purpose.

Any way around it?

Note : It is a recursive function.

function flatten(data, outputArray) {
      outputArray.push(
)
        data.forEach(function (asset){
            if(asset.children.length) {
              outputArray.push(
<button onClick={_ => this.appendAssets(asset.name)}>{asset.name}</button>
);
              flatten(asset.children, outputArray);
            }
            else{
              outputArray.push(
<button onClick={_ => this.appendAssets(asset.name)}>{asset.name}</button>
);
            }
        });
      outputArray.push(
)
    }```

答:
Consider following structure</p>

```<code>let enclosure = [];
loop {
   enclosure.push(jsx);
}
return (<ul>{enclosre}</ul>);
</code>```

Title: Element Push without closing tag JSX

Body:
Consider following structure

let enclosure = [];
loop {
   enclosure.push(jsx);
}
return (<ul>{enclosre}</ul>);


问:
Can this be refactored to use generic functional principles?
A comparator function ascending accepts two arguments - a and b. It must return an integer comparing the two.

I have a list that I want to sort by name, so I wrote the following functions.

Is there a functional idiom I can use to combine these two functions, rather than having byName take responsibility for composing the resulting function?

```<code>const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i.get('name');
const useTogether = (...fns) => ...; // is there an idiomatic function like this?

// usage
items.sort(useTogether(byName(ascending)));
</code>```

答:
You're looking for contravariant functors

To appreciate them properly, let's start by examining the most basic sorting program

const compare = (a, b) =>
  a.localeCompare (b)

const data =
  [ 'Cindy'
  , 'Alice'
  , 'Darius'
  , 'Bertrand'
  ]

data.sort (compare)

console.log (data)
// Alice, Bertrand, Cindy, Darius```
</div>
</div>
</p>

<p>Nothing special there. Let's make our first contravariant functor, <code>Comparison</code>. The sort causes mutation, but it's just for demonstration anyway. Focus on <code>contramap</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const compare = (a, b) =>
  a.localeCompare (b)

const Comparison = (f = compare) =>
  ({ contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Cindy' }
  , { name: 'Alice' }
  , { name: 'Darius' }
  , { name: 'Bertrand' }
  ]

Comparison ()
  .contramap (x => x.name)
  .sort (data)

console.log (data)
// Alice, Bertrand, Cindy, Darius</code>```

Composition law holds

```<code>m.contramap(f).contramap(g) == m.contramap(compose(f,g))
</code>```

const compare = (a, b) =>
  a.localeCompare (b)

const Comparison = (f = compare) =>
  ({ contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Cindy' }
  , { name: 'Alice' }
  , { name: 'Darius' }
  , { name: 'Bertrand' }
  ]

const compose = (f, g) =>
  x => f (g (x))

Comparison ()
  .contramap (compose (x => x.substr (1), x => x.name))
  // equivalent to
  // .contramap (x => x.substr (1)) // sort starting with second letter
  // .contramap (x => x.name)       // get name property
  .sort (data)

console.log (data)
// sorted by second letter this time (A, E, I, L)
// Darius, Bertrand, Cindy, Alice
//  ^       ^         ^      ^```
</div>
</div>
</p>

<p>Implementing the monoid interface gives you cool things like "multi-sort"</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Eq =
  0

const Lt =
  -1

const Gt =
  1

const Ord =
  { empty: Eq
  , concat: (a,b) =>
      a === Eq ? b : a
  }

const compare = (a, b) =>
  a < b ? Lt
    : a > b ? Gt
      : Eq

const Comparison = (f = compare) =>
  ({ compare: f
   , contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , concat : m =>
       Comparison ((a, b) =>
         Ord.concat (f (a, b), m.compare (a, b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Alicia', age: 10 }
  , { name: 'Alice', age: 15 }
  , { name: 'Alice', age: 10 }
  , { name: 'Alice', age: 16 }
  ]

const sortByName =
  Comparison ()
    .contramap (x => x.name)

const sortByAge =
  Comparison ()
    .contramap (x => x.age)

sortByName
  .concat (sortByAge)
  .sort (data)

console.log ('sorted by (name,age)', data)
// Alice 10
// Alice 15
// Alice 16
// Alicia 10

sortByAge
  .concat (sortByName)
  .sort (data)

console.log ('sorted by (age,name)', data)
// Alice 10
// Alicia 10
// Alice 15
// Alice 16</code>```

Read the linked article for more useful information and an introduction to transducers

Body:
A comparator function ascending accepts two arguments - a and b. It must return an integer comparing the two.

I have a list that I want to sort by name, so I wrote the following functions.

Is there a functional idiom I can use to combine these two functions, rather than having byName take responsibility for composing the resulting function?

const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i.get('name');
const useTogether = (...fns) => ...; // is there an idiomatic function like this?

// usage
items.sort(useTogether(byName(ascending)));

Body:
You're looking for contravariant functors

To appreciate them properly, let's start by examining the most basic sorting program

const compare = (a, b) =>
  a.localeCompare (b)

const data =
  [ 'Cindy'
  , 'Alice'
  , 'Darius'
  , 'Bertrand'
  ]

data.sort (compare)

console.log (data)
// Alice, Bertrand, Cindy, Darius

Nothing special there. Let's make our first contravariant functor, Comparison. The sort causes mutation, but it's just for demonstration anyway. Focus on contramap

const compare = (a, b) =>
  a.localeCompare (b)

const Comparison = (f = compare) =>
  ({ contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Cindy' }
  , { name: 'Alice' }
  , { name: 'Darius' }
  , { name: 'Bertrand' }
  ]

Comparison ()
  .contramap (x => x.name)
  .sort (data)

console.log (data)
// Alice, Bertrand, Cindy, Darius

Composition law holds

m.contramap(f).contramap(g) == m.contramap(compose(f,g))

const compare = (a, b) =>
  a.localeCompare (b)

const Comparison = (f = compare) =>
  ({ contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Cindy' }
  , { name: 'Alice' }
  , { name: 'Darius' }
  , { name: 'Bertrand' }
  ]

const compose = (f, g) =>
  x => f (g (x))

Comparison ()
  .contramap (compose (x => x.substr (1), x => x.name))
  // equivalent to
  // .contramap (x => x.substr (1)) // sort starting with second letter
  // .contramap (x => x.name)       // get name property
  .sort (data)

console.log (data)
// sorted by second letter this time (A, E, I, L)
// Darius, Bertrand, Cindy, Alice
//  ^       ^         ^      ^

Implementing the monoid interface gives you cool things like "multi-sort"

const Eq =
  0

const Lt =
  -1

const Gt =
  1

const Ord =
  { empty: Eq
  , concat: (a,b) =>
      a === Eq ? b : a
  }

const compare = (a, b) =>
  a < b ? Lt
    : a > b ? Gt
      : Eq

const Comparison = (f = compare) =>
  ({ compare: f
   , contramap : g =>
       Comparison ((a, b) => f (g (a), g (b)))
   , concat : m =>
       Comparison ((a, b) =>
         Ord.concat (f (a, b), m.compare (a, b)))
   , sort : xs =>
       xs.sort (f)
   })

const data =
  [ { name: 'Alicia', age: 10 }
  , { name: 'Alice', age: 15 }
  , { name: 'Alice', age: 10 }
  , { name: 'Alice', age: 16 }
  ]

const sortByName =
  Comparison ()
    .contramap (x => x.name)

const sortByAge =
  Comparison ()
    .contramap (x => x.age)

sortByName
  .concat (sortByAge)
  .sort (data)

console.log ('sorted by (name,age)', data)
// Alice 10
// Alice 15
// Alice 16
// Alicia 10

sortByAge
  .concat (sortByName)
  .sort (data)

console.log ('sorted by (age,name)', data)
// Alice 10
// Alicia 10
// Alice 15
// Alice 16

Read the linked article for more useful information and an introduction to transducers


问:
Batch convert dae to scn
Is there a way to batch convert Collada dae files to Scenekit scn files?

My project uses approx 50 models created in sketchup that are updated regularly, these are exported to DAE but also need to be converted to SCN files for usage in xCode. I know it can be done manually via xCode and "Convert to SceneKit scene file format (scn)" but this take to much manual labour.

答: @HixField has a good shell script for invoking scntool. Another way to do that is to leverage Xcode's build system, which does the same thing for any .dae files you put in a project's scnassets folder. Even if you're not bundling those files in your app, you can create a dummy Xcode target or project that contains all the assets you want to convert, and it'll convert them all whenever you build the target. (Which you could then integrate into a CI system or other automation.)

Title: Batch convert dae to scn


问:
Find a range address #2
So because I wasn't specific with my previous question I need your help again.

Basically, I asked if there's a way to find a range between some value/cells, because I was sure that when i will get that range this below will work (so I can select lets say "headers" of the columns with all the data below:

totalRange(Selection, Selection.End(xlDown)).Select

So one of you came up with help and provide code below, which is working just fine, but i'm not sure if I can use it in my case. Because as I said, what im trying to do is to first find a range between  two cells in firstrow and then select all the data below with it. Something like on screenshot below.
I want to find Col7 and Col12 and then select the whole range below.
The problem is this Col7/Col12 range might start from different column in each file.

https://ibb.co/gtuvEb

```<code>Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long, r2 As Long

r1 = 0
r2 = 0

c1 = 1
c2 = 1
With Worksheets("Sheet1") 'Change to your worksheet

    c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
    c1 = c1 - 1

    c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
    c2 = c2 - 1

    On Error Resume Next
        r1 = Application.WorksheetFunction.Match("A", .Columns(c1), 0)
        r2 = Application.WorksheetFunction.Match("B", .Columns(c2), 0)
    On Error GoTo 0

    If r1 > 0 And r2 > 0 Then
        Set totalRange = .Range(.Cells(r1, c1), .Cells(r2, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub
</code>```

Thanks for any suggestions.

答:
```<code>Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long

With Worksheets("Sheet1") 'Change to your worksheet

    On Error Resume Next
        'Find the Columns
        c1 = Application.WorksheetFunction.Match("Col7", .Rows(1), 0)
        c2 = Application.WorksheetFunction.Match("Col12", .Rows(1), 0)
    On Error GoTo 0

    If c1 > 0 And c2 > 0 Then
        'Find last row with data
        r1 = .Cells(.Rows.Count, c2).End(xlUp).Row
        'Set the range to the whole
        Set totalRange = .Range(.Cells(1, c1), .Cells(r1, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub
</code>```

Title: Find a range address #2

Body:
So because I wasn't specific with my previous question I need your help again.

Basically, I asked if there's a way to find a range between some value/cells, because I was sure that when i will get that range this below will work (so I can select lets say "headers" of the columns with all the data below:

totalRange(Selection, Selection.End(xlDown)).Select

So one of you came up with help and provide code below, which is working just fine, but i'm not sure if I can use it in my case. Because as I said, what im trying to do is to first find a range between  two cells in firstrow and then select all the data below with it. Something like on screenshot below.
I want to find Col7 and Col12 and then select the whole range below.
The problem is this Col7/Col12 range might start from different column in each file.

https://ibb.co/gtuvEb

Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long, r2 As Long

r1 = 0
r2 = 0

c1 = 1
c2 = 1
With Worksheets("Sheet1") 'Change to your worksheet

    c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
    c1 = c1 - 1

    c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
    c2 = c2 - 1

    On Error Resume Next
        r1 = Application.WorksheetFunction.Match("A", .Columns(c1), 0)
        r2 = Application.WorksheetFunction.Match("B", .Columns(c2), 0)
    On Error GoTo 0

    If r1 > 0 And r2 > 0 Then
        Set totalRange = .Range(.Cells(r1, c1), .Cells(r2, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub

Thanks for any suggestions.


问:
Designs for counting occurrences of events in streaming processing?
The following discussion is in the context of Apache Flink:

Imagine that we have a keyedStream whose key is its id and event time is its timestamp, if we want to calculate how many events arrived within 10 minutes for each event.

The problems need to be solved are:

How to design the window ?

We can create a window of 10 minutes after each event arrives, but this mean that for each event, there will be a delay of 10 minutes because the wait for the window of 10 minutes.

We can create a window of 10 minutes which takes the timestamp of each event as the maximum timestamp in this window, which means that we don't need to wait for 10 minutes, because we take the last 10 minutes of elements before the element arrives. But this kind of window is not easy to define, as far as I know.

How to deal with memory or other resource issues ? Even we succeed to create a window, maybe the kind of ids of events are diverse, so many window like this, how the system keep their states in the memory ? There is a big possibility of stakoverflow of memory.

Maybe there are some problems that I don't mention here, or maybe there are some good solutions except window(i.e. Patterns). If you have a good solutions, please give me a clue, thank you.

答:
You could do this with a GlobalWindow and a Trigger than fires on every event and an Evictor that removes events that are more than 10 minutes old before counting the remaining events. (A naive implementation could easily perform very poorly, however.)

Yes, this may require keeping a lot of state -- you'll be keeping every event from the past 10 minutes (well, you only need to store the timestamp from each event). If you setup the RocksDB state backend then Flink will spill to disk if need be, but with some obvious performance penalty. Probably better to use a cluster large enough to hold 10 minutes of traffic in memory. Even at one million events per second, each with a 32-bit timestamp, that's only 2.4GB in 10 minutes (1 million events per second x 600 seconds x 4 bytes per event) -- doesn't seem like a problem at all.


问:
Does protobuf-net support nullable types?
Is it possible to generate nullable members in protobuf-net?</p>

```<code>message ProtoBuf1 {
    optional Int32? databit = 1;
    optional Nullable<bool> databool = 2;
}
</code>```

答:
Yes, but it doesn't generate them by default if you are doing codegen from .proto.

If this is just C#, of course, you don't need a .proto - just:

```<code>[ProtoContract]
public class ProgoBuf1
{
    [ProtoMember(1)]
    public int? Foo {get;set;}

    [ProtoMember(2)]
    public float? Bar {get;set;}
}
</code>```

If you are working from .proto, you could consider copying and editing csharp.xslt to suit your preferred layout.

Body:
Is it possible to generate nullable members in protobuf-net?

message ProtoBuf1 {
    optional Int32? databit = 1;
    optional Nullable<bool> databool = 2;
}

Body:
Yes, but it doesn't generate them by default if you are doing codegen from .proto.

If this is just C#, of course, you don't need a .proto - just:

[ProtoContract]
public class ProgoBuf1
{
    [ProtoMember(1)]
    public int? Foo {get;set;}

    [ProtoMember(2)]
    public float? Bar {get;set;}
}

If you are working from .proto, you could consider copying and editing csharp.xslt to suit your preferred layout.


问:
Can I delete all migration files and start from scratch?
I have a Rails-API app that I'm going to re-deploy after a long time. The app is non-production, but I am ready to deploy the production version. I want to basically delete all the migration files and start from scratch using the schema, is there any problem with this approach? Assuming I can do this, what do I need to alter the schema.rb to? Is this a common practice? Seems reasonable to me.</p>

```<code># what do I change the version param value to?
ActiveRecord::Schema.define(version: 20171129023538)
</code>```

答:
Migrations are used to update your database or to rollback to previous versions. Once migrations have been run in all environments, they're never looked at again (unless you're manually messing around with the schema_migrations table of course). Once all your migrations have been run, the current state of the database is in db/schema.rb (or db/structure.sql) so schema.rb is all you need to start with a fresh database.

I tend to clear out old migrations every couple months just to cut down on clutter.

As far as the version goes, you can leave it alone. As long as it represent a time in the past (such as 2017-11-29 02:35:38) and it is lower than any migrations that need to be run (which doesn't apply as you're deleting them all) then it doesn't matter what it is.

Go ahead and clear out all the migrations, they're already reflected in schema.rb and you can always dig them out of revision control if you really need them.

Body:
I have a Rails-API app that I'm going to re-deploy after a long time. The app is non-production, but I am ready to deploy the production version. I want to basically delete all the migration files and start from scratch using the schema, is there any problem with this approach? Assuming I can do this, what do I need to alter the schema.rb to? Is this a common practice? Seems reasonable to me.

# what do I change the version param value to?
ActiveRecord::Schema.define(version: 20171129023538)


问:
How to add item to dynamically created QComboboxes in Pyqt
I'm trying to add items to the dynamically created comboboxes.
I know my variables override themselves and i can't get the desired result. Combobox actions add the items to the last one which i don't want. It needs to add items to the right next one.

```<code>from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
i = 1

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(620, 500)

        #LAYOUT SETTINGS
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(30, 30))
        self.pushButton.setMaximumSize(QtCore.QSize(30, 30))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)

        self.pushButton.clicked.connect(self.addNewCombobox)
        self.pushButton.clicked.connect(self.addNewSCombobox)
        self.pushButton.clicked.connect(self.addNewButton)

        self.comboBox = QtGui.QComboBox(self.centralwidget)
        self.comboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.gridLayout.addWidget(self.comboBox, 0, 1, 1, 1)

        self.scomboBox = QtGui.QComboBox(self.centralwidget)
        self.scomboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.scomboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.scomboBox.setObjectName(_fromUtf8("ScomboBox"))
        self.gridLayout.addWidget(self.scomboBox, 0, 2, 1, 1)

        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 9999, 0, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def addNewButton(self):
        print "Added"
        global i
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(30, 30))
        self.pushButton.setMaximumSize(QtCore.QSize(30, 30))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.setText("-")
        self.gridLayout.addWidget(self.pushButton, i, 0, 1, 1)
        self.pushButton.clicked.connect(self.comboBox.deleteLater)
        self.pushButton.clicked.connect(self.scomboBox.deleteLater)
        self.pushButton.clicked.connect(self.pushButton.deleteLater)
        i += 1

    def addNewCombobox(self):
        self.comboBox = QtGui.QComboBox(self.centralwidget)
        self.comboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.comboBox.addItem("foo")
        self.comboBox.addItem("bar")
        self.comboBox.setObjectName(_fromUtf8("comboBox_" + str(i)))
        self.gridLayout.addWidget(self.comboBox, i, 1, 1, 1)
        self.comboBox.activated[str].connect(self.addItem)

    def addNewSCombobox(self):
        self.scomboBox = QtGui.QComboBox(self.centralwidget)
        self.scomboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.scomboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.scomboBox.setObjectName(_fromUtf8("ScomboBox_" + str(i)))
        self.gridLayout.addWidget(self.scomboBox, i, 2, 1, 1)

    def addItem(self, activetext):
        # sendin = self.centralwidget.sender()
        self.scomboBox.addItem(activetext)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.comboBox.setItemText(0, _translate("MainWindow", "New Item", None))
        self.pushButton.setText(_translate("MainWindow", "+", None))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

I think i need some changes right here. I tried setting objectnames and somehow connect comboboxes but i didn't.

```<code>    def addItem(self, activetext):
    # sendin = self.centralwidget.sender()
    self.scomboBox.addItem(activetext)
</code>```

答:
I solve the problem. Found the use of ObjectName and findChild and make some changes.Voila!

Here is solution.

```<code>    def addItem(self, text):
    sendin  = self.centralwidget.sender()
    objname = str(sendin.objectName())
    objnamevalue =  objname.split('_')[1]
    self.centralwidget.findChild(QtGui.QComboBox, 'ScomboBox_' + objnamevalue).addItem(text)
</code>```

Body:
I'm trying to add items to the dynamically created comboboxes.
I know my variables override themselves and i can't get the desired result. Combobox actions add the items to the last one which i don't want. It needs to add items to the right next one.

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
i = 1

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(620, 500)

        #LAYOUT SETTINGS
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(30, 30))
        self.pushButton.setMaximumSize(QtCore.QSize(30, 30))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)

        self.pushButton.clicked.connect(self.addNewCombobox)
        self.pushButton.clicked.connect(self.addNewSCombobox)
        self.pushButton.clicked.connect(self.addNewButton)

        self.comboBox = QtGui.QComboBox(self.centralwidget)
        self.comboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.gridLayout.addWidget(self.comboBox, 0, 1, 1, 1)

        self.scomboBox = QtGui.QComboBox(self.centralwidget)
        self.scomboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.scomboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.scomboBox.setObjectName(_fromUtf8("ScomboBox"))
        self.gridLayout.addWidget(self.scomboBox, 0, 2, 1, 1)

        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 9999, 0, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def addNewButton(self):
        print "Added"
        global i
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(30, 30))
        self.pushButton.setMaximumSize(QtCore.QSize(30, 30))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.setText("-")
        self.gridLayout.addWidget(self.pushButton, i, 0, 1, 1)
        self.pushButton.clicked.connect(self.comboBox.deleteLater)
        self.pushButton.clicked.connect(self.scomboBox.deleteLater)
        self.pushButton.clicked.connect(self.pushButton.deleteLater)
        i += 1

    def addNewCombobox(self):
        self.comboBox = QtGui.QComboBox(self.centralwidget)
        self.comboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.comboBox.addItem("foo")
        self.comboBox.addItem("bar")
        self.comboBox.setObjectName(_fromUtf8("comboBox_" + str(i)))
        self.gridLayout.addWidget(self.comboBox, i, 1, 1, 1)
        self.comboBox.activated[str].connect(self.addItem)

    def addNewSCombobox(self):
        self.scomboBox = QtGui.QComboBox(self.centralwidget)
        self.scomboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.scomboBox.setMaximumSize(QtCore.QSize(16777215, 30))
        self.scomboBox.setObjectName(_fromUtf8("ScomboBox_" + str(i)))
        self.gridLayout.addWidget(self.scomboBox, i, 2, 1, 1)

    def addItem(self, activetext):
        # sendin = self.centralwidget.sender()
        self.scomboBox.addItem(activetext)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.comboBox.setItemText(0, _translate("MainWindow", "New Item", None))
        self.pushButton.setText(_translate("MainWindow", "+", None))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

I think i need some changes right here. I tried setting objectnames and somehow connect comboboxes but i didn't.

    def addItem(self, activetext):
    # sendin = self.centralwidget.sender()
    self.scomboBox.addItem(activetext)

Body:
I solve the problem. Found the use of ObjectName and findChild and make some changes.Voila!

Here is solution.

    def addItem(self, text):
    sendin  = self.centralwidget.sender()
    objname = str(sendin.objectName())
    objnamevalue =  objname.split('_')[1]
    self.centralwidget.findChild(QtGui.QComboBox, 'ScomboBox_' + objnamevalue).addItem(text)


问:
Algorithms - Circular Array Rotation
Is this linear complexity implementation of circular array rotation correct?

n = number of elements
k = number of rotations

```<code>    int write_to     = 0;
    int copy_current = 0;
    int copy_final   = a[0];
    int rotation     = k;
    int position     = 0;

    for (int i = 0; i < n; i++) {
        write_to     = (position + rotation) % n;
        copy_current = a[write_to];
        a[write_to]  = copy_final;
        position     = write_to;
        copy_final   = copy_current;
     }
</code>```

答:
Rotate an Array of length n for k times in left or right directions.

The code is in Java

I define a Direction Enum:

```<code>public enum Direction {
    L, R
};
</code>```

Rotation with times and direction:

```<code>public static final void rotate(int[] arr, int times, Direction direction) {
    if (arr == null || times < 0) {
        throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
    }
    int offset = arr.length - times % arr.length;
    if (offset > 0) {
        int[] copy = arr.clone();
        for (int i = 0; i < arr.length; ++i) {
            int j = (i + offset) % arr.length;
            if (Direction.R.equals(direction)) {
                arr[i] = copy[j];
            } else {
                arr[j] = copy[i];
            }
        }
    }
}
</code>```

Complexity: O(n).

Example:
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Rotate 3 times left
Output: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]

Input: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Rotate 3 times right
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Title: Algorithms - Circular Array Rotation

Body:
Is this linear complexity implementation of circular array rotation correct?

n = number of elements
k = number of rotations

    int write_to     = 0;
    int copy_current = 0;
    int copy_final   = a[0];
    int rotation     = k;
    int position     = 0;

    for (int i = 0; i < n; i++) {
        write_to     = (position + rotation) % n;
        copy_current = a[write_to];
        a[write_to]  = copy_final;
        position     = write_to;
        copy_final   = copy_current;
     }

Body:
Rotate an Array of length n for k times in left or right directions.

The code is in Java

I define a Direction Enum:

public enum Direction {
    L, R
};

Rotation with times and direction:

public static final void rotate(int[] arr, int times, Direction direction) {
    if (arr == null || times < 0) {
        throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
    }
    int offset = arr.length - times % arr.length;
    if (offset > 0) {
        int[] copy = arr.clone();
        for (int i = 0; i < arr.length; ++i) {
            int j = (i + offset) % arr.length;
            if (Direction.R.equals(direction)) {
                arr[i] = copy[j];
            } else {
                arr[j] = copy[i];
            }
        }
    }
}

Complexity: O(n).

Example:
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Rotate 3 times left
Output: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]

Input: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Rotate 3 times right
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


问:
How to set the foreign key entity in Hibernate
Well, I am new to Hibernate and the question I have is quite trivial. I found few answers explaining it but may be I am not getting it exactly and I am still stuck.

I found that to map a foreign key I need to map an entity, like below

```<code>// this is GroupEntity
// mapping bond_id from Bond table
   @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name ="bond_id")
    private BondEntity bondEntity;
</code>```

I believe this maps bond_id column from BondEntity's table to bond_id of present table.

Now how do I set this bond_id to DB while persisting the entity of this table. Unlike other columns this field now takes an object.

I tried setting only the bond_id, like

```<code>BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);
</code>```

If I go ahead and try persisting this entity, I get detached entity passed to persist in hibernate.

Whats the correct way of doing it. May be I am not getting it correctly.

答:
This is incorrect

```<code>@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;
</code>```

Perhaps you want to use

```<code>@ManyToOne
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;
</code>```

Please, read this

what is @JoinColumn and how it is used in Hibernate

This should work. Maybe you are using it in the incorrect place

```<code>BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);
</code>```

You can try to use session.load() in place of above.

Body:
Well, I am new to Hibernate and the question I have is quite trivial. I found few answers explaining it but may be I am not getting it exactly and I am still stuck.

I found that to map a foreign key I need to map an entity, like below

// this is GroupEntity
// mapping bond_id from Bond table
   @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name ="bond_id")
    private BondEntity bondEntity;

I believe this maps bond_id column from BondEntity's table to bond_id of present table.

Now how do I set this bond_id to DB while persisting the entity of this table. Unlike other columns this field now takes an object.

I tried setting only the bond_id, like

BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);

If I go ahead and try persisting this entity, I get detached entity passed to persist in hibernate.

Whats the correct way of doing it. May be I am not getting it correctly.

Body:
This is incorrect

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;

Perhaps you want to use

@ManyToOne
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;

Please, read this

what is @JoinColumn and how it is used in Hibernate

This should work. Maybe you are using it in the incorrect place

BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);

You can try to use session.load() in place of above.


问:
Is there an R equivalent of python's string `format` function?
In python there's a nice function (str .format) that can really easily replace variables (encoded like {variable}) in a string with values stored in a dict (with values named by variable name). Like so:

```<code>vars=dict(animal="shark", verb="ate", noun="fish")
string="Sammy the {animal} {verb} a {noun}."
print(string.format(**vars))
</code>```

Sammy the shark ate a fish.

What is the simplest solution in R? Is there a built-in equivalent 2-argument function that takes a string with variables encoded in the same
way and replaces them with named values from a named list?

If there is no built-in function in R, is there one in a published package?

If there is none in a published package, what would you use to write one?

The rules: the string is given to you with variables encoded like "{variable}". The variables must be encoded as a list. I will answer with my custom-made version, but will accept an answer that does it better than I did.

答:
The stringr package almost has an exact replacement in the function str_interp. it requires just a bit of adjustment:

```<code>fmt = function(str, vals) {
    # str_interp requires variables encoded like ${var}, so we substitute
    # the {var} syntax here.
    str = stringr::str_replace_all(str, "\\{", "${")
    stringr::str_interp(str, vals)
}
</code>```

Body:
In python there's a nice function (str .format) that can really easily replace variables (encoded like {variable}) in a string with values stored in a dict (with values named by variable name). Like so:

vars=dict(animal="shark", verb="ate", noun="fish")
string="Sammy the {animal} {verb} a {noun}."
print(string.format(**vars))

Sammy the shark ate a fish.

What is the simplest solution in R? Is there a built-in equivalent 2-argument function that takes a string with variables encoded in the same
way and replaces them with named values from a named list?

If there is no built-in function in R, is there one in a published package?

If there is none in a published package, what would you use to write one?

The rules: the string is given to you with variables encoded like "{variable}". The variables must be encoded as a list. I will answer with my custom-made version, but will accept an answer that does it better than I did.

Body:
The stringr package almost has an exact replacement in the function str_interp. it requires just a bit of adjustment:

fmt = function(str, vals) {
    # str_interp requires variables encoded like ${var}, so we substitute
    # the {var} syntax here.
    str = stringr::str_replace_all(str, "\\{", "${")
    stringr::str_interp(str, vals)
}


问:
How to specify which version of perl to use on CentOS
I am running CentOS 5.4 which only has version 5.8 of perl available by default, and I have a program which requires perl 5.10, so I compiled perl 5.10 on CentOS.  How do I specify which perl I want to run the program with because the perl command uses 5.8 by default.</p>

答:
I like to make symbolic links to my different perl executables in /usr/local/bin:

```<code>$ [sudo] ln -s /path/to/perl5.10.1.exe /usr/local/bin/perl510
$ [sudo] ln -s /path/to/perl5.13.8.exe /usr/local/bin/perl513
$ ... etc. ...
$ # and just for completeness
$ ln -s /usr/bin/perl /usr/local/bin/perl58
</code>```

and then just invoke:

```<code>$ perl510 script_to_use_with_v5.10.pl
</code>```

Body:
I like to make symbolic links to my different perl executables in /usr/local/bin:

$ [sudo] ln -s /path/to/perl5.10.1.exe /usr/local/bin/perl510
$ [sudo] ln -s /path/to/perl5.13.8.exe /usr/local/bin/perl513
$ ... etc. ...
$ # and just for completeness
$ ln -s /usr/bin/perl /usr/local/bin/perl58

and then just invoke:

$ perl510 script_to_use_with_v5.10.pl


问:
Generating new random number in python?
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

```<code>import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()
</code>```

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

```<code>import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")
</code>```

答: The last line of your code is input(). All this does is take input, not store it anywhere. To store it, you have to assign it to user_number like user_number = input(). Also, (assuming you are using Python 3) input() returns a string, not a number, so it will never be equal. You have to convert it to a number with user_number = int(input())

Title: Generating new random number in python?

Body:
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")


问:
How to start with mobile testing with Appium
Can anyone suggest to startup way with Appium mobile testing. Already have knowledge of Automation testing using Selenium.</p>

答:
You can get started with Android automation which is easy to understand and resources & tutorials are easily available.

Refer : http://appium.io/slate/en/tutorial/android.html?java#

Also , if you are starting with Android first , get familiar with few basic Android commands - like ADB , AAPT .
Learn how to obtain package name of any application. UDID of Android device etc.

try this to get package name /udid of android phone - https://www.youtube.com/channel/UCEUDm1ZxsX6teks8wM71bmQ/videos
&
https://qahumor.blogspot.in/2015/06/

Hope these are helpful to get start with basic things.


问:
JavaFX Combobox List Styling
I'm trying to change the text color of a JavaFX combobox list but it does not seem to work.

```<code>.combo-box .list-cell {
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}
.combo-box-popup .list-view{
    -fx-background-color: -fx-my-menu-color;
}

.combo-box-popup .list-view .list-cell{
    -fx-text-fill: #ff0000;
    -fx-padding: 4 0 4 5;
    -fx-background-color: -fx-my-menu-color;
}

.combo-box-popup .list-view .list-cell:filled:selected, .combo-box-popup .list-view .list-cell:filled:selected:hover{
    -fx-background-color: -fx-my-menu-color-highlighted;
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}

.combo-box-popup .list-view .list-cell:filled:hover{
    -fx-background-color: -fx-my-menu-color-highlighted;
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}

.combo-box-base{
    -fx-background-color: -fx-my-menu-color;
    -fx-padding: 0;
}
</code>```

This returns the following:
The Dropdown list text is not white

How do I fix this? My CSS knowledge is not very strong.

答:
Example below should work fine - if not, remove other entries from your CSS which could affect the popop list as well. Possibly another entry has higher priority.

```<code>.combo-box-popup .list-cell {
    -fx-background-color: white;
    -fx-text-fill: red;
}
</code>```

to increase the specificity you can also try the setting below

```<code>.combo-box-popup > .list-view > .virtual-flow > .clipped-container > .sheet > .list-cell {
        -fx-background-color: white;
        -fx-text-fill: red;
}
</code>```

Title: JavaFX Combobox List Styling

Body:
I'm trying to change the text color of a JavaFX combobox list but it does not seem to work.

.combo-box .list-cell {
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}
.combo-box-popup .list-view{
    -fx-background-color: -fx-my-menu-color;
}

.combo-box-popup .list-view .list-cell{
    -fx-text-fill: #ff0000;
    -fx-padding: 4 0 4 5;
    -fx-background-color: -fx-my-menu-color;
}

.combo-box-popup .list-view .list-cell:filled:selected, .combo-box-popup .list-view .list-cell:filled:selected:hover{
    -fx-background-color: -fx-my-menu-color-highlighted;
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}

.combo-box-popup .list-view .list-cell:filled:hover{
    -fx-background-color: -fx-my-menu-color-highlighted;
    -fx-text-fill: -fx-my-menu-font-color-highlighted;
}

.combo-box-base{
    -fx-background-color: -fx-my-menu-color;
    -fx-padding: 0;
}

This returns the following:
The Dropdown list text is not white

How do I fix this? My CSS knowledge is not very strong.

Body:
Example below should work fine - if not, remove other entries from your CSS which could affect the popop list as well. Possibly another entry has higher priority.

.combo-box-popup .list-cell {
    -fx-background-color: white;
    -fx-text-fill: red;
}

to increase the specificity you can also try the setting below

.combo-box-popup > .list-view > .virtual-flow > .clipped-container > .sheet > .list-cell {
        -fx-background-color: white;
        -fx-text-fill: red;
}


问:
Xcode -- finding dead methods in a project
I am curious if there are any tools that provide partial solutions for this.  It is a tricky problem because of performSelector . . . but a tool ought to at least be able to come up with candidates, making the human's job easier.</p>

答:
Using static analysis, it is impossible to detect functions/methods that are defined but not used due to dynamic nature of Objective-C. The only reasonable solution is to run a coverage using GCov or similar tool. Even then, you will have to make your program do everything possible in order to make sure that you do not strip out some feature that was just not used during testing.

Also, this script has some interesting thoughts on this.


问:
DRBD with temprorary hostname change
I have set-up a test 2-node HA cluster for an application which writes data to local disk. DRBD has been set up for this to sync the data onto the 2nd node. My application is having dependency on the hostname to start/stop and perform any task. To have it highly available, I have set up Cluster IP and temporarily renaming my node from its actual name to the name of the virtual IP.

All this works fine with manually promoting DRBD resource to primary and mounting it on any node where the virtual IP is set at any moment.

As soon as I try to add DRBD resource in pacemaker and then to start my application with the temporary name (hostname change using hostname command, example:- nodeA:~# hostname test-ip), The HA cluster fails for DRBD and umounts from the server promoted to primary earlier. Thus I am unable to get my application fully managed by the cluster.

Is there anyway in which DRBD can work with the virtual IP's hostname (renaming a host) in a 2-node cluster?

答:
You can configure DRBD to associate with an IP address instead of a hostname via the "floating peers" feature. For example:

```<code>resource r0 {
    device /dev/drbd0;
    protocol C;

    floating 192.168.40.125:7789 {
        disk /dev/sdb;
        meta-disk internal;
    }

    floating 192.168.40.126:7789 {
        disk /dev/sdb;
        meta-disk internal;
    }
}
</code>```

This was designed for using multiple DRBD host attached to the same shared storage, but it should still work for your use case and local storage.

Title: DRBD with temprorary hostname change

Body:
You can configure DRBD to associate with an IP address instead of a hostname via the "floating peers" feature. For example:

resource r0 {
    device /dev/drbd0;
    protocol C;

    floating 192.168.40.125:7789 {
        disk /dev/sdb;
        meta-disk internal;
    }

    floating 192.168.40.126:7789 {
        disk /dev/sdb;
        meta-disk internal;
    }
}

This was designed for using multiple DRBD host attached to the same shared storage, but it should still work for your use case and local storage.


问:
Why Neo4j CSV loader doesn't increment the load with large number of records
I have a csv file with following columns-

```<code>Child_Object_ID;
Child_Object_Name;
Child_Object_Type;
Parent_Object_ID;
Parent_Object_Name;
Parent_Object_Type
</code>```

As the name goes, node that contains (Child_Object_ID Child_Object_Name and Child_Object_Type) is the child for (Parent_Object_ID Parent_Object_Name and Parent_Object_Type). These Parent Nodes could be a child for some other Parent node.

This CSV file contains 1.1 million of records. The problem that I am facing, while loading is after 100K records, I dont see any increment in the load process. But the Loading process was continuously running but I don't see any further nodes or relationship are being built.

I am using the following Cypher query to load the data into Neo4j Windows edition-

```<code>CREATE INDEX ON :Object(Object_ID)
CREATE INDEX ON :Object(Object_ID, Object_Name, Object_Type)
CREATE INDEX ON :Object(Object_Type)

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object1:Object {Object_ID:csvLine.CHILD_OBJECT_ID, Object_Name:csvLine.CHILD_OBJECT_NAME, Object_Type:csvLine.CHILD_OBJECT_TYPE})
MERGE  (object2:Object {Object_ID:csvLine.PARENT_OBJECT_ID, Object_Name:csvLine.PARENT_OBJECT_NAME, Object_Type:csvLine.PARENT_OBJECT_TYPE})
MERGE (object1)-[:Child_Of]->(object2)
</code>```

答:
Here is the updated Cypher query (re-written based on InverseFalcon suggestion) that worked:</p>

```<code>USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object1:Object {Object_ID:csvLine.CHILD_OBJECT_ID, Object_Name:COALESCE(csvLine.CHILD_OBJECT_NAME, 'NA'), Object_Type:csvLine.CHILD_OBJECT_TYPE, Folder:COALESCE(csvLine.CHILD_FOLDER, 'NA')})

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object2:Object {Object_ID:csvLine.PARENT_OBJECT_ID, Object_Name:COALESCE(csvLine.PARENT_OBJECT_NAME, 'NA'), Object_Type:csvLine.PARENT_OBJECT_TYPE, Folder:COALESCE(csvLine.PARENT_FOLDER, 'NA')})

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MATCH (a:Object {Object_ID:csvLine.CHILD_OBJECT_ID})
MATCH (b:Object {Object_ID:csvLine.PARENT_OBJECT_ID})
MERGE (a)-[:CHILD_OF]->(b)
</code>```

Body:
I have a csv file with following columns-

Child_Object_ID;
Child_Object_Name;
Child_Object_Type;
Parent_Object_ID;
Parent_Object_Name;
Parent_Object_Type

As the name goes, node that contains (Child_Object_ID Child_Object_Name and Child_Object_Type) is the child for (Parent_Object_ID Parent_Object_Name and Parent_Object_Type). These Parent Nodes could be a child for some other Parent node.

This CSV file contains 1.1 million of records. The problem that I am facing, while loading is after 100K records, I dont see any increment in the load process. But the Loading process was continuously running but I don't see any further nodes or relationship are being built.

I am using the following Cypher query to load the data into Neo4j Windows edition-

CREATE INDEX ON :Object(Object_ID)
CREATE INDEX ON :Object(Object_ID, Object_Name, Object_Type)
CREATE INDEX ON :Object(Object_Type)

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object1:Object {Object_ID:csvLine.CHILD_OBJECT_ID, Object_Name:csvLine.CHILD_OBJECT_NAME, Object_Type:csvLine.CHILD_OBJECT_TYPE})
MERGE  (object2:Object {Object_ID:csvLine.PARENT_OBJECT_ID, Object_Name:csvLine.PARENT_OBJECT_NAME, Object_Type:csvLine.PARENT_OBJECT_TYPE})
MERGE (object1)-[:Child_Of]->(object2)

Body:
Here is the updated Cypher query (re-written based on InverseFalcon suggestion) that worked:

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object1:Object {Object_ID:csvLine.CHILD_OBJECT_ID, Object_Name:COALESCE(csvLine.CHILD_OBJECT_NAME, 'NA'), Object_Type:csvLine.CHILD_OBJECT_TYPE, Folder:COALESCE(csvLine.CHILD_FOLDER, 'NA')})

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MERGE  (object2:Object {Object_ID:csvLine.PARENT_OBJECT_ID, Object_Name:COALESCE(csvLine.PARENT_OBJECT_NAME, 'NA'), Object_Type:csvLine.PARENT_OBJECT_TYPE, Folder:COALESCE(csvLine.PARENT_FOLDER, 'NA')})

USING PERIODIC COMMIT 1000
LOAD CSV WITH HEADERS FROM "file:///file1.csv" AS csvLine
MATCH (a:Object {Object_ID:csvLine.CHILD_OBJECT_ID})
MATCH (b:Object {Object_ID:csvLine.PARENT_OBJECT_ID})
MERGE (a)-[:CHILD_OF]->(b)


问:
eval an input string on button press in react
I want to create a web-app coding game with react that involves evaluating some user (javascript) input.

```<code>  constructor(props) {
    super(props);
    this.state = {
      code: ''
    };
  }

  handleChange(key) {
    return event => this.setState({ [key]: event.target.value });
  }

  funScript() {
    eval(this.state.code);
  }

  anotherScript() {
    console.log("Will this work?");
  }

  render() {
    return (
      <div>
        <input
          type={"text"}
          value={this.state.code}
          onChange={this.handleChange('code')}
         />
        <button onClick={this.funScript()} >run</button>
      </div>
    );
  }
</code>```

I was hoping that the text input would be able to evaluate javascript on button press by the user (the user types in this.anotherScript(); and the console logs "Will this work?". Unfortunately, it doesn't work and I suspect its an issue specific to React. As soon as the input box is typed in, it tries to evaluate the string (without the button even being pressed!). See here for an example: https://codesandbox.io/s/54rkp584ll

Anyone have a proper React solution that doesn't break javascript on the first character input (and evaluates the function)?

答:
Here you have funScript, which evaluates your code with proper context:

```<code>class Test {

    // ...

    funScript() {
        const code = ("" + this.state.code).replace(/this/ig, "__self__");
        const execute = new Function("__self__", code);
        execute(this);
    }

    // ...
}
</code>```

Body:
I want to create a web-app coding game with react that involves evaluating some user (javascript) input.

  constructor(props) {
    super(props);
    this.state = {
      code: ''
    };
  }

  handleChange(key) {
    return event => this.setState({ [key]: event.target.value });
  }

  funScript() {
    eval(this.state.code);
  }

  anotherScript() {
    console.log("Will this work?");
  }

  render() {
    return (

        <input
          type={"text"}
          value={this.state.code}
          onChange={this.handleChange('code')}
         />
        <button onClick={this.funScript()} >run</button>

    );
  }

I was hoping that the text input would be able to evaluate javascript on button press by the user (the user types in this.anotherScript(); and the console logs "Will this work?". Unfortunately, it doesn't work and I suspect its an issue specific to React. As soon as the input box is typed in, it tries to evaluate the string (without the button even being pressed!). See here for an example: https://codesandbox.io/s/54rkp584ll

Anyone have a proper React solution that doesn't break javascript on the first character input (and evaluates the function)?

Body:
Here you have funScript, which evaluates your code with proper context:

class Test {

    // ...

    funScript() {
        const code = ("" + this.state.code).replace(/this/ig, "__self__");
        const execute = new Function("__self__", code);
        execute(this);
    }

    // ...
}


问:
Receive AJAX response from controller function defined in included file
I have a form that submits an ajax call to the controller file below which has a function defined in another file "processes.php" [that I've included]. The challenge is receiving the json response; the browser expects to find it in the controller yet it's generated within the function. How can I retrieve the response from the function and make it readable from the controller [outside its functions] so that the response can be read by the browser?

controller.php

```<code><?php
    session_start();
    $_SESSION['postdata'] = $_POST;
    require "constants.php";
    $file = $_SESSION["Form"].".php";
    require $file;
    if( isset($_POST["Save"]) ){
        save_record($connection);
    }
</code>```

process.php

```<code><?php
    $_POST = $_SESSION['postdata'];
    function save_record($connection){
        $errors = array();      // array to hold validation errors
        $data = array();        // array to pass back data
        $name = mysqli_real_escape_string($connection, $_POST["name"]);
        $strQuery = "INSERT INTO names (name) VALUES ('$name')";
        $result = mysqli_query($connection, $strQuery); //or exit("Error in query execution attempt!");

        if($result){

            $data['success'] = true;
            $data['message'] = 'Success!';
        }
        else{
            $errors['errorinexecute'] = "Error in query execution attempt!";
        }
        mysqli_close($connection);
        unset($_SESSION["postdata"]);

        if ( ! empty($errors)) {

            // if there are items in our errors array, return those errors
            $data['success'] = false;
            $data['errors']  = $errors;
        }
        else{
            $data['success'] = true;
            $data['errors']  = $errors;
        }
        // return all our data to an AJAX call
        echo json_encode($data);

    }
?>
</code>```

答:
You can't use:

```<code>if( isset($_POST["Save"]) ){
    save_record($connection);
}
</code>```

when doing AJAX, so what I did is pass the button id into the JavaScript function like so:

```<code>onclick="saveInfo(this.id)"
</code>```

The button id shows whether it's a "Delete", "Save", "Edit" request and so on and then from there the PHP file can read like this:

```<code>if( $buttonId == "Save" ){

save_record($connection);

}
</code>```

Body:
I have a form that submits an ajax call to the controller file below which has a function defined in another file "processes.php" [that I've included]. The challenge is receiving the json response; the browser expects to find it in the controller yet it's generated within the function. How can I retrieve the response from the function and make it readable from the controller [outside its functions] so that the response can be read by the browser?

controller.php

<?php
    session_start();
    $_SESSION['postdata'] = $_POST;
    require "constants.php";
    $file = $_SESSION["Form"].".php";
    require $file;
    if( isset($_POST["Save"]) ){
        save_record($connection);
    }

process.php

<?php
    $_POST = $_SESSION['postdata'];
    function save_record($connection){
        $errors = array();      // array to hold validation errors
        $data = array();        // array to pass back data
        $name = mysqli_real_escape_string($connection, $_POST["name"]);
        $strQuery = "INSERT INTO names (name) VALUES ('$name')";
        $result = mysqli_query($connection, $strQuery); //or exit("Error in query execution attempt!");

        if($result){

            $data['success'] = true;
            $data['message'] = 'Success!';
        }
        else{
            $errors['errorinexecute'] = "Error in query execution attempt!";
        }
        mysqli_close($connection);
        unset($_SESSION["postdata"]);

        if ( ! empty($errors)) {

            // if there are items in our errors array, return those errors
            $data['success'] = false;
            $data['errors']  = $errors;
        }
        else{
            $data['success'] = true;
            $data['errors']  = $errors;
        }
        // return all our data to an AJAX call
        echo json_encode($data);

    }
?>

Body:
You can't use:

if( isset($_POST["Save"]) ){
    save_record($connection);
}

when doing AJAX, so what I did is pass the button id into the JavaScript function like so:

onclick="saveInfo(this.id)"

The button id shows whether it's a "Delete", "Save", "Edit" request and so on and then from there the PHP file can read like this:

if( $buttonId == "Save" ){

save_record($connection);

}


问:
reading special characters text from .ini file in python
I am running a script which takes a text "rAh%19u^l\&G" i.e which contains special characters as seen.

When i pass this text in my script as a argument it runs fine without any error.

example - : ./abc.py <username><pwd>

The above text is basically a password.

Now, when i place my values in a config file and read the above text, the script fails.

*******abc.ini *******

```<code>[DEFAULT]
username = rahul
pwd =  rAh%19u^l\&G
</code>```

it says

```<code>/bin/sh:M command not found.
</code>```

Reading the above values with help of config parser

******Below is the program abc.py  ******

```<code>#! /usr/bin/python

parser = configparser.ConfigParser()
parser.read('abc.ini')
username = parser.get('DEFAULT','username')
pwd = parser.get('DEFAULT','pwd')

p = subprocess.Popen(
    "abc.py {0} {1}" .format(username, pwd),
    shell=True,
    stdout=subprocess.PIPE
)

out, err = p.communicate()

print(out)
</code>```

I tried searching a lot but found nothing concrete.

So the question is how to read a text that contains special characters in a .ini file.

答:
Looks like the % character is the problem here. It has special meaning if you are using ConfigParser. If you are not using interpolation, then use just RawConfigParser instead, otherwise you must escape the % by doubling it.

When I try the example file with ConfigParser it will blow with the following exception:

```<code>InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%19u^l\\&G"'
</code>```

If I replace ConfigParser with RawConfigParser everything is fine.

The error you posted has nothing to do with it. We can't even tell if it is a python exception or a shell error message. Please update your question with the full error message. You may also want to check the sh module, a higher level wrapper around subprocess.

Body:
I am running a script which takes a text "rAh%19u^l\&G" i.e which contains special characters as seen.

When i pass this text in my script as a argument it runs fine without any error.

example - : ./abc.py <username><pwd>

The above text is basically a password.

Now, when i place my values in a config file and read the above text, the script fails.

*******abc.ini *******

[DEFAULT]
username = rahul
pwd =  rAh%19u^l\&G

it says

/bin/sh:M command not found.

Reading the above values with help of config parser

******Below is the program abc.py  ******

#! /usr/bin/python

parser = configparser.ConfigParser()
parser.read('abc.ini')
username = parser.get('DEFAULT','username')
pwd = parser.get('DEFAULT','pwd')

p = subprocess.Popen(
    "abc.py {0} {1}" .format(username, pwd),
    shell=True,
    stdout=subprocess.PIPE
)

out, err = p.communicate()

print(out)

I tried searching a lot but found nothing concrete.

So the question is how to read a text that contains special characters in a .ini file.

Body:
Looks like the % character is the problem here. It has special meaning if you are using ConfigParser. If you are not using interpolation, then use just RawConfigParser instead, otherwise you must escape the % by doubling it.

When I try the example file with ConfigParser it will blow with the following exception:

InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%19u^l\\&G"'

If I replace ConfigParser with RawConfigParser everything is fine.

The error you posted has nothing to do with it. We can't even tell if it is a python exception or a shell error message. Please update your question with the full error message. You may also want to check the sh module, a higher level wrapper around subprocess.


答:
I like to use this snippet, it makes sure that the user answers one of the following "0","1","2","3".."10" or else it keeps asking for valid input.

```<code>valid_num = [str(i) for i in range(11)]

while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
</code>```

Now to the full code:

```<code>import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(11)]

while user_number != number:

    # Ask for user input
    while True:
        user_number = input("Enter a number between 1-10: ")
        if user_number in valid_num:
            user_number = int(user_number)
            break
        else:
            print("Not valid!")

    # Check if correct guess
    if user_number == number:
        print("GREAT! You guessed the right number! :)")
    else:
        print("AWW! You guessed the wrong number, try again! :)")
</code>```

Title: Generating new random number in python?

Body:
I like to use this snippet, it makes sure that the user answers one of the following "0","1","2","3".."10" or else it keeps asking for valid input.

valid_num = [str(i) for i in range(11)]

while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")

Now to the full code:

import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(11)]

while user_number != number:

    # Ask for user input
    while True:
        user_number = input("Enter a number between 1-10: ")
        if user_number in valid_num:
            user_number = int(user_number)
            break
        else:
            print("Not valid!")

    # Check if correct guess
    if user_number == number:
        print("GREAT! You guessed the right number! :)")
    else:
        print("AWW! You guessed the wrong number, try again! :)")


问:
Jenkins - Groovy pipeline - Using FilePath gives Could not find matching constructor
Building on this suggestion:
Using FilePath to access workspace on slave in Jenkins pipeline  I am trying to get the files that are dropped into the workspace by git, and iterate through those files using eachFileRecurse, by passing in the adjusted folder.  However, when calling into FilePath, I get errors.

```<code>    import groovy.io.FileType
    import java.io.File
    import java.lang.Object
    import hudson.FilePath
    import jenkins.model.Jenkins

    def createFilePath(path) {
    return new FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path);
    }

@NonCPS // has to be NonCPS or the build breaks on the call to .each
def getFiles(dirLoc) {
    def dir = new File (dirLoc)
    def list = []
    dir.eachFileRecurse (FileType.FILES)
            {file -> if (file.name.endsWith('.txt')) {list << file}}
    return list
}
</code>```

I get this error

```<code>groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(hudson.FilePath)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1737)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1537)
</code>```

I cannot figure out what I am missing here to make this work.  Thanks in advance!

答:
There is no Constructor for java.io.file with hudson.FilePath as a parameter.

Refer to java doc at following link: https://docs.oracle.com/javase/7/docs/api/java/io/File.html

Body:
Building on this suggestion:
Using FilePath to access workspace on slave in Jenkins pipeline  I am trying to get the files that are dropped into the workspace by git, and iterate through those files using eachFileRecurse, by passing in the adjusted folder.  However, when calling into FilePath, I get errors.

    import groovy.io.FileType
    import java.io.File
    import java.lang.Object
    import hudson.FilePath
    import jenkins.model.Jenkins

    def createFilePath(path) {
    return new FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path);
    }

@NonCPS // has to be NonCPS or the build breaks on the call to .each
def getFiles(dirLoc) {
    def dir = new File (dirLoc)
    def list = []
    dir.eachFileRecurse (FileType.FILES)
            {file -> if (file.name.endsWith('.txt')) {list << file}}
    return list
}

I get this error

groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(hudson.FilePath)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1737)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1537)

I cannot figure out what I am missing here to make this work.  Thanks in advance!


问:
Android - How to Monitor Hardware Buttons when Screen Off or Not in Focus?
Didnt see anything recently on Stack regarding this matter.  I'm hoping someone has finally come up with  a solution.  This is an app development question.

I want to monitor the hardware buttons (ie. Power, Volume, Home, Back, Menu) and if tapped in quick succession 3 times it is intercepted and passed to my app, which could be a service if need be.

Now the catch: i want to be able to do this while the screen is not awake or the screen is locked or if the app is not in focus (ie. the system is in Launcher or some other app).  If the hardware button is tapped in some defined sequence my app gets the information.  BroadcastReceiver seems interesting but i dont see this ability for my scenario (maybe just Volume key only).

I'm wondering if a combo of a special Lockscreen app + Launcher app + Service all chained together could overcome the limitations.

Ideally the app would work under Android 4.4+ and on a Non-Rooted device but i'm also open to Rooted only.  I'm looking into the app, TASKER, to see if it somehow gained the ability to monitor hardware buttons as described.

Thanks.

答: Apparently you can monitor the volume buttons by use of ContentObserver as described in the answer to this question.


问:
Thread thread = new Thread(() -> { /code } and Executorservice.submit(thread). How to write junit on this using powermock
Please help me write Junit for this piece of code using Mockito /Powermock, Finding it difficult due to lamda expression and executor service.</p>

```<code>public class myClass {

    ExecutorService executorService;

    public void testMethod(String a){
        Thread thread = new Thread(() -> {
            //logic
            a= testDAo.getStatus();
            while (true) {
                if (Thread.interrupted()) {
                    break;
                }

                if (a() != "done" || a() != "fail") {
                    Thread.yield();
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    break;
                }
            }
        }
        Future task = executorService.submit(thread);

        while (!task.isDone()) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        }
    }

}
</code>```

答:
Various things here:

first of all: for testing executors and parallel execution, using a same thread executor can be extremely helpful (because it takes out the parallel aspect)

you have difficulties writing a unit test - because your production code is way too complicated.

Thus the real answer is: step back and improve your production code. Why again are you pushing a thread into an executor service?

The executor service is already doing things on a thread pool (at least that is how you normally use them). So you push a thread into a thread pool, and then you have code that waits "two" times (first within that thread, and then outside on the future). That just adds a ton of complexity for small gain.

Long story short:

I would get rid of that "inner thread" - just have the executor task wait until the result becomes available

Then: if lambda's give you trouble - then don't use them. Just create a named small class that implements that code. And then you can write unit tests for that small class. In other words: don't create huge "units" that do 5 different things. The essence of a good unit is to one thing (single responsibility principle!). And as soon as you follow that idea testing becomes much easier, too.

Body:
Please help me write Junit for this piece of code using Mockito /Powermock, Finding it difficult due to lamda expression and executor service.

public class myClass {

    ExecutorService executorService;

    public void testMethod(String a){
        Thread thread = new Thread(() -> {
            //logic
            a= testDAo.getStatus();
            while (true) {
                if (Thread.interrupted()) {
                    break;
                }

                if (a() != "done" || a() != "fail") {
                    Thread.yield();
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    break;
                }
            }
        }
        Future task = executorService.submit(thread);

        while (!task.isDone()) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        }
    }

}


问:
Filter using Underscore.js
I need to filter the JSON above using Underscore.js

How can I return just the items that "Balance" is different from 0

{
 Currency: 'BCC',
 Balance: 0,
 Available: 0,
 Pending: 0,
 CryptoAddress: null
}, {
 Currency: 'BLOCK',
 Balance: 0,
 Available: 0,
 Pending: 0,
 CryptoAddress: 'Bd24akqYDG97k6xmUqsnxAtrBRoXeffQhx'
}, {
 Currency: 'BTC',
 Balance: 0.00153928,
 Available: 0.00153928,
 Pending: 0,
 CryptoAddress: '1BgWkjF1mwe1MZoCvxMmfSJ6fppNMD5GSx'
}, {
 Currency: 'BTG',
 Balance: 2e-8,
 Available: 2e-8,
 Pending: 0,
 CryptoAddress: null
}```

答:
Try this:</p>

```<code>_.filter(yourList, function(obj){
   return obj.Balance !== 0
})
</code>```

Title: Filter using Underscore.js

Body:
Try this:

_.filter(yourList, function(obj){
   return obj.Balance !== 0
})


问:
IEnumerable from IEnumerator
I have writen about custom IEnumerator. Whats the simplest way to make IEnumerable from it ? Ideal solution (one line of code) would be if there was some class for that purpose. Or do I have to create my own ?

答:
There's no built-in method, unfortunately. I have this extension method that I use often enough:</p>

```<code>static IEnumerable Iterate(this IEnumerator iterator)
{
while (iterator.MoveNext())
    yield return iterator.Current;
}
</code>```

Title: IEnumerable from IEnumerator

Body:
There's no built-in method, unfortunately. I have this extension method that I use often enough:

static IEnumerable Iterate(this IEnumerator iterator)
{
while (iterator.MoveNext())
    yield return iterator.Current;
}