问:
How to catch segmentation fault with Google Test?
How do I test that a function won't produce a segmentation fault?

Here what I know right now, I can do:

```<code>EXPECT_DEATH(foo(nullParameter))
</code>```

In side the function, a segmentation fault is produce which is the behavior that I want to make fail. The snippet above will make the test pass because that is what is expected, the death of the process.

Now, how can I make it fail?

答:
Here's a function that will segfault if passed a null pointer argument and otherwise
not:

```<code>int deref(int * pint)
{
    return *pint;
}
</code>```

And here is a googletest program that tests that behaviour:

main.cpp

```<code>#include <gtest/gtest.h>

int deref(int * pint)
{
    return *pint;
}

TEST(test_deref_1,will_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::KilledBySignal(SIGSEGV),".*");
}

TEST(test_dref_2,will_not_segfault)
{
    int i = 42;
    ASSERT_EXIT((deref(&i),exit(0)),::testing::ExitedWithCode(0),".*");
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
</code>```

Compile and link:

```<code>$ g++ -Wall -Wextra -pedantic -o tester main.cpp -pthread -lgtest
</code>```

Run:

```<code>$ ./tester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (168 ms)
[----------] 1 test from test_deref_1 (168 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
[       OK ] test_dref_2.will_not_segfault (1 ms)
[----------] 1 test from test_dref_2 (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (169 ms total)
[  PASSED  ] 2 tests.
</code>```

As far as I can imagine, TEST(test_deref_1,will_segfault) is a pointless test,
because I cannot think of any circumstances in which I would want to assure
myself that a program will segfault as a result of making a certain call to a
function I have written.

TEST(test_dref_2,will_not_segfault) is possibly a useful kind of test. In effect,
it is a test that the program:

```<code>int main()
{
    int i = 42;
    defref(&i);
    exit(0);
}
</code>```

will terminate by exit(0) rather than in any premature abnormal way. A better name for
this test would probably be TEST(test_dref,does_not_crash), or similar.

It is a possibly useful kind of test because there could be a significant risk of it
failing, if defref was some sufficiently complicated code, and the test suite
could report that failure without crashing itself. We can force a failure by rewriting
it:

```<code>TEST(test_dref_2,will_not_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::ExitedWithCode(0),".*");
}
</code>```

and then test test report is:

```<code>$ ./tester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (147 ms)
[----------] 1 test from test_deref_1 (147 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
main.cpp:25: Failure
Death test: (deref(nullptr),exit(0))
    Result: died but not with expected exit code:
            Terminated by signal 11 (core dumped)
Actual msg:
[  DEATH   ]
[  FAILED  ] test_dref_2.will_not_segfault (90 ms)
[----------] 1 test from test_dref_2 (90 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (237 ms total)
[  PASSED  ] 1 test.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] test_dref_2.will_not_segfault

 1 FAILED TEST
</code>```

See the documentation of {ASSERT|EXPECT}_EXIT
to understand these macros.

Body:
How do I test that a function won't produce a segmentation fault?

Here what I know right now, I can do:

EXPECT_DEATH(foo(nullParameter))

In side the function, a segmentation fault is produce which is the behavior that I want to make fail. The snippet above will make the test pass because that is what is expected, the death of the process.

Now, how can I make it fail?

Body:
Here's a function that will segfault if passed a null pointer argument and otherwise
not:

int deref(int * pint)
{
    return *pint;
}

And here is a googletest program that tests that behaviour:

main.cpp

#include <gtest/gtest.h>

int deref(int * pint)
{
    return *pint;
}

TEST(test_deref_1,will_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::KilledBySignal(SIGSEGV),".*");
}

TEST(test_dref_2,will_not_segfault)
{
    int i = 42;
    ASSERT_EXIT((deref(&i),exit(0)),::testing::ExitedWithCode(0),".*");
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Compile and link:

$ g++ -Wall -Wextra -pedantic -o tester main.cpp -pthread -lgtest

Run:

$ ./tester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (168 ms)
[----------] 1 test from test_deref_1 (168 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
[       OK ] test_dref_2.will_not_segfault (1 ms)
[----------] 1 test from test_dref_2 (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (169 ms total)
[  PASSED  ] 2 tests.

As far as I can imagine, TEST(test_deref_1,will_segfault) is a pointless test,
because I cannot think of any circumstances in which I would want to assure
myself that a program will segfault as a result of making a certain call to a
function I have written.

TEST(test_dref_2,will_not_segfault) is possibly a useful kind of test. In effect,
it is a test that the program:

int main()
{
    int i = 42;
    defref(&i);
    exit(0);
}

will terminate by exit(0) rather than in any premature abnormal way. A better name for
this test would probably be TEST(test_dref,does_not_crash), or similar.

It is a possibly useful kind of test because there could be a significant risk of it
failing, if defref was some sufficiently complicated code, and the test suite
could report that failure without crashing itself. We can force a failure by rewriting
it:

TEST(test_dref_2,will_not_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::ExitedWithCode(0),".*");
}

and then test test report is:

$ ./tester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (147 ms)
[----------] 1 test from test_deref_1 (147 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
main.cpp:25: Failure
Death test: (deref(nullptr),exit(0))
    Result: died but not with expected exit code:
            Terminated by signal 11 (core dumped)
Actual msg:
[  DEATH   ]
[  FAILED  ] test_dref_2.will_not_segfault (90 ms)
[----------] 1 test from test_dref_2 (90 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (237 ms total)
[  PASSED  ] 1 test.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] test_dref_2.will_not_segfault

 1 FAILED TEST

See the documentation of {ASSERT|EXPECT}_EXIT
to understand these macros.


来源: stackexchange

问:
Cancel the action of deleting of a recyclerview item with snackbar
That's my deletion code for recyclerview items.

```<code>viewHolder.button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        context.getContentResolver().delete(ContractParaGastos.CONTENT_URI,ContractParaGastos.Columnas.MONTO + " = ?", new String[]{nom});
        SyncAdapter.sincronizarAhora(context, true);
    }
});
</code>```

I would like to know how to implement a cancel function in a snackbar.

答:
Usually you don't delete the item. You could just remove it from the recyclerview, but still store it. Then you can put up a snackbar with the confirmation message. If the user clicks Cancel then you could just put the item into the  recyclerview again.

So you could basically have a view called undo which gets replaced with the "deleted" item:

```<code>View undo = yourView;
</code>```

So if the user decides to cancel his operation just get the view from your undo, put it into the RecyclerView and set your undo view to null.

There is a great explanation on this page: Confirmation and undo removing in RecyclerView

ContentLicense: CC BY-SA 3.0

Body:
That's my deletion code for recyclerview items.

viewHolder.button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        context.getContentResolver().delete(ContractParaGastos.CONTENT_URI,ContractParaGastos.Columnas.MONTO + " = ?", new String[]{nom});
        SyncAdapter.sincronizarAhora(context, true);
    }
});

I would like to know how to implement a cancel function in a snackbar.

Body:
Usually you don't delete the item. You could just remove it from the recyclerview, but still store it. Then you can put up a snackbar with the confirmation message. If the user clicks Cancel then you could just put the item into the  recyclerview again.

So you could basically have a view called undo which gets replaced with the "deleted" item:

View undo = yourView;

So if the user decides to cancel his operation just get the view from your undo, put it into the RecyclerView and set your undo view to null.

There is a great explanation on this page: Confirmation and undo removing in RecyclerView


问:
what could be wrong with this uml relationships
Hi I am trying to create class diagrams, but I am not sure enough that my opinion is good, could you tell me what should I change, thanks.

dont sure also maybe association?

maybe association?

答:
I think I understand your question, although as the commenters are trying to explain to you you haven't asked it clearly. I believe you are asking what type of association you should use between your classes.

The composition association, as you appear to partially understand, means that the lifetime of an object in a composition relationship depends on the object of which it is a part.

Your first diagram, then, is saying that your train is composed of train stops, and that therefore if there were no train, there would no longer be any train stops. This is obviously not true; other trains could stop at the same stops. Furthermore, your train is probably going to associate with a "route" object, which will be an aggregate of a number of stops. I'll leave you to work out the details of that.

Your next diagram is saying that a train is composed (at least in part) of passengers, so that if the train is destroyed, there are no more passengers. But a passenger can switch trains and continue to be a passenger, so you don't have a composition relationship between train and passenger. The passenger rides trains, the train may or may not have passengers, so you have a simple association (no diamond of any kind).

Finally, your last diagram is saying that available routes are composed of cities. This is plausible. However, there is also the issue that a given city may be a member of different routes. If so, it may be better to say that a given city "has" a number of routes associated with it. In such a case, there would be a white diamond on the city end. Of course, if you do that, you're going to have to rethink your distance_between attribute. It might be best to create a distance class, which itself is associated with two and only two city objects.


