问:
Sql Server equivalent Join update Oracle
My update query Sql Server as follows:

```<code>Update Project set Name=Project.Name+' assignedTo '
FROM Project
INNER JOIN EmployeeProject ON Project.ID = EmployeeProject.ProjectID
INNER JOIN Employee ON EmployeeProject.EmployeeID = Employee.ID
WHERE (Employee.Name = N'Minion')
</code>```

what is equivalent Oracle query.My try as follows:

```<code>Update (SELECT Project.Name as ProjectName,Employee.Name as EmpName
        FROM Project
        INNER JOIN EmployeeProject ON Project.ID = EmployeeProject.ProjectID
        INNER JOIN Employee ON EmployeeProject.EmployeeID = Employee.ID
        where Employee.Name=N'Minion'
       ) T
set T.ProjectName=' somting'
</code>```

But gives me error cannot modify a column which maps to a non key-preserved table.Sql server works fine.

答:
You just need exists:

```<code>update Project p
    set Name = p.Name+' assignedTo '
where exists (select 1
              from EmployeeProject join
                   Employee e
                   on ep.EmployeeID = e.ID
              where e.Name = N'Minion' and p.ID = ep.ProjectID
             );
</code>```

Body:
My update query Sql Server as follows:

Update Project set Name=Project.Name+' assignedTo '
FROM Project
INNER JOIN EmployeeProject ON Project.ID = EmployeeProject.ProjectID
INNER JOIN Employee ON EmployeeProject.EmployeeID = Employee.ID
WHERE (Employee.Name = N'Minion')

what is equivalent Oracle query.My try as follows:

Update (SELECT Project.Name as ProjectName,Employee.Name as EmpName
        FROM Project
        INNER JOIN EmployeeProject ON Project.ID = EmployeeProject.ProjectID
        INNER JOIN Employee ON EmployeeProject.EmployeeID = Employee.ID
        where Employee.Name=N'Minion'
       ) T
set T.ProjectName=' somting'

But gives me error cannot modify a column which maps to a non key-preserved table.Sql server works fine.

Body:
You just need exists:

update Project p
    set Name = p.Name+' assignedTo '
where exists (select 1
              from EmployeeProject join
                   Employee e
                   on ep.EmployeeID = e.ID
              where e.Name = N'Minion' and p.ID = ep.ProjectID
             );


来源: stackexchange

问:
How to read a text file into command line history
I have a .txt file with command line commands on each line. How can I load the contents of this text file back into the "clipboard" or "history" memory of a command prompt session and be able to arrow key up/down through them?

Example of commands and format inside blah.txt:

```<code>ipconfig
ipconfig /flushdns
cd C:\blah
</code>```

答:
Jonathan

I'm not currently a Windows user, but it looks like this could solve your problem. You'll have to add commands via .csv or .xml, not .txt file though.

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/add-history

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have a .txt file with command line commands on each line. How can I load the contents of this text file back into the "clipboard" or "history" memory of a command prompt session and be able to arrow key up/down through them?

Example of commands and format inside blah.txt:

ipconfig
ipconfig /flushdns
cd C:\blah


问:
Is there a .row substitution?
I have two .row sections in my HTML page, which I want different CSS for, yet for my CSS, they both fall under .row, and all aspects in the .row are spread through both of them. How do I individualize these .row's to have separate CSS, without losing the .row characteristic for one of them?

Please advise if this makes no sense whatsoever... :P

My problem in HTML + CSS

```<code><style>
.row {
            margin: 0 5px;
            position: relative;
        }
.row {
            padding: 0 30px;
        }
</style>

<div class="row">
    <div class="col-sm-6 col-md-4">
        <div class="thumbnail">
            <img width="100%" src="https://image.ibb.co/gweBdQ/image.jpg" alt="Annas Blog">
             <div class="caption">
            <h3><font face="Calibri"><strong>The Blog!</strong></font></h3>
            <p><small>View Anna's Blog! That's why you're here anyway... right?</small></p>
            <p><a href="BLOG.html" class="btn btn-primary" role="button">View Blogs!</a></p>
          </div>
        </div>
       </div>
</code>```

And the separate .row

```<code><div class="container">
        <div class="row">
            <div class="col-sm-3">
                <ul class="list-group">
                    <li class="list-group-item text-center"><label><font class="text" align="center" face="Indie Flower" size="6">See Anna's People!</font></label>
                    <br/>
                    <img style="vertical-align:middle" width="299" height="299" class="img-circle" src="https://pbs.twimg.com/profile_images/880522424705441799/EPujLjrD_400x400.jpg" />
                </li>
            </div>
         </div>
    </div>
</code>```

And the padding on the second .row effects the first .row.

Without .row padding

With .row padding

You see, its much smaller?

答:
I'm not sure if I understand your problem correctly, but I think you want something like this:

.row {
  font-size: 30px;
}

.divA {
  color: red;
}

.divB {
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row divA">
  <p> I'm Div A</p>
</div>

<div class="row divB">
  <p>I'm Div B</p>
</div></code>```

They both have font-size:30px but have different colors

Title: Is there a .row substitution?

Body:
I have two .row sections in my HTML page, which I want different CSS for, yet for my CSS, they both fall under .row, and all aspects in the .row are spread through both of them. How do I individualize these .row's to have separate CSS, without losing the .row characteristic for one of them?

Please advise if this makes no sense whatsoever... :P

My problem in HTML + CSS

The Blog!

View Anna's Blog! That's why you're here anyway... right?

View Blogs!

And the separate .row

See Anna's People!

And the padding on the second .row effects the first .row.

Without .row padding

With .row padding

You see, its much smaller?

Body:
I'm not sure if I understand your problem correctly, but I think you want something like this:

.row {
  font-size: 30px;
}

.divA {
  color: red;
}

.divB {
  color: blue;
}

<div class="row divA">
  <p> I'm Div A</p>
</div>

<div class="row divB">
  <p>I'm Div B</p>
</div>

They both have font-size:30px but have different colors


问:
Sum of All Messages Sent
Mongodb Version 2.6.9

I'm attempting to count the total a company has been involved in a messaging interaction. I'm able to get one side of the interaction using the aggregate $group, but I've come up empty on essentially looking at the two fields and aggregating those together for each unique company ID.

The sender_id and receiver_id relate to the same company Id's.

```<code>{ "_id" : a, "sender_id" : 1, "receiver_id" : 2, payload: "data" }
{ "_id" : b, "sender_id" : 2, "receiver_id" : 5, payload: "data" }
{ "_id" : c, "sender_id" : 2, "receiver_id" : 4, payload: "data" }
{ "_id" : d, "sender_id" : 3, "receiver_id" : 2, payload: "data" }
{ "_id" : e, "sender_id" : 4, "receiver_id" : 1, payload: "data" }
</code>```

Using the above data structure, I attempting to produce a result set similar to

```<code>{ "_id" : 1, count:  2}
{ "_id" : 2, count:  4}
{ "_id" : 3, count:  1}
{ "_id" : 4, count:  2}
{ "_id" : 5, count:  1}
</code>```

where for example Company 2 was involved in messages a, b, c, d.

答:
Your options are limited in 2.6 pipeline. You can try below pipeline.

$group with $push to create single value array for both sender_id and receiver_id.

$project with $setUnion to merge ids into single array.

$unwind and $group to count the occurrences.

```<code>db.collection.aggregate({
    "$group": {
        "_id": "$_id",
        "sender_id": {
            "$push": "$sender_id"
        },
        "receiver_id": {
            "$push": "$receiver_id"
        }
    }
}, {
    "$project": {
        "id": {
            "$setUnion": ["$sender_id", "$receiver_id"]
        }
    }
}, {
    "$unwind": "$id"
}, {
    "$group": {
        "_id": "$id",
        "count": {
            "$sum": 1
        }
    }
})
</code>```

You can use below pipeline for newer versions. Use [] to create array.

```<code>db.collection.aggregate({
    $project: {
        id: ["$sender_id", "$receiver_id"]
    }
}, {
    $unwind: "$id"
}, {
    $group: {
        _id: "$id",
        count: {
            $sum: 1
        }
    }
})
</code>```

Title: Sum of All Messages Sent

Body:
Mongodb Version 2.6.9

I'm attempting to count the total a company has been involved in a messaging interaction. I'm able to get one side of the interaction using the aggregate $group, but I've come up empty on essentially looking at the two fields and aggregating those together for each unique company ID.

The sender_id and receiver_id relate to the same company Id's.

{ "_id" : a, "sender_id" : 1, "receiver_id" : 2, payload: "data" }
{ "_id" : b, "sender_id" : 2, "receiver_id" : 5, payload: "data" }
{ "_id" : c, "sender_id" : 2, "receiver_id" : 4, payload: "data" }
{ "_id" : d, "sender_id" : 3, "receiver_id" : 2, payload: "data" }
{ "_id" : e, "sender_id" : 4, "receiver_id" : 1, payload: "data" }

Using the above data structure, I attempting to produce a result set similar to

{ "_id" : 1, count:  2}
{ "_id" : 2, count:  4}
{ "_id" : 3, count:  1}
{ "_id" : 4, count:  2}
{ "_id" : 5, count:  1}

where for example Company 2 was involved in messages a, b, c, d.

Body:
Your options are limited in 2.6 pipeline. You can try below pipeline.

$group with $push to create single value array for both sender_id and receiver_id.

$project with $setUnion to merge ids into single array.

$unwind and $group to count the occurrences.

db.collection.aggregate({
    "$group": {
        "_id": "$_id",
        "sender_id": {
            "$push": "$sender_id"
        },
        "receiver_id": {
            "$push": "$receiver_id"
        }
    }
}, {
    "$project": {
        "id": {
            "$setUnion": ["$sender_id", "$receiver_id"]
        }
    }
}, {
    "$unwind": "$id"
}, {
    "$group": {
        "_id": "$id",
        "count": {
            "$sum": 1
        }
    }
})

You can use below pipeline for newer versions. Use [] to create array.

db.collection.aggregate({
    $project: {
        id: ["$sender_id", "$receiver_id"]
    }
}, {
    $unwind: "$id"
}, {
    $group: {
        _id: "$id",
        count: {
            $sum: 1
        }
    }
})


问:
Scanner not waiting for NewLine to collect input with a loop
I am very new to coding and was hoping you guys could help me.
I am having an issue with nextDouble not waiting for a print.ln to collect data.
With my priming input I have to put in two numbers for it to move to the next line and ask for the second number that I already put in because it didn't wait.
By that point it also decides to ask for the third number and accept input for that one as well, but it is fine asking for third and the fourth numbers with no issues.
It also happens inside the loop when it repeats.

I understand that using nextDouble doesn't mean it will "wait" for the newline and I know nextNumbertype doesn't have a newline flag but the usual trick of
adding in "input.nextLine" after getting a double does not seem to be working.

I know I could just take all input as strings and convert them later, but this is a homework assignment and my prof seems to want things a very specific way.

Any ideas for what is wrong or what I could try?

Here is what outputs:

```<code>Enter x1 or <crtl + z> to quit
1
4
Please input the x2 number:
Please input the y1 number:
1
Please input the y2 number:
5
Distance is 5.000000

Enter x1 or <crtl + z> to quit
</code>```

Here is the actual code:

```<code>import java.util.Scanner;

public class distanceFinder {

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    double x1 = 0;

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    while(input.hasNext())
    {

    System.out.println("Please input the x2 number:");
    double x2 = input.nextDouble();

    System.out.println("Please input the y1 number:");
    double y1 = input.nextDouble();

    System.out.println("Please input the y2 number:");
    double y2 = input.nextDouble();

    double x3 = 0;
    double y3 = 0;
    double xy1 = 0;

    x3 = Math.pow((x2 - x1), 2);
    y3 = Math.pow((y2 - y1), 2);

    xy1 = x3 + y3;

    double distance = Math.sqrt(xy1);

    System.out.printf("Distance is %.6f %n%n%n",  distance);

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    }
input.close();
}
</code>```

}

答:
You need to correct your code:

```<code>import java.util.Scanner;

public class DistanceFinder {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter x1 or <crtl + z> to quit");

        while (input.hasNext()) {
            double x1 = input.nextDouble();

            System.out.println("Please input the x2 number:");
            double x2 = input.nextDouble();

            System.out.println("Please input the y1 number:");
            double y1 = input.nextDouble();

            System.out.println("Please input the y2 number:");
            double y2 = input.nextDouble();

            double x3 = 0;
            double y3 = 0;
            double xy1 = 0;

            x3 = Math.pow((x2 - x1), 2);
            y3 = Math.pow((y2 - y1), 2);

            xy1 = x3 + y3;

            double distance = Math.sqrt(xy1);

            System.out.printf("Distance is %.6f %n%n%n", distance);

            System.out.println("Enter x1 or <crtl + z> to quit");
        }
        input.close();
    }
}
</code>```

OUTPUT:

```<code>Enter x1 or <crtl + z> to quit
1
Please input the x2 number:
2
Please input the y1 number:
1
Please input the y2 number:
3
Distance is 2.236068

