问:
Reducing template parameter with using or typedef
I'm trying to increase my code readabiliy by introducing the "using" keyword.

```<code>namespace EigenRM
{
    template<typename T>
    using MatrixX<T> = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
}
</code>```

This code is not working.
I've seen examples using "using" to remove all template parameters but none for retaining one. Is this even possible?

答:
Try removing the <T> after MatrixX

```<code>template<typename T>
using MatrixX<T> = Eigen::Matrix<T, ...
// wrong ....^^^
</code>```

If you precede the using definition of a name foo with a template declaration, it's implicit that you're defining the template argument over foo, so simply

```<code>namespace EigenRM
{
    template<typename T>
    using MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
}
</code>```

-- EDIT --

The OP says

This is exactly what i am not trying to do. I am trying to write EigenRM::MatrixX<double> //instead of Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> within an untemplated function

This is exactly what you get if you remove the "<T>": EigenRM::MatrixX<double> become an alias for Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>.

I'm without an Eigen installation but the following example should explain what I mean

```<code>#include <type_traits>

template <typename, typename, typename>
struct foo;

template <typename T>
using bar = foo<T, float, int>;

int main ()
 {
   static_assert(std::is_same< bar<double>,
                               foo<double, float, int> >{}, "!");
 }
</code>```

Body:
I'm trying to increase my code readabiliy by introducing the "using" keyword.

namespace EigenRM
{
    template<typename T>
    using MatrixX<T> = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
}

This code is not working.
I've seen examples using "using" to remove all template parameters but none for retaining one. Is this even possible?

Body:
Try removing the <T> after MatrixX

template<typename T>
using MatrixX<T> = Eigen::Matrix<T, ...
// wrong ....^^^

If you precede the using definition of a name foo with a template declaration, it's implicit that you're defining the template argument over foo, so simply

namespace EigenRM
{
    template<typename T>
    using MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
}

-- EDIT --

The OP says

This is exactly what i am not trying to do. I am trying to write EigenRM::MatrixX<double> //instead of Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> within an untemplated function

This is exactly what you get if you remove the "<T>": EigenRM::MatrixX<double> become an alias for Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>.

I'm without an Eigen installation but the following example should explain what I mean

#include <type_traits>

template <typename, typename, typename>
struct foo;

template <typename T>
using bar = foo<T, float, int>;

int main ()
 {
   static_assert(std::is_same< bar<double>,
                               foo<double, float, int> >{}, "!");
 }


来源: stackexchange

问:
Immutable.js setIn not working
I have the following list that I'm trying to return a new List from, but I keep getting the error shown below. Any thoughts?

```<code>export const questions = List([
  {uuid: uuid(), order: 0, text: 'Which country do you live in?', choices: [
    { choice: 'United States', added: true },
    { choice: 'Canada', added: true },
    { choice: 'Australia', added: true }
  ]},
  {uuid: uuid(), order: 1, text: 'Which country were you born in?', choices: [
    { choice: 'Mexico', added: true },
    { choice: 'California', added: true },
    { choice: 'Seoul', added: true }
  ]}
]);

questions.setIn([0, 'text'], 'changed')
</code>```

Results in this error:

```<code>immutable.js:870 Uncaught Error: invalid keyPath
    at invariant (immutable.js:870)
    at updateInDeepMap (immutable.js:1974)
    at updateInDeepMap (immutable.js:1980)
    at List.Map.updateIn (immutable.js:1278)
    at List.Map.setIn (immutable.js:1256)
    at eval (eval at ./src/reducers/questionsList.js (questionsList.js:17), <anonymous>:1:11)
</code>```

答:
In Immutable 4.0.0-rc9, this should actually do what you want. In 3.x, setIn only worked with deeply immutable lists, but according to the most recent docs:

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and setIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.

See this answer.

The issue is that questions is an Immutable List of vanilla JS objects. List#setIn() only works on deeply immutable objects. You probably want to set questions = Immutable.fromJS(...) to get a deeply immutable object.

If, however, it is intentional that you're putting vanilla JS objects inside of your immutable object (which I really hope it isn't), what you'd want to do is use Immutable to get the vanilla object, then use regular ol' assignment to change the values:

```<code>questions.get(0)['text'] = 'changed'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Immutable.js setIn not working

Body:
I have the following list that I'm trying to return a new List from, but I keep getting the error shown below. Any thoughts?

export const questions = List([
  {uuid: uuid(), order: 0, text: 'Which country do you live in?', choices: [
    { choice: 'United States', added: true },
    { choice: 'Canada', added: true },
    { choice: 'Australia', added: true }
  ]},
  {uuid: uuid(), order: 1, text: 'Which country were you born in?', choices: [
    { choice: 'Mexico', added: true },
    { choice: 'California', added: true },
    { choice: 'Seoul', added: true }
  ]}
]);

questions.setIn([0, 'text'], 'changed')

Results in this error:

immutable.js:870 Uncaught Error: invalid keyPath
    at invariant (immutable.js:870)
    at updateInDeepMap (immutable.js:1974)
    at updateInDeepMap (immutable.js:1980)
    at List.Map.updateIn (immutable.js:1278)
    at List.Map.setIn (immutable.js:1256)
    at eval (eval at ./src/reducers/questionsList.js (questionsList.js:17), <anonymous>:1:11)

Body:
In Immutable 4.0.0-rc9, this should actually do what you want. In 3.x, setIn only worked with deeply immutable lists, but according to the most recent docs:

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and setIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.

See this answer.

The issue is that questions is an Immutable List of vanilla JS objects. List#setIn() only works on deeply immutable objects. You probably want to set questions = Immutable.fromJS(...) to get a deeply immutable object.

If, however, it is intentional that you're putting vanilla JS objects inside of your immutable object (which I really hope it isn't), what you'd want to do is use Immutable to get the vanilla object, then use regular ol' assignment to change the values:

questions.get(0)['text'] = 'changed'


Title: How to make list of tuple from list of list?

Body:
How do I convert this list of lists:

[['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]

To this list of tuples:

[(0, [1, 2, 3]), (1, [0, 4, 6, 7, 9]), (2, [0, 3, 6, 8, 9])]

I am unsure how to implement this next step? (I can't use dictionaries,
sets, deque, bisect module. You can though, and in fact should, use .sort or sorted functions.)

Here is my attempt:

network= [['10'], ['0 1'], ['0 2'], ['0 3'], ['1 4'], ['1 6'], ['1 7'], ['1 9'], ['2 3'], ['2 6'], ['2 8'], ['2 9']]
network.remove(network[0])
friends=[]

for i in range(len(network)):
    element= (network[i][0]).split(' ')
    friends.append(element)

t=len(friends)
s= len(friends[0])
lst=[]

for i in range(t):
    a= (friends[i][0])
    if a not in lst:
        lst.append(int(a))
        for i in range(t):
            if a == friends[i][0]:
                b=(friends[i][1])
                lst.append([b])
print(tuple(lst))

It outputs:

(0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'])

I am very close it seems, not sure what to do??

Body:
You can use Pandas:

import pandas as pd
import numpy as np
l = [['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]
df = pd.DataFrame(l, dtype=np.int)
s = df.groupby(0)[1].apply(list)
list(zip(s.index, s))

Output:

[(0, [1, 2, 3]), (1, [4, 6, 7, 9]), (2, [3, 6, 8, 9])]


问:
ASP.NET (C#) event to happen before printing
I have a web form in ASP.Net with C# code behind. It's a simple thing, and I'm pretty new so I'm kind of stuck.

In the source code of the web form I have a button called "print" that looks like this:

```<code><asp:Button ID="btnPrint" runat="server" onclientclick="window.print();" Text="Print" />
</code>```

No problem. In the code behind I have this:

```<code> protected void btnPrint_Click(object sender, EventArgs e)
{
    //get current Date/Time
    string dateTime = DateTime.Now.ToLongDateString() + ", at " + DateTime.Now.ToShortTimeString();

    //set it to labelDate
    lblDate.Text = "Requested on " + dateTime;

}
</code>```

So the problem is that when I hit the print button, the form prints before the code executes and stamps the label (lblDate.Text).

Soooo... my noob question is how to get that date/time stamp to process before the form prints?

Thanks for your advice.

Mark

答:
Instead of calling a windows.print(), call a function that adds the Requested datetime.
That will do the work.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a web form in ASP.Net with C# code behind. It's a simple thing, and I'm pretty new so I'm kind of stuck.

In the source code of the web form I have a button called "print" that looks like this:

<asp:Button ID="btnPrint" runat="server" onclientclick="window.print();" Text="Print" />

No problem. In the code behind I have this:

 protected void btnPrint_Click(object sender, EventArgs e)
{
    //get current Date/Time
    string dateTime = DateTime.Now.ToLongDateString() + ", at " + DateTime.Now.ToShortTimeString();

    //set it to labelDate
    lblDate.Text = "Requested on " + dateTime;

}

So the problem is that when I hit the print button, the form prints before the code executes and stamps the label (lblDate.Text).

Soooo... my noob question is how to get that date/time stamp to process before the form prints?

Thanks for your advice.

Mark


问:
Need help displaying min/max values of integers entered by user
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}
</code>```

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

答:
In addition to the first answer, this loop makes no sense:

```<code>for (int x = 1; x <= randomNum; x++) {
    cout << "Enter an integer: ";
    cin >> num[randomNum];
}
</code>```

randomNum is the same every loop, so you just keep overwriting the same array value.

And...

```<code>for (int i = 0; i <= i; i++)
</code>```

This loop is wrong. You are checking i <= i which will always evaluate true.

Body:
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

Body:
In addition to the first answer, this loop makes no sense:

for (int x = 1; x <= randomNum; x++) {
    cout << "Enter an integer: ";
    cin >> num[randomNum];
}

randomNum is the same every loop, so you just keep overwriting the same array value.

And...

for (int i = 0; i <= i; i++)

This loop is wrong. You are checking i <= i which will always evaluate true.


问:
Difference between () and $()
What's the difference between

```<code>Write-Host (Get-Date) # just paren
</code>```

and

```<code>Write-Host $(Get-Date) # dollar-paren
</code>```

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

答:
The sub expression ($(...)) contains a StatementBlockAst.  It can take any number of statements, meaning keywords (if, foreach, etc), pipelines, commands, etc.  Parsing is similar to the inside of a named block like begin/process/end.

The paren expression ((...)) can contain a single ExpressionAst which is a limited subset of the AST.  The most notable difference between a statement and an expression is that keywords are not parsed.

```<code>$(if ($true) { 'It worked!' })
# It worked!

(if ($true) { 'It worked!' })
# if : The term 'if' is not recognized as the name of a cmdlet, function,
# script file, or operable program. Check the spelling of the name, or
# if a path was included, verify that the path is correct and try again.
# At line:1 char:2
# + (if ($true) { 'It worked' })
# +  ~~
#     + CategoryInfo          : ObjectNotFound: (if:String) [], CommandNotFoundException
#     + FullyQualifiedErrorId : CommandNotFoundException
</code>```

Also as others have noted, the sub expression will expand in double quoted strings.

Title: Difference between () and $()

Body:
What's the difference between

Write-Host (Get-Date) # just paren

and

Write-Host $(Get-Date) # dollar-paren

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

Body:
The sub expression ($(...)) contains a StatementBlockAst.  It can take any number of statements, meaning keywords (if, foreach, etc), pipelines, commands, etc.  Parsing is similar to the inside of a named block like begin/process/end.

The paren expression ((...)) can contain a single ExpressionAst which is a limited subset of the AST.  The most notable difference between a statement and an expression is that keywords are not parsed.

$(if ($true) { 'It worked!' })
# It worked!

(if ($true) { 'It worked!' })
# if : The term 'if' is not recognized as the name of a cmdlet, function,
# script file, or operable program. Check the spelling of the name, or
# if a path was included, verify that the path is correct and try again.
# At line:1 char:2
# + (if ($true) { 'It worked' })
# +  ~~
#     + CategoryInfo          : ObjectNotFound: (if:String) [], CommandNotFoundException
#     + FullyQualifiedErrorId : CommandNotFoundException

Also as others have noted, the sub expression will expand in double quoted strings.


问:
Ivy mis-resolve resources
I've a simple ivy.xml file:

```<code><dependencies>
  <dependency org="javax.validation" name="validation-api" rev="1.0.0.GA" conf="compile->master,sources"/>
</dependencies>
</code>```

where compile is my configuration name, and master,sources are the mapped Maven types.
This is resolved correctly and give me these files:

```<code>validation-api-1.0.0.GA.jar
validation-api-1.0.0.GA-sources.jar
</code>```

Now, i've to add this dependency:

```<code><dependency org="com.google.gwt" name="gwt-user" rev="2.8.1" conf="compile->default"/>
</code>```

which has validation-api as its dependecy, the same i specified at the top.

Ivy resolves this giving me these files:

```<code>gwt-user-2.8.1.jar
<its dependecies>
validation-api-1.0.0.GA-sources.jar
</code>```

but this time the file validation-api-1.0.0.GA.jar is not retrieved.
Why?
I think this file is not in conflict... what should i do to have gwt-user and the validation-api jars (binary and source)?

答:
This happens mainly due to the way configurations are declared in the ivy xmls. If you are dealing with a Maven artifact, it's very common that the ivy xml generated from the Maven artifact uses a different conf tag for the dependency. You are resolving the "default" conf of gwt-user. Normally, "default" extends "master, runtime". So, if validation-api-1.0.0.GA was declared under "master" or "runtime" conf in gwt-user's ivy.xml, it would have got resolved.

In order to give more accurate answer, I need the  part of your ivy.xml as well as the ivy.xml of gwt-user

Title: Ivy mis-resolve resources

Body:
I've a simple ivy.xml file:

<dependencies>
  <dependency org="javax.validation" name="validation-api" rev="1.0.0.GA" conf="compile->master,sources"/>
</dependencies>

where compile is my configuration name, and master,sources are the mapped Maven types.
This is resolved correctly and give me these files:

validation-api-1.0.0.GA.jar
validation-api-1.0.0.GA-sources.jar

Now, i've to add this dependency:

<dependency org="com.google.gwt" name="gwt-user" rev="2.8.1" conf="compile->default"/>

which has validation-api as its dependecy, the same i specified at the top.

Ivy resolves this giving me these files:

gwt-user-2.8.1.jar
<its dependecies>
validation-api-1.0.0.GA-sources.jar

but this time the file validation-api-1.0.0.GA.jar is not retrieved.
Why?
I think this file is not in conflict... what should i do to have gwt-user and the validation-api jars (binary and source)?


问:
Why does Task Runner in VS2017 give such verbose output for "ng build"
I create a new angular-cli project with "ng new xxx". I move to xxx and run "ng build". I normally get about 8 lines of output:

```<code>Date: 2017-11-12T03:14:13.719Z
Hash: 4a82f3de6e254818919f
Time: 6413ms
chunk {inline} inline.bundle.js, inline.bundle.js.map ....
chunk {main} main.bundle.js, main.bundle.js.map ...
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map ...
chunk {styles} styles.bundle.js, styles.bundle.js.map ...
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) ...
</code>```

[ ADDED: I put the project on Github - https://github.com/johnpankowicz/angular-cli-and-dotnet-core ]

If I run the package.json "build":"ng build" script from the command line (using  "npm run-script build"), I get about the same output as above.

I added the angular-cli app to an empty Asp.Net core app in Visual Studio.
In Visual Studio, when I double click the "build" task in Task Runner Explorer, I get a great amount of verbose output. I lose the initial output top of the window. So I don't even know how much output there is. Below is some of output (the entire amount would take pages)

How can I turn off this verbose output? It appears to be from Webpack.

I should mention that I don't think that it is a conflict with VS running different versions of npm, angular-cli or webpack. I already arranged the order in Tools -> Projects and Solutions -> Web Package Management -> External Web Tools. I have ".\node_modules\.bin" on top and "$(PATH)" below it. Reversing that order doesn't help.

```<code>...ngular\cli\src\app\app.component.html 11% building modules 12/14 modules 2 active ...cli\node_modules\zone.js\dist\zone.js 11% building modules 12/15 modules 3 active ...i\node_modules\core-js\es7\reflect.js 11% building modules 12/16 modules 4 active ...es\@angular\core\@angular\core.es5.js 11% building modules 12/17 modules 5 active ...gular\platform-browser-dynamic.es5.js 11% building modules 13/17 modules 4 active ...gular\platform-browser-dynamic.es5.js 11% building modules 14/17 modules 3 active ...gular\platform-browser-dynamic.es5.js 11% building modules 15/17 modules 2 active ...gular\platform-browser-dynamic.es5.js 11% building modules 16/17 modules 1 active ...es\@angular\core\@angular\core.es5.js                                          12% building modules 17/17 modules 0 active 12% building modules 17/18 modules 1 active ...wser\@angular\platform-browser.es5.js 12% building modules 17/19 modules 2 active ...S\DebugAngular\cli\src\$$_gendir lazy 12% building modules 18/19 modules 1 active ...wser\@angular\platform-browser.es5.js                                          12% building modules 19/19 modules 0 active 12% building modules 19/20 modules 1 active
</code>```

答:
To silence the output in build, you're looking for the --no-progress flag.

--no-progress also works for other commands as well, such as ng test and ng serve.

Body:
I create a new angular-cli project with "ng new xxx". I move to xxx and run "ng build". I normally get about 8 lines of output:

Date: 2017-11-12T03:14:13.719Z
Hash: 4a82f3de6e254818919f
Time: 6413ms
chunk {inline} inline.bundle.js, inline.bundle.js.map ....
chunk {main} main.bundle.js, main.bundle.js.map ...
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map ...
chunk {styles} styles.bundle.js, styles.bundle.js.map ...
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) ...