问:
Error in AndroidManifest.xml file !
```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.example.sudoku"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Sudoku"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  //error here->//      <activity android:name=".about"
        android:label="@string/about_title">

</activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest>
</code>```

<p>//Th problem is ,when I was developing a sudoku game I got an error in defining the activity (.about).
Above I have written the code and the place where the error occurred. Please help// </p>

答: I see nothing strange. Could it be that you where trying for ".About" instead of ".about" ?

ContentLicense: CC BY-SA 2.5

Title: Error in AndroidManifest.xml file !

Body:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.example.sudoku"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Sudoku"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  //error here->//      <activity android:name=".about"
        android:label="@string/about_title">

</activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest>

//Th problem is ,when I was developing a sudoku game I got an error in defining the activity (.about).
Above I have written the code and the place where the error occurred. Please help//


问:
How can I create a button programmatically in C# window app?
In the Form1_Load method what code should I write to create a simple button?

```<code> private void Form1_Load(object sender, System.EventArgs e)
 {

 }
</code>```

So that on Load the button would show.

答:
As you said it is Winforms, you can do the following...

First create a new Button object.

Button newButton = new Button();

Then add it to the form inside that function using:

this.Controls.Add(newButton);

Extra properties you can set...

```<code>newButton.Text = "Created Button";
newButton.Location = new Point(70,70);
newButton.Size = new Size(50, 100);
</code>```

Your issue you're running to is that you're trying to set it on Form_Load event, at that stage the form does not exist yet and your buttons are overwritten. You need a delegate for the Shown or Activated events in order to show the button.

For example inside your Form1 constructor,

```<code>public Form1()
{
    InitializeComponent();
    this.Shown += CreateButtonDelegate;
}
</code>```

Your actual delegate is where you create your button and add it to the form, something like this will work.

```<code>private void CreateButtonDelegate(object sender, EventArgs e)
{
    Button newButton= new Button();
    this.Controls.Add(newButton);
    newButton.Text = "Created Button";
    newButton.Location = new Point(70,70);
    newButton.Size = new Size(50, 100);
    newButton.Location = new Point(20, 50);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the Form1_Load method what code should I write to create a simple button?

 private void Form1_Load(object sender, System.EventArgs e)
 {

 }

So that on Load the button would show.

Body:
As you said it is Winforms, you can do the following...

First create a new Button object.

Button newButton = new Button();

Then add it to the form inside that function using:

this.Controls.Add(newButton);

Extra properties you can set...

newButton.Text = "Created Button";
newButton.Location = new Point(70,70);
newButton.Size = new Size(50, 100);

Your issue you're running to is that you're trying to set it on Form_Load event, at that stage the form does not exist yet and your buttons are overwritten. You need a delegate for the Shown or Activated events in order to show the button.

For example inside your Form1 constructor,

public Form1()
{
    InitializeComponent();
    this.Shown += CreateButtonDelegate;
}

Your actual delegate is where you create your button and add it to the form, something like this will work.

private void CreateButtonDelegate(object sender, EventArgs e)
{
    Button newButton= new Button();
    this.Controls.Add(newButton);
    newButton.Text = "Created Button";
    newButton.Location = new Point(70,70);
    newButton.Size = new Size(50, 100);
    newButton.Location = new Point(20, 50);
}


问:
Could not find tools.jar React Native Android In windows 10
guys . i just try to install react native in my laptop. i've followed all setup instruction but i stiil get those error .

```<code>* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Could not find tools.jar
</code>```

i used genymotion with os version 5.1.0, i've setup environment variable for android_home. Any idea what i miss here ?

答:
If you have the Android Studio embedded JDK, then it may cause conflicts. A workaround for this problem I've found is setting your JAVA_HOME to the default JDK location specified in Android Studio.

Open Android Studio

Press Ctrl+Alt+Shift+S to open Project Structure window.

Set your JAVA_HOME environment variable to the path specified under "JDK location".

Body:
guys . i just try to install react native in my laptop. i've followed all setup instruction but i stiil get those error .

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Could not find tools.jar

i used genymotion with os version 5.1.0, i've setup environment variable for android_home. Any idea what i miss here ?


问:
retrieve data rows in a specific time period in LINUX command
I'm developing some LINUX code to filter some data from the cus.txt file. below shows the table in text format

```<code>12/3/2017  13:25:16  SAM      reject
12/3/2017  13:25:26  NEEL     pass
12/3/2017  13:25:58  SAM      pass
12/3/2017  14:55:11  COOK     pass
12/13/2017 21:25:45  ANDRUE   pass
12/15/2017 23:46:31  FLINTOF  pass
12/19/2017 16:25:51  KEVIN    pass
12/20/2017 13:15:35  JHON     reject
12/20/2017 13:15:25  ADEM     pass
12/20/2017 13:15:51  JHON     pass
12/22/2017 15:39:09  KEVIN    pass
12/25/2017 19:25:28  SIMON    reject
12/25/2017 19:25:31  JHON     pass
12/25/2017 19:25:38  COOK     pass
12/25/2017 19:25:50  SIMON    pass
12/26/2017 22:19:20  SAM      pass
12/27/2017 20:12:55  KEVIN    pass
</code>```

Here i need is,
If you meet every "reject" word in 4th column, it should check name in name column and filter the next "pass" line with the same name within 30 seconds of time period. below shows my linux code.

```<code>awk 'function get_time(d_str){ split(d_str, d, /[/:[:space:]]/);
return mktime(sprintf("%d %d %d %d %d %d",d[3],d[1],d[2],d[4],d[5],d[6])) }$5=="pass" && status=="reject" &&
(get_time(prev_date)-get_time($1" "$2))<=30;{ prev_date=$1" "$2;
status=$5 }' cus.txt
</code>```

With this code i can filter below results. that is not what i need.

Above is not my required result. Below shows my needed result:

答:
While you can use awk if required, you can also use a simple shell script and date -d to compute the difference in time between the last reject and next pass with the same name. Then just test if the difference is less than or equal to 30 seconds and print the line if it is, e.g.

```<code>#!/bin/bash

rdate=   ## empty variables to use for reject
rtime=
rname=

while read -r dt tm nm res; do      ## read date time name result
    if [ "$res" = "reject" ]; then  ## if result "reject"
        rdate="$dt"                 ## save date time name
        rtime="$tm"
        rname="$nm"
    ## elif result is pass, if rname set check name = last reject name
    elif [ -n "$rname" ] && [ "$nm" = "$rname" ]; then
        ## compute time difference between reject and current
        tmdiff=$(( $(date -d "$dt $tm" +%s) - $(date -d "$rdate $rtime" +%s) ))
        ## if less than or equal to 30 output line
        [ "$tmdiff" -le "30" ] && \
            printf "%-9s %s %-7s %s\n" "$dt" "$tm" "$nm" "$res"
    fi