Enter x1 or <crtl + z> to quit
1
Please input the x2 number:
2
Please input the y1 number:
1
Please input the y2 number:
3
Distance is 2.236068

Enter x1 or <crtl + z> to quit
</code>```

Body:
I am very new to coding and was hoping you guys could help me.
I am having an issue with nextDouble not waiting for a print.ln to collect data.
With my priming input I have to put in two numbers for it to move to the next line and ask for the second number that I already put in because it didn't wait.
By that point it also decides to ask for the third number and accept input for that one as well, but it is fine asking for third and the fourth numbers with no issues.
It also happens inside the loop when it repeats.

I understand that using nextDouble doesn't mean it will "wait" for the newline and I know nextNumbertype doesn't have a newline flag but the usual trick of
adding in "input.nextLine" after getting a double does not seem to be working.

I know I could just take all input as strings and convert them later, but this is a homework assignment and my prof seems to want things a very specific way.

Any ideas for what is wrong or what I could try?

Here is what outputs:

Enter x1 or <crtl + z> to quit
1
4
Please input the x2 number:
Please input the y1 number:
1
Please input the y2 number:
5
Distance is 5.000000

Enter x1 or <crtl + z> to quit

Here is the actual code:

import java.util.Scanner;

public class distanceFinder {

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    double x1 = 0;

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    while(input.hasNext())
    {

    System.out.println("Please input the x2 number:");
    double x2 = input.nextDouble();

    System.out.println("Please input the y1 number:");
    double y1 = input.nextDouble();

    System.out.println("Please input the y2 number:");
    double y2 = input.nextDouble();

    double x3 = 0;
    double y3 = 0;
    double xy1 = 0;

    x3 = Math.pow((x2 - x1), 2);
    y3 = Math.pow((y2 - y1), 2);

    xy1 = x3 + y3;

    double distance = Math.sqrt(xy1);

    System.out.printf("Distance is %.6f %n%n%n",  distance);

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    }
input.close();
}

}

Body:
You need to correct your code:

import java.util.Scanner;

public class DistanceFinder {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter x1 or <crtl + z> to quit");

        while (input.hasNext()) {
            double x1 = input.nextDouble();

            System.out.println("Please input the x2 number:");
            double x2 = input.nextDouble();

            System.out.println("Please input the y1 number:");
            double y1 = input.nextDouble();

            System.out.println("Please input the y2 number:");
            double y2 = input.nextDouble();

            double x3 = 0;
            double y3 = 0;
            double xy1 = 0;

            x3 = Math.pow((x2 - x1), 2);
            y3 = Math.pow((y2 - y1), 2);

            xy1 = x3 + y3;

            double distance = Math.sqrt(xy1);

            System.out.printf("Distance is %.6f %n%n%n", distance);

            System.out.println("Enter x1 or <crtl + z> to quit");
        }
        input.close();
    }
}

OUTPUT:

Enter x1 or <crtl + z> to quit
1
Please input the x2 number:
2
Please input the y1 number:
1
Please input the y2 number:
3
Distance is 2.236068

Enter x1 or <crtl + z> to quit
1
Please input the x2 number:
2
Please input the y1 number:
1
Please input the y2 number:
3
Distance is 2.236068

Enter x1 or <crtl + z> to quit


问:
Subset data frame to include only levels of one factor that have values in both levels of another factor
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

```<code>ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)
</code>```

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

答:
With dplyr, you can use group_by %>% filter:

```<code>library(dplyr)
d %>% group_by(ID) %>% filter(all(c("juvenile", "adult") %in% age))

# A tibble: 7 x 3
# Groups:   ID [3]
#      ID      age       size
#  <fctr>   <fctr>      <dbl>
#1     a1 juvenile -0.6947697
#2     a2 juvenile -0.3665272
#3     a3 juvenile  1.0293555
#4     a1 juvenile  0.2745224
#5     a2    adult  0.5299029
#6     a1    adult  2.2247802
#7     a3    adult -0.4717160
</code>```

Body:
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

Body:
With dplyr, you can use group_by %>% filter:

library(dplyr)
d %>% group_by(ID) %>% filter(all(c("juvenile", "adult") %in% age))

# A tibble: 7 x 3
# Groups:   ID [3]
#      ID      age       size
#  <fctr>   <fctr>      <dbl>
#1     a1 juvenile -0.6947697
#2     a2 juvenile -0.3665272
#3     a3 juvenile  1.0293555
#4     a1 juvenile  0.2745224
#5     a2    adult  0.5299029
#6     a1    adult  2.2247802
#7     a3    adult -0.4717160


问:
python - does a function in the right side of a conditional `and` run when the left side fails?
consider this:

```<code>valid = data and func(data)
</code>```

In the cases where data will be False, will python still run the function on the right side of the and condition? (it will error if run, so I'm trying to figure out if I need to check data within func or is the above code fine as is)

答:
Well, it's easy to try:

```<code>>>> 0 and False
0
</code>```

so the answer is: python will not run func(data) if data is False.

Body:
consider this:

valid = data and func(data)

In the cases where data will be False, will python still run the function on the right side of the and condition? (it will error if run, so I'm trying to figure out if I need to check data within func or is the above code fine as is)

Body:
Well, it's easy to try:

>>> 0 and False
0

so the answer is: python will not run func(data) if data is False.


问:
How to change first activity in Android Studio?
I want to change my first activity, first I have activity named MainActivity. And I add new activity named ActivityFirst. Surely I have to change AndroidManifest.xml. Previously I have androidManifest like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

And after I add my new activity, also I change my androidManifest file.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I'm confused where I put the MainActivity after I add ActivityFirst. This my ActivityFirst.java:

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

  private Button mulai;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mulai = (Button) findViewById(R.id.mulai);

    mulai.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ActivityFirst.this, MainActivity.class);
            startActivity(intent);
        }
    });
  }
}
</code>```