[ ADDED: I put the project on Github - https://github.com/johnpankowicz/angular-cli-and-dotnet-core ]

If I run the package.json "build":"ng build" script from the command line (using  "npm run-script build"), I get about the same output as above.

I added the angular-cli app to an empty Asp.Net core app in Visual Studio.
In Visual Studio, when I double click the "build" task in Task Runner Explorer, I get a great amount of verbose output. I lose the initial output top of the window. So I don't even know how much output there is. Below is some of output (the entire amount would take pages)

How can I turn off this verbose output? It appears to be from Webpack.

I should mention that I don't think that it is a conflict with VS running different versions of npm, angular-cli or webpack. I already arranged the order in Tools -> Projects and Solutions -> Web Package Management -> External Web Tools. I have ".\node_modules\.bin" on top and "$(PATH)" below it. Reversing that order doesn't help.

...ngular\cli\src\app\app.component.html 11% building modules 12/14 modules 2 active ...cli\node_modules\zone.js\dist\zone.js 11% building modules 12/15 modules 3 active ...i\node_modules\core-js\es7\reflect.js 11% building modules 12/16 modules 4 active ...es\@angular\core\@angular\core.es5.js 11% building modules 12/17 modules 5 active ...gular\platform-browser-dynamic.es5.js 11% building modules 13/17 modules 4 active ...gular\platform-browser-dynamic.es5.js 11% building modules 14/17 modules 3 active ...gular\platform-browser-dynamic.es5.js 11% building modules 15/17 modules 2 active ...gular\platform-browser-dynamic.es5.js 11% building modules 16/17 modules 1 active ...es\@angular\core\@angular\core.es5.js                                          12% building modules 17/17 modules 0 active 12% building modules 17/18 modules 1 active ...wser\@angular\platform-browser.es5.js 12% building modules 17/19 modules 2 active ...S\DebugAngular\cli\src\$$_gendir lazy 12% building modules 18/19 modules 1 active ...wser\@angular\platform-browser.es5.js                                          12% building modules 19/19 modules 0 active 12% building modules 19/20 modules 1 active


问:
Current slide in materialize css carousel
How to get current slide in materializecss carousel component? I don't know how to link from carousel content to active class in li tags.

For example i need get id element from div, where li class is active

答:
You can get the current slides index using onCycleTo. Adding this answer since the previous answers don't show what to do within the function. Here's an example to get you started:</p>

```<code>$('.carousel').carousel({
    onCycleTo: function (ele) {
      console.log(ele);
      console.log($(ele).index()); // the slide's index
    }
});
</code>```

Body:
You can get the current slides index using onCycleTo. Adding this answer since the previous answers don't show what to do within the function. Here's an example to get you started:

$('.carousel').carousel({
    onCycleTo: function (ele) {
      console.log(ele);
      console.log($(ele).index()); // the slide's index
    }
});

ContentLicense: CC BY-SA 4.0


问:
How do i fix "Unable to access Jar file" in IntelliJ idea?
So, I made a simple HelloWorld program and followed the IntelliJ idea tips and instructions on how to create my first program, although I still have a problem which is after I made an artifact of the program and set it at the "Edit Configurations" tab, it says this error.

```<code>Error: Unable to access jarfile C:\Users\nazgi\IdeaProjects\HelloWorld\artifacts\HelloWorld_jar
</code>```

And before you ask I did change the directory, the original directory was
C:/Users/nazgi/IdeaProjects/HelloWorld

答:
Okay so i figured it out, my directory was not specific enough so the program couldnt find the JAR file, so i changes the directory to</p>

```<code>....\Java\HelloWorld\out\artifacts...\HelloWorld.jar
</code>```

Body:
So, I made a simple HelloWorld program and followed the IntelliJ idea tips and instructions on how to create my first program, although I still have a problem which is after I made an artifact of the program and set it at the "Edit Configurations" tab, it says this error.

Error: Unable to access jarfile C:\Users\nazgi\IdeaProjects\HelloWorld\artifacts\HelloWorld_jar

And before you ask I did change the directory, the original directory was
C:/Users/nazgi/IdeaProjects/HelloWorld

Body:
Okay so i figured it out, my directory was not specific enough so the program couldnt find the JAR file, so i changes the directory to

....\Java\HelloWorld\out\artifacts...\HelloWorld.jar


问:
Php how to correctly use return function?
Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result

```<code>$fullname = "Ayoub Chafik" ;

function orderID($data){
    $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    $str[0];

}
// I want to see resulte here of this function
   echo orderID($fullname) ;

?>
</code>```

This is the second Block

```<code><?php

$fullname = "Ayoub Chafik" ;

function orderID($data){
    echo $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    echo $str[0];

}

echo orderID($fullname) ;

?>
</code>```

答:
As I explained in comment you store it in a variable and return it. Check below example. Also it is a good practice to open the {} even its only one line for more readability.

```<code>$fullname = "Ayoub Chafik" ;

function orderID($data) {
    $string  = strtoupper($data);
    $strs    = explode(" ", $string);
    $results = '';

    foreach($strs as $str) {
        $results .= $str[0];
    }

    return $results;
}

echo orderID($fullname) ;
</code>```

Body:
Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result

$fullname = "Ayoub Chafik" ;

function orderID($data){
    $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    $str[0];

}
// I want to see resulte here of this function
   echo orderID($fullname) ;

?>

This is the second Block

<?php

$fullname = "Ayoub Chafik" ;

function orderID($data){
    echo $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    echo $str[0];

}

echo orderID($fullname) ;

?>

Body:
As I explained in comment you store it in a variable and return it. Check below example. Also it is a good practice to open the {} even its only one line for more readability.

$fullname = "Ayoub Chafik" ;

function orderID($data) {
    $string  = strtoupper($data);
    $strs    = explode(" ", $string);
    $results = '';

    foreach($strs as $str) {
        $results .= $str[0];
    }

    return $results;
}

echo orderID($fullname) ;


问:
Javascript Round function
```<code>a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000
</code>```

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.

答:
Here is a javascript rounding function which fixes javascript floating point rounding errors as well as takes care of what you were asking for. A more complete description can be found in this post.

Javascript floating point errors can occur as described by this post:

Binary floating point math is like this. In most programming
  languages, it is based on the IEEE 754 standard. JavaScript uses
  64-bit floating point representation, which is the same as Java's
  double. The crux of the problem is that numbers are represented in
  this format as a whole number times a power of two; rational numbers
  (such as 0.1, which is 1/10) whose denominator is not a power of two
  cannot be exactly represented.

function round(number, precision) {
  number = +number;
  precision = precision ? +precision : 0;
  if (precision == 0) {
    return Math.round(number);
  }
  var sign = 1;
  if (number < 0) {
    sign = -1;
    number = Math.abs(number);
  }

  // Shift
  number = number.toString().split('e');
  number = Math.round(+(number[0] + 'e' + (number[1] ? (+number[1] + precision) : precision)));
  // Shift back
  number = number.toString().split('e');
  return +(number[0] + 'e' + (number[1] ? (+number[1] - precision) : -precision)) * sign;
}

console.log(round(31283700000, -6)) //31,284,000,000
console.log(round(60204605, -4)) //60,200,000```

Title: Javascript Round function

Body:
a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.


问:
CODE-PUSH error on release through VSTS
While pushing a release through code-push extension on VSTS i am getting the following error unable to know why!

Tried one of the below solution as adding a variable named as "Build.SourceDirectory" in your build definition and getting the following error log

```<code>2017-11-17T09:13:07.6795222Z npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
2017-11-17T09:13:07.6795222Z ZUMOAPPNAME@1.0.0 d:\a\3\s
2017-11-17T09:13:07.6795222Z `-- (empty)
2017-11-17T09:13:07.6795222Z npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
2017-11-17T09:13:07.6795222Z
2017-11-17T09:13:07.6835014Z npm WARN ZUMOAPPNAME@1.0.0 No description
2017-11-17T09:13:07.8445206Z npm WARN ZUMOAPPNAME@1.0.0 No license field.
2017-11-17T09:13:07.8465194Z npm ERR! Windows_NT 10.0.14393
2017-11-17T09:13:07.8475041Z npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "cordova"
2017-11-17T09:13:07.8475041Z npm ERR! node v6.10.0
2017-11-17T09:13:07.8475041Z npm ERR! npm  v3.10.10
2017-11-17T09:13:07.8475041Z npm ERR! path d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd
2017-11-17T09:13:07.8475041Z npm ERR! code EEXIST
2017-11-17T09:13:07.8475041Z
2017-11-17T09:13:07.8475041Z npm ERR! Refusing to delete d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd: ..\acorn\bin\acorn symlink target is not controlled by npm d:\a\3\s\node_modules\cordova\node_modules\acorn
2017-11-17T09:13:07.8475041Z npm ERR! File exists: d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd
2017-11-17T09:13:07.8475041Z npm ERR! Move it away, and try again.
2017-11-17T09:13:07.8475041Z
2017-11-17T09:13:07.8475041Z npm ERR! Please include the following file with any support request:
2017-11-17T09:13:07.8475041Z npm ERR!     d:\a\3\s\Client Components\Main\Source\vr9-11\npm-debug.log
2017-11-17T09:13:07.8475041Z npm ERR! code 1
2017-11-17T09:13:07.9305055Z ##[debug]load strings from: d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\vsts-task-lib\lib.json
2017-11-17T09:13:07.9325060Z Unhandled: Command failed: npm install cordova
2017-11-17T09:13:07.9325060Z ##[debug]load loc strings from: d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\vsts-task-lib\Strings\resources.resjson\en-US\resources.resjson
2017-11-17T09:13:07.9325060Z ##[debug]task result: Failed
2017-11-17T09:13:07.9365053Z ##[debug]Processed: ##vso[task.complete result=Failed;]Unhandled: Command failed: npm install cordova
</code>```

The log file can be seen at the following link: https://drive.google.com/open?id=1OC49xlDOEQekO9gqdrj0NQCMPz8onTRX

Tried the solution suggested by Eddie(removing files of bower and node modules as they are regenerated while building) and got the following error.

```<code>2017-11-21T06:39:48.8214252Z ##[debug]Finished Building Command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli release-cordova "Syngenta_Visit_Report1" "android" --deploymentName "Staging" --rollout "100%"
2017-11-21T06:39:48.8254247Z ##[debug]Attempting execution of command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli release-cordova "Syngenta_Visit_Report1" "android" --deploymentName "Staging" --rollout "100%"
2017-11-21T06:39:49.6774368Z Running "cordova prepare" command:
2017-11-21T06:39:49.6774368Z
2017-11-21T06:39:49.6874306Z 'cordova' is not recognized as an internal or external command,
2017-11-21T06:39:49.6904319Z operable program or batch file.
2017-11-21T06:39:49.6924371Z [Error]  Unable to prepare project. Please ensure that this is a Cordova project and that platform "android" was added with "cordova platform add android"
2017-11-21T06:39:49.7014305Z ##[debug]Finished Building Command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli logout
2017-11-21T06:39:50.5584321Z ##[debug]task result: Failed
2017-11-21T06:39:50.5624318Z ##[debug]Processed: ##vso[task.complete result=Failed;]Command failed: release-cordova
2017-11-21T06:39:50.5624318Z Command failed: release-cordova
</code>```

答:
The task runs "cordova prepare" command from the root of Build.SourcesDirectory folder like "d:\a\3\s". I suspect that your code files are placed in a sub folder like "d:\a\3\s\yourappname" which cause the command cannot find the project. However, there isn't any option to specify the project directory in the task.

As a workaround, you can add a variable named as "Build.SourceDirectory" in your build definition like below:

Title: CODE-PUSH error on release through VSTS

Body:
While pushing a release through code-push extension on VSTS i am getting the following error unable to know why!

Tried one of the below solution as adding a variable named as "Build.SourceDirectory" in your build definition and getting the following error log

2017-11-17T09:13:07.6795222Z npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
2017-11-17T09:13:07.6795222Z ZUMOAPPNAME@1.0.0 d:\a\3\s
2017-11-17T09:13:07.6795222Z `-- (empty)
2017-11-17T09:13:07.6795222Z npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
2017-11-17T09:13:07.6795222Z
2017-11-17T09:13:07.6835014Z npm WARN ZUMOAPPNAME@1.0.0 No description
2017-11-17T09:13:07.8445206Z npm WARN ZUMOAPPNAME@1.0.0 No license field.
2017-11-17T09:13:07.8465194Z npm ERR! Windows_NT 10.0.14393
2017-11-17T09:13:07.8475041Z npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "cordova"
2017-11-17T09:13:07.8475041Z npm ERR! node v6.10.0
2017-11-17T09:13:07.8475041Z npm ERR! npm  v3.10.10
2017-11-17T09:13:07.8475041Z npm ERR! path d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd
2017-11-17T09:13:07.8475041Z npm ERR! code EEXIST
2017-11-17T09:13:07.8475041Z
2017-11-17T09:13:07.8475041Z npm ERR! Refusing to delete d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd: ..\acorn\bin\acorn symlink target is not controlled by npm d:\a\3\s\node_modules\cordova\node_modules\acorn
2017-11-17T09:13:07.8475041Z npm ERR! File exists: d:\a\3\s\node_modules\cordova\node_modules\.bin\acorn.cmd
2017-11-17T09:13:07.8475041Z npm ERR! Move it away, and try again.
2017-11-17T09:13:07.8475041Z
2017-11-17T09:13:07.8475041Z npm ERR! Please include the following file with any support request:
2017-11-17T09:13:07.8475041Z npm ERR!     d:\a\3\s\Client Components\Main\Source\vr9-11\npm-debug.log
2017-11-17T09:13:07.8475041Z npm ERR! code 1
2017-11-17T09:13:07.9305055Z ##[debug]load strings from: d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\vsts-task-lib\lib.json
2017-11-17T09:13:07.9325060Z Unhandled: Command failed: npm install cordova
2017-11-17T09:13:07.9325060Z ##[debug]load loc strings from: d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\vsts-task-lib\Strings\resources.resjson\en-US\resources.resjson
2017-11-17T09:13:07.9325060Z ##[debug]task result: Failed
2017-11-17T09:13:07.9365053Z ##[debug]Processed: ##vso[task.complete result=Failed;]Unhandled: Command failed: npm install cordova

The log file can be seen at the following link: https://drive.google.com/open?id=1OC49xlDOEQekO9gqdrj0NQCMPz8onTRX

Tried the solution suggested by Eddie(removing files of bower and node modules as they are regenerated while building) and got the following error.

2017-11-21T06:39:48.8214252Z ##[debug]Finished Building Command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli release-cordova "Syngenta_Visit_Report1" "android" --deploymentName "Staging" --rollout "100%"
2017-11-21T06:39:48.8254247Z ##[debug]Attempting execution of command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli release-cordova "Syngenta_Visit_Report1" "android" --deploymentName "Staging" --rollout "100%"
2017-11-21T06:39:49.6774368Z Running "cordova prepare" command:
2017-11-21T06:39:49.6774368Z
2017-11-21T06:39:49.6874306Z 'cordova' is not recognized as an internal or external command,
2017-11-21T06:39:49.6904319Z operable program or batch file.
2017-11-21T06:39:49.6924371Z [Error]  Unable to prepare project. Please ensure that this is a Cordova project and that platform "android" was added with "cordova platform add android"
2017-11-21T06:39:49.7014305Z ##[debug]Finished Building Command: node d:\a\_tasks\CodePushReleaseCordova_f5990527-f512-4c14-9f8e-1254240dc3cb\1.0.5\node_modules\code-push-cli\script\cli logout
2017-11-21T06:39:50.5584321Z ##[debug]task result: Failed
2017-11-21T06:39:50.5624318Z ##[debug]Processed: ##vso[task.complete result=Failed;]Command failed: release-cordova
2017-11-21T06:39:50.5624318Z Command failed: release-cordova


问:
Validate the user's input of only 0's and 1's
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

```<code>while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break
</code>```

答:
If you're a fan of regexes:

```<code>import re
s1='10010011'
print(re.match(r'[10]{8}', s1) is None)
</code>```

This will match 10010011, but not 110010100 or 12345689 or 12345678.

Body:
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break

Body:
If you're a fan of regexes:

import re
s1='10010011'
print(re.match(r'[10]{8}', s1) is None)

This will match 10010011, but not 110010100 or 12345689 or 12345678.


问:
How to download and unzip file via pipelines in gulp?
I'm trying to download and unpack zip archive in gulp by using gulp-decompress. But get an error. My gulp task looks like the following:

```<code>var request = require('request');
var decompress = require('gulp-decompress');

gulp.task('unzip', function () {
   request('http://my-server-url/files/report.zip')
      .pipe(decompress())
      .pipe('./uploads')
});
</code>```

After executing gulp I'm getting the following error:

```<code>node_modules\gulp-decompress\index.js:11
                if (file.isNull()) {
                         ^

TypeError: file.isNull is not a function
</code>```

答:
I tried it with request and got the same error as you.  It probably has to be transformed into a readable or writeable stream (fs.) before continuing in the pipeline which I couldn't get to work without spending too much time.

So let me recommend gulp-download which is much simpler than request.

```<code>const gulp = require('gulp');
const download = require("gulp-download");
const decompress = require('gulp-decompress');

const url = 'http://my-server-url/files/report.zip';

gulp.task('unzip', function () {

  download(url)

   .pipe(decompress())
   .pipe(gulp.dest("unzipped"));
});
</code>```

It's pretty simple.  I'm sure others could tell you how to get the module request to work if that is necessary.

Body:
I'm trying to download and unpack zip archive in gulp by using gulp-decompress. But get an error. My gulp task looks like the following:

var request = require('request');
var decompress = require('gulp-decompress');

gulp.task('unzip', function () {
   request('http://my-server-url/files/report.zip')
      .pipe(decompress())
      .pipe('./uploads')
});

After executing gulp I'm getting the following error:

node_modules\gulp-decompress\index.js:11
                if (file.isNull()) {
                         ^

TypeError: file.isNull is not a function

Body:
I tried it with request and got the same error as you.  It probably has to be transformed into a readable or writeable stream (fs.) before continuing in the pipeline which I couldn't get to work without spending too much time.

So let me recommend gulp-download which is much simpler than request.

const gulp = require('gulp');
const download = require("gulp-download");
const decompress = require('gulp-decompress');

const url = 'http://my-server-url/files/report.zip';

gulp.task('unzip', function () {

  download(url)

   .pipe(decompress())
   .pipe(gulp.dest("unzipped"));
});

It's pretty simple.  I'm sure others could tell you how to get the module request to work if that is necessary.


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答:
I usually do this:

```<code>InputStream in = null;
try {
  in = acquire();
  ...
} finally {
   if( in != null ) try {
       in.close();
    } catch( IOException ioe ) {
       // ignore exception while closing
    }
}
</code>```

While closing the resource, an exception may be thrown, in which case you'll need an extra try/catch , but most of the times it's ok for me to ignore it ( I'm closing it after all ) but this is the only place where I use an if without braces.

I saw this from Huckster code  long ago.

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

Body:
I usually do this:

InputStream in = null;
try {
  in = acquire();
  ...
} finally {
   if( in != null ) try {
       in.close();
    } catch( IOException ioe ) {
       // ignore exception while closing
    }
}

While closing the resource, an exception may be thrown, in which case you'll need an extra try/catch , but most of the times it's ok for me to ignore it ( I'm closing it after all ) but this is the only place where I use an if without braces.

I saw this from Huckster code  long ago.


问:
Creating VSTS ServiceHooks (WebHooks) via Rest Api for work item created event fails. Please give a solution
My API Request is as

URL : https://kogul-ceymplon.visualstudio.com/_apis/hooks/subscriptions?api-version=4.1-preview

Method: POST

Content: "application/json" of "
   {\"PublisherId\":\"tfs\",\"EventType\":\"workitem.created\",\"ResourceVersion\":\"1.0-preview.1\",\"ConsumerId\":\"webHooks\",\"ConsumerActionId\":\"httpRequest\",\"PublisherInputs\":{\"ProjectId\":\"d028a77b-50c4-4bdc-943d-6b072799b884\"},\"ConsumerInputs\":{\"Url\":\"https://myservice/newreceiver\"}}"

Header : Bearer {accesToken}

My Response is as

  {"$id":"1","innerException":null,"message":"TF400898: An Internal Error Occurred. Activity Id: 31deba9c-369c-4a31-9be3-67af8ce6249e.","typeName":"System.Exception, mscorlib","typeKey":"Exception","errorCode":0,"eventId":0}

Code:

```<code>'using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    ServiceHook hook = new ServiceHook();
                    hook.PublisherId = "tfs";
                    hook.EventType = "workitem.created";
                    hook.ResourceVersion = "1.0-preview.1";
                    hook.ConsumerId = "webHooks";
                    hook.ConsumerActionId = "httpRequest";
                    hook.PublisherInputs = new PublisherInput
                    {
                        projectId = "d028a77b-50c4-4bdc-943d-6b072799b884"
                    };
                    hook.ConsumerInputs = new ConsumerInput
                    {
                        url= "https://myservice/newreceiver"
                    };
                    var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string jsonString = javaScriptSerializer.Serialize(hook);

                    var request = new HttpRequestMessage(HttpMethod.Post, "https://kogul-ceymplon.visualstudio.com/_apis/hooks/subscriptions?api-version=4.1-preview");
                    request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    string ccc = request.Content.ReadAsStringAsync().Result;
                    using (HttpResponseMessage response = client.SendAsync(request).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        string responseBody = await response.Content.ReadAsStringAsync();
                        return responseBody;
                    }
                }'
</code>```

What could be the fault at my side?

答:
First, the json is incorrect for workitem.created EventType, you need to specify area and task (Try to create a webhook manually and check the inputs)

The json could be like this:

```<code>{
    "consumerActionId":"httpRequest",
    "consumerId":"webHooks",
    "consumerInputs":{
        "url":"XXX"
    },
    "eventType":"workitem.created",
    "publisherId":"tfs",
    "publisherInputs":{
        "areaPath":"[area path]",
        "workItemType":"Task",
        "projectId":"[project id]"
    },
    "resourceVersion":"1.0"
}
</code>```

Secondly, based on my test, we can’t use OAuth token to create a webhook with workitem.created EventType, it will throw that error. (Can create a webhook with build.complete EventType) You can use personal access token or alternate account instead.

I submit a feedback here: Create webhook with workitem.created EventType and OAuth token fail, you can vote and follow.

Body:
My API Request is as

URL : https://kogul-ceymplon.visualstudio.com/_apis/hooks/subscriptions?api-version=4.1-preview

Method: POST

Content: "application/json" of "
   {\"PublisherId\":\"tfs\",\"EventType\":\"workitem.created\",\"ResourceVersion\":\"1.0-preview.1\",\"ConsumerId\":\"webHooks\",\"ConsumerActionId\":\"httpRequest\",\"PublisherInputs\":{\"ProjectId\":\"d028a77b-50c4-4bdc-943d-6b072799b884\"},\"ConsumerInputs\":{\"Url\":\"https://myservice/newreceiver\"}}"

Header : Bearer {accesToken}

My Response is as

  {"$id":"1","innerException":null,"message":"TF400898: An Internal Error Occurred. Activity Id: 31deba9c-369c-4a31-9be3-67af8ce6249e.","typeName":"System.Exception, mscorlib","typeKey":"Exception","errorCode":0,"eventId":0}

Code:

'using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    ServiceHook hook = new ServiceHook();
                    hook.PublisherId = "tfs";
                    hook.EventType = "workitem.created";
                    hook.ResourceVersion = "1.0-preview.1";
                    hook.ConsumerId = "webHooks";
                    hook.ConsumerActionId = "httpRequest";
                    hook.PublisherInputs = new PublisherInput
                    {
                        projectId = "d028a77b-50c4-4bdc-943d-6b072799b884"
                    };
                    hook.ConsumerInputs = new ConsumerInput
                    {
                        url= "https://myservice/newreceiver"
                    };
                    var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string jsonString = javaScriptSerializer.Serialize(hook);

                    var request = new HttpRequestMessage(HttpMethod.Post, "https://kogul-ceymplon.visualstudio.com/_apis/hooks/subscriptions?api-version=4.1-preview");
                    request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    string ccc = request.Content.ReadAsStringAsync().Result;
                    using (HttpResponseMessage response = client.SendAsync(request).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        string responseBody = await response.Content.ReadAsStringAsync();
                        return responseBody;
                    }
                }'

What could be the fault at my side?

Body:
First, the json is incorrect for workitem.created EventType, you need to specify area and task (Try to create a webhook manually and check the inputs)

The json could be like this:

{
    "consumerActionId":"httpRequest",
    "consumerId":"webHooks",
    "consumerInputs":{
        "url":"XXX"
    },
    "eventType":"workitem.created",
    "publisherId":"tfs",
    "publisherInputs":{
        "areaPath":"[area path]",
        "workItemType":"Task",
        "projectId":"[project id]"
    },
    "resourceVersion":"1.0"
}

Secondly, based on my test, we can’t use OAuth token to create a webhook with workitem.created EventType, it will throw that error. (Can create a webhook with build.complete EventType) You can use personal access token or alternate account instead.

I submit a feedback here: Create webhook with workitem.created EventType and OAuth token fail, you can vote and follow.


问:
At each subtotal, for then loop copy and paste above data vba
I am trying to copy each subtotal and paste above each data set using the for then loop. Maybe there is a more appropriate loop to use here I am not 100% sure. I am having trouble getting the loop to copy the subtotal after the condition is met. See code below:

```<code>For I = 1000 To 2 Step -1 ' adjust 1000 to the row number of the last element
If Cells(I, 7).Font.Bold Then
    Cells(I + 1, 1).Copy
    Selection.End(xlUp).Select
    Selection.Offset(1, -7).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
End If
Next
</code>```

What I can't get the macro to do is copy the actual subtotal, it doesn't even copy the cell it was selected. In case you need to see what I'm trying to get the loop to do see pic below.

答:
Cells(I + 1, 1).Copy is correctly copying the cell contents, but it isn't actually selecting the cell.  Then you are trying to set the destination by moving the selection starting with the selected cell, but the starting point for selection hasn't actually been set by the loop in the first place.

One way to change it is to not use .select until it is time to paste.  This is also more efficient because .select is very inefficient and should be minimized.

```<code>For I = 1000 To 2 Step -1 ' adjust 1000 to the row number of the last element
If Cells(I, 7).Font.Bold Then
    Cells(I + 1, 7).Copy
    Cells(I + 1, 7).End(xlUp).Offset(1, -6).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
End If
Next
</code>```

Body:
I am trying to copy each subtotal and paste above each data set using the for then loop. Maybe there is a more appropriate loop to use here I am not 100% sure. I am having trouble getting the loop to copy the subtotal after the condition is met. See code below:

For I = 1000 To 2 Step -1 ' adjust 1000 to the row number of the last element
If Cells(I, 7).Font.Bold Then
    Cells(I + 1, 1).Copy
    Selection.End(xlUp).Select
    Selection.Offset(1, -7).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
End If
Next

What I can't get the macro to do is copy the actual subtotal, it doesn't even copy the cell it was selected. In case you need to see what I'm trying to get the loop to do see pic below.

Body:
Cells(I + 1, 1).Copy is correctly copying the cell contents, but it isn't actually selecting the cell.  Then you are trying to set the destination by moving the selection starting with the selected cell, but the starting point for selection hasn't actually been set by the loop in the first place.

One way to change it is to not use .select until it is time to paste.  This is also more efficient because .select is very inefficient and should be minimized.

For I = 1000 To 2 Step -1 ' adjust 1000 to the row number of the last element
If Cells(I, 7).Font.Bold Then
    Cells(I + 1, 7).Copy
    Cells(I + 1, 7).End(xlUp).Offset(1, -6).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
End If
Next


问:
Technical detail regarding suspending and resuming a running thread
I have a class which use to perform currency exchange monitoring activities, and it is having ability to suspend and resume. I have the following questions regarding my class design.

Is it necessary to have has_started as volatile?

Is it necessary to have suspend as volatile? I had seen the example from Exampledepot, the flag is not marked as volatile.

When I catch InterruptedException during wait, shall I return, or shall I just ignore the exception?

Also, I am getting NetBeans warning on having multiple synchronized block. Is it a valid warning?

```<code>public synchronized void suspend() {
    synchronized(currencyExchangeRunnable) {
        suspend = true;
    }
}
</code>```

My first level synchronized are use to prevent multiple threads from executing suspend/resume/start/stop. And my second level of synchronized block, is to pair with wait/notify

My initial testing on suspend/resume/start/stop is that, they work as expected. However, I am not sure is there any other catches behind?

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author yccheok
 */
public class CurrencyExchangeMonitor {

    /**
     * Starts currency exchange monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void start() {
        if (has_started) {
            return;
        }
        executor.submit(currencyExchangeRunnable);
        has_started = true;
    }

    /**
     * Stop all currency exchange monitoring activities. Once it is stopped, it
     * cannot be started again. This method will only return once it is being
     * terminated completely. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void stop() {
        executor.shutdownNow();
        try {
            executor.awaitTermination(100, TimeUnit.DAYS);
        } catch (InterruptedException ex) {
            log.error(null, ex);
        }
    }

    /**
     * Temporary suspend all ongoing monitoring activities. This method can be
     * called multiple times. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void suspend() {
        synchronized(currencyExchangeRunnable) {
            suspend = true;
        }
    }

    /**
     * Resume all ongoing monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void resume() {
        synchronized(currencyExchangeRunnable) {
            suspend = false;
            currencyExchangeRunnable.notify();
        }
    }

    private class CurrencyExchangeRunnable implements Runnable {
        @Override
        public void run() {
            while (!executor.isShutdown()) {
                synchronized(this) {
                    while (suspend) {
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                            log.error(null, ex);
                            // Usually triggered by executor.shutdownNow
                            return;
                        }
                    }
                }
            }
        }
    }

    private volatile boolean suspend = false;
    private volatile boolean has_started = false;
    private final CurrencyExchangeRunnable currencyExchangeRunnable = new CurrencyExchangeRunnable();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final Log log = LogFactory.getLog(CurrencyExchangeMonitor.class);
}
</code>```

答:
Since multiple threads my change has_started, you would usually mark it as volatile.  Since it is accessed only within a synchronized block, you need not do this

Since multiple threads may change suspend, you would usually mark it as volatile.  Since it is accessed only within a synchronized block, you need not do this

It is a good practice to always do something with InterruptedException.  InterruptedException means your wait has been interrupted by some other thread - perhaps a shut down thread from a browser plug-in (for an applet) or an application server (in JavaEE).  When you catch interrupted exception, the recommended thing to do is call Thread.currentThread().interrupt(); to handle it.  That is what your executor will be expecting.

The excellent book Java Concurrency in Practice would be just what you need to dig into the details on concurrency.

Body:
I have a class which use to perform currency exchange monitoring activities, and it is having ability to suspend and resume. I have the following questions regarding my class design.

Is it necessary to have has_started as volatile?

Is it necessary to have suspend as volatile? I had seen the example from Exampledepot, the flag is not marked as volatile.

When I catch InterruptedException during wait, shall I return, or shall I just ignore the exception?

Also, I am getting NetBeans warning on having multiple synchronized block. Is it a valid warning?

public synchronized void suspend() {
    synchronized(currencyExchangeRunnable) {
        suspend = true;
    }
}

My first level synchronized are use to prevent multiple threads from executing suspend/resume/start/stop. And my second level of synchronized block, is to pair with wait/notify

My initial testing on suspend/resume/start/stop is that, they work as expected. However, I am not sure is there any other catches behind?

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author yccheok
 */
public class CurrencyExchangeMonitor {

    /**
     * Starts currency exchange monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void start() {
        if (has_started) {
            return;
        }
        executor.submit(currencyExchangeRunnable);
        has_started = true;
    }

    /**
     * Stop all currency exchange monitoring activities. Once it is stopped, it
     * cannot be started again. This method will only return once it is being
     * terminated completely. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void stop() {
        executor.shutdownNow();
        try {
            executor.awaitTermination(100, TimeUnit.DAYS);
        } catch (InterruptedException ex) {
            log.error(null, ex);
        }
    }

    /**
     * Temporary suspend all ongoing monitoring activities. This method can be
     * called multiple times. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void suspend() {
        synchronized(currencyExchangeRunnable) {
            suspend = true;
        }
    }

    /**
     * Resume all ongoing monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void resume() {
        synchronized(currencyExchangeRunnable) {
            suspend = false;
            currencyExchangeRunnable.notify();
        }
    }

    private class CurrencyExchangeRunnable implements Runnable {
        @Override
        public void run() {
            while (!executor.isShutdown()) {
                synchronized(this) {
                    while (suspend) {
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                            log.error(null, ex);
                            // Usually triggered by executor.shutdownNow
                            return;
                        }
                    }
                }
            }
        }
    }

    private volatile boolean suspend = false;
    private volatile boolean has_started = false;
    private final CurrencyExchangeRunnable currencyExchangeRunnable = new CurrencyExchangeRunnable();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final Log log = LogFactory.getLog(CurrencyExchangeMonitor.class);
}


问:
Anaconda Python: where are the virtual environments stored?
I am new to Anaconda Python and I am setting up a project in Sublime Text 3. I have installed Anaconda and created a virtual environment using:

```<code>conda create -n python27 python=2.7 anaconda
conda create -n python35 python=3.5 anaconda
</code>```

I am having trouble setting up the Virtualenvs plugin for SublimeText 3.

When I try, it asks me for a virtualenvs path which I give:

```<code>~/users/../anaconda/envs/python27
</code>```

Then it asks for what I'm assuming is a path to a python distribution because it lists file paths for the system versions of python -- but not the anaconda install.

I have no real desire to use the plug in, I just want to be able to use both versions of python.  Could I use a project settings file to set the version of python instead?

答:
If you activate the environment you're interested in, you can find that answer in the environment variables.

on MacOS/Linux:

```<code>source activate python35
echo $CONDA_PREFIX
</code>```

on Windows:

```<code>conda activate python35
echo %CONDA_PREFIX%
</code>```

You can also run conda info --envs, and that will show the paths to all your environments.

To get the path to the instance of python being used by a particular environment, do the following:

on MacOS/Linux:

```<code>source activate python35
which python
</code>```

on Windows:

```<code>conda activate python35
where python
</code>```

That should return the path you're looking for.

Body:
I am new to Anaconda Python and I am setting up a project in Sublime Text 3. I have installed Anaconda and created a virtual environment using:

conda create -n python27 python=2.7 anaconda
conda create -n python35 python=3.5 anaconda

I am having trouble setting up the Virtualenvs plugin for SublimeText 3.

When I try, it asks me for a virtualenvs path which I give:

~/users/../anaconda/envs/python27

Then it asks for what I'm assuming is a path to a python distribution because it lists file paths for the system versions of python -- but not the anaconda install.

I have no real desire to use the plug in, I just want to be able to use both versions of python.  Could I use a project settings file to set the version of python instead?

Body:
If you activate the environment you're interested in, you can find that answer in the environment variables.

on MacOS/Linux:

source activate python35
echo $CONDA_PREFIX

on Windows:

conda activate python35
echo %CONDA_PREFIX%

You can also run conda info --envs, and that will show the paths to all your environments.

To get the path to the instance of python being used by a particular environment, do the following:

on MacOS/Linux:

source activate python35
which python

on Windows:

conda activate python35
where python

That should return the path you're looking for.


问:
scheduling backup in heroku command faills
According to the heroku documentation, to schedule a pg backup you issue the command:

```<code>heroku pg:backups:schedule DATABASE_URL --at '02:00 America/Los_Angeles' --app sushi
</code>```

This command doesn't seem to work for me and gives me the error:

```<code>Unexpected argument America/Los_Angeles
</code>```

I tried with different time zones including the abbreviated ones like UTC.

答:
To get this fixed in Windows you should use double quotes instead of singles quotes.

That would be:

heroku pg:backups:schedule DATABASE_URL --at "02:00 America/Los_Angeles" --app sushi

Body:
According to the heroku documentation, to schedule a pg backup you issue the command:

heroku pg:backups:schedule DATABASE_URL --at '02:00 America/Los_Angeles' --app sushi

This command doesn't seem to work for me and gives me the error:

Unexpected argument America/Los_Angeles

I tried with different time zones including the abbreviated ones like UTC.


问:
Android SeekBar thumb gets clipped/cut off
When using a custom thumb drawable with a SeekBar view, the thumb drawable is clipped at the left and right edges of the view.

How can I fix this behavior?

答: I ran into this issue myself, and I believe the "correct" decision would be to modify android:thumbOffset as the default style for a SeekBar sets it to 8px.


问:
iOS will CATransaction wait after viewDidDisappear before calling the completion block
will CATransaction wait after viewDidDisappear before calling the completion block?

```<code>  CATransaction.begin()
    view_controller.navigationController?.popViewController(animated: false)
    CATransaction.setCompletionBlock {
        self.call_some_function()
    }
    CATransaction.commit()
</code>```

If the view_controller has a custom viewDidDisappear function, will self.call_some_function() execute after that viewDidDisappear function finishes its execution?

I tried to set breakpoints and it turned out that viewDidDisappear did get executed before the completion block. Not sure if this behavior is always predictable as I wasn't able to find any documentation.

答:
Try seting the completion block before pop view controller

```<code>CATransaction.begin()
CATransaction.setCompletionBlock {
    self.call_some_function()
}
view_controller.navigationController?.popViewController(animated: false)
CATransaction.commit()
</code>```

or

```<code>CATransaction.setCompletionBlock {
    self.call_some_function()
}
CATransaction.begin()
view_controller.navigationController?.popViewController(animated: false)
CATransaction.commit()
</code>```

Body:
will CATransaction wait after viewDidDisappear before calling the completion block?

  CATransaction.begin()
    view_controller.navigationController?.popViewController(animated: false)
    CATransaction.setCompletionBlock {
        self.call_some_function()
    }
    CATransaction.commit()

If the view_controller has a custom viewDidDisappear function, will self.call_some_function() execute after that viewDidDisappear function finishes its execution?

I tried to set breakpoints and it turned out that viewDidDisappear did get executed before the completion block. Not sure if this behavior is always predictable as I wasn't able to find any documentation.

Body:
Try seting the completion block before pop view controller

CATransaction.begin()
CATransaction.setCompletionBlock {
    self.call_some_function()
}
view_controller.navigationController?.popViewController(animated: false)
CATransaction.commit()

or

CATransaction.setCompletionBlock {
    self.call_some_function()
}
CATransaction.begin()
view_controller.navigationController?.popViewController(animated: false)
CATransaction.commit()


问:
Django ORM: Tried to do inner join with foreign key but causes FieldError
I am new to django orm.
I've tables look like this.

```<code>class Product(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   name = models.CharField(max_length=60)

class ProductOption(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
</code>```

I would like to query productoption id that related to product. I made query like this to do inner join.

```<code>Query = Product.select_related(‘product_id’).filter(name='a')
</code>```

And it gaves me error message saying

```<code>django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none)
</code>```

I want to know if there is something wrong in models or query.

答:
This is not how you query a related object. Since you used a foreign key and if I understand correctly, you probably want to use something like this:</p>

```<code> Product.objects.filter(name='a').productoption_set.all()
</code>```

Body:
I am new to django orm.
I've tables look like this.

class Product(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   name = models.CharField(max_length=60)

class ProductOption(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)

I would like to query productoption id that related to product. I made query like this to do inner join.

Query = Product.select_related(‘product_id’).filter(name='a')

And it gaves me error message saying

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none)

I want to know if there is something wrong in models or query.

Body:
This is not how you query a related object. Since you used a foreign key and if I understand correctly, you probably want to use something like this:

 Product.objects.filter(name='a').productoption_set.all()


问:
EXCEL: find matching values
the following problem: I have an array of tables of witch I want to get a sum range of matching values. Here is the sheet:
Tables
The matching values do not have to be exact matches. For example, for 28car.com I am interested in 28car, car28 or 28 car, so values which closely resemble the website keyword. This is because these keywords are based on queries from search keywords of the respective websites and may be prone to change.
SUMIFS would therefore not work as I can only find exact matches (and these keywords may change on a monthly basis). I thought about VLOOKUP or INDEX & MATCH, but I don't know how to possibly execute either two.
Any suggestions?

https://imgur.com/a/OtzkE

答:
well you can use VLOOKUP with true as the last parameter i think, that will give you a non-exact matching word.

Alternatively you could add another table whith all the options for the KEY you would like to find.

Maybe if you give a little more information or some sort of image, we can help you better.

Title: EXCEL: find matching values


问:
Split to volumes using batch
I am using the following command in a batch file in order to archive MY_LARGE_FOLDER and my .rar file is too big:

```<code>WinRAR a -r D:\MY_LARGE_FOLDER.rar D:\MY_LARGE_FOLDER\*.txt D:\MY_LARGE_FOLDER\
</code>```

How can I archive MY_LARGE_FOLDER, into small .rar files of 4MB each using batch file?
(or in other words, How to use the "Split to volumes, bytes" option using batch file?)

Thanks.

Thanks for the help!
I used the -v switch:

```<code>          WinRAR a -r **-v4000** D:\MY_LARGE_FOLDER.rar D:\MY_LARGE_FOLDER\*.txt D:\MY_LARGE_FOLDER\
</code>```

and I got now 4 files of 4000 bytes each but after opening some of the files I saw that the files are duplicated on more than one archive (e.g. on Part01.rar and on Part02.rar) ???
1. I also tried the -s (solid) switch and the result is the same?

How can I solve it?

答:
My solution for 20Mb volumes was:

"%ProgramFiles(x86)%\WinRAR.Rar.exe" a -cfg- -ep1 -idcdp -m5 -md4096 -r -s -v20M "C:\test.rar" "C:\test\"

Title: Split to volumes using batch

Body:
I am using the following command in a batch file in order to archive MY_LARGE_FOLDER and my .rar file is too big:

WinRAR a -r D:\MY_LARGE_FOLDER.rar D:\MY_LARGE_FOLDER\*.txt D:\MY_LARGE_FOLDER\

How can I archive MY_LARGE_FOLDER, into small .rar files of 4MB each using batch file?
(or in other words, How to use the "Split to volumes, bytes" option using batch file?)

Thanks.

Thanks for the help!
I used the -v switch:

          WinRAR a -r **-v4000** D:\MY_LARGE_FOLDER.rar D:\MY_LARGE_FOLDER\*.txt D:\MY_LARGE_FOLDER\

and I got now 4 files of 4000 bytes each but after opening some of the files I saw that the files are duplicated on more than one archive (e.g. on Part01.rar and on Part02.rar) ???
1. I also tried the -s (solid) switch and the result is the same?

How can I solve it?


问:
Code first migration modeling class with two AppUser references
I am trying to model a message class, for private messages for a user, using code first migrations.

```<code>public class Message
{
     public int MessageId { get; set; }

    [Required]
    public string MessageForUserId { get; set; }
    public virtual ApplicationUser MessageForUser { get; set; }

    [Required]
    public string MessageFromUserId { get; set; }

    public virtual ApplicationUser MessageFromUser { get; set; }

    [Required]
    public string MessageContent { get; set; }

    public bool MessageRead { get; set; }

    [Required]
    public DateTime MessageCreatedOn { get; set; }

    public DateTime? MessageReadOn { get; set; }
}
</code>```

and in the ApplicationUser class I have added two collections

```<code>public class ApplicationUser : IdentityUser
{
    // other properties removed for brevity
    public ICollection<Message> UserMessages { get; set; }
    public ICollection<Message> SentMessages { get; set; }
}
</code>```

When I do the migration I not only get the MessageFrom and MessageFor Id's, two additional Id's get added ApplicationUser_Id and ApplicationUser _Id1 to the Message table.

I know this because their are two foreign keys in message. The foreign key annotations are commented out right now as I was getting an error in migration.

This was the error when the ForeignKeys were live and I tried to migrate.

Unable to determine the relationship represented by navigation property 'ApplicationUser.UserMessages' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

I'd like to use fluent annotations to define this class in the OnModelCreating method but am not sure how to do this properly. I'm clearly not understanding why EF Code First is not determining the relationships.

The problem is that I am not sure how to define the message class foreign keys. Each message involves two users the sender and the receiver. I thought about splitting message into two classes, MessageSent and MessageReceived but that wouldn't help because each of those would have a sender and receiver as well.

Any assistance on how to define this properly using fluent annotations would be appreciated.

Update:

Following Dominick's recommendations and prior post references, I have tried the following which is not working.

This is the DbSet code

```<code> public DbSet<Message> Messages { get; set; }
 public DbSet<ApplicationUser> AppUsers { get; set; }
</code>```

And in OnModelCreating

```<code> builder.Entity(typeof(Message))
            .HasOne(typeof(ApplicationUser), "MessageFromUser")
            .WithMany()
            .HasForeignKey("MessageFromUserId")
            .OnDelete(DeleteBehavior.Restrict); // no ON DELETE

 builder.Entity(typeof(Message))
            .HasOne(typeof(ApplicationUser), "MessageForUser")
            .WithMany()
            .HasForeignKey("MessageForUserId")
            .OnDelete(DeleteBehavior.Cascade); // set ON DELETE CASCADE
</code>```

I am getting the same error as noted above, even though the builder options make sense. The entity has one type of ApplicationUser, MessagesFromUser, there can be many and the foreignkey id is correct. Same is true for the other property.

答:
```<code>builder.Entity<Message>()
    .HasOne(x => x.MessageForUser)
    .WithMany(x => x.UserMessages)
    .HasForeignKey(x => x.MessageForUserId)
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<Message>()
    .HasOne(x => x.MessageFromUser)
    .WithMany(x => x.SentMessages)
    .HasForeignKey(x => x.MessageFromUserId)
    .OnDelete(DeleteBehavior.Cascade);
</code>```

Body:
I am trying to model a message class, for private messages for a user, using code first migrations.

public class Message
{
     public int MessageId { get; set; }

    [Required]
    public string MessageForUserId { get; set; }
    public virtual ApplicationUser MessageForUser { get; set; }

    [Required]
    public string MessageFromUserId { get; set; }

    public virtual ApplicationUser MessageFromUser { get; set; }

    [Required]
    public string MessageContent { get; set; }

    public bool MessageRead { get; set; }

    [Required]
    public DateTime MessageCreatedOn { get; set; }

    public DateTime? MessageReadOn { get; set; }
}

and in the ApplicationUser class I have added two collections

public class ApplicationUser : IdentityUser
{
    // other properties removed for brevity
    public ICollection<Message> UserMessages { get; set; }
    public ICollection<Message> SentMessages { get; set; }
}

When I do the migration I not only get the MessageFrom and MessageFor Id's, two additional Id's get added ApplicationUser_Id and ApplicationUser _Id1 to the Message table.

I know this because their are two foreign keys in message. The foreign key annotations are commented out right now as I was getting an error in migration.

This was the error when the ForeignKeys were live and I tried to migrate.

Unable to determine the relationship represented by navigation property 'ApplicationUser.UserMessages' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

I'd like to use fluent annotations to define this class in the OnModelCreating method but am not sure how to do this properly. I'm clearly not understanding why EF Code First is not determining the relationships.

The problem is that I am not sure how to define the message class foreign keys. Each message involves two users the sender and the receiver. I thought about splitting message into two classes, MessageSent and MessageReceived but that wouldn't help because each of those would have a sender and receiver as well.

Any assistance on how to define this properly using fluent annotations would be appreciated.

Update:

Following Dominick's recommendations and prior post references, I have tried the following which is not working.

This is the DbSet code

 public DbSet<Message> Messages { get; set; }
 public DbSet<ApplicationUser> AppUsers { get; set; }

And in OnModelCreating

 builder.Entity(typeof(Message))
            .HasOne(typeof(ApplicationUser), "MessageFromUser")
            .WithMany()
            .HasForeignKey("MessageFromUserId")
            .OnDelete(DeleteBehavior.Restrict); // no ON DELETE

 builder.Entity(typeof(Message))
            .HasOne(typeof(ApplicationUser), "MessageForUser")
            .WithMany()
            .HasForeignKey("MessageForUserId")
            .OnDelete(DeleteBehavior.Cascade); // set ON DELETE CASCADE

I am getting the same error as noted above, even though the builder options make sense. The entity has one type of ApplicationUser, MessagesFromUser, there can be many and the foreignkey id is correct. Same is true for the other property.


问:
Bugzilla 5.0 install on OpenShift - Can't locate parent.pm in @INC
Attempting to install Bugzilla on an OpenShift small gear. Using SSH to wget 5.0 tarball, untar-ing and running the checksetup.pl --check-modules script gives me this error:

```<code>Can't locate parent.pm in @INC (INC contains: . lib /var/openshift/[app-id]/app-root
/runtime/repo/libs /var/lib/openshift/[app-id]/perl/perl5lib/lib/perl5 /usr/local/lib64
/perl5 /usr/local/share/perl5 /usr/lib/lib64/perl5/vendor-perl /usr/share/perl5/vendor-perl
/usr/lib64/perl5 usr/share/perl5) at Bugzilla/Constants.pm line 14.
BEGIN failed--compilation aborted at Bugzilla/Constants.pm line 14.
Compilation failed in require at ./checksetup.pl line 27.
BEGIN failed--compilation aborted at ./checksetup.pl line 27.

Line 14 of Bugzilla/Constants.pm: `use parent qw(Exporter);`

Line 27 of ./checksetup.pl: `use Bugzilla::Constants;`
</code>```

[app-id] in the paths is just a random string of hex digits used to identify an OpenShift application.

All help would be greatly appreciated. Thanks in advance!

答:
#please install above packages:

```<code>[root@rsync ~]# yum install perl-parent -y
</code>```

Body:
Attempting to install Bugzilla on an OpenShift small gear. Using SSH to wget 5.0 tarball, untar-ing and running the checksetup.pl --check-modules script gives me this error:

Can't locate parent.pm in @INC (INC contains: . lib /var/openshift/[app-id]/app-root
/runtime/repo/libs /var/lib/openshift/[app-id]/perl/perl5lib/lib/perl5 /usr/local/lib64
/perl5 /usr/local/share/perl5 /usr/lib/lib64/perl5/vendor-perl /usr/share/perl5/vendor-perl
/usr/lib64/perl5 usr/share/perl5) at Bugzilla/Constants.pm line 14.
BEGIN failed--compilation aborted at Bugzilla/Constants.pm line 14.
Compilation failed in require at ./checksetup.pl line 27.
BEGIN failed--compilation aborted at ./checksetup.pl line 27.

Line 14 of Bugzilla/Constants.pm: `use parent qw(Exporter);`

Line 27 of ./checksetup.pl: `use Bugzilla::Constants;`

[app-id] in the paths is just a random string of hex digits used to identify an OpenShift application.

All help would be greatly appreciated. Thanks in advance!

Body:
#please install above packages:

[root@rsync ~]# yum install perl-parent -y


Body:
How do I convert this list of lists:

[['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]

To this list of tuples:

[(0, [1, 2, 3]), (1, [0, 4, 6, 7, 9]), (2, [0, 3, 6, 8, 9])]

I am unsure how to implement this next step? (I can't use dictionaries,
sets, deque, bisect module. You can though, and in fact should, use .sort or sorted functions.)

Here is my attempt:

network= [['10'], ['0 1'], ['0 2'], ['0 3'], ['1 4'], ['1 6'], ['1 7'], ['1 9'], ['2 3'], ['2 6'], ['2 8'], ['2 9']]
network.remove(network[0])
friends=[]

for i in range(len(network)):
    element= (network[i][0]).split(' ')
    friends.append(element)

t=len(friends)
s= len(friends[0])
lst=[]

for i in range(t):
    a= (friends[i][0])
    if a not in lst:
        lst.append(int(a))
        for i in range(t):
            if a == friends[i][0]:
                b=(friends[i][1])
                lst.append([b])
print(tuple(lst))

It outputs:

(0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 0, ['1'], ['2'], ['3'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 1, ['4'], ['6'], ['7'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'], 2, ['3'], ['6'], ['8'], ['9'])

I am very close it seems, not sure what to do??

Body:
A simpler method:

l = [['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]
a=set(i[0] for i in l)
b=list( (i,[]) for i in a)
[b[int(i[0])][1].append(i[1]) for i in l]
print(b)

Output:

[('0', ['1', '2', '3']), ('1', ['4', '6', '7', '9']), ('2', ['3', '6', '8', '9'])]

Alternate Answer (without using set)

l = [['0', '1'], ['0', '2'], ['0', '3'], ['1', '4'], ['1', '6'], ['1', '7'], ['1', '9'], ['2', '3'], ['2', '6'], ['2', '8'], ['2', '9']]
a=[]
for i in l:
    if i[0] not in a:
        a.append(i[0])
b=list( (i,[]) for i in a)
[b[int(i[0])][1].append(i[1]) for i in l]
print(b)

also outputs

[('0', ['1', '2', '3']), ('1', ['4', '6', '7', '9']), ('2', ['3', '6', '8', '9'])]


问:
CUDA installation on Windows
I installed CUDA Toolkit 3.2, CUDA SDK and MS Visual Studio  2008 (not necessarily in this order) on my Windows 7 that does not have an nvidia graphics card.
But when I try running my CUDA code, the CUDA keywords are'nt identified.
I am a beginner. Pls tell me what I am doing wrong here.

Thanks

答:
CUDA is only supported on machines with nVidia video cards.  That is likely an issue.

Furthermore, you need to install drivers (dev or otherwise) that is new enough to support the CUDA Toolkit version.

Third, what do you mean by the keywords aren't identified?  Do you mean there's no syntax highlighting in your IDE?  If so, try [this][1]http://codereflect.com/2008/09/04/how-to-enable-syntax-highlighting-for-cuda-files-in-visual-studio-2005/

Title: CUDA installation on Windows


问:
Need to specify screen react native tabnavigator
Problem
I made a very basic app using React Native, and now I want to have multiple tabs. When I tried to add a feed and comments tab, I get an error saying:

```<code>Uncaught Error: Route 'Feed' should declare a screen.
For example:

import MyScreen from './MyScreen'
...
Feed: {
Screen: MyScreen,
}
</code>```

I don't know why I am getting this error, since the first class I call is the 'App' screen, which is what I named the screen. I would love some help getting this tab error fixed. Thank you!

Code

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button, FlatList } from 'react-native';
import { Font } from 'expo';
import * as firebase from 'firebase';
import { TabNavigator } from 'react-navigation';

const firebaseConfig = {
  apiKey: "API-key",
  authDomain: "candidtwo.firebaseapp.com",
  databaseURL: "https://candidtwo.firebaseio.com",
  storageBucket: "candidtwo.appspot.com",
};

const MyApp = TabNavigator({
  Feed: {
    screen: App,
  },
  CommentScreen: {
    screen: Comments,
  },
}, {
  tabBarPosition: 'top',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#fe8200',
  },
});

const firebaseApp = firebase.initializeApp(firebaseConfig);

var fontLoaded = false;
var ref = firebase.database().ref('posts');
var brightColor = ['#ffffff'];
var darkColor = ['#D3D3D3'];
var animalNames = ['WittyRhino','FriendlyRhino'];
var newPostRef = ref.push();

var postWidth = 360;

class App extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
  };
//App Code
}

class Comments extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Notifications',
  };
render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('App')}
        title="Go to notifications"
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
  button: {
    flex: 1,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
});
</code>```

答:
Define App and Comments components before

```<code>const MyApp = TabNavigator(...)
</code>```

Hope this will help.

Body:
Problem
I made a very basic app using React Native, and now I want to have multiple tabs. When I tried to add a feed and comments tab, I get an error saying:

Uncaught Error: Route 'Feed' should declare a screen.
For example:

import MyScreen from './MyScreen'
...
Feed: {
Screen: MyScreen,
}

I don't know why I am getting this error, since the first class I call is the 'App' screen, which is what I named the screen. I would love some help getting this tab error fixed. Thank you!

Code

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button, FlatList } from 'react-native';
import { Font } from 'expo';
import * as firebase from 'firebase';
import { TabNavigator } from 'react-navigation';

const firebaseConfig = {
  apiKey: "API-key",
  authDomain: "candidtwo.firebaseapp.com",
  databaseURL: "https://candidtwo.firebaseio.com",
  storageBucket: "candidtwo.appspot.com",
};

const MyApp = TabNavigator({
  Feed: {
    screen: App,
  },
  CommentScreen: {
    screen: Comments,
  },
}, {
  tabBarPosition: 'top',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#fe8200',
  },
});

const firebaseApp = firebase.initializeApp(firebaseConfig);

var fontLoaded = false;
var ref = firebase.database().ref('posts');
var brightColor = ['#ffffff'];
var darkColor = ['#D3D3D3'];
var animalNames = ['WittyRhino','FriendlyRhino'];
var newPostRef = ref.push();

var postWidth = 360;

class App extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
  };
//App Code
}

class Comments extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Notifications',
  };
render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('App')}
        title="Go to notifications"
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
  button: {
    flex: 1,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
});

Body:
Define App and Comments components before

const MyApp = TabNavigator(...)

Hope this will help.


问:
Why do some webpages use a little HTML, but so much JavaScript
Why do some webpages use a little HTML, but so much JavaScript? Someone even used JavaScript to append the HTML like:
  and so on; the HTML source code was hidden in JavaScript.

Like this:

答:
The modern web is growing greatly in terms of complexity and user expectations.

Users want more complex, rich content, delivered faster. JavaScript provides the capability to enable meeting this demand.

HTML by definition, (HyperText Markup Language) provides zero functionality to a website. It simply displays stuff. And CSS (Cascading Style Sheets), in particular CSS3, provides a minimal level functionality (like import -ing a font for example, or making a div spin or fade in and out)

For anything and everything else, you gotta use JavaScript. From controlling HTML, CSS, retrieving data from APIs (Application Progamming Interface) and handling user input, JavaScript does it all.