done <cus.txt
</code>```

Example Output

```<code>$ bash cus.sh
12/20/2017 13:15:51 JHON    pass
12/25/2017 19:25:50 SIMON   pass
</code>```

Body:
I'm developing some LINUX code to filter some data from the cus.txt file. below shows the table in text format

12/3/2017  13:25:16  SAM      reject
12/3/2017  13:25:26  NEEL     pass
12/3/2017  13:25:58  SAM      pass
12/3/2017  14:55:11  COOK     pass
12/13/2017 21:25:45  ANDRUE   pass
12/15/2017 23:46:31  FLINTOF  pass
12/19/2017 16:25:51  KEVIN    pass
12/20/2017 13:15:35  JHON     reject
12/20/2017 13:15:25  ADEM     pass
12/20/2017 13:15:51  JHON     pass
12/22/2017 15:39:09  KEVIN    pass
12/25/2017 19:25:28  SIMON    reject
12/25/2017 19:25:31  JHON     pass
12/25/2017 19:25:38  COOK     pass
12/25/2017 19:25:50  SIMON    pass
12/26/2017 22:19:20  SAM      pass
12/27/2017 20:12:55  KEVIN    pass

Here i need is,
If you meet every "reject" word in 4th column, it should check name in name column and filter the next "pass" line with the same name within 30 seconds of time period. below shows my linux code.

awk 'function get_time(d_str){ split(d_str, d, /[/:[:space:]]/);
return mktime(sprintf("%d %d %d %d %d %d",d[3],d[1],d[2],d[4],d[5],d[6])) }$5=="pass" && status=="reject" &&
(get_time(prev_date)-get_time($1" "$2))<=30;{ prev_date=$1" "$2;
status=$5 }' cus.txt

With this code i can filter below results. that is not what i need.

Above is not my required result. Below shows my needed result:

Body:
While you can use awk if required, you can also use a simple shell script and date -d to compute the difference in time between the last reject and next pass with the same name. Then just test if the difference is less than or equal to 30 seconds and print the line if it is, e.g.

#!/bin/bash

rdate=   ## empty variables to use for reject
rtime=
rname=

while read -r dt tm nm res; do      ## read date time name result
    if [ "$res" = "reject" ]; then  ## if result "reject"
        rdate="$dt"                 ## save date time name
        rtime="$tm"
        rname="$nm"
    ## elif result is pass, if rname set check name = last reject name
    elif [ -n "$rname" ] && [ "$nm" = "$rname" ]; then
        ## compute time difference between reject and current
        tmdiff=$(( $(date -d "$dt $tm" +%s) - $(date -d "$rdate $rtime" +%s) ))
        ## if less than or equal to 30 output line
        [ "$tmdiff" -le "30" ] && \
            printf "%-9s %s %-7s %s\n" "$dt" "$tm" "$nm" "$res"
    fi
done <cus.txt

Example Output

$ bash cus.sh
12/20/2017 13:15:51 JHON    pass
12/25/2017 19:25:50 SIMON   pass


问:
Better way to write many if statements in Java?
So I have this homework where I need to build a vending machine, and I assigned a coordinate to every product (A1, A2, A3..) and when the user enters the coin value I have to calculate if he can buy the product that he chose and if yes calculate the change, since i'm still new to programming I now have ended up with many statements like this

```<code>if ("a1".equals(choice)) {
    System.out.println("You chose SNICKERS!");
    if (money < 50) {
        System.out.println("This is not enough money to buy this product");
    } else if (money >= 50) {
        System.out.println(" Price = 50  Your change = " + (money - 50));
    }
}
</code>```

where the only things changing are the coordinates (a1, a2, a3, a4, b1, b2 and so on) and the prices. What would be a better way to do this?

答:
You could use a more OO approach.

Make a class called Product:

```<code>class Product {
    private String name;
    private int price;

    public String getName() { return name; }
    public int getPrice() { return price; }

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }
}
</code>```

Then, create a HashMap<String, Product> and add all your products and their coordinates in:

```<code>HashMap<String, Product> productMap = new HashMap<>();
productMap.put("A1", new Product("Snickers", 50));
productMap.put("A2", new Product("Something else", 40));
// do this for every coordinate...
</code>```

Now, you can just use this code:

```<code>Product chosenProduct = productMap.get(choice);
System.out.println("You chose " + chosenProduct.getName() + "!");
if (money < chosenProduct.getPrice()) {
    System.out.println("This is not enough money to buy this product");
} else {
    System.out.println(" Price = " + chosenProduct.getPrice() + "  Your change = " + (money - chosenProduct.getPrice()));
}
</code>```

Body:
So I have this homework where I need to build a vending machine, and I assigned a coordinate to every product (A1, A2, A3..) and when the user enters the coin value I have to calculate if he can buy the product that he chose and if yes calculate the change, since i'm still new to programming I now have ended up with many statements like this

if ("a1".equals(choice)) {
    System.out.println("You chose SNICKERS!");
    if (money < 50) {
        System.out.println("This is not enough money to buy this product");
    } else if (money >= 50) {
        System.out.println(" Price = 50  Your change = " + (money - 50));
    }
}

where the only things changing are the coordinates (a1, a2, a3, a4, b1, b2 and so on) and the prices. What would be a better way to do this?

Body:
You could use a more OO approach.

Make a class called Product:

class Product {
    private String name;
    private int price;

    public String getName() { return name; }
    public int getPrice() { return price; }

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

Then, create a HashMap<String, Product> and add all your products and their coordinates in:

HashMap<String, Product> productMap = new HashMap<>();
productMap.put("A1", new Product("Snickers", 50));
productMap.put("A2", new Product("Something else", 40));
// do this for every coordinate...

Now, you can just use this code:

Product chosenProduct = productMap.get(choice);
System.out.println("You chose " + chosenProduct.getName() + "!");
if (money < chosenProduct.getPrice()) {
    System.out.println("This is not enough money to buy this product");
} else {
    System.out.println(" Price = " + chosenProduct.getPrice() + "  Your change = " + (money - chosenProduct.getPrice()));
}


问:
protecting adobe air apps
I am about to deliver an Adobe AIR app to a customer.
But it's my first delivery of any sort, I.e. I have
no experience whatsoever with licensing etc.

Users of this app may or may not be online, so
can't count on that. In fact it's 99% sure that
they will be offline.

Nor do I expect them to very tech-savvy, who will
spend enough time scouting for ways to "crack" it.

So, is there an okeish type of way to protect this
app. That is, I don't want people to simply copy
the installation folder, take it to another machine
and run it. It should be slightly harder than this.

Oh, and I am also using PHP and MySql, with which
this AIR app communicates. So anything you guys could
help me with is very very welcome.

答:
When the app installs, I would do the following:

Create a file in "app-storage" that basically indicates the app has been installed.

Fire off a service call and make a record of the install

Change a file in the app directory to indicate the app has been installed

On subsequent startups, check for the presence of the file as long as the file in the app directory indicates the app has been installed.  If you see the customer keeps installing their app over and over, this could be flagged in their account and appropriate action taken. If you want to get fancy, the file in "app-storage" could a one-way hash of some information from the file in the app directory (install date?) plus some value baked into the AIR application.

In general, I think the key here is to trust your users and not make the assumption they are trying to steal.  You want to make the system as painless as possible.  It does not build a good relationship with customers when you treat them like criminals, so creating an "ironclad" approach probably isn't even the best idea.

OwnerDisplayName: dta

Title: protecting adobe air apps


问:
Get sound from a URL with Java
I'm learning english and I'd like to develop a software to help me with the pronunciation.

There is a site called HowJSay, if you enter here: http://www.howjsay.com/index.php?word=car
immediatly you'll hear the pronunciation of the word car . I'd like to develop a software in JAVA that could play this sound without necessity of enter in the site =]

I tried this, but doesn't work =/

```<code>public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.howjsay.com/index.php?word=car");
    url.openConnection();
    AudioStream as = new AudioStream(url.openStream());
    AudioPlayer.player.start(as);
    AudioPlayer.player.stop(as);
}
</code>```

Any Ideas? Please.

答:
If you're having issues with the code provided by Marek, make sure you're meeting this criteria:

Use a supported audio format, such as 16 bit .wav

Make sure that the URL you're using is actually playing audio automatically.

It isn't sufficient to simply reference the download page for an audio file. It has to be streaming the audio. YouTube URLs won't work, as they're videos. Audacity is a good approach to converting your audio file to a compatible 16 bit .wav file, and if you have your own domain / website, you can provide a direct link to the file from there.

Title: Get sound from a URL with Java

Body:
I'm learning english and I'd like to develop a software to help me with the pronunciation.

There is a site called HowJSay, if you enter here: http://www.howjsay.com/index.php?word=car
immediatly you'll hear the pronunciation of the word car . I'd like to develop a software in JAVA that could play this sound without necessity of enter in the site =]

I tried this, but doesn't work =/

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.howjsay.com/index.php?word=car");
    url.openConnection();
    AudioStream as = new AudioStream(url.openStream());
    AudioPlayer.player.start(as);
    AudioPlayer.player.stop(as);
}

Any Ideas? Please.


问:
Why the method in some class I created, ask me for input "self"?
I am new in OO programming. It is python 3.
Let be some example code:

```<code>class MyClass:
      def __init__(self,a=1,b=2):
          self.a=a
          self.b=b
      def function1(self):
          c.self=salf.a/self.b + 5
          return(c.self)
</code>```

When I call a method from MyClass. i.e:

```<code>MyClass.function1()
</code>```

it returns:
NameError: name 'self' is not defined.

I understand that if I initialize the code as:

```<code>class MyClass(object):
     code etc...
</code>```

It is all right if I put:
      somevariable=MyClass; somevariable.function1()

It works... I do not know why this is happening.

Thank you so much !

答:
You have to create an object of your class:

```<code>class MyClass:
  def __init__(self,a=1,b=2):
      self.a=a
      self.b=b
  def function1(self):
      self.c=self.a/self.b + 5
      return(self.c)