答:
You need <activity> tags for each Activity in your app's manifest file as mentioned here in the docs:

All activities must be represented by  elements in the
  manifest file. Any that are not declared there will not be seen by the
  system and will never be run.

So in your case, it'd be like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
    </application>

</manifest>
</code>```

Body:
I want to change my first activity, first I have activity named MainActivity. And I add new activity named ActivityFirst. Surely I have to change AndroidManifest.xml. Previously I have androidManifest like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And after I add my new activity, also I change my androidManifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I'm confused where I put the MainActivity after I add ActivityFirst. This my ActivityFirst.java:

public class ActivityFirst extends AppCompatActivity {

  private Button mulai;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mulai = (Button) findViewById(R.id.mulai);

    mulai.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ActivityFirst.this, MainActivity.class);
            startActivity(intent);
        }
    });
  }
}

Body:
You need <activity> tags for each Activity in your app's manifest file as mentioned here in the docs:

All activities must be represented by  elements in the
  manifest file. Any that are not declared there will not be seen by the
  system and will never be run.

So in your case, it'd be like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
    </application>

</manifest>


问:
What is the best way to download a big file in NodeJS?
The below server code is working fine for 5GB file using
 wget http://localhost:11146/base/bigFile.zip but not using client side code.

Server side code.

```<code>var http = require("http");
var fs = require("fs");
var filename = "base/bigFile.zip";

var serv = http.createServer(function (req, res) {
    var stat = fs.statSync(filename);
    res.writeHeader(200, {"Content-Length": stat.size});
    var fReadStream = fs.createReadStream(filename);
    fReadStream.on('data', function (chunk) {
       if(!res.write(chunk)){
           fReadStream.pause();
       }
   });
   fReadStream.on('end', function () {
      res.end();
   });
   res.on("drain", function () {
      fReadStream.resume();
   });
});