print(MyClass().function1())
</code>```

MyClass() creates an object that can be used to access attributes in the class.

For a general instance:

```<code>m = MyClass()
print(m.function1())
</code>```

Body:
I am new in OO programming. It is python 3.
Let be some example code:

class MyClass:
      def __init__(self,a=1,b=2):
          self.a=a
          self.b=b
      def function1(self):
          c.self=salf.a/self.b + 5
          return(c.self)

When I call a method from MyClass. i.e:

MyClass.function1()

it returns:
NameError: name 'self' is not defined.

I understand that if I initialize the code as:

class MyClass(object):
     code etc...

It is all right if I put:
      somevariable=MyClass; somevariable.function1()

It works... I do not know why this is happening.

Thank you so much !

Body:
You have to create an object of your class:

class MyClass:
  def __init__(self,a=1,b=2):
      self.a=a
      self.b=b
  def function1(self):
      self.c=self.a/self.b + 5
      return(self.c)

print(MyClass().function1())

MyClass() creates an object that can be used to access attributes in the class.

For a general instance:

m = MyClass()
print(m.function1())


问:
How to remove every third element from a linked list recursively?
I would like to iterate over a linked list and remove every third element recursively.

If the end of the list is reached, I do the same call on those elements which are left in the linked list. I'm doing that until only one element is left in the linked list.

My solution which does not work as expected:

```<code>import java.util.LinkedList;
import java.util.List;

    public class test {

    public static void main(String[] args) {
        int randomNumber = (int )(Math.random() * 50 + 1);
        List<Integer> testList = new LinkedList<Integer>();

        for (int i = 1; i <= randomNumber; i++)
        {
            testList.add(i);
        }
    }
        public void removeElements(List testList)
        {
           for(int i = 0; i < testList.size();i++){
                if(i % 3 == 0){
                    testList.remove(i);
                }
            }
            if(testList.isEmpty()){
                return;
            }
            removeElements(testList-1);
        }
 }
</code>```

答:
You are removing items from the list you are iterating over. That makes it vulnerable. The list gets smaller while the iteration gets bigger. This leads to IndexOutOfBounds like errors.

It is probably a better idea to make a copy of the list and remove stuff from the copy based on iteration over the orinal and then return the reduced copy.

Body:
I would like to iterate over a linked list and remove every third element recursively.

If the end of the list is reached, I do the same call on those elements which are left in the linked list. I'm doing that until only one element is left in the linked list.

My solution which does not work as expected:

import java.util.LinkedList;
import java.util.List;

    public class test {

    public static void main(String[] args) {
        int randomNumber = (int )(Math.random() * 50 + 1);
        List<Integer> testList = new LinkedList<Integer>();

        for (int i = 1; i <= randomNumber; i++)
        {
            testList.add(i);
        }
    }
        public void removeElements(List testList)
        {
           for(int i = 0; i < testList.size();i++){
                if(i % 3 == 0){
                    testList.remove(i);
                }
            }
            if(testList.isEmpty()){
                return;
            }
            removeElements(testList-1);
        }
 }


问:
using a relational database to store results from head-to-head(-to-head) gaming
I've got a site where people record game results. 95% of the games are played solo, but the 5% that aren't throw off the win-draw-win statistics for each scenario.

Each battle has 2 sides, and all possible results are:

Side 1 wins

Side 2 wins

Draw

If 2 people play each other, and both record a play, you get 2 wins for a given side when there should only be one, (making sense?) and it throws off the balance rating. Those records should be merged when it comes time to display the battle's stats.

My original kludge was to program the PHP such that same play date + same result = group into one result only, however as the userbase has grown collisions (people playing on the same day and getting the same result by chance) have become more frequent.

As my programming ability has increased, I feel ready to strip out the kludge and replace it with a proper head-to-head handler, but am having trouble coming up with an acceptable database structure.

Currently, all records are stored in one table, battle_results, which has the following structure:

```<code>[play_id] [user_id] [battle_id] [play_date] [win_side]
  000001    007       DeRa001    2010-01-01     1
  000002    010       DeRa001    2010-01-01     1
</code>```

I want to give my users the ability to list whether it was a solo or head-to-head play, and what side they were playing, so I plan to modify the table like so:

```<code>[play_id] [user_id] [battle_id] [play_date] [win_side] [play_type] [user_side]
  000001    007       DeRa001    2010-01-01    1           multi        2
  000002    010       DeRa001    2010-01-01    1           multi        1
</code>```

that's easy enough. But the users need to be able to say who they were playing with. At first I thought a many-to-many table would do the trick:

```<code>[play_id] [user_id] [opponent_id]
  00001     007        010
</code>```

but then I realized that when the opponent submits the same record you'll just be reversing columns:

```<code>[play_id] [user_id] [opponent_id]
  00001     007        010
  00002     010        007
</code>```

and I really have no idea how to pull that data out and construct a win-draw-win ratio that would recognize that these people were all playing together...

Am I making sense? How do I match up those records?

答:
What's wrong with storing the data like this:

```<code>[battle_id] [opponent_1] [opponent_2] [result_1] [result_2]
    1            007         010          1          0
    2            011         007          0          1
    3            007         012          0          0
</code>```

looking for 007 player wins (will result 2):

```<code>select count(*) from battles
where
   (opponent_1 = '007' AND result_1 = 1 and result_2 = 0)
   OR
   (opponent_2 = '007' AND result_1 = 0 and result_2 = 1)
</code>```

looking for players 007 draws (will result 1):

```<code>select count(*) from battles
where
     (opponent_1 = '007' AND result_1 = 0 and result_2 = 0)
     OR
     (opponent_2 = '007' AND result_1 = 0 and result_2 = 0)
</code>```

etc.

Body:
I've got a site where people record game results. 95% of the games are played solo, but the 5% that aren't throw off the win-draw-win statistics for each scenario.

Each battle has 2 sides, and all possible results are:

Side 1 wins

Side 2 wins

Draw

If 2 people play each other, and both record a play, you get 2 wins for a given side when there should only be one, (making sense?) and it throws off the balance rating. Those records should be merged when it comes time to display the battle's stats.

My original kludge was to program the PHP such that same play date + same result = group into one result only, however as the userbase has grown collisions (people playing on the same day and getting the same result by chance) have become more frequent.

As my programming ability has increased, I feel ready to strip out the kludge and replace it with a proper head-to-head handler, but am having trouble coming up with an acceptable database structure.

Currently, all records are stored in one table, battle_results, which has the following structure:

[play_id] [user_id] [battle_id] [play_date] [win_side]
  000001    007       DeRa001    2010-01-01     1
  000002    010       DeRa001    2010-01-01     1

I want to give my users the ability to list whether it was a solo or head-to-head play, and what side they were playing, so I plan to modify the table like so:

[play_id] [user_id] [battle_id] [play_date] [win_side] [play_type] [user_side]
  000001    007       DeRa001    2010-01-01    1           multi        2
  000002    010       DeRa001    2010-01-01    1           multi        1

that's easy enough. But the users need to be able to say who they were playing with. At first I thought a many-to-many table would do the trick:

[play_id] [user_id] [opponent_id]
  00001     007        010

but then I realized that when the opponent submits the same record you'll just be reversing columns:

[play_id] [user_id] [opponent_id]
  00001     007        010
  00002     010        007

and I really have no idea how to pull that data out and construct a win-draw-win ratio that would recognize that these people were all playing together...

Am I making sense? How do I match up those records?

Body:
What's wrong with storing the data like this:

[battle_id] [opponent_1] [opponent_2] [result_1] [result_2]
    1            007         010          1          0
    2            011         007          0          1
    3            007         012          0          0

looking for 007 player wins (will result 2):

select count(*) from battles
where
   (opponent_1 = '007' AND result_1 = 1 and result_2 = 0)
   OR
   (opponent_2 = '007' AND result_1 = 0 and result_2 = 1)

looking for players 007 draws (will result 1):

select count(*) from battles
where
     (opponent_1 = '007' AND result_1 = 0 and result_2 = 0)
     OR
     (opponent_2 = '007' AND result_1 = 0 and result_2 = 0)

etc.


问:
What programming language should I use for my dream app
So, I have enrolled my software engineering course and I am really excited about it. In fact, I have already a project in mind but the problem is I don't know where or how to start, what are the tools that I am going to need, what language should I use and etc.

Well, here's how my dream project would be. I want to create an app that will help people set an appointment to their doctors. Of course, there are two users. One is for the patient and one's for the doctor. Now the patient can search a doctor who is in our database. That patient can set an appointment to the doctor in his desired date but it requires approval of the doctor first.

Now for the doctor. If the user is a doctor and wants to register in our app so that he can put his name in the database. The doctor can view the patients who sets an appointment in the date selected and can approve or disapprove patients. The doctor can also add a note if ever he/she disapprove the patients appointment request so that the doctor can explain why he can't attend on the specified date. If the doctor approves the set date of the patient, it will notify the patient that his doctor approves his requested date for check-up.

Now here's my questions:

1) What programming tools should I use to create that app? (Please specify the purpose of the tools you suggest)

2) Is it better off responsive website rather than a mobile app. (because I also want this app to work on desktop. :D)

3) How complex is this app to make? (We only have a span of 6 months to do an app.)

4) Where can  find free tutorials?

5) Any tips you can suggest to make the development time faster and easier.

That's all, Thank you.

答: Use Android Studio as Development tool, Java for coding, and Google Firebase for Database or Storage or Notification etc</p>


问:
findViewById() not finding custom view but it exists in layout
Somehow my acitivity_main.xml has the view BottomSelectElement (custom view) but I cannot find it in the activity, but I can find anything else.

activity_main.xml (removed unnecessary parts)

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="it.bachmann.studytimer.ui.MainActivity">

    <!-- THIS IS THE VIEW I CANNOT FIND IN THE MainActivity.java (BottomSelectElement) -->
    <it.bachmann.studytimer.ui.elements.BottomSelectElement
        android:id="@+id/customBottomSelect"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="bottom|center" />

    <com.github.clans.fab.FloatingActionMenu

</android.support.design.widget.CoordinatorLayout>
</code>```

my custom view class which is shown perfectly in the activity_main.xml

```<code>public class BottomSelectElement extends ConstraintLayout {

    private Spinner spinner;

    public BottomSelectElement(Context context) {
        super(context);

            init();
        }

        public BottomSelectElement(Context context, AttributeSet attributeSet) {
            super(context);
            init();
        }

        private void init() {
            inflate(getContext(), R.layout.bottom_select_element, this);
            spinner = findViewById(R.id.spinner);
            List<String> categories = Arrays.asList("foo", "bar", "baz");
            ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text, categories);
            adapter.setDropDownViewResource(R.layout.spinner_text_checked);
            spinner.setAdapter(adapter);
        }

        public Spinner getSpinner() {
            return spinner;
        }
    }
</code>```

and finally my MainActivity.java which doesn't find the customBottomSelect, but it finds anything else.

```<code>public class MainActivity extends AppCompatActivity {

    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onStart() {
        super.onStart();
        BottomSelectElement bottomSelectElement = findViewById(R.id.customBottomSelect);
        Log.d(TAG, "onStart: bottomSelectElement " + bottomSelectElement); // this returns null, althought it should exist!
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}
</code>```

I restarted Android Studio several times, rebuilt and cleaned it. It just doesn't seem to find this id.

答:
Because in the constructor, you had super(context) instead of super(context, attrs).

Makes sense, if you don't pass in the attributes, such as the id, then the view will have no id and therefore not be findable using that id. :-)

Answer ref : findViewById() returns null for custom component in layout XML, not for other components

Body:
Somehow my acitivity_main.xml has the view BottomSelectElement (custom view) but I cannot find it in the activity, but I can find anything else.

activity_main.xml (removed unnecessary parts)

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="it.bachmann.studytimer.ui.MainActivity">

    <it.bachmann.studytimer.ui.elements.BottomSelectElement
        android:id="@+id/customBottomSelect"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="bottom|center" />

    <com.github.clans.fab.FloatingActionMenu

</android.support.design.widget.CoordinatorLayout>

my custom view class which is shown perfectly in the activity_main.xml

public class BottomSelectElement extends ConstraintLayout {

    private Spinner spinner;

    public BottomSelectElement(Context context) {
        super(context);

            init();
        }

        public BottomSelectElement(Context context, AttributeSet attributeSet) {
            super(context);
            init();
        }

        private void init() {
            inflate(getContext(), R.layout.bottom_select_element, this);
            spinner = findViewById(R.id.spinner);
            List<String> categories = Arrays.asList("foo", "bar", "baz");
            ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text, categories);
            adapter.setDropDownViewResource(R.layout.spinner_text_checked);
            spinner.setAdapter(adapter);
        }

        public Spinner getSpinner() {
            return spinner;
        }
    }

and finally my MainActivity.java which doesn't find the customBottomSelect, but it finds anything else.