serv.listen(1114);
</code>```

Client side code using Request module. What is wrong in this code?

```<code>var request = require('request')
request('http:/localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
</code>```

error for above client side code is below -

```<code>error: Error: Invalid protocol
    at Request.init (/Users/air/Projects/node_modules/request/request.js:338:51)
    at new Request (/Users/air/Projects//node_modules/request/request.js:105:8)
    at request (/Users/air/Projects/Vertico/Vertico-CLI/node_modules/request/index.js:53:11)
    at Object.<anonymous> (/Users/air/Projects/req.js:2:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
statusCode: undefined
body: undefined
</code>```

I revised client side to use wget shell process instead of request package, that code is below, the problem is - I am not able to see nice download progress of wget, any work around for this code, such that I can see the progress bar in child process.

```<code>const fs = require('fs');
   const child_process = require('child_process');

   var workerProcess = child_process.spawn('wget', ['-O','fdsf.zip', 'http://localhost:11146/base/bigFile.zip']);

   workerProcess.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
   });

   workerProcess.stderr.on('data', function (data) {
     //console.log('stderr: ' + data);
   });

   workerProcess.on('close', function (code) {
      console.log('Download Completed' + code);
   });
</code>```

So finally I want to know how to download a file using client side code written in nodejs?

答:
My version of code . </p>

```<code>const fs = require( 'fs' );
const request = require( 'request' );
const progress = require( 'request-progress' );
const pre = '----';
const downloadManager = function ( url, filename ) {
    progress( request( url ), {
        throttle: 500
    } ).on( 'progress', function ( state ) {
        process.stdout.write( pre + '' + ( Math.round( state.percent * 100 ) ) + "%" );
    } ).on( 'error', function ( err ) {
        console.log( 'error :( ' + err );
    } ).on( 'end', function () {
        console.log( pre + '100% \n Download Completed' );
    } ).pipe( fs.createWriteStream( filename ) );
}
downloadManager( 'http://localhost:4181', 's.zip' );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The below server code is working fine for 5GB file using
 wget http://localhost:11146/base/bigFile.zip but not using client side code.

Server side code.

var http = require("http");
var fs = require("fs");
var filename = "base/bigFile.zip";

var serv = http.createServer(function (req, res) {
    var stat = fs.statSync(filename);
    res.writeHeader(200, {"Content-Length": stat.size});
    var fReadStream = fs.createReadStream(filename);
    fReadStream.on('data', function (chunk) {
       if(!res.write(chunk)){
           fReadStream.pause();
       }
   });
   fReadStream.on('end', function () {
      res.end();
   });
   res.on("drain", function () {
      fReadStream.resume();
   });
});

serv.listen(1114);

Client side code using Request module. What is wrong in this code?

var request = require('request')
request('http:/localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

error for above client side code is below -

error: Error: Invalid protocol
    at Request.init (/Users/air/Projects/node_modules/request/request.js:338:51)
    at new Request (/Users/air/Projects//node_modules/request/request.js:105:8)
    at request (/Users/air/Projects/Vertico/Vertico-CLI/node_modules/request/index.js:53:11)
    at Object.<anonymous> (/Users/air/Projects/req.js:2:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
statusCode: undefined
body: undefined

I revised client side to use wget shell process instead of request package, that code is below, the problem is - I am not able to see nice download progress of wget, any work around for this code, such that I can see the progress bar in child process.

const fs = require('fs');
   const child_process = require('child_process');

   var workerProcess = child_process.spawn('wget', ['-O','fdsf.zip', 'http://localhost:11146/base/bigFile.zip']);

   workerProcess.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
   });

   workerProcess.stderr.on('data', function (data) {
     //console.log('stderr: ' + data);
   });

   workerProcess.on('close', function (code) {
      console.log('Download Completed' + code);
   });

So finally I want to know how to download a file using client side code written in nodejs?

Body:
My version of code .

const fs = require( 'fs' );
const request = require( 'request' );
const progress = require( 'request-progress' );
const pre = '----';
const downloadManager = function ( url, filename ) {
    progress( request( url ), {
        throttle: 500
    } ).on( 'progress', function ( state ) {
        process.stdout.write( pre + '' + ( Math.round( state.percent * 100 ) ) + "%" );
    } ).on( 'error', function ( err ) {
        console.log( 'error :( ' + err );
    } ).on( 'end', function () {
        console.log( pre + '100% \n Download Completed' );
    } ).pipe( fs.createWriteStream( filename ) );
}
downloadManager( 'http://localhost:4181', 's.zip' );


问:
How can I store the conversation of LINE Bot using LINE API and HEROKU?
I created line bot using LINE API and HEROKU.
My bot works perfectly(echo example) but I wanna store the conversation with bot.
So I added the code using bufferedwriter and filewriter but txt file doesn't be created..

If I run my code on Spring boot app, the txt file created properly in the path. But if I run my code on Heroku, it doesn't.

what should I do?

答:
There is another answer that tells you why this isn't working, but I want to point out that you shouldn't do it this way on Heroku. If you need to store data that is persistent, you should put it in a database. Heroku gives you a free Postgres database. Run the following command:

```<code>$ heroku addons:create heroku-postgresql
</code>```

Then add the code that uses it by following the Heroku guide for Connecting to Relational Databases.

Body:
There is another answer that tells you why this isn't working, but I want to point out that you shouldn't do it this way on Heroku. If you need to store data that is persistent, you should put it in a database. Heroku gives you a free Postgres database. Run the following command:

$ heroku addons:create heroku-postgresql

Then add the code that uses it by following the Heroku guide for Connecting to Relational Databases.


问:
How to Delete DataRow from DataTable quickly
I input data in DataTable in column direction.

```<code>for(int i=0 ; i<mTable.Count ; i++){
  Table.Columns.Add(i);
  foreach(DataRow row in Table.Rows){
    if(result == 1)
      row[i] = result;
    else
      row[i] = null;
  }
}
</code>```

From here, If All data of column is null, I want to delete row.

For example,

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20

11, 12, 13, 14, 15 are null, I want to delete Table.Rows[2].

So, I use next way.

```<code>for(int i = Table.Rows.Count-1;i >= 0;i--)
{
                for (int j = 0; j < mTable.Count; j++)
                {
                    if (Table.Rows[i][j] != null)
                        break;
                    if(j == mTable.Count-1)
                        Table.Rows.Remove(Table.Rows[i]);
                }
}
</code>```

But, If There's a lot of data, It will slow down considerably.

Is there another fast way?

答:
Instead of deleting the rows, you can select the non null rows from your table.

```<code>public void DtSelect()
    {
        var dt = new DataTable();
        var columns = Enumerable.Range(1, 10).Select(x => "Col" + x).ToList();
        columns.ForEach(x => dt.Columns.Add(x));
        Enumerable.Range(1, 1000).ToList().ForEach(x =>
         {
             var row = dt.NewRow();
             if (x % 15 == 0) columns.ForEach(z => row[z] = x);
             dt.Rows.Add(row);
         });
         var query =  "(" + string.Join(" is not null) or (", columns) + " is not null)";

        var nonEmpty = dt.Select(query).CopyToDataTable();

    }
</code>```

nonEmpty will not be a datatable with all rows that are non empty;

Body:
I input data in DataTable in column direction.

for(int i=0 ; i<mTable.Count ; i++){
  Table.Columns.Add(i);
  foreach(DataRow row in Table.Rows){
    if(result == 1)
      row[i] = result;
    else
      row[i] = null;
  }
}

From here, If All data of column is null, I want to delete row.

For example,

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20

11, 12, 13, 14, 15 are null, I want to delete Table.Rows[2].

So, I use next way.

for(int i = Table.Rows.Count-1;i >= 0;i--)
{
                for (int j = 0; j < mTable.Count; j++)
                {
                    if (Table.Rows[i][j] != null)
                        break;
                    if(j == mTable.Count-1)
                        Table.Rows.Remove(Table.Rows[i]);
                }
}

But, If There's a lot of data, It will slow down considerably.

Is there another fast way?

Body:
Instead of deleting the rows, you can select the non null rows from your table.

public void DtSelect()
    {
        var dt = new DataTable();
        var columns = Enumerable.Range(1, 10).Select(x => "Col" + x).ToList();
        columns.ForEach(x => dt.Columns.Add(x));
        Enumerable.Range(1, 1000).ToList().ForEach(x =>
         {
             var row = dt.NewRow();
             if (x % 15 == 0) columns.ForEach(z => row[z] = x);
             dt.Rows.Add(row);
         });
         var query =  "(" + string.Join(" is not null) or (", columns) + " is not null)";

        var nonEmpty = dt.Select(query).CopyToDataTable();

    }

nonEmpty will not be a datatable with all rows that are non empty;


问:
Convert PipelinedRDD to dataframe
I'm attempting to convert a pipelinedRDD in pyspark to a dataframe. This is the code snippet:

newRDD = rdd.map(lambda row: Row(row.__fields__ + ["tag"])(row + (tagScripts(row), )))
df = newRDD.toDF()

When I run the code though, I receive this error:

'list' object has no attribute 'encode'

I've tried multiple other combinations, such as converting it to a Pandas dataframe using:

newRDD = rdd.map(lambda row: Row(row.__fields__ + ["tag"])(row + (tagScripts(row), )))
 df = newRDD.toPandas()

But then I end up receiving this error:

AttributeError: 'PipelinedRDD' object has no attribute 'toPandas'

Any help would be greatly appreciated. Thank you for your time.

答:
rdd.toDF() or rdd.toPandas() is only used for SparkSession.

To fix your code, try below:

```<code>spark = SparkSession.builder.getOrCreate()

rdd = spark.sparkContext.textFile()
newRDD = rdd.map(...)
df = newRDD.toDF() or newRDD.toPandas()
</code>```

Title: Convert PipelinedRDD to dataframe

Body:
rdd.toDF() or rdd.toPandas() is only used for SparkSession.

To fix your code, try below:

spark = SparkSession.builder.getOrCreate()

rdd = spark.sparkContext.textFile()
newRDD = rdd.map(...)
df = newRDD.toDF() or newRDD.toPandas()


问:
Using GETDATE() and also adding time parameters such as between 9AM and 8:59AM
I am trying to complete a query where I and looking at data from the previous day but I want to add a time frame such as 9 am (previous day) to 8:59 am (current day).

I am using the code below that gets me the previous day data but I want to add the time.

```<code>AND [GasTime] BETWEEN CONVERT(DATETIME, GETDATE() -2, 102)  AND CONVERT(DATETIME, GETDATE() -1, 102)
</code>```

Thanks for your help.

答:
I would just use:

```<code>[GasTime] >= CONVERT(DATETIME, CONVERT(DATE, GETDATE() - 2)) + CONVERT(TIME, '09:00') AND
[GasTime] < CONVERT(DATETIME, CONVERT(DATE, GETDATE() - 1)) + CONVERT(TIME, '09:00')
</code>```

There is no need bounce between strings and date types.

Body:
I am trying to complete a query where I and looking at data from the previous day but I want to add a time frame such as 9 am (previous day) to 8:59 am (current day).

I am using the code below that gets me the previous day data but I want to add the time.

AND [GasTime] BETWEEN CONVERT(DATETIME, GETDATE() -2, 102)  AND CONVERT(DATETIME, GETDATE() -1, 102)

Thanks for your help.

Body:
I would just use:

[GasTime] >= CONVERT(DATETIME, CONVERT(DATE, GETDATE() - 2)) + CONVERT(TIME, '09:00') AND
[GasTime] < CONVERT(DATETIME, CONVERT(DATE, GETDATE() - 1)) + CONVERT(TIME, '09:00')

There is no need bounce between strings and date types.


问:
Migrating old table to new table in laravel
I have a problem where i need to migrate old table to new table. The old table data example like this:

Old table(Leave table)

Id   User_id    Reason    Date

1    100          Fever      29/01/2013

2    100          Fever      30/01/2013

3    100          Fever      31/01/2013

4    100          Fever      01/02/2013

New table(Leave table)

Id   User_id    Reason    Start Date   End Date

1    100          Fever      29/01/2013   01/02/2013

Is there any way where i can iterate old table and store like new table.?

29/01/2013 - 01/02/2013 produce 4 rows.. new table need 1 rows which start date and end date which 29/01/2013 be the start date and 01/02/2013 be the end date

new table i already created. i just want to iterate the list of old table and insert it into new table which have start date and end date.

答:
You can rename the Date column to Start Date and add a new column End Date like this,

```<code>Schema::table('users', function($table)
{
    $table->renameColumn('Date', 'Start Date');
    $table->dateTime('End Date');
});
</code>```

Body:
You can rename the Date column to Start Date and add a new column End Date like this,

Schema::table('users', function($table)
{
    $table->renameColumn('Date', 'Start Date');
    $table->dateTime('End Date');
});


问:
How can I customize string:message in spring to allow for internal variables in the message.proporties file?
While using spring:message tag I found the need to create internal variables the message.proporties file. Specifically what I was hoping to do was something like this:

favoriteFood = My favorite food is $bestfood$

givemeFood = Please give me $bestfood$

bestfood = carrots

What I would like to do is define variables inside of the message.proporties file that can reference eachother. The reason for doing this would be to eliminate the need to change a value in multiple places whenever a change was made. In the example if my favorite food changed I could just alter the "bestfood" value rather than having to change the string for favoriteFood and givemeFood.

答:
There is no such thing as create a variable inside a string and change it dynamically, besides that, strings in Java are immutable, and you would need to create a new one anyway.
Looks like you are searching for something like "two-way data binding" that we can find in AngularJS for example, but in that case, we are binding a variable to a html element content, far different when using a Java string.

I would suggest to save your property like:

message=My name is {0} and I am {1}

Then use MessageFormat:

MessageFormat.format(yourProperty, "Flavio", "cool");

Resulting in:

My name is Flavio and I am cool


问:
How test @WebServlet with Jersey Test Framework? (Throws Http 404 not found)
When I run my Maven tests with the Jersey Test Framework for a class with @Path, it works fine. But when i try to test a @WebServlet class, it does not and says it's a 404 error.

how do I test a web servlet with Jersey Test Framework? (Or, if this isn't possible, how else can i test this?)

Web Servlet:

```<code>package com.testservlet;

@WebServlet("/test")
public class TestServlet extends HttpServlet
{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        resp.getWriter().println( "The Result" );
    }
}
</code>```

Test class:

```<code>import com.testservlet.TestServlet;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.core.Application;

public class TestEndpoint extends JerseyTest
{
    @Override
    protected Application configure()
    {
        return new ResourceConfig( JPAServlet.class );
    }

    @Test
    public void baseGetTest()
    {
        String response = target( "/test" ).request().get( String.class );
        Assert.assertTrue( "92096".equals( response ) );
    }
}
</code>```

Maven:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>TestWeb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <!-- Tell Maven what language version to use -->
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Enables the annotations, etc needed -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.exterprise</groupId>
                    <artifactId>cdi-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Our jersey libs -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.25.1</version>
        </dependency>

        <!-- CDI to JAX-RS Binding -->
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
        <dependency>
            <groupId>org.glassfish.jersey.containers.glassfish</groupId>
            <artifactId>jersey-gf-cdi</artifactId>
            <version>2.14</version>
        </dependency>

        <!-- TESTING WEB -->
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
            <version>2.25.1</version>
        </dependency>

    </dependencies>

</project>
</code>```

答:
First you will need to use a container that supports servlet deployment, like the grizzly container

```<code><dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>${jersey2.version}</version>
</dependency>
</code>```

Then you need to configure the test class to deploy as a servlet container.

```<code>@Override
public TestContainerFactory getTestContainerFactory() {
    return new GrizzlyWebTestContainerFactory();
}

@Override
public DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(TestServlet.class)
            .build();
}
</code>```

Here, you will not need to override configure method like you're currently doing. However, the above configuration doesn't configure a Jersey application. It only configures your test servlet. If you want to run Jersey in a servlet environment (which the default JerseyTest does not do), then you would configure Jersey like

```<code>@Override
public DeploymentContext configureDeployment() {
    final ResouceConfig config = ResourceConfig();
    return ServletDeploymentContext.builder(config)
            .build();
}
</code>```

There a lot of other things you can configure with the ServletDeploymentContext; just look at the docs.

UPDATE

Instead of trying to start up a server. You might be better off writing a unit test (rather than an integration test), and just mock dependencies using a mocking framework like Mockito. There's an example below. I added some comment as to what each line does. For more info on Mockito, please refer to the linked docs.

```<code>public class WebServletTest {

    @Test
    public void testServletGet() throws Exception {
        // create some mocks
        SomeDao dao = mock(SomeDao.class);
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
        PrintWriter writer = mock(PrintWriter.class);

        // do some stubbing
        when(response.getWriter()).thenReturn(writer);
        when(dao.getData(anyString())).thenReturn("Hello World");
        // used to capture argument to writer.println
        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);

        // create the servlet and call the method under test
        TestServlet servlet = new TestServlet(dao);
        servlet.doGet(request, response);

        // capture the argument to writer.println
        verify(writer).println(captor.capture());
        String arg = captor.getValue();

        // make assetions
        assertThat(arg).isEqualTo("Hello World");
    }

    private interface SomeDao {
        String getData(String param);
    }

    @WebServlet("/test")
    public static class TestServlet extends HttpServlet {
        private final SomeDao dao;

        @Inject
        public TestServlet(SomeDao dao) {
            this.dao = dao;
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.getWriter().println(this.dao.getData(""));
        }
    }
}
</code>```

Body:
When I run my Maven tests with the Jersey Test Framework for a class with @Path, it works fine. But when i try to test a @WebServlet class, it does not and says it's a 404 error.

how do I test a web servlet with Jersey Test Framework? (Or, if this isn't possible, how else can i test this?)

Web Servlet:

package com.testservlet;

@WebServlet("/test")
public class TestServlet extends HttpServlet
{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        resp.getWriter().println( "The Result" );
    }
}

Test class:

import com.testservlet.TestServlet;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.core.Application;

public class TestEndpoint extends JerseyTest
{
    @Override
    protected Application configure()
    {
        return new ResourceConfig( JPAServlet.class );
    }

    @Test
    public void baseGetTest()
    {
        String response = target( "/test" ).request().get( String.class );
        Assert.assertTrue( "92096".equals( response ) );
    }
}

Maven:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>TestWeb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.exterprise</groupId>
                    <artifactId>cdi-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.25.1</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers.glassfish</groupId>
            <artifactId>jersey-gf-cdi</artifactId>
            <version>2.14</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
            <version>2.25.1</version>
        </dependency>

    </dependencies>

</project>

Body:
First you will need to use a container that supports servlet deployment, like the grizzly container

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>${jersey2.version}</version>
</dependency>

Then you need to configure the test class to deploy as a servlet container.

@Override
public TestContainerFactory getTestContainerFactory() {
    return new GrizzlyWebTestContainerFactory();
}

@Override
public DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(TestServlet.class)
            .build();
}

Here, you will not need to override configure method like you're currently doing. However, the above configuration doesn't configure a Jersey application. It only configures your test servlet. If you want to run Jersey in a servlet environment (which the default JerseyTest does not do), then you would configure Jersey like

@Override
public DeploymentContext configureDeployment() {
    final ResouceConfig config = ResourceConfig();
    return ServletDeploymentContext.builder(config)
            .build();
}

There a lot of other things you can configure with the ServletDeploymentContext; just look at the docs.

UPDATE

Instead of trying to start up a server. You might be better off writing a unit test (rather than an integration test), and just mock dependencies using a mocking framework like Mockito. There's an example below. I added some comment as to what each line does. For more info on Mockito, please refer to the linked docs.

public class WebServletTest {

    @Test
    public void testServletGet() throws Exception {
        // create some mocks
        SomeDao dao = mock(SomeDao.class);
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
        PrintWriter writer = mock(PrintWriter.class);

        // do some stubbing
        when(response.getWriter()).thenReturn(writer);
        when(dao.getData(anyString())).thenReturn("Hello World");
        // used to capture argument to writer.println
        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);

        // create the servlet and call the method under test
        TestServlet servlet = new TestServlet(dao);
        servlet.doGet(request, response);

        // capture the argument to writer.println
        verify(writer).println(captor.capture());
        String arg = captor.getValue();

        // make assetions
        assertThat(arg).isEqualTo("Hello World");
    }

    private interface SomeDao {
        String getData(String param);
    }

    @WebServlet("/test")
    public static class TestServlet extends HttpServlet {
        private final SomeDao dao;

        @Inject
        public TestServlet(SomeDao dao) {
            this.dao = dao;
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.getWriter().println(this.dao.getData(""));
        }
    }
}


问:
How to add class only to the header of group of links
I have a list like to:

```<code><ul>
<li><a class="group-active">Group 1</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page1']">Group 1 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page2']">Group 1 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group1/page3']">Group 1 - Page 3</a>
    </ul>