public class MainActivity extends AppCompatActivity {

    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onStart() {
        super.onStart();
        BottomSelectElement bottomSelectElement = findViewById(R.id.customBottomSelect);
        Log.d(TAG, "onStart: bottomSelectElement " + bottomSelectElement); // this returns null, althought it should exist!
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

I restarted Android Studio several times, rebuilt and cleaned it. It just doesn't seem to find this id.


问:
How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?
I'm trying to install Rails 3 on a brand new MacBook Pro running OS X 10.6.3, Ruby 1.8.7, and Rails 2.3.5 and I'm wondering if I've hosed myself.  So far, I've run these commands:

```<code>$ gem update --system
$ gem install arel tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n
$ gem install rails --pre
</code>```

However, when I run the last command, I get this error:

```<code>ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions into the /usr/bin directory.
</code>```

I think it wants me to run the command with sudo so that it can write over /usr/bin/rails.  But if I do that, won't I be overwriting my Rails 2.3.5 executable?  I don't want to do that.  Instead, I'd like to keep both versions of Rails.  How do I do that?

答:
You can use sudo gem install -n /usr/local/bin cocoapods

This works for me.

Body:
I'm trying to install Rails 3 on a brand new MacBook Pro running OS X 10.6.3, Ruby 1.8.7, and Rails 2.3.5 and I'm wondering if I've hosed myself.  So far, I've run these commands:

$ gem update --system
$ gem install arel tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n
$ gem install rails --pre

However, when I run the last command, I get this error:

ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions into the /usr/bin directory.

I think it wants me to run the command with sudo so that it can write over /usr/bin/rails.  But if I do that, won't I be overwriting my Rails 2.3.5 executable?  I don't want to do that.  Instead, I'd like to keep both versions of Rails.  How do I do that?


问:
ficus configuration load generic
Loading a ficus configuration like

```<code>loadConfiguration[T <: Product](): T = {
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import net.ceedubs.ficus.Ficus._
val config: Config = ConfigFactory.load()
config.as[T]
</code>```

fails with:

```<code>Cannot generate a config value reader for type T, because it has no apply method in a companion object that returns type T, and it doesn't have a primary constructor
</code>```

when instead directly specifying a case class instead of T i.e. SomeClass it works just fine. What am I missing here?

答:
Ficus uses the type class pattern, which allows you to constrain generic types by specifying operations that must be available for them. Ficus also provides type class instance "derivation", which in this case is powered by a macro that can inspect the structure of a specific case class-like type and automatically create a type class instance.

The problem in this case is that T isn't a specific case class-like type—it's any old type that extends Product, which could be something nice like this:

```<code>case class EasyToDecode(a: String, b: String, c: String)
</code>```

But it could also be:

```<code>trait X extends Product {
  val youWillNeverDecodeMe: String
}
</code>```

The macro you've imported from ArbitraryTypeReader has no idea at this point, since T is generic here. So you'll need a different approach.

The relevant type class here is ValueReader, and you could minimally change your code to something like the following to make sure T has a ValueReader instance (note that the T: ValueReader syntax here is what's called a "context bound"):

```<code>import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ValueReader
import com.typesafe.config.{ Config, ConfigFactory }

def loadConfiguration[T: ValueReader]: T = {
  val config: Config = ConfigFactory.load()
  config.as[T]

}
</code>```

This specifies that T must have a ValueReader instance (which allows us to use .as[T]) but says nothing else about T, or about where its ValueReader instance needs to come from.

The person calling this method with a concrete type MyType then has several options. Ficus provides instances that are automatically available everywhere for many standard library types, so if MyType is e.g. Int, they're all set:

```<code>scala> ValueReader[Int]
res0: net.ceedubs.ficus.readers.ValueReader[Int] = net.ceedubs.ficus.readers.AnyValReaders$$anon$2@6fb00268
</code>```

If MyType is a custom type, then either they can manually define their own ValueReader[MyType] instance, or they can import one that someone else has defined, or they can use generic derivation (which is what ArbitraryTypeReader does).

The key point here is that the type class pattern allows you as the author of a generic method to specify the operations you need, without saying anything about how those operations will be defined for a concrete type. You just write T: ValueReader, and your caller imports ArbitraryTypeReader as needed.

Title: ficus configuration load generic

Body:
Loading a ficus configuration like

loadConfiguration[T <: Product](): T = {
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import net.ceedubs.ficus.Ficus._
val config: Config = ConfigFactory.load()
config.as[T]

fails with:

Cannot generate a config value reader for type T, because it has no apply method in a companion object that returns type T, and it doesn't have a primary constructor

when instead directly specifying a case class instead of T i.e. SomeClass it works just fine. What am I missing here?

Body:
Ficus uses the type class pattern, which allows you to constrain generic types by specifying operations that must be available for them. Ficus also provides type class instance "derivation", which in this case is powered by a macro that can inspect the structure of a specific case class-like type and automatically create a type class instance.

The problem in this case is that T isn't a specific case class-like type—it's any old type that extends Product, which could be something nice like this:

case class EasyToDecode(a: String, b: String, c: String)

But it could also be:

trait X extends Product {
  val youWillNeverDecodeMe: String
}

The macro you've imported from ArbitraryTypeReader has no idea at this point, since T is generic here. So you'll need a different approach.

The relevant type class here is ValueReader, and you could minimally change your code to something like the following to make sure T has a ValueReader instance (note that the T: ValueReader syntax here is what's called a "context bound"):

import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ValueReader
import com.typesafe.config.{ Config, ConfigFactory }

def loadConfiguration[T: ValueReader]: T = {
  val config: Config = ConfigFactory.load()
  config.as[T]

}

This specifies that T must have a ValueReader instance (which allows us to use .as[T]) but says nothing else about T, or about where its ValueReader instance needs to come from.

The person calling this method with a concrete type MyType then has several options. Ficus provides instances that are automatically available everywhere for many standard library types, so if MyType is e.g. Int, they're all set:

scala> ValueReader[Int]
res0: net.ceedubs.ficus.readers.ValueReader[Int] = net.ceedubs.ficus.readers.AnyValReaders$$anon$2@6fb00268

If MyType is a custom type, then either they can manually define their own ValueReader[MyType] instance, or they can import one that someone else has defined, or they can use generic derivation (which is what ArbitraryTypeReader does).

The key point here is that the type class pattern allows you as the author of a generic method to specify the operations you need, without saying anything about how those operations will be defined for a concrete type. You just write T: ValueReader, and your caller imports ArbitraryTypeReader as needed.


问:
Why can't we use the let keyword inside a class in typescript
I am new to TypeScript. I want to know why we can't use the let keyword for variable declaration inside a class as below. Thanks in advance.

```<code>class Greeter {
    let greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greet())
</code>```

答:
Because it is not a keyword in that context.  And given the purpose of let, I'm not sure it would ever make sense for it to be a keyword there -- it is used to restrict the scope of a variable.

Class properties (in languages that support them) are naturally restricted to the class, explicitly using the same syntax doesn't seem beneficial.

In particular, it works against how properties are currently added (assigned in the constructor), and causing confusing about what the scope actually is.

Body:
I am new to TypeScript. I want to know why we can't use the let keyword for variable declaration inside a class as below. Thanks in advance.

class Greeter {
    let greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greet())


问:
Angular CLI with Yarn Offline
Is it possible to have yarn's offline mode be the default, without the need to specify "--offline"?

For an Angular project, I've set yarn as the package manager using:

```<code> ng set --global packageManager=yarn
</code>```

I then performed steps to grab all required @angular/cli resources and their dependencies and stored them into the yarn cache, setting the cache location and performing add's such as

```<code>yarn add @angular/cli --offline
</code>```

When running ng new my-app I'd like the dependency resolution to occur using those offline, cached yarn dependencies, yet I'm not able to inform angular that this is desired. Ideally, I'd hope it'd be possible to run a command such as

```<code>ng new my-project --offline
</code>```

Is there a way of accomplishing this?

答:
Found out that the default setting can be placed in the .yarnrc config file as:

```<code>--*.offline true
</code>```

This will cause yarn to always prefer the cached libraries when configuring apps that it manages.

Title: Angular CLI with Yarn Offline

Body:
Is it possible to have yarn's offline mode be the default, without the need to specify "--offline"?

For an Angular project, I've set yarn as the package manager using:

 ng set --global packageManager=yarn

I then performed steps to grab all required @angular/cli resources and their dependencies and stored them into the yarn cache, setting the cache location and performing add's such as

yarn add @angular/cli --offline

When running ng new my-app I'd like the dependency resolution to occur using those offline, cached yarn dependencies, yet I'm not able to inform angular that this is desired. Ideally, I'd hope it'd be possible to run a command such as

ng new my-project --offline

Is there a way of accomplishing this?

Body:
Found out that the default setting can be placed in the .yarnrc config file as:

--*.offline true

This will cause yarn to always prefer the cached libraries when configuring apps that it manages.


问:
How can I pass the absolute path of my function load into my function predict?
I would like to get the path and the file name of my load function and pass it to my predict function

Every time I use the code self.load() I also need to call its arguments which is the path and the filename. How do I get the path and the filename that is inside my load function.

This is the screenshot of my problem

I try to run the function load inside my predict function but i need the parameters [path] and [filename]

```<code>def load(self, path, filename):
    with open(os.path.join(path, filename[0])) as stream:
        self.ids.image.source = filename[0]
    self.dismiss_popup()
    pathh = (os.path.join(path,filename[0]))
    return os.path.join(path,filename[0])
def predict(self):
    #need to pass the path and filename here
</code>```

答:
You can declare empty strings on the top of your functions and when load() is called assign the values:

```<code>pth = ""
fname = ""

def load(self, path, filename):
    pth = path
    fname = filename
    # your code here

def predict(self):
    # use pth and fname here
</code>```

Body:
I would like to get the path and the file name of my load function and pass it to my predict function

Every time I use the code self.load() I also need to call its arguments which is the path and the filename. How do I get the path and the filename that is inside my load function.

This is the screenshot of my problem

I try to run the function load inside my predict function but i need the parameters [path] and [filename]

def load(self, path, filename):
    with open(os.path.join(path, filename[0])) as stream:
        self.ids.image.source = filename[0]
    self.dismiss_popup()
    pathh = (os.path.join(path,filename[0]))
    return os.path.join(path,filename[0])
def predict(self):
    #need to pass the path and filename here

Body:
You can declare empty strings on the top of your functions and when load() is called assign the values:

pth = ""
fname = ""

def load(self, path, filename):
    pth = path
    fname = filename
    # your code here

def predict(self):
    # use pth and fname here


问:
Replacing all words except one - regex perl
i try to have a regular expresion which will change "dir1/dir2/" to "dir1/dir3/"
only if dir2 is not tmp, and if it is tmp ,I want it not to change and stay "dir1/tmp".

I think I need a lookahead regex but I cant manage.

答:
You can use negative lookahead assertion to do the substitution only if there is not tmp after /dir1:

```<code>s#(dir1/)(?!tmp/)[^/]+#\1/dir3#;
</code>```

See it

Body:
You can use negative lookahead assertion to do the substitution only if there is not tmp after /dir1:

s#(dir1/)(?!tmp/)[^/]+#\1/dir3#;

See it


问:
How to setup models in flask with pymongo
I want to use PyMongo directly within flask, is it possible to create models.py for MongoDB without ORMs? If so, is it recommended?

I don't know how/if possible to create models.py so I just work with db without it

config.py

```<code>class Config(object):
    # ...
    DATABASE_URI = os.environ.get('DATABASE_URI') or \
        'mongodb+srv://kay:myRealPassword@cluster0-wpeiv.mongodb.net/test'
</code>```

app/__ init __.py

```<code>from flask import Flask
from config import Config
from pymongo import MongoClient

app = Flask(__name__)
# ...
client = MongoClient(app.config['DATABASE_URI'])
db = client.test
</code>```

app/routes.py

```<code># ...
from app import db

users = db.users
posts = db.posts

@app.route('/')
# ...
</code>```

Should I just use the driver directly in my routes.py?

答:
It is certainly possible to do without an "ORM" (or technically an "ODM" ) like Mongoose.

However, it would certainly not be recommended to use your driver, or anything that indicates that you are using mongo, into routes.py. Instead, routes.py should make calls to a service layer (for example, a module or modules with all your business logic as service functions). Then your service layer should make calls to a data access layer where you can, if you like, make calls to pymongo directly.

This might not be a bad way to do things if the documents in your mongodb have widely varying structure, for which the constraints imposed by Mongoose or similar ODMs which assume a consistent schema of documents within a collection might be painful.

However if you go this route (no pun intended) then remember:

This is no excuse to avoid layering your system and separate the concerns of routes, services, and data access.

You will have to write your own validation functions for types, lengths, required values, etc. These kinds of validations are generally given to you for free within an ODM. Look for some validation packages that you can pip install, which should help you to avoid too much wheel invention.

Proceed carefully and with a good design and lots of tests, and this can be an acceptable architecture. However, if you have a situation in which all documents within a collection always have the same structure, there is nothing wrong with Mongoose. But it’s fine to use PyMongo directly if you have a simple app with lots of schema variation in your documents.

Body:
I want to use PyMongo directly within flask, is it possible to create models.py for MongoDB without ORMs? If so, is it recommended?

I don't know how/if possible to create models.py so I just work with db without it

config.py

class Config(object):
    # ...
    DATABASE_URI = os.environ.get('DATABASE_URI') or \
        'mongodb+srv://kay:myRealPassword@cluster0-wpeiv.mongodb.net/test'

app/__ init __.py

from flask import Flask
from config import Config
from pymongo import MongoClient

app = Flask(__name__)
# ...
client = MongoClient(app.config['DATABASE_URI'])
db = client.test

app/routes.py

# ...
from app import db

users = db.users
posts = db.posts

@app.route('/')
# ...

Should I just use the driver directly in my routes.py?


问:
How to merge two or more mp3 audio file in android?
I'm trying to merge mp3 audio files But not successful.

Here is my code.

```<code>public static void meargeAudio(List<File> filesToMearge)
{

    while (filesToMearge.size()!=1){

        try {
            FileInputStream fistream1 = new FileInputStream(new File(filesToMearge.get(0).getPath()));  //(/storage/emulated/0/Audio Notes/1455194356500.mp3) first source file
            FileInputStream fistream2 = new FileInputStream(new File(filesToMearge.get(1).getPath()));//second source file

            File file1 = new File(filesToMearge.get(0).getPath());
            boolean deleted = file1.delete();
            File file2 = new File(filesToMearge.get(1).getPath());
            boolean deleted1 = file2.delete();

            SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
            FileOutputStream fostream = new FileOutputStream(new File(filesToMearge.get(0).getPath()),true);//destinationfile

            int temp;

            while ((temp = sistream.read()) != -1) {
                // System.out.print( (char) temp ); // to print at DOS prompt
                fostream.write(temp);   // to write to file
            }

            filesToMearge.add(0,new File(filesToMearge.get(0).getPath()));
            filesToMearge.remove(1);
            filesToMearge.remove(1);

            fostream.close();
            sistream.close();
            fistream1.close();
            fistream2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
</code>```

e.g

firstFileSize =12kb

secondFileSize =10kb

finalfileSize=22kb

Size is accurate But sound is missing

No error but in result i found finalfile contains only first file audio second file audio is missing.

Don't know what is the issue.if any one know the solution help me.

Thanks

答:
Well there's a function to merge Audio or Video files

```<code>public static boolean mergeMediaFiles(boolean isAudio, String sourceFiles[], String targetFile) {
        try {
            String mediaKey = isAudio ? "soun" : "vide";
            List<Movie> listMovies = new ArrayList<>();
            for (String filename : sourceFiles) {
                listMovies.add(MovieCreator.build(filename));
            }
            List<Track> listTracks = new LinkedList<>();
            for (Movie movie : listMovies) {
                for (Track track : movie.getTracks()) {
                    if (track.getHandler().equals(mediaKey)) {
                        listTracks.add(track);
                    }
                }
            }
            Movie outputMovie = new Movie();
            if (!listTracks.isEmpty()) {
                outputMovie.addTrack(new AppendTrack(listTracks.toArray(new Track[listTracks.size()])));
            }
            Container container = new DefaultMp4Builder().build(outputMovie);
            FileChannel fileChannel = new RandomAccessFile(String.format(targetFile), "rws").getChannel();
            container.writeContainer(fileChannel);
            fileChannel.close();
            return true;
        }
        catch (IOException e) {
            Log.e("MYTAG", "Error merging media files. exception: "+e.getMessage());
            return false;
        }
    }
</code>```

If you got Audios, isAudio should be true. if you got videos isAudio should be false

sourceFiles[] array should contain the destinations of the media files such as

/sdcard/my_songs/audio_1, /sdcard/my_songs/audio_2, /sdcard/my_songs/audio_3

targetFile is your final audio merged file should be somthing like

/sdcard/my_songs/final_audio_1

If you deal with large files it's preferred to merge file in background, you can use AsynkTask

Body:
I'm trying to merge mp3 audio files But not successful.

Here is my code.

public static void meargeAudio(List<File> filesToMearge)
{

    while (filesToMearge.size()!=1){

        try {
            FileInputStream fistream1 = new FileInputStream(new File(filesToMearge.get(0).getPath()));  //(/storage/emulated/0/Audio Notes/1455194356500.mp3) first source file
            FileInputStream fistream2 = new FileInputStream(new File(filesToMearge.get(1).getPath()));//second source file

            File file1 = new File(filesToMearge.get(0).getPath());
            boolean deleted = file1.delete();
            File file2 = new File(filesToMearge.get(1).getPath());
            boolean deleted1 = file2.delete();

            SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
            FileOutputStream fostream = new FileOutputStream(new File(filesToMearge.get(0).getPath()),true);//destinationfile

            int temp;

            while ((temp = sistream.read()) != -1) {
                // System.out.print( (char) temp ); // to print at DOS prompt
                fostream.write(temp);   // to write to file
            }

            filesToMearge.add(0,new File(filesToMearge.get(0).getPath()));
            filesToMearge.remove(1);
            filesToMearge.remove(1);

            fostream.close();
            sistream.close();
            fistream1.close();
            fistream2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

e.g

firstFileSize =12kb

secondFileSize =10kb

finalfileSize=22kb

Size is accurate But sound is missing

No error but in result i found finalfile contains only first file audio second file audio is missing.

Don't know what is the issue.if any one know the solution help me.

Thanks

Body:
Well there's a function to merge Audio or Video files

public static boolean mergeMediaFiles(boolean isAudio, String sourceFiles[], String targetFile) {
        try {
            String mediaKey = isAudio ? "soun" : "vide";
            List<Movie> listMovies = new ArrayList<>();
            for (String filename : sourceFiles) {
                listMovies.add(MovieCreator.build(filename));
            }
            List<Track> listTracks = new LinkedList<>();
            for (Movie movie : listMovies) {
                for (Track track : movie.getTracks()) {
                    if (track.getHandler().equals(mediaKey)) {
                        listTracks.add(track);
                    }
                }
            }
            Movie outputMovie = new Movie();
            if (!listTracks.isEmpty()) {
                outputMovie.addTrack(new AppendTrack(listTracks.toArray(new Track[listTracks.size()])));
            }
            Container container = new DefaultMp4Builder().build(outputMovie);
            FileChannel fileChannel = new RandomAccessFile(String.format(targetFile), "rws").getChannel();
            container.writeContainer(fileChannel);
            fileChannel.close();
            return true;
        }
        catch (IOException e) {
            Log.e("MYTAG", "Error merging media files. exception: "+e.getMessage());
            return false;
        }
    }

If you got Audios, isAudio should be true. if you got videos isAudio should be false

sourceFiles[] array should contain the destinations of the media files such as

/sdcard/my_songs/audio_1, /sdcard/my_songs/audio_2, /sdcard/my_songs/audio_3

targetFile is your final audio merged file should be somthing like

/sdcard/my_songs/final_audio_1

If you deal with large files it's preferred to merge file in background, you can use AsynkTask


问:
Unity3D Firebase: InvalidOperationException: FirebaseApp was not initialized with a bucket name
I am using the latest version of FirebaseSDK (currently 4.2.1) in my Unity game. I have everything setup as mentioned in the docs. Realtime database and authentication are working fine but I am getting the following error when running in Editor:

InvalidOperationException: FirebaseApp was not initialized with a bucket name.

when I does the following:

```<code>StorageReference storageRef = FirebaseStorage.DefaultInstance.RootReference;
</code>```

But if I make the reference using bucket name its fine, for example:

```<code>StorageReference storageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl("gs://bucketname");
</code>```

does not produce an error.

Anybody having any idea what's wrong?

答:
When calling App.Create, you can pass in options via the app options struct.  I believe this gets filled automatically, if you are running on device (and it can access the google-services plist/xml) but in the editor, you need to specify it.  If you call FirebaseStorage.DefaultInstance.RootReference without doing so, then it won't actually know what the root reference for your project is.  (Getting references directly from gs:// links works, since those are absolute.)

Try setting the bucket via AppOptions when you call App.Create().

Body:
I am using the latest version of FirebaseSDK (currently 4.2.1) in my Unity game. I have everything setup as mentioned in the docs. Realtime database and authentication are working fine but I am getting the following error when running in Editor:

InvalidOperationException: FirebaseApp was not initialized with a bucket name.

when I does the following:

StorageReference storageRef = FirebaseStorage.DefaultInstance.RootReference;

But if I make the reference using bucket name its fine, for example:

StorageReference storageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl("gs://bucketname");

does not produce an error.

Anybody having any idea what's wrong?


问:
jQuery hover is too slow
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.

How to fix it? (the white holes)

I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.

Any help appreciated :)

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      $(this).css("background-color","red");
    },
    function() { //hover-out

    }
   );

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}</code>```

```

答:
This is another approach with nextUntil to select siblings..

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  line.on( 'mouseover', function(ev){
    $('.tile').first().nextUntil( $('.tile').eq(ev.pageX) ).css("background-color","red");
  });

  line.on( 'mouseleave', function(ev){
    $('.tile').css("background-color","#ddd");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}</code>```

```

Title: jQuery hover is too slow

Body:
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.

How to fix it? (the white holes)

I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.

Any help appreciated :)

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      $(this).css("background-color","red");
    },
    function() { //hover-out

    }
   );

});

#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}

Body:
This is another approach with nextUntil to select siblings..

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('<div class="tile" id="t'+(i+1)+'"></div>');

  }

  var tile = $(".tile");

  line.on( 'mouseover', function(ev){
    $('.tile').first().nextUntil( $('.tile').eq(ev.pageX) ).css("background-color","red");
  });

  line.on( 'mouseleave', function(ev){
    $('.tile').css("background-color","#ddd");
  });

});

#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>


问:
With List<KeyValuePair<int, int>>, to make 1 in 4 of the values equal 1
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

```<code>[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]
</code>```

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

```<code>List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}
</code>```

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

答:
If I understand your intent correctly, here is what you might do

```<code>public class BucketsWithRandomValues
{
    private Random random = new Random();

    public void FillWithValuesInEachBucket(IList<KeyValuePair<int, int>> list, int bucketSize = 4, int valueToPut = 1)
    {
        if (list == null) throw new ArgumentNullException(nameof(list));

        int i = 0;
        while (i + bucketSize <= list.Count)
        {
            var index = random.Next(i, i + bucketSize); // exclusive upper bound
            list[index] = new KeyValuePair<int, int>(list[index].Key, valueToPut);
            i += bucketSize;
        }
    }
}
</code>```

I would also suggest using a ValueTuple instead of KeyValuePair since you don't really have the Key-Value semantics because of possible duplicate keys. When people see KeyValuePair they immediately think Dictionary, not List.