</li>
<li><a>Group 2</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page1']">Group 2 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page2']">Group 2 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group2/page3']">Group 2 - Page 3</a>
    </ul>
</li>
<li><a>Group 3</a>
    <ul>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page1']">Group 3 - Page 1</a>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page2']">Group 3 - Page 2</a>
        <li routerLinkActive="active"><a [routerLink]="['/group3/page3']">Group 3 - Page 3</a>
    </ul>
</li>
</ul>
</code>```

I need:
change the class "group-active" (of the first group) when i choose one of their elements. Their elements works fine, but i can't apply the style to corresponding element header.

Any idea?

Thanks

答:
Well,
I found my solution and i share it with you. Angular is very smart. Just I need to add the same routerLinkActive in the corresponding element:

```<code><li><a routerLinkActive="group-active">Group 1</a>
...
<li><a routerLinkActive="group-active">Group 2</a>
...
<li><a routerLinkActive="group-active">Group 3</a>
...
</code>```

I hope it helps someone else.

Body:
I have a list like to:

Group 1

Group 1 - Page 1

Group 1 - Page 2

Group 1 - Page 3

Group 2

Group 2 - Page 1

Group 2 - Page 2

Group 2 - Page 3

Group 3

Group 3 - Page 1

Group 3 - Page 2

Group 3 - Page 3

I need:
change the class "group-active" (of the first group) when i choose one of their elements. Their elements works fine, but i can't apply the style to corresponding element header.

Any idea?

Thanks

Body:
Well,
I found my solution and i share it with you. Angular is very smart. Just I need to add the same routerLinkActive in the corresponding element:

<li><a routerLinkActive="group-active">Group 1</a>
...
<li><a routerLinkActive="group-active">Group 2</a>
...
<li><a routerLinkActive="group-active">Group 3</a>
...

I hope it helps someone else.


问:
algorithm to evenly space objects across containers
I have a line of 12 cups and I will receive a random number of balls to be placed in those cups. I could receive between 1 and 12 balls (inclusive). No matter the number of balls I receive, I want to evenly space them across the line of cups. Each cup may only contain one ball.

The concept of "even" is up for debate. For instance, if I get 6 balls, I can space them every-other cup, but if I get 7 balls, the location of that 7th ball isn't terribly important to me, as long as it follows a logical pattern. Similarly, the location of the extra space between balls when I only have 5 balls is not important to me either.

So, is anyone familiar with an distribution algorithm of this sort? I've cobbled something together, but it's so bad that it will never see the light of day.

答: Normally if you get N balls, you'd put the ith ball (counting from zero) in bucket floor((i+0.5)*12/N) (also counting from zero), or something like that


问:
AntiForgery Token implementation in Angular 2 and Web Api using Aps.Net Core
I have separate frontend project in Angular 2 without using MVC and backend project is Web Api (Asp.Net Core) both are hosted on different domain. I implemented AntiForgery token functionality but it is not working.

Frontend project (UI)- http://localhost:8080/

Backend project (Web Api) - http://localhost:4823/

I am able to receive and send XSRF-Token cookie in every request but api gives 400 Bad Request error.
I followed this link-
Angular2 ASP.NET Core AntiForgeryToken

Startup.cs-

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllCorsPolicy",
        builder => builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials());
     });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IAntiforgery antiforgery)
{
    app.Use(async (context, next) =>
      {
        if (context.Request.Path == "/")
           {
             //send the request token as a JavaScript-readable cookie, and Angular will use it by default
             var tokens = antiforgery.GetAndStoreTokens(context);
             context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
           }
       }
}
</code>```

Controller code-

```<code>[EnableCors("AllowAllCorsPolicy")]
[ValidateAntiForgeryToken]
[Produces("application/json")]
[Route("api/Aoi")]
public class AoiController : Controller
{
 ...
}
</code>```

Angular code-

```<code>let options = new RequestOptions({ headers: headers, withCredentials:true });
this._http.post(this.aoiUrl, bodydata, options)
       .map((res: Response) => {
          let data = res.json();
          return data;
})
</code>```

答: I think you should be able to get this working by enabling CORS.  For more info, see here - https://learn.microsoft.com/en-us/aspnet/core/security/cors</p>

Body:
I have separate frontend project in Angular 2 without using MVC and backend project is Web Api (Asp.Net Core) both are hosted on different domain. I implemented AntiForgery token functionality but it is not working.

Frontend project (UI)- http://localhost:8080/

Backend project (Web Api) - http://localhost:4823/

I am able to receive and send XSRF-Token cookie in every request but api gives 400 Bad Request error.
I followed this link-
Angular2 ASP.NET Core AntiForgeryToken

Startup.cs-

public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllCorsPolicy",
        builder => builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials());
     });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IAntiforgery antiforgery)
{
    app.Use(async (context, next) =>
      {
        if (context.Request.Path == "/")
           {
             //send the request token as a JavaScript-readable cookie, and Angular will use it by default
             var tokens = antiforgery.GetAndStoreTokens(context);
             context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
           }
       }
}

Controller code-

[EnableCors("AllowAllCorsPolicy")]
[ValidateAntiForgeryToken]
[Produces("application/json")]
[Route("api/Aoi")]
public class AoiController : Controller
{
 ...
}

Angular code-

let options = new RequestOptions({ headers: headers, withCredentials:true });
this._http.post(this.aoiUrl, bodydata, options)
       .map((res: Response) => {
          let data = res.json();
          return data;
})


问:
What's a good, efficient way to implement run()?
Should it just contain a loop like ```while (true) { ... }```

I find it not so efficient as it consumes the CPU so much. I would like my thread to keep on waiting for something but what's the best way to make it wait without consuming so much CPU?

答:
There are many ways to do this efficiently using Object.wait and Object.notify (see here), or using various higher level Java concurrency classes such as blocking queues, latches, futures, semaphores or barriers.

===================================================

You are correct that repeatedly testing the condition is a really bad idea; e.g.

```<code>    while (!condition) {
        // really bad idea ... burns CPU cycles.
    }
</code>```

The following is an improvement, but can still be problematic:

```<code>    while (!condition) {
        Thread.sleep(...);  // bad idea
    }
</code>```

The problem is that if you set the sleep interval short, the loop gets expensive.  But if you set it longer (e.g. a second or so), then the thread can take up to that amount of time to respond to the condition becoming true.  The net result can be reduced throughput and / or sluggish user interfaces.

Sometimes the loop{test; sleep} approach is the best available option, unfortunately, but if you can avoid it, you should.

ContentLicense: CC BY-SA 2.5

Body:
Should it just contain a loop like
while (true) { ... }

I find it not so efficient as it consumes the CPU so much. I would like my thread to keep on waiting for something but what's the best way to make it wait without consuming so much CPU?

Body:
There are many ways to do this efficiently using Object.wait and Object.notify (see here), or using various higher level Java concurrency classes such as blocking queues, latches, futures, semaphores or barriers.

===================================================

You are correct that repeatedly testing the condition is a really bad idea; e.g.

    while (!condition) {
        // really bad idea ... burns CPU cycles.
    }

The following is an improvement, but can still be problematic:

    while (!condition) {
        Thread.sleep(...);  // bad idea
    }

The problem is that if you set the sleep interval short, the loop gets expensive.  But if you set it longer (e.g. a second or so), then the thread can take up to that amount of time to respond to the condition becoming true.  The net result can be reduced throughput and / or sluggish user interfaces.

Sometimes the loop{test; sleep} approach is the best available option, unfortunately, but if you can avoid it, you should.


答:
The problem is that Scanner.hasNext() blocks until there's input. Once you type something, it enters the loop, executes the first print statement, grabs the input, prints the second statement, and waits for the next input.

Another issue is that you're checking hasNext() before reading x2 instead of before x1. Try this structure instead:

```<code>System.out.println("Enter x1 or <crtl + z> to quit");
while (input.hasNext()) {
    double x1 = input.nextDouble();

    System.out.println("Please input the x2 number:");
    double x2 = input.nextDouble();

    //...

    System.out.println("Enter x1 or <crtl + z> to quit");
}
</code>```

Title: Scanner not waiting for NewLine to collect input with a loop

Body:
I am very new to coding and was hoping you guys could help me.
I am having an issue with nextDouble not waiting for a print.ln to collect data.
With my priming input I have to put in two numbers for it to move to the next line and ask for the second number that I already put in because it didn't wait.
By that point it also decides to ask for the third number and accept input for that one as well, but it is fine asking for third and the fourth numbers with no issues.
It also happens inside the loop when it repeats.

I understand that using nextDouble doesn't mean it will "wait" for the newline and I know nextNumbertype doesn't have a newline flag but the usual trick of
adding in "input.nextLine" after getting a double does not seem to be working.

I know I could just take all input as strings and convert them later, but this is a homework assignment and my prof seems to want things a very specific way.

Any ideas for what is wrong or what I could try?

Here is what outputs:

Enter x1 or <crtl + z> to quit
1
4
Please input the x2 number:
Please input the y1 number:
1
Please input the y2 number:
5
Distance is 5.000000

Enter x1 or <crtl + z> to quit

Here is the actual code:

import java.util.Scanner;

public class distanceFinder {

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    double x1 = 0;

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    while(input.hasNext())
    {

    System.out.println("Please input the x2 number:");
    double x2 = input.nextDouble();

    System.out.println("Please input the y1 number:");
    double y1 = input.nextDouble();

    System.out.println("Please input the y2 number:");
    double y2 = input.nextDouble();

    double x3 = 0;
    double y3 = 0;
    double xy1 = 0;

    x3 = Math.pow((x2 - x1), 2);
    y3 = Math.pow((y2 - y1), 2);

    xy1 = x3 + y3;

    double distance = Math.sqrt(xy1);

    System.out.printf("Distance is %.6f %n%n%n",  distance);

    System.out.println("Enter x1 or <crtl + z> to quit");
    x1 = input.nextDouble();

    }
input.close();
}

}

Body:
The problem is that Scanner.hasNext() blocks until there's input. Once you type something, it enters the loop, executes the first print statement, grabs the input, prints the second statement, and waits for the next input.

Another issue is that you're checking hasNext() before reading x2 instead of before x1. Try this structure instead:

System.out.println("Enter x1 or <crtl + z> to quit");
while (input.hasNext()) {
    double x1 = input.nextDouble();

    System.out.println("Please input the x2 number:");
    double x2 = input.nextDouble();

    //...

    System.out.println("Enter x1 or <crtl + z> to quit");
}


问:
Importing CSV with line breaks in Excel 2007
I'm working on a feature to export search results to a CSV file to be opened in Excel.  One of the fields is a free-text field, which may contain line breaks, commas, quotations, etc.  In order to counteract this, I have wrapped the field in double quotes (").

However, when I import the data into Excel 2007, set the appropriate delimiter, and set the text qualifier to double quote, the line breaks are still creating new records at the line breaks, where I would expect to see the entire text field in a single cell.

I've also tried replacing CR/LF (\r\n) with just CR (\r), and again with just LF (\n), but no luck.

Has anyone else encountered this behavior, and if so, how did you fix it?

TIA,

-J

EDIT:

Here's a quick file I wrote by hand to duplicate the problem.

ID,Name,Description

  "12345","Smith, Joe","Hey.

  My name is Joe."

When I import this into Excel 2007, I end up with a header row, and two records.  Note that the comma in "Smith, Joe" is being handled properly.  It's just the line breaks that are causing problems.

答:
This worked on Mac, using csv and opening the file in Excel.

Using python to write the csv file.

data= '"first line of cell a1\r 2nd line in cell a1\r 3rd line in cell a1","cell b1","1st line in cell c1\r 2nd line in cell c1"\n"first line in cell a2"\n'

file.write(data)


问:
XSD scheme syntax and gSoap
I have a question, is this XSD syntax valid? Because when I use gSOAP, it pruduces me warnings because it creates struct (C/C++ code), which consists two other structs with the same name (name C), and then when I try to compile that code in c/c++ compiler it prodeces errors (because of the struct with the same name inside one struct). Is here any possibility how to solve this without touching the XSD file?