Body:
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

Body:
If I understand your intent correctly, here is what you might do

public class BucketsWithRandomValues
{
    private Random random = new Random();

    public void FillWithValuesInEachBucket(IList<KeyValuePair<int, int>> list, int bucketSize = 4, int valueToPut = 1)
    {
        if (list == null) throw new ArgumentNullException(nameof(list));

        int i = 0;
        while (i + bucketSize <= list.Count)
        {
            var index = random.Next(i, i + bucketSize); // exclusive upper bound
            list[index] = new KeyValuePair<int, int>(list[index].Key, valueToPut);
            i += bucketSize;
        }
    }
}

I would also suggest using a ValueTuple instead of KeyValuePair since you don't really have the Key-Value semantics because of possible duplicate keys. When people see KeyValuePair they immediately think Dictionary, not List.


问:
Angular *ngFor not populating any data
```<code>export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}
</code>```

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

```<code><ul class="w3-ul w3-card-4" align="right" >
          <li class="list-group-item" *ngFor="let channels of currentPickSelection">
            <strong><font size="2">{{ channels.channel }}</font><span class="w3-right"><font size="2">{{ channels.pickCode }}</font></span></strong>
          </li>
        </ul>
</code>```

Please advise! thanks

答:
```<code>export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
this.keysofdata = Object.keys(this.currentPickSelection) <---can get keys
  }
}

ul class="w3-ul w3-card-4" align="right" >
          <li class="list-group-item" *ngFor="let channels of currentPickSelection;let i = index;">
            <strong><font size="2">{{ currentPickSelection[i][i].channel  }}</font><span class="w3-right"><font size="2">{{currentPickSelection[i][i].pickCode }}</font></span></strong>
          </li>
        </ul>
</code>```

Title: Angular *ngFor not populating any data

Body:
export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

            {{ channels.channel }}{{ channels.pickCode }}

Please advise! thanks


问:
How can I create a button programmatically in C# window app?
In the Form1_Load method what code should I write to create a simple button?

```<code> private void Form1_Load(object sender, System.EventArgs e)
 {

 }
</code>```

So that on Load the button would show.

答:
It's simple :</p>

```<code>private void Form1_Load(object sender, System.EventArgs e)
 {
     Button btn1 = new Button();
     this.Controls.add(btn1);
     btn1.Top=100;
     btn1.Left=100;
     btn1.Text="My Button";

 }
</code>```

Body:
In the Form1_Load method what code should I write to create a simple button?

 private void Form1_Load(object sender, System.EventArgs e)
 {

 }

So that on Load the button would show.

Body:
It's simple :

private void Form1_Load(object sender, System.EventArgs e)
 {
     Button btn1 = new Button();
     this.Controls.add(btn1);
     btn1.Top=100;
     btn1.Left=100;
     btn1.Text="My Button";

 }


问:
How to add header to row for each record
I have a big file, columns separated by ";"

I have transposed this to rows, but I need to add headers to the rows.

Example

Input file

```<code>31561;49215;10;1196825801480000
31561;49215;12;1196825801480000
31561;48665;14;1196825806980000
</code>```

I transpose the columns to rows using this code.

```<code>sed '$'!'G' file | tr ';' '\n'
</code>```

the output i got is :

```<code>31561
49215
10
1196825801480000

31561
49215
12
1196825801480000

31561
48665
14
1196825806980000
</code>```

But I will like to add headers and got something like this:

```<code>Status1
Information1
Line     : 31561
Point    : 49215
Code:    : 10
TB      :  1196825801480000

Status1
Information1
Line     : 31561
Point    : 49215
Code:    : 12
TB      :  1196825801480000

Status1
Information1
Line     : 31561
Point    : 48665
Code:    : 14
TB      :  1196825806980000
</code>```

Please, can help to solve this. Thanks

I change the code like this:

```<code>awk -F';' '{
   print "Status1"
   print "Information1"
   print "Line     :" $1;
   print "Point    :" $2;
   print "Code     :" $3;
   print "TB      :" $4"\n";
}' file
</code>```

it works :)

答:
Solution using awk:

```<code>awk -F';'  '{
   if ( NR != 1 ) printf "\n";
   print "Status1\nInformation1";
   print "Line: " $1;
   print "Point: " $2;
   print "Code: " $3;
   print "TB:", $4;
}' file
</code>```

To use in-place editing:

```<code>awk -i inplace -F';' ...
...
...
</code>```

Body:
I have a big file, columns separated by ";"

I have transposed this to rows, but I need to add headers to the rows.

Example

Input file

31561;49215;10;1196825801480000
31561;49215;12;1196825801480000
31561;48665;14;1196825806980000

I transpose the columns to rows using this code.

sed '$'!'G' file | tr ';' '\n'

the output i got is :

31561
49215
10
1196825801480000

31561
49215
12
1196825801480000

31561
48665
14
1196825806980000

But I will like to add headers and got something like this:

Status1
Information1
Line     : 31561
Point    : 49215
Code:    : 10
TB      :  1196825801480000

Status1
Information1
Line     : 31561
Point    : 49215
Code:    : 12
TB      :  1196825801480000

Status1
Information1
Line     : 31561
Point    : 48665
Code:    : 14
TB      :  1196825806980000

Please, can help to solve this. Thanks

I change the code like this:

awk -F';' '{
   print "Status1"
   print "Information1"
   print "Line     :" $1;
   print "Point    :" $2;
   print "Code     :" $3;
   print "TB      :" $4"\n";
}' file

it works :)

Body:
Solution using awk:

awk -F';'  '{
   if ( NR != 1 ) printf "\n";
   print "Status1\nInformation1";
   print "Line: " $1;
   print "Point: " $2;
   print "Code: " $3;
   print "TB:", $4;
}' file

To use in-place editing:

awk -i inplace -F';' ...
...
...


问:
Json object to C# model object in mvc View
I have json object rendered as part of view source. I want to convert that json to C# model object and pass that object to a partial view, since partial view is strongly typed to model object.

Eg:

```<code>jsonIdentifier = '{"Identifier": { "name":"uno","contextId":"dos"}}'

@{ model.Identifier = Parsing(jsonIdentifier)}
@Html.Partial("_IdentifierPartial", m=>m.Identifier) //where Identifier is the object needs to be passed to  _IdentifierPartial
</code>```

答:
You should use @Html.Action instead of @Html.Partial.  Just pass the jsonIdentifier in as a string parameter and then use Json.NET to convert it into the appropriately type object.

As in..

```<code>Output my partial with that Json:
<div>
    @{
        string json = "{Make: \"Toyota\", Model: \"Camry\", Year: 2017}";
    }
    @Html.Action("RenderCarScreen", new { carJson = json });
</div>
</code>```

Your webmethod would look something like this...

```<code>    public ActionResult RenderCarScreen(string carJson)
    {

        Car car = Newtonsoft.Json.JsonConvert.DeserializeObject<Car>(carJson);
        return PartialView("CarScreen", car);
    }
</code>```

Body:
I have json object rendered as part of view source. I want to convert that json to C# model object and pass that object to a partial view, since partial view is strongly typed to model object.

Eg:

jsonIdentifier = '{"Identifier": { "name":"uno","contextId":"dos"}}'

@{ model.Identifier = Parsing(jsonIdentifier)}
@Html.Partial("_IdentifierPartial", m=>m.Identifier) //where Identifier is the object needs to be passed to  _IdentifierPartial

Body:
You should use @Html.Action instead of @Html.Partial.  Just pass the jsonIdentifier in as a string parameter and then use Json.NET to convert it into the appropriately type object.

As in..

Output my partial with that Json:
<div>
    @{
        string json = "{Make: \"Toyota\", Model: \"Camry\", Year: 2017}";
    }
    @Html.Action("RenderCarScreen", new { carJson = json });
</div>

Your webmethod would look something like this...

    public ActionResult RenderCarScreen(string carJson)
    {

        Car car = Newtonsoft.Json.JsonConvert.DeserializeObject<Car>(carJson);
        return PartialView("CarScreen", car);
    }