```<code><complexType name="A">
<choice>
<sequence>
<element name="B" type="base64Binary"/>
<element name="C" type="base64Binary" minOccurs="0"/>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<sequence>
<element name="C" type="base64Binary"/>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</choice>
</complexType>
</code>```

in gSOAP I create it using: wsdl2h.exe -oSoap.h -s -y -c a.wsdl b.wsdl ... and

soapcpp2.exe -C -L -n -x -w -c -d.\source Soap.h

答:
The soapcpp2 tool only complains, but the generated code works by design. I worked on this and tested it.

Here is what I get generated by soapcpp2:

```<code>class ns__A
{ public:
//  BEGIN CHOICE <xs:choice>
/// @note <xs:choice> with embedded <xs:sequence> or <xs:group> prevents the use of a union for <xs:choice>. Instead of being members of a union, the following members are declared optional. Only one member should be non-NULL by choice.
//  BEGIN SEQUENCE <xs:sequence>
/// Element "B" of XSD type xs:base64Binary.
    xsd__base64Binary*                   B                              nullptr;    ///< Required nillable (xsi:nil when NULL) element.
/// Element "C" of XSD type xs:base64Binary.
    xsd__base64Binary*                   C                             ;    ///< Required element.
/// Size of the array of XML or DOM nodes is 0..unbounded.
    std::vector<_XML                   > __any                         0;   ///< Catch any element content in XML string.
//  END OF SEQUENCE
//  BEGIN SEQUENCE <xs:sequence>
/// Element "C" of XSD type xs:base64Binary.
    xsd__base64Binary*                   C                              nullptr;    ///< Required nillable (xsi:nil when NULL) element.
/// Size of the array of XML or DOM nodes is 0..unbounded.
    std::vector<_XML                   > __any                         0;   ///< Catch any element content in XML string.
//  END OF SEQUENCE
//  END OF CHOICE
/// A handle to the soap struct context that manages this instance when instantiated by a context or NULL otherwise (automatically set).
    struct soap                         *soap                          ;
};
</code>```

The reason for the "issue" reported by soapcpp2 is that the streaming serializer can't distinguish the choices for C. So both are encoded. The second C is renamed C_ and is never used to deserialize data.

Simple explanation: you're fine.

Title: XSD scheme syntax and gSoap

Body:
I have a question, is this XSD syntax valid? Because when I use gSOAP, it pruduces me warnings because it creates struct (C/C++ code), which consists two other structs with the same name (name C), and then when I try to compile that code in c/c++ compiler it prodeces errors (because of the struct with the same name inside one struct). Is here any possibility how to solve this without touching the XSD file?

<complexType name="A">
<choice>
<sequence>
<element name="B" type="base64Binary"/>
<element name="C" type="base64Binary" minOccurs="0"/>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<sequence>
<element name="C" type="base64Binary"/>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</choice>
</complexType>

in gSOAP I create it using: wsdl2h.exe -oSoap.h -s -y -c a.wsdl b.wsdl ... and

soapcpp2.exe -C -L -n -x -w -c -d.\source Soap.h

Body:
The soapcpp2 tool only complains, but the generated code works by design. I worked on this and tested it.

Here is what I get generated by soapcpp2:

class ns__A
{ public:
//  BEGIN CHOICE <xs:choice>
/// @note <xs:choice> with embedded <xs:sequence> or <xs:group> prevents the use of a union for <xs:choice>. Instead of being members of a union, the following members are declared optional. Only one member should be non-NULL by choice.
//  BEGIN SEQUENCE <xs:sequence>
/// Element "B" of XSD type xs:base64Binary.
    xsd__base64Binary*                   B                              nullptr;    ///< Required nillable (xsi:nil when NULL) element.
/// Element "C" of XSD type xs:base64Binary.
    xsd__base64Binary*                   C                             ;    ///< Required element.
/// Size of the array of XML or DOM nodes is 0..unbounded.
    std::vector<_XML                   > __any                         0;   ///< Catch any element content in XML string.
//  END OF SEQUENCE
//  BEGIN SEQUENCE <xs:sequence>
/// Element "C" of XSD type xs:base64Binary.
    xsd__base64Binary*                   C                              nullptr;    ///< Required nillable (xsi:nil when NULL) element.
/// Size of the array of XML or DOM nodes is 0..unbounded.
    std::vector<_XML                   > __any                         0;   ///< Catch any element content in XML string.
//  END OF SEQUENCE
//  END OF CHOICE
/// A handle to the soap struct context that manages this instance when instantiated by a context or NULL otherwise (automatically set).
    struct soap                         *soap                          ;
};

The reason for the "issue" reported by soapcpp2 is that the streaming serializer can't distinguish the choices for C. So both are encoded. The second C is renamed C_ and is never used to deserialize data.

Simple explanation: you're fine.


问:
Game Maker - Touch Event
I´m making my first game in Game Maker.

In the game i need to the user to draw a figure, for example a rectangle, and the game has to recognize the figure. How can i do this?

Thanks!

答:
The way I would solve this problem is pretty simple. I would create a few variables for each point when someone clicked on one of the points it would equal true. and wait for the player to click on the next point. If the player clicked on the next point i would call in a sprite as a line using image_angle to line both points up and wait for the player to click the next point.

Next I would have a step event waiting to see if all points were clicked and when they were then to either draw a triangle at those coordinates or place an sprite at the correct coordinates to fill in the triangle.

Another way you could do it would be to decide what those points would be and check against mouse_x, and mouse_y to see if that was a point and if it was then do as above. There are many ways to solve this problem. Just keep trying you will find one that works for your skill level and what you want to do.

Title: Game Maker - Touch Event


答:
As Matt already said, just .. A very simple solution is, if the ball is B take the nearest integer to B plus a half times 12 divided by the number of balls in the run.

The more smart ass way to do it, and you don't even have to know how many balls there are in total, is: take a ball; find the longest run of holes: put the ball in a random position in that run.  Just repeat that until you run out of balls.  In a random way and over time, they will be evenly distributed and, uh, "random" looking.  This is how you do it if you have lots of slots and lots of balls. Interestingly, you can abstract it to more than one dimension.

Title: algorithm to evenly space objects across containers

Body:
I have a line of 12 cups and I will receive a random number of balls to be placed in those cups. I could receive between 1 and 12 balls (inclusive). No matter the number of balls I receive, I want to evenly space them across the line of cups. Each cup may only contain one ball.

The concept of "even" is up for debate. For instance, if I get 6 balls, I can space them every-other cup, but if I get 7 balls, the location of that 7th ball isn't terribly important to me, as long as it follows a logical pattern. Similarly, the location of the extra space between balls when I only have 5 balls is not important to me either.

So, is anyone familiar with an distribution algorithm of this sort? I've cobbled something together, but it's so bad that it will never see the light of day.


问:
Border with a Grid child not centering when a RotateTransform is applied
I have a border

```<code><Border ClipToBounds="True" Background="Black" Grid.ColumnSpan="2">
    <Grid>
        <Image x:Name="ImageBox" RenderOptions.BitmapScalingMode="HighQuality"/>
    </Grid>
</Border>
</code>```

When I resize the dialog, the image stays in the center of the border.
However, if i apply a RotationTransform (104 degrees) to the Grid, and resize the form, the grid\image will no longer stay in the center of the border.

Black is the border

Pink is the Grid

Image is the image

Initially: http://imgur.com/a/nOTnW
After resizing horizontally: http://imgur.com/a/CKRvA

I have also tried applying the RotateTransform to the Image instead of the grid and get this: http://imgur.com/a/Sb8c1

which seems to work a little better, but the image is not staying centered on the grid. Resizing the dialog horizontally produced this: http://imgur.com/a/Sa1PM

Also note, this RotateTransform is applied at the center of the image.

答: Using layout transfer instead of rendertransform fixed my problem!</p>

Body:
I have a border

<Border ClipToBounds="True" Background="Black" Grid.ColumnSpan="2">
    <Grid>
        <Image x:Name="ImageBox" RenderOptions.BitmapScalingMode="HighQuality"/>
    </Grid>
</Border>

When I resize the dialog, the image stays in the center of the border.
However, if i apply a RotationTransform (104 degrees) to the Grid, and resize the form, the grid\image will no longer stay in the center of the border.

Black is the border

Pink is the Grid

Image is the image

Initially: http://imgur.com/a/nOTnW
After resizing horizontally: http://imgur.com/a/CKRvA

I have also tried applying the RotateTransform to the Image instead of the grid and get this: http://imgur.com/a/Sb8c1

which seems to work a little better, but the image is not staying centered on the grid. Resizing the dialog horizontally produced this: http://imgur.com/a/Sa1PM

Also note, this RotateTransform is applied at the center of the image.


问:
how to get jpl latest version: jpl7?
I'm using a java project with the jpl library, but i'm getting the compile error "the package org.jpl7 does not exist". I've tried to download the latest version, but I've probably get the jpl3 version.

How to get the latest version of jpl7? I've searched extensively, and even found the http://jpl7.org, but there is no hint about how to download that version.

Thanks

答: You will find it on Maven, look for it on Maven Central!</p>

Title: how to get jpl latest version: jpl7?


问:
Send data from Activity to Fragment already created
I only have found information about how to create a Fragment sending some data to it, but only in its instantiation with the constructor.

But I want to know if it is possible to send some data (for instance, two Double objects) to a Fragment from an Activity without having to create a new instance of the Fragment.

A Fragment that has been previously created.

答:
Just add a method in Fragment which you want to receive arguments, then invoke the method in Activity.

Activity's Code:

Fragment's Code:


问:
New-azurermadserviceprincipal : quota exceeded error
I am creating a new application registration in AD, and then creating Service principal. For my login I have only 5 applications registered. When I try to create a new one I get "quota exceeded error". But for another user in same subscription it allows to create many registrations.

Is there a way to list all service principals for a specific user and then clean them up?

答:
Yes, it is possible.

You could use Get-AzureRmADServicePrincipal to list all your service principals.

Use Remove-AzureRmADServicePrincipal to delete your service principals.

You also could manage your service principals on Azure Portal.  Azure Active Directory--App registrations>

Update:

Please ensure your account have the permission to create service principals.

More information please refer to this link.


问:
How to calculate two dataframe'value with scala in spark
I hava two dataframe ,the count of two dataframe is same,I want to get the sum of each value in two dataframe
this is input:

```<code>+---+  and       +---+
|df1|            |df2|
+---+            +---+
| 11|            |  1|
| 12|            |  2|
| 13|            |  3|
| 14|            |  4|
| 15|            |  5|
| 16|            |  6|
| 17|            |  7|
| 18|            |  8|
| 19|            |  9|
| 20|            | 10|
+---+            +---+
</code>```

this is my code:

```<code>val df1 = sc.parallelize(1 to 10,2).toDF("df1")
    val df2 = sc.parallelize(11 to 20,2).toDF("df2")
    val df3=df1.rdd.zip(df2.rdd).map(x=>{
      x._1.getInt(0)+x._2.getInt(0)
    }).toDF("result")
    df3.show()
</code>```

the result is:

```<code>+-----+
|result|
+-----+
|   12|
|   14|
|   16|
|   18|
|   20|
|   22|
|   24|
|   26|
|   28|
|   30|
+-----+
</code>```

I have to change dataframe to rdd then zip two rdd,how to calculate two dataframe with not transform to rdd?

答:
You can simply use Window function to create row_number for joining both dataframes. After joining just sum the two columns .

```<code>import org.apache.spark.sql.expressions.Window
import sqlContext.implicits._
import org.apache.spark.sql.functions._

val df1 = sc.parallelize(1 to 10,2).toDF("df1")
val df2 = sc.parallelize(11 to 20,2).toDF("df2")

df1.withColumn("rowNo", row_number() over Window.orderBy("df1"))
  .join(df2.withColumn("rowNo", row_number() over Window.orderBy("df2")), Seq("rowNo"))
  .select(($"df1"+$"df2").alias("result"))
  .show(false)
</code>```

Body:
I hava two dataframe ,the count of two dataframe is same,I want to get the sum of each value in two dataframe
this is input:

+---+  and       +---+
|df1|            |df2|
+---+            +---+
| 11|            |  1|
| 12|            |  2|
| 13|            |  3|
| 14|            |  4|
| 15|            |  5|
| 16|            |  6|
| 17|            |  7|
| 18|            |  8|
| 19|            |  9|
| 20|            | 10|
+---+            +---+

this is my code:

val df1 = sc.parallelize(1 to 10,2).toDF("df1")
    val df2 = sc.parallelize(11 to 20,2).toDF("df2")
    val df3=df1.rdd.zip(df2.rdd).map(x=>{
      x._1.getInt(0)+x._2.getInt(0)
    }).toDF("result")
    df3.show()

the result is:

+-----+
|result|
+-----+
|   12|
|   14|
|   16|
|   18|
|   20|
|   22|
|   24|
|   26|
|   28|
|   30|
+-----+

I have to change dataframe to rdd then zip two rdd,how to calculate two dataframe with not transform to rdd?

Body:
You can simply use Window function to create row_number for joining both dataframes. After joining just sum the two columns .

import org.apache.spark.sql.expressions.Window
import sqlContext.implicits._
import org.apache.spark.sql.functions._

val df1 = sc.parallelize(1 to 10,2).toDF("df1")
val df2 = sc.parallelize(11 to 20,2).toDF("df2")

df1.withColumn("rowNo", row_number() over Window.orderBy("df1"))
  .join(df2.withColumn("rowNo", row_number() over Window.orderBy("df2")), Seq("rowNo"))
  .select(($"df1"+$"df2").alias("result"))
  .show(false)


问:
text in index.html is bottom aligned, I want it to be top alined
I have a html file that when renders the text is bottom aligned. When the web-browser is open wide, the whole text is very far from the top as it can been seen here:

Now if I make the web-browser window narrower the text goes up like this:

Here is what I have in the html file:

```<code><div class="post">

        <h1>Title of Sample Work 2</h1>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>

        <p>Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.</p>
</code>```

and here is what I have in the css:

```<code>.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}
</code>```

I tried to add position: absolute; to .post{ like this:

```<code>.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
    position: absolute;
}
</code>```

but then it messes up left and right margins as it can be seen here:

As can be seen the right margin now is much smaller than left margin.

Any suggestion on how I align the text to the top without messing up left and right margin is really appreciated.

答:
Delete margin-top: 5em; from .post if you don't want the space on top

Delete max-width: 1200px; from .post p for the even sides

.post {
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p {
    padding: .5em;
    margin: 0;
    text-align: justify;
    top: 1.25em;
}

.post h1{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="post">
    <h1>Title of Sample Work 2</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
    <p>Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.</p>
</div></code>```

jsfiddle.net/julysfx/sj3q65kn/1/

Body:
I have a html file that when renders the text is bottom aligned. When the web-browser is open wide, the whole text is very far from the top as it can been seen here:

Now if I make the web-browser window narrower the text goes up like this:

Here is what I have in the html file:

Title of Sample Work 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.

Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.

and here is what I have in the css:

.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

I tried to add position: absolute; to .post{ like this:

.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
    position: absolute;
}

but then it messes up left and right margins as it can be seen here:

As can be seen the right margin now is much smaller than left margin.

Any suggestion on how I align the text to the top without messing up left and right margin is really appreciated.

Body:
Delete margin-top: 5em; from .post if you don't want the space on top

Delete max-width: 1200px; from .post p for the even sides

.post {
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p {
    padding: .5em;
    margin: 0;
    text-align: justify;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

<div class="post">
    <h1>Title of Sample Work 2</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
    <p>Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.</p>
</div>

jsfiddle.net/julysfx/sj3q65kn/1/


问:
UINavigationController and UINavigationItem
Apple's documentation on UINavigationItem states the following:

The managing UINavigationController object uses the navigation items
  of the topmost two view controllers to populate the navigation bar
  with content.

Why the topmost two view controllers instead of just the topmost? Is it just so that when you pop the view controller, it fades one item out and another in?

答:
I think it's because the title of the "Back" button is (by default) the navigation title of the view controller just underneath the top one.

Navigation title: Title of top view controller.

Back Button title: Title of previous view controller.


问:
How does SPARK read data and manage in Memory
Can anyone please help me understanding how does SPARK read hdfs data and manage it in main memory?

In other words,

If I create 3 RDD, first RDD from hadoop file and do some transformation on it and create a second RDD and again do some transformation on the 2nd RDD and create a 3rd RDD then call some action on 3rd RDD.

How many times data will be read from hdfs?

Will all three RDD data stay in Memory if we don't call the cache or persist explicitly? i.e. when an action is executing on the 3rd RDD that time whether 1st RDD data remains in memory

答:
If all RDD share one file, data will only be read once on the action, not on any transformation. </p>

<p>The DAG to regenerate the third RDD will be in memory, since as mentioned, only RDD #3 will contain any actual data. </p>

Body:
If all RDD share one file, data will only be read once on the action, not on any transformation.

The DAG to regenerate the third RDD will be in memory, since as mentioned, only RDD #3 will contain any actual data.


问:
How do I completely remove Exceptionless from a server?
I recently installed Exceptionless on a server for testing purposes.  Now how do I go about completely removing it from said server?  I have uninstalled and deleted all the directories for both ElasticSearch and Exceptionless.  When I reinstall it again, it says my email already exists.  I basically need to completely remove the tool from my system, so that I can try different configurations.  Any help would be greatly appreciated.</p>

答: I work on the Exceptionless Project. You just need to remove the website and Elasticsearch instance that you configured (if you only set it up for Exceptionless). If you delete the Elasticsearch folder you should be completely free. If you are using redis, you may want to flush the redis db to start over. Were you able to get it working?</p>