问:
CKEditor strips inline attributes
I have been using CKEditor for some time and it has worked great. I've pretty much gotten rid of any problems that ive had but this one i cant seem to figure out. When i add inline attributes to elements for instance style = "color: #ff0;" on a

 tag they are stripped out when i switch from wysiwyg to source view. No saving or submission is done and ckeditor is has been added to my site which is my own script. Any ideas as to what would cause this. All of the search results i can find correspond to this happening in Drupal but Drupal seems to be the problem not the editor in all instances. Thanks again!

答:
I faced the same issue and below answer solved my problem:</p>

```<code>config.allowedContent = true;
config.extraAllowedContent = '*(*);*{*}';
config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';
</code>```

Title: CKEditor strips inline attributes

Body:
I faced the same issue and below answer solved my problem:

config.allowedContent = true;
config.extraAllowedContent = '*(*);*{*}';
config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';


来源: stackexchange

问:
pandas convert column names to column
below is the dataframe (default indexes)

```<code>    value 1901 1902 1903 1904
44   good  12   13   14   15
70   avge  23   24   25   26
</code>```

(the 44, 70 are indexes which i dont want)

Output should be:

```<code>time  good  avge
1901   12    23
1902   13    24
1903   14    25
1904   15    26
</code>```

I tried df.T but not quite in the required format.
thanks a lot in advance. (can you refer some nice textbooks for this kind of operational exercises).

答:
You can use set_index with transpose by T:

```<code>df = df.set_index('value').T
print (df)
value  good  avge
1901     12    23
1902     13    24
1903     14    25
1904     15    26
</code>```

If need change column and index names add rename_axis and reset_index:

```<code>df = df.set_index('value').T.rename_axis(None,axis=1).rename_axis('time').reset_index()
print (df)
   time  good  avge
0  1901    12    23
1  1902    13    24
2  1903    14    25
3  1904    15    26
</code>```

ContentLicense: CC BY-SA 3.0

Title: pandas convert column names to column

Body:
below is the dataframe (default indexes)

    value 1901 1902 1903 1904
44   good  12   13   14   15
70   avge  23   24   25   26

(the 44, 70 are indexes which i dont want)

Output should be:

time  good  avge
1901   12    23
1902   13    24
1903   14    25
1904   15    26

I tried df.T but not quite in the required format.
thanks a lot in advance. (can you refer some nice textbooks for this kind of operational exercises).

Body:
You can use set_index with transpose by T:

df = df.set_index('value').T
print (df)
value  good  avge
1901     12    23
1902     13    24
1903     14    25
1904     15    26

If need change column and index names add rename_axis and reset_index:

df = df.set_index('value').T.rename_axis(None,axis=1).rename_axis('time').reset_index()
print (df)
   time  good  avge
0  1901    12    23
1  1902    13    24
2  1903    14    25
3  1904    15    26


问:
Implementing GoTo in WF 4
Given a SQL Server-persisted .NET 4 Windows Workflow Foundation (WF) workflow service deployed under AppFabric, how can I "jump" the service from one activity to another? The workflow could be sequential or flowchart.

The use case is administrative. A long-running workflow is idle at Receive activity A. Some client mistakenly calls the service, progressing it to Receive activity B. The workflow (which could be embedded in a larger workflow) has no path back to A. The client calls the support desk and requests that the workflow be set back to A.

We've seen this case occur frequently in production. Our existing BPM system supports a "goto" call. How can this be accomplished in WF 4?

EDIT: If the above is not practical, what is a good design pattern for implementing a "fail" activity off from the "happy path" that can branch to one of a limited number of known prior activities (restart from here) based on a variable? The goal is to avoid creating an unreadable workflow with a multitude of lines.

EDIT 2: We decided not to go this route, but there's a newer MSDN article on doing just this.

EDIT 3: We changed our minds again and are going with Leon Welicki's solution from the MSDN article linked above. :)

答:
This can't be done out of the box.

If it can be done at all it would mean opening up the workflow state, stored in 4 binary columns and changing those to the previous state knowing that any number of activities could have executed and any variables could have been changed or even dropped because they are no longer in scope.

Suppose I was going to try this I would try copying the state from the SQL database every time a workflow went idle so you get a sort of stack with all previous idle states of a workflow. Then at some later time when the workflow is idle and not in memory you can replace the current state with a previous state and reload the workflow. I have never tried it so don't know if it will work and see quite a few potential problems, thinks like DB transaction having competed or emails having been send but executing a second time.

Title: Implementing GoTo in WF 4

ContentLicense: CC BY-SA 2.5


问:
SQL display total on the first row only
I want to display my data like this</p>

```<code>Name             Product         Amount     Total
_______________________________________________
John Smith     Burger          60.00      100.00
John Smith     Fries           40.00
Michael Smith  Burger          60.00      60.00
</code>```

答:
You didn't mention your DBMS so this is ANSI standard SQL:

```<code>select name, product, amount,
       case
         when row_Number() over (partition by name order by ????) = 1 then
            sum(amount) over (partition by name)
       end as total
from the_table
order by name, ???;
</code>```

Note that there is no such thing as "the first row" in a relational database. To identify the first one, you need a column that defines your order and that you can use for the order by. You need to replace both ??? with that column from your table

Title: SQL display total on the first row only

Body:
I want to display my data like this

Name             Product         Amount     Total
_______________________________________________
John Smith     Burger          60.00      100.00
John Smith     Fries           40.00
Michael Smith  Burger          60.00      60.00

Body:
You didn't mention your DBMS so this is ANSI standard SQL:

select name, product, amount,
       case
         when row_Number() over (partition by name order by ????) = 1 then
            sum(amount) over (partition by name)
       end as total
from the_table
order by name, ???;

Note that there is no such thing as "the first row" in a relational database. To identify the first one, you need a column that defines your order and that you can use for the order by. You need to replace both ??? with that column from your table


问:
how to change the amount of java memory heap for Jason-JEdit generated processes? [Linux]
how to change the amount of java memory heap for Jason-JEdit generated processes?

I'm running code edited in Jason-JEdit, as part of the application a NetLogo process is started, originated by the first one, but a heap size error appears.
The main process in Jason-Jedit is:

user  6006  6003  9 19:44 ?        00:00:02 java -Xms256m -Xmx1024m -classpath ~/Jacamo/lib/jacamo.jar:/usr/local/lib/netlogo5.2/NetLogo.jar:. -jar ~/Jason-1.4.2/bin/jedit/jedit.jar

The generated process from Jason-Jedit are:

1-The normal launcher process of the agent

user  6055  6006 11 19:44 ?        00:00:00 /usr/lib/jvm/java-7-oracle/bin/java -classpath ~/Jacamo/lib/ant-launcher.jar org.apache.tools.ant.launch.Launcher -e -f bin/build.xml run

2- The NetLogo lauched process

user  6069  6055 99 19:44 ?        00:00:05 /usr/lib/jvm/java-7-oracle/jre/bin/java -classpath ~/JaCaMo/workingDir:~/JaCaMo/workingDir/bin/classes:~/Jacamo/lib/jason.jar:/usr/local/lib/netlogo5.2/NetLogo.jar jason.infra.centralised.RunCentralisedMAS systemMAS-JNL.mas2j

As it can be seen the generated processes do not have the heap size option: -Xms256m -Xmx1024m, as the first one process does.

I already tried the following:
1) Edit the jason.sh/Jacamo.sh files adding:
java -Xms256m -Xmx1024m -classpath [...]

2) Add the variable _JAVA_OPTIONS in the .profile
export _JAVA_OPTIONS="-Xms256m -Xmx1024m"

And this works for the main process only, the Jason-Jedit application, but the problem persist in the generated process. Any idea about how to change the settings in JEdit?

答: I don't think this has anything to do with jEdit itself, as it is just shipped and used as editor and host for the custom plugin the jason project is providing. From a very short look at the plugin code, I'd say it generates an Ant build script that starts the RunCentralisedMAS class and it doesn't inject any jvmargs into this Ant build script. But the build-template.xml file has a commented-out line with jvmargs. So I guess if you search for the build-template.xml file and change it so that the jvmarg are set, it will work for you.


问:
Python: Read CSV file and write to another text file
I have this .csv file ...

```<code>    id,first_name,last_name,email,date,opt-in,unique_code
    1,Jimmy,Reyes,jreyes0@macromedia.com,12/29/2016,FALSE,ER45DH
    2,Doris,Wood,dwood1@1und1.de,04/22/2016,,MU34T3
    3,Steven,Miller,smiller2@go.com,07/31/2016,FALSE,G34FGH
    4,Earl,Parker,eparker3@ucoz.com,01-08-17,FALSE,ASY67J
    5,Barbara,Cruz,bcruz4@zdnet.com,12/30/2016,FALSE,NHG67P
</code>```

If the opt-in value is empty, its should print "0". The last value in csv should print first, and then all the name, value pairs in a specific format,  like shown in the expected output file below.

My expected output

```<code>ER45DH<tab>"id"="1","first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE"
MU34T3<tab>"id"="2","first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016,"opt-in"="0"
.......
</code>```

My code so far ..

```<code>import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        for i,rows in enumerate(reader):
            if i == 0:
               header = rows
            else:
                if rows[5] == '':
                   rows[5] = 0;
                pat = rows[0]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
                print pat
                f2.write(pat % tuple(header[1:]) % tuple(rows[1:]))
    f2.close()
</code>```

This code produces this output

```<code>1   "first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE","unique_code"="ASD34R"
2   "first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016","opt-in"="0","unique_code"="SDS56N"
</code>```

As you can see column "id" is missing, and I want unque_code at first place.

I will really appreciate any help/ideas/pointers.

Thanks

答:
You could just modify the way you enter your list in the file like this:

```<code># -*- encoding: utf-8 -*-
import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = list(csv.reader(infile))  # load the whole file as a list
        header = reader[0]  # the first line is your header
        for row in reader[1:]:  # content is all the other lines
            if row[5] == '':
                row[5] = 0
            line = row[-1]+'\t'  # adding the unique code
            for j, e in enumerate(row[:-2]):
                line += '"'+header[j]+'"="'+e+'",'  # adding elements in order
            f2.write(line[:-1]+'\n')  # writing line without last comma
</code>```

I modified a little bit the way you get the header, in order to avoid an unnecessary test for all the lines.

If your file is really big and/or you don't want to load it entirely in memory, you could modify to:

```<code>...
reader = csv.reader(infile)  # no conversion to list
header = next(reader)  # get first line
for row in reader:  # continue to read one line per loop
    ...
</code>```

Body:
I have this .csv file ...

    id,first_name,last_name,email,date,opt-in,unique_code
    1,Jimmy,Reyes,jreyes0@macromedia.com,12/29/2016,FALSE,ER45DH
    2,Doris,Wood,dwood1@1und1.de,04/22/2016,,MU34T3
    3,Steven,Miller,smiller2@go.com,07/31/2016,FALSE,G34FGH
    4,Earl,Parker,eparker3@ucoz.com,01-08-17,FALSE,ASY67J
    5,Barbara,Cruz,bcruz4@zdnet.com,12/30/2016,FALSE,NHG67P

If the opt-in value is empty, its should print "0". The last value in csv should print first, and then all the name, value pairs in a specific format,  like shown in the expected output file below.

My expected output

ER45DH<tab>"id"="1","first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE"
MU34T3<tab>"id"="2","first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016,"opt-in"="0"
.......

My code so far ..

import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        for i,rows in enumerate(reader):
            if i == 0:
               header = rows
            else:
                if rows[5] == '':
                   rows[5] = 0;
                pat = rows[0]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
                print pat
                f2.write(pat % tuple(header[1:]) % tuple(rows[1:]))
    f2.close()

This code produces this output

1   "first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE","unique_code"="ASD34R"
2   "first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016","opt-in"="0","unique_code"="SDS56N"

As you can see column "id" is missing, and I want unque_code at first place.

I will really appreciate any help/ideas/pointers.

Thanks

Body:
You could just modify the way you enter your list in the file like this:

# -*- encoding: utf-8 -*-
import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = list(csv.reader(infile))  # load the whole file as a list
        header = reader[0]  # the first line is your header
        for row in reader[1:]:  # content is all the other lines
            if row[5] == '':
                row[5] = 0
            line = row[-1]+'\t'  # adding the unique code
            for j, e in enumerate(row[:-2]):
                line += '"'+header[j]+'"="'+e+'",'  # adding elements in order
            f2.write(line[:-1]+'\n')  # writing line without last comma

I modified a little bit the way you get the header, in order to avoid an unnecessary test for all the lines.

If your file is really big and/or you don't want to load it entirely in memory, you could modify to:

...
reader = csv.reader(infile)  # no conversion to list
header = next(reader)  # get first line
for row in reader:  # continue to read one line per loop
    ...


问:
How can I force Master Render event to fire with partial rendering enabled?
I have some code in the Render event of my Master page that needs to be run on every postback, as it's used to translate some of the HTML content. However, the event does not seem to trigger on postback when I'm using an UpdatePanel and a ScriptManager with partial rendering set to true. Can I force the event to fire, or can I run my code elsewhere to produce the same result?</p>

```<code>protected override void Render(HtmlTextWriter writer)
{
    string originalContent = String.Empty;
    string translatedContent = String.Empty;

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            base.Render(htw);
            htw.Close();

            originalContent = sw.ToString();
        }
    }

    // Translate content:
    translatedContent = ApplyGlobalization(Page, originalContent);

    // Write updated HTML:
    writer.Write(translatedContent);
}
</code>```

答: Solved the problem by creating my own UpdatePanel with Render overridden. I put the same code into that method, but had to make some changes to adjust to the translation method to accustom to the special output that the UpdatePanel creates on partial postback.</p>

Body:
I have some code in the Render event of my Master page that needs to be run on every postback, as it's used to translate some of the HTML content. However, the event does not seem to trigger on postback when I'm using an UpdatePanel and a ScriptManager with partial rendering set to true. Can I force the event to fire, or can I run my code elsewhere to produce the same result?

protected override void Render(HtmlTextWriter writer)
{
    string originalContent = String.Empty;
    string translatedContent = String.Empty;

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            base.Render(htw);
            htw.Close();

            originalContent = sw.ToString();
        }
    }

    // Translate content:
    translatedContent = ApplyGlobalization(Page, originalContent);

    // Write updated HTML:
    writer.Write(translatedContent);
}


问:
Dragging composite objects in Unity
I am writing a card game in Unity2D that requires dragging a card to a table that has fixed positions.
The card is a composite gameobject that contains these items:

Parent -> Empty

BG -> Image

MID -> Image

FG -> Image

Values -> Text

I want to be able to drag the card to the table and remove it from the player's hand.
While i have found some implementations of drag/drop they all seem to rely on dragging a single image and not a gameobject.
What can i use to accomplish this?
Thanks in advance

答:
Implement IBeginDragHandler, IDragHandler, IEndDragHandler interfaces in your script that is attached to the draggable game object.

```<code>public void OnBeginDrag(PointerEventData eventData) {
    // Set parent to a RectTransform that is in front of everything else
    this.transform.SetParent(draggablesRoot);
}

public void OnDrag(PointerEventData eventData) {
    this.transform.position = eventData.position;
}

public void OnEndDrag(PointerEventData eventData) {
    // Use "EventSystem.current.RaycastAll()" to detect whether the object was dropped onto the correct panel
}
</code>```

Title: Dragging composite objects in Unity

Body:
Implement IBeginDragHandler, IDragHandler, IEndDragHandler interfaces in your script that is attached to the draggable game object.

public void OnBeginDrag(PointerEventData eventData) {
    // Set parent to a RectTransform that is in front of everything else
    this.transform.SetParent(draggablesRoot);
}

public void OnDrag(PointerEventData eventData) {
    this.transform.position = eventData.position;
}

public void OnEndDrag(PointerEventData eventData) {
    // Use "EventSystem.current.RaycastAll()" to detect whether the object was dropped onto the correct panel
}


问:
Is it possible to calculate the return type of a Rust function or trait method based on its arguments?
Can I achieve something similar to boost::math::tools::promote_args in Rust? See also Idiomatic C++11 type promotion

To be more specific: is it possible to calculate the return type of a function or trait method based on its arguments and ensure, that the return type has the same type as one of the arguments?

Consider the following case. I have two structs:

```<code>#[derive(Debug, Clone, Copy)]
struct MySimpleType(f64);

#[derive(Debug, Clone, Copy)]
struct MyComplexType(f64, f64);
</code>```

where MySimpleType can be promoted to MyComplexType via the From trait.

```<code>impl From<MySimpleType> for MyComplexType {
    fn from(src: MySimpleType) -> MyComplexType {
        let MySimpleType(x1) = src;
        MyComplexType(x1, 0.0)
    }
 }
</code>```

I want to write a function that takes two arguments of types MySimpleType or MyComplexType and return a value of type MySimpleType if all arguments are typed as MySimpleType, otherwise the function should return a value of type MyComplexType. Assuming I have implemented Add<Output=Self> for both types I could do something like this:

```<code>trait Foo<S, T> {
    fn foo(s: S, t: T) -> Self;
}

impl<S, T, O> Foo<S, T> for O
    where O: From<S> + From<T> + Add<Output = Self>
{
    fn foo(s: S, t: T) -> Self {
        let s: O = From::from(s);
        let t: O = From::from(t);
        s + t
    }
}
</code>```

but then the compiler doesn't know that O should be either S or T and I have to annotate most method calls.

My second attempt is to use a slightly different trait and write two implementations:

```<code>trait Foo<S, T> {
    fn foo(s: S, t: T) -> Self;
}

impl Foo<MySimpleType, MySimpleType> for MySimpleType {
    fn foo(s: MySimpleType, t: MySimpleType) -> Self {
        s + t
    }
}

impl<S, T> Foo<S, T> for MyComplexType
    where MyComplexType: From<S> + From<T>
{
    fn foo(s: S, t: T) -> Self {
        let s: MyComplexType = From::from(s);
        let t: MyComplexType = From::from(t);
        s + t
    }
}
</code>```

but again, the compiler isn't able to figure the return type of

```<code>Foo::foo(MySimpleType(1.0), MySimpleType(1.0))
</code>```

The third attempt is something similar to the std::ops::{Add, Mul, ...}. Use an associated type and write a specific implementation for each possible combination of argument types

```<code>trait Foo<T> {
    type Output;
    fn foo(self, t: T) -> Self::Output;
}

impl<T: Add<Output=T>> Foo<T> for T {
    type Output = Self;
    fn foo(self, t: T) -> Self::Output {
        self + t
    }
}

impl Foo<MySimpleType> for MyComplexType {
    type Output = Self;
    fn foo(self, t: MySimpleType) -> Self::Output {
        let t: Self = From::from(t);
        self + t
    }
}

impl Foo<MyComplexType> for MySimpleType {
    type Output = MyComplexType;
    fn foo(self, t: MyComplexType) -> Self::Output {
        let s: MyComplexType = From::from(self);
        s + t
    }
}
</code>```

This seems to be the best solution until one needs a function with n arguments. Because then one has to write 2^n - n + 1 impl statements. Of course, this gets even worse if more then two types being considered.

===

Edit:

In my code I've multiple nested function calls and I want to avoid non necessary type promotion, since the evaluation of the functions for the simple type is cheap and expensive for the complex type. By using @MatthieuM. 's proposed solution, this is not achieved. Please consider the following example

```<code>#![feature(core_intrinsics)]

use std::ops::Add;

trait Promote<Target> {
    fn promote(self) -> Target;
}

impl<T> Promote<T> for T {
    fn promote(self) -> T {
        self
    }
}

impl Promote<u64> for u32 {
    fn promote(self) -> u64 {
        self as u64
    }
}

fn foo<Result, Left, Right>(left: Left, right: Right) -> Result
    where Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    println!("============\nFoo called");
    println!("Left: {}", unsafe { std::intrinsics::type_name::<Left>() });
    println!("Right: {}",
            unsafe { std::intrinsics::type_name::<Right>() });
    println!("Result: {}",
            unsafe { std::intrinsics::type_name::<Result>() });
    left.promote() + right.promote()
}

fn bar<Result, Left, Right>(left: Left, right: Right) -> Result
    where Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    left.promote() + right.promote()
}

fn baz<Result, A, B, C, D>(a: A, b: B, c: C, d: D) -> Result
    where A: Promote<Result>,
        B: Promote<Result>,
        C: Promote<Result>,
        D: Promote<Result>,
        Result: Add<Output = Result>
{
    let lhs = foo(a, b).promote();
    let rhs = bar(c, d).promote();
    lhs + rhs
}

fn main() {
    let one = baz(1u32, 1u32, 1u64, 1u32);
    println!("{}", one);
}
</code>```

答:
I would expect the simplest way to implement promotion is to create a Promote trait:

```<code>trait Promote<Target> {
    fn promote(self) -> Target;
}

impl<T> Promote<T> for T {
    fn promote(self) -> T { self }
}
</code>```

Note: I provide a blanket implementation as all types can be promoted to themselves.

Using associated types is NOT an option here, because a single type can be promoted to multiple types; thus we just use a regular type parameter.

Using this, a simple example is:

```<code>impl Promote<u64> for u32 {
    fn promote(self) -> u64 { self as u64 }
}

fn add<Result, Left, Right>(left: Left, right: Right) -> Result
    where
        Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    left.promote() + right.promote()
}

fn main() {
    let one: u32 = add(1u32, 1u32);
    let two: u64 = add(1u32, 2u64);
    let three: u64 = add(2u64, 1u32);
    let four: u64 = add(2u64, 2u64);
    println!("{} {} {} {}", one, two, three, four);
}
</code>```

The only issue is that in the case of two u32 arguments, the result type must be specified otherwise the compiler cannot choose between which possible Promote implementation to use: Promote<u32> or Promote<u64>.

I am not sure if this is an issue in practice, however, since at some point you should have a concrete type to anchor type inference. For example:

```<code>fn main() {
    let v = vec![add(1u32, 1u32), add(1u32, 2u64)];
    println!("{:?}", v);
}
</code>```

compiles without type hint, because add(1u32, 2u64) can only be u64, and therefore since a Vec is a homogeneous collection, add(1u32, 1u32) has to return a u64 here.

As you experienced, though, sometimes you need the ability to direct the result beyond what type inference can handle. It's fine, you just need another trait for it:

```<code>trait PromoteTarget {
    type Output;
}

impl<T> PromoteTarget for (T, T) {
    type Output = T;
}
</code>```

And then a little implementation:

```<code>impl PromoteTarget for (u32, u64) {
    type Output = u64;
}

impl PromoteTarget for (u64, u32) {
    type Output = u64;
}
</code>```

With that out of the way, we can rewrite baz signature to correctly account for all intermediate types. Unfortunately I don't know any way to introduce aliases in a where clause, so brace yourself:

```<code>fn baz<Result, A, B, C, D>(a: A, b: B, c: C, d: D) -> Result
    where
        A: Promote<<(A, B) as PromoteTarget>::Output>,
        B: Promote<<(A, B) as PromoteTarget>::Output>,
        C: Promote<<(C, D) as PromoteTarget>::Output>,
        D: Promote<<(C, D) as PromoteTarget>::Output>,
        (A, B): PromoteTarget,
        (C, D): PromoteTarget,
        <(A, B) as PromoteTarget>::Output: Promote<Result> + Add<Output = <(A, B) as PromoteTarget>::Output>,
        <(C, D) as PromoteTarget>::Output: Promote<Result> + Add<Output = <(C, D) as PromoteTarget>::Output>,
        Result: Add<Output = Result>
{
    let lhs = foo(a, b).promote();
    let rhs = bar(c, d).promote();
    lhs + rhs
}
</code>```

Link to the playground here, so you can check the result:

```<code>============
Foo called
Left: u32
Right: u32
Result: u32
4
</code>```

Body:
Can I achieve something similar to boost::math::tools::promote_args in Rust? See also Idiomatic C++11 type promotion

To be more specific: is it possible to calculate the return type of a function or trait method based on its arguments and ensure, that the return type has the same type as one of the arguments?

Consider the following case. I have two structs:

#[derive(Debug, Clone, Copy)]
struct MySimpleType(f64);

#[derive(Debug, Clone, Copy)]
struct MyComplexType(f64, f64);

where MySimpleType can be promoted to MyComplexType via the From trait.

impl From<MySimpleType> for MyComplexType {
    fn from(src: MySimpleType) -> MyComplexType {
        let MySimpleType(x1) = src;
        MyComplexType(x1, 0.0)
    }
 }

I want to write a function that takes two arguments of types MySimpleType or MyComplexType and return a value of type MySimpleType if all arguments are typed as MySimpleType, otherwise the function should return a value of type MyComplexType. Assuming I have implemented Add<Output=Self> for both types I could do something like this:

trait Foo<S, T> {
    fn foo(s: S, t: T) -> Self;
}

impl<S, T, O> Foo<S, T> for O
    where O: From<S> + From<T> + Add<Output = Self>
{
    fn foo(s: S, t: T) -> Self {
        let s: O = From::from(s);
        let t: O = From::from(t);
        s + t
    }
}

but then the compiler doesn't know that O should be either S or T and I have to annotate most method calls.

My second attempt is to use a slightly different trait and write two implementations:

trait Foo<S, T> {
    fn foo(s: S, t: T) -> Self;
}

impl Foo<MySimpleType, MySimpleType> for MySimpleType {
    fn foo(s: MySimpleType, t: MySimpleType) -> Self {
        s + t
    }
}

impl<S, T> Foo<S, T> for MyComplexType
    where MyComplexType: From<S> + From<T>
{
    fn foo(s: S, t: T) -> Self {
        let s: MyComplexType = From::from(s);
        let t: MyComplexType = From::from(t);
        s + t
    }
}

but again, the compiler isn't able to figure the return type of

Foo::foo(MySimpleType(1.0), MySimpleType(1.0))

The third attempt is something similar to the std::ops::{Add, Mul, ...}. Use an associated type and write a specific implementation for each possible combination of argument types

trait Foo<T> {
    type Output;
    fn foo(self, t: T) -> Self::Output;
}

impl<T: Add<Output=T>> Foo<T> for T {
    type Output = Self;
    fn foo(self, t: T) -> Self::Output {
        self + t
    }
}

impl Foo<MySimpleType> for MyComplexType {
    type Output = Self;
    fn foo(self, t: MySimpleType) -> Self::Output {
        let t: Self = From::from(t);
        self + t
    }
}

impl Foo<MyComplexType> for MySimpleType {
    type Output = MyComplexType;
    fn foo(self, t: MyComplexType) -> Self::Output {
        let s: MyComplexType = From::from(self);
        s + t
    }
}

This seems to be the best solution until one needs a function with n arguments. Because then one has to write 2^n - n + 1 impl statements. Of course, this gets even worse if more then two types being considered.

===

Edit:

In my code I've multiple nested function calls and I want to avoid non necessary type promotion, since the evaluation of the functions for the simple type is cheap and expensive for the complex type. By using @MatthieuM. 's proposed solution, this is not achieved. Please consider the following example

#![feature(core_intrinsics)]

use std::ops::Add;

trait Promote<Target> {
    fn promote(self) -> Target;
}

impl<T> Promote<T> for T {
    fn promote(self) -> T {
        self
    }
}

impl Promote<u64> for u32 {
    fn promote(self) -> u64 {
        self as u64
    }
}

fn foo<Result, Left, Right>(left: Left, right: Right) -> Result
    where Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    println!("============\nFoo called");
    println!("Left: {}", unsafe { std::intrinsics::type_name::<Left>() });
    println!("Right: {}",
            unsafe { std::intrinsics::type_name::<Right>() });
    println!("Result: {}",
            unsafe { std::intrinsics::type_name::<Result>() });
    left.promote() + right.promote()
}

fn bar<Result, Left, Right>(left: Left, right: Right) -> Result
    where Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    left.promote() + right.promote()
}

fn baz<Result, A, B, C, D>(a: A, b: B, c: C, d: D) -> Result
    where A: Promote<Result>,
        B: Promote<Result>,
        C: Promote<Result>,
        D: Promote<Result>,
        Result: Add<Output = Result>
{
    let lhs = foo(a, b).promote();
    let rhs = bar(c, d).promote();
    lhs + rhs
}

fn main() {
    let one = baz(1u32, 1u32, 1u64, 1u32);
    println!("{}", one);
}

Body:
I would expect the simplest way to implement promotion is to create a Promote trait:

trait Promote<Target> {
    fn promote(self) -> Target;
}

impl<T> Promote<T> for T {
    fn promote(self) -> T { self }
}

Note: I provide a blanket implementation as all types can be promoted to themselves.

Using associated types is NOT an option here, because a single type can be promoted to multiple types; thus we just use a regular type parameter.

Using this, a simple example is:

impl Promote<u64> for u32 {
    fn promote(self) -> u64 { self as u64 }
}

fn add<Result, Left, Right>(left: Left, right: Right) -> Result
    where
        Left: Promote<Result>,
        Right: Promote<Result>,
        Result: Add<Output = Result>
{
    left.promote() + right.promote()
}

fn main() {
    let one: u32 = add(1u32, 1u32);
    let two: u64 = add(1u32, 2u64);
    let three: u64 = add(2u64, 1u32);
    let four: u64 = add(2u64, 2u64);
    println!("{} {} {} {}", one, two, three, four);
}

The only issue is that in the case of two u32 arguments, the result type must be specified otherwise the compiler cannot choose between which possible Promote implementation to use: Promote<u32> or Promote<u64>.

I am not sure if this is an issue in practice, however, since at some point you should have a concrete type to anchor type inference. For example:

fn main() {
    let v = vec![add(1u32, 1u32), add(1u32, 2u64)];
    println!("{:?}", v);
}

compiles without type hint, because add(1u32, 2u64) can only be u64, and therefore since a Vec is a homogeneous collection, add(1u32, 1u32) has to return a u64 here.

As you experienced, though, sometimes you need the ability to direct the result beyond what type inference can handle. It's fine, you just need another trait for it:

trait PromoteTarget {
    type Output;
}

impl<T> PromoteTarget for (T, T) {
    type Output = T;
}

And then a little implementation:

impl PromoteTarget for (u32, u64) {
    type Output = u64;
}

impl PromoteTarget for (u64, u32) {
    type Output = u64;
}

With that out of the way, we can rewrite baz signature to correctly account for all intermediate types. Unfortunately I don't know any way to introduce aliases in a where clause, so brace yourself:

fn baz<Result, A, B, C, D>(a: A, b: B, c: C, d: D) -> Result
    where
        A: Promote<<(A, B) as PromoteTarget>::Output>,
        B: Promote<<(A, B) as PromoteTarget>::Output>,
        C: Promote<<(C, D) as PromoteTarget>::Output>,
        D: Promote<<(C, D) as PromoteTarget>::Output>,
        (A, B): PromoteTarget,
        (C, D): PromoteTarget,
        <(A, B) as PromoteTarget>::Output: Promote<Result> + Add<Output = <(A, B) as PromoteTarget>::Output>,
        <(C, D) as PromoteTarget>::Output: Promote<Result> + Add<Output = <(C, D) as PromoteTarget>::Output>,
        Result: Add<Output = Result>
{
    let lhs = foo(a, b).promote();
    let rhs = bar(c, d).promote();
    lhs + rhs
}

Link to the playground here, so you can check the result:

============
Foo called
Left: u32
Right: u32
Result: u32
4


问:
Problem with adding to list inside a loop in java
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

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

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}
</code>```

And this is the result I got after running:

```<code>current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New
</code>```

Please help!!!!

答:
I assume you are new to java.
And I also assume that this is a sample program, or some sort of an exercise.

You want to check whether a list contains an array. You are using list.contains which is correct.

The problem is how you are constructing the array.

In the following snippet

```<code>   int [] f = new int [2];

   for(int i=0; i<2; i++)
   {
      for(int j=0; j<2; j++)
      {
         f[0] = i;
         f[1] = j;
         list.add(f);
      }
  }
</code>```

there is only one array you are constructing, outside the for loop.

You are actually adding to the same array again and again.
And adding this array again and again to the list. The list will contain 4 elements, but all 4 will refer to the same array.

If you want the list to contain different elements, then you have to create them first:

```<code>for(int i=0; i<2; i++)
       {
          for(int j=0; j<2; j++)
          {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = j;
             list.add(f);
          }
      }
</code>```

Coming to your contains check:

Your check will always be false, because the list G will always be empty (from the code you have given) you are not adding anything to it.

Since G.contains... check will always be false (G contains nothing), all the elements will be added to New.

If you want to have some sample code to understand contains, you might want to add something to G first.

```<code>       for(int i=0; i<2; i++)
       {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = i;
             G.add(f);
       }

     //G will now contain [0,0] and [1,1]

       for(int i=0; i<2; i++)
       {
          for(int j=0; j<2; j++)
          {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = j;
             if(!G.contains(f))
             {
                New.add(f); //Will add only [0,1] and [1,0]
             }
          }
      }
</code>```

Final notes: In java, it is conventional to have lowercase variable names.
Perhaps not very importane for a sample program, but try to have meaningful variable names. Names like f and G don't convey much.

Body:
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

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

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}

And this is the result I got after running:

current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New

Please help!!!!

Body:
I assume you are new to java.
And I also assume that this is a sample program, or some sort of an exercise.

You want to check whether a list contains an array. You are using list.contains which is correct.

The problem is how you are constructing the array.

In the following snippet

   int [] f = new int [2];

   for(int i=0; i<2; i++)
   {
      for(int j=0; j<2; j++)
      {
         f[0] = i;
         f[1] = j;
         list.add(f);
      }
  }

there is only one array you are constructing, outside the for loop.

You are actually adding to the same array again and again.
And adding this array again and again to the list. The list will contain 4 elements, but all 4 will refer to the same array.

If you want the list to contain different elements, then you have to create them first:

for(int i=0; i<2; i++)
       {
          for(int j=0; j<2; j++)
          {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = j;
             list.add(f);
          }
      }

Coming to your contains check:

Your check will always be false, because the list G will always be empty (from the code you have given) you are not adding anything to it.

Since G.contains... check will always be false (G contains nothing), all the elements will be added to New.

If you want to have some sample code to understand contains, you might want to add something to G first.

       for(int i=0; i<2; i++)
       {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = i;
             G.add(f);
       }

     //G will now contain [0,0] and [1,1]

       for(int i=0; i<2; i++)
       {
          for(int j=0; j<2; j++)
          {
             int [] f = new int [2]; //<-- new array everytime
             f[0] = i;
             f[1] = j;
             if(!G.contains(f))
             {
                New.add(f); //Will add only [0,1] and [1,0]
             }
          }
      }

Final notes: In java, it is conventional to have lowercase variable names.
Perhaps not very importane for a sample program, but try to have meaningful variable names. Names like f and G don't convey much.


问:
Very slow sql query for count
I need get report count for each user role, but my sql query very slow (40 sec on good server). My sql query:

```<code>SELECT `auth_assignment`.`item_name`, COUNT(*) as count
FROM `report`
LEFT JOIN `company` ON company.id = report.company_id
LEFT JOIN `auth_assignment`
ON auth_assignment.user_id = company.user_id
GROUP BY `auth_assignment`.`item_name`
ORDER BY `count`
</code>```

auth_assignment.item_name is role type.

auth_assignment has ~23k rows.
company ~11k rows.

reports ~12k rows (one company can have many reports).

report.id and company.id, have binding

答:
First, you are aggregating on a column from the third table in a left join.  I'm guessing you don't want NULL for the value, so use inner join or change the order of the tables.

Table aliases make the query easier to write and to read:

```<code>SELECT aa.item_name, COUNT(*) as cnt
FROM report r JOIN
     company c
     ON c.id = r.company_id JOIN
     auth_assignment aa
     ON aa.user_id = c.user_id
GROUP BY aa.item_name
ORDER BY cnt;
</code>```

Assuming the join's are correct for the tables, then you just want to be sure that you have indexes.  These should go on the columns used for the joins:  company(id, user_id), auth_assignment(user_id, item_name).

Title: Very slow sql query for count

Body:
I need get report count for each user role, but my sql query very slow (40 sec on good server). My sql query:

SELECT `auth_assignment`.`item_name`, COUNT(*) as count
FROM `report`
LEFT JOIN `company` ON company.id = report.company_id
LEFT JOIN `auth_assignment`
ON auth_assignment.user_id = company.user_id
GROUP BY `auth_assignment`.`item_name`
ORDER BY `count`

auth_assignment.item_name is role type.

auth_assignment has ~23k rows.
company ~11k rows.

reports ~12k rows (one company can have many reports).

report.id and company.id, have binding

Body:
First, you are aggregating on a column from the third table in a left join.  I'm guessing you don't want NULL for the value, so use inner join or change the order of the tables.

Table aliases make the query easier to write and to read:

SELECT aa.item_name, COUNT(*) as cnt
FROM report r JOIN
     company c
     ON c.id = r.company_id JOIN
     auth_assignment aa
     ON aa.user_id = c.user_id
GROUP BY aa.item_name
ORDER BY cnt;

Assuming the join's are correct for the tables, then you just want to be sure that you have indexes.  These should go on the columns used for the joins:  company(id, user_id), auth_assignment(user_id, item_name).


问:
Build Failed 'duplicate entry: com/google/api/client/googleapis/auth/clientlogin/ClientLogin$Response.class
Error description:

```<code>    Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/api/client/googleapis/auth/clientlogin/ClientLogin$Response.class
</code>```

build.gradle code here

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '23.0.3'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.jasp.eventapp"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.8.2'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.couchbase.lite:couchbase-lite-android:1.4-46'
    //compile 'com.google.api-client:google-api-client-android:1.22.0'
    //compile 'com.google.api-client:google-api-client-xml:1.22.0'
    compile 'com.google.api.client:google-api-client:1.4.1-beta'
    compile 'com.google.api-client:google-api-client-jackson2:1.22.0'
    compile files('libs/google-api-client-1.5.0-beta.jar')
    compile 'com.google.android.gms:play-services:9.2.1'
}
</code>```

Any version problem in imported libs...?How can I handle this...?I tried by cleaning the project
Build - > Clean
after that rebuild, But no effect...Can any one please help me...

答:
This error occurs when you are using duplicate version of same library, or when you use a library project which has same dependency

```<code>compile 'com.google.api.client:google-api-client:1.4.1-beta'
compile 'com.google.api-client:google-api-client-jackson2:1.22.0'
compile files('libs/google-api-client-1.5.0-beta.jar')
</code>```

these three looks like same library , removing duplicate version of the library should fix your error

Body:
Error description:

    Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/api/client/googleapis/auth/clientlogin/ClientLogin$Response.class

build.gradle code here

apply plugin: 'com.android.application'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '23.0.3'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.jasp.eventapp"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.8.2'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.couchbase.lite:couchbase-lite-android:1.4-46'
    //compile 'com.google.api-client:google-api-client-android:1.22.0'
    //compile 'com.google.api-client:google-api-client-xml:1.22.0'
    compile 'com.google.api.client:google-api-client:1.4.1-beta'
    compile 'com.google.api-client:google-api-client-jackson2:1.22.0'
    compile files('libs/google-api-client-1.5.0-beta.jar')
    compile 'com.google.android.gms:play-services:9.2.1'
}

Any version problem in imported libs...?How can I handle this...?I tried by cleaning the project
Build - > Clean
after that rebuild, But no effect...Can any one please help me...

Body:
This error occurs when you are using duplicate version of same library, or when you use a library project which has same dependency

compile 'com.google.api.client:google-api-client:1.4.1-beta'
compile 'com.google.api-client:google-api-client-jackson2:1.22.0'
compile files('libs/google-api-client-1.5.0-beta.jar')

these three looks like same library , removing duplicate version of the library should fix your error


问:
How can I correct the calling URL?
I am making a basic login based project using Servlets in Eclipse IDE. I have made a jdbc file that first validates the user from the database and then redirects the page to the welcome page, that is an html file.
Everything is saved in their default folders. But everytime I try to execute my project, I get this error - . The called URL here is localhost:8080/Diary/welcome but the called URL should be localhost:8080/Diary/welcome.html.
How can I solve it?

Login.java:

```<code>import java.sql.*;
public class Login {

    public static boolean validate(String user,String pass){
        boolean status=false;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Diary", "root", "root");
            PreparedStatement ps=con.prepareStatement("SELECT * FROM trial WHERE user=? and pass=? and authorized=?");
            ps.setString(1,user);
            ps.setString(2,pass);
            ps.setString(3,"yes");
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                status=true;
            }

        }catch(Exception e){System.out.println(e);}

        return status;
    }
}
</code>```

LoginServlet.java:

```<code>import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
        String user=req.getParameter("user");
        String pass=req.getParameter("pass");
        if(Login.validate(user, pass)){
            out.println("you are successfully logged in!");
            req.getSession().setAttribute("login", "true");
            req.getSession().setAttribute("user", user);
            res.sendRedirect("welcome.html");

        }else{
            out.println("<p>Sorry, username or password error</p>");
            req.getRequestDispatcher("login.html").include(req, res);
        }

        out.close();
    }

}
</code>```

答: You are correctly redirecting to the 'welcome.html' file. There must be an interceptor in your project that removes the '.html' part.</p>

Title: How can I correct the calling URL?

Body:
I am making a basic login based project using Servlets in Eclipse IDE. I have made a jdbc file that first validates the user from the database and then redirects the page to the welcome page, that is an html file.
Everything is saved in their default folders. But everytime I try to execute my project, I get this error - . The called URL here is localhost:8080/Diary/welcome but the called URL should be localhost:8080/Diary/welcome.html.
How can I solve it?

Login.java:

import java.sql.*;
public class Login {

    public static boolean validate(String user,String pass){
        boolean status=false;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Diary", "root", "root");
            PreparedStatement ps=con.prepareStatement("SELECT * FROM trial WHERE user=? and pass=? and authorized=?");
            ps.setString(1,user);
            ps.setString(2,pass);
            ps.setString(3,"yes");
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                status=true;
            }

        }catch(Exception e){System.out.println(e);}

        return status;
    }
}

LoginServlet.java:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
        String user=req.getParameter("user");
        String pass=req.getParameter("pass");
        if(Login.validate(user, pass)){
            out.println("you are successfully logged in!");
            req.getSession().setAttribute("login", "true");
            req.getSession().setAttribute("user", user);
            res.sendRedirect("welcome.html");

        }else{
            out.println("
Sorry, username or password error
");
            req.getRequestDispatcher("login.html").include(req, res);
        }

        out.close();
    }

}


问:
CGPoint(_,_) Requiring CGFloat Inputs on Linux
My Swift code runs fine in Xcode on my Mac, but when I deploy to my third-party Cloud hosting service built for server-side Swift I run into this problem.  I am getting the error: Cannot convert value of type 'Int' to expected argument type 'CGFloat' when using CGPoint(x: Int, y: Int). I would rather use an integer over a float.

I believe that this is an issue with Swift specifically on Linux.  In addition to this question, are there anyways to debug Swift on a Mac, but for a Linux environment? Also, what other inconsistencies does Swift for Linux have? I have found that arc4random is not supported and that Dispatch needs to be imported for any dispatch related code.

答:
On Linux (and other non-Apple platforms),
CGPoint is defined in NSGeometry.swift as part of the
swift-corelibs-foundation project.

As one can see in the source code, there is no initializer taking Int parameters, so you have to convert them explicitly:

```<code>let xVal: Int = ...
let yVal: Int = ...

let point = CGPoint(x: CGFloat(xVal), y: CGFloat(yVal))
</code>```

Body:
On Linux (and other non-Apple platforms),
CGPoint is defined in NSGeometry.swift as part of the
swift-corelibs-foundation project.

As one can see in the source code, there is no initializer taking Int parameters, so you have to convert them explicitly:

let xVal: Int = ...
let yVal: Int = ...

let point = CGPoint(x: CGFloat(xVal), y: CGFloat(yVal))


问:
Using Datumbox in Python for Sentiment Analysis
as I am relatively new to Python Programming I am not sure how to use Datumbox in a code properly. I need it to perform some sentiment analysis, however, I am not able to implement it by conda/pip install DatumBox as I would normally do!

The following stuff is available on github. DatumBox seems to be offered in many different programming languages but has no big community in Python so far:

https://github.com/Lily418/Datumbox-Python-Wrapper

How do I have to use the material from the link to use DatumBox as a module in Python? I already have an API KEY and now I want to implement it in my code import DatumBox etc.....

Many thanks in advance!

答:
You have to use this wrapper: https://github.com/irish315/Datumbox-Python-Wrapper</p>

```<code>$ git clone git@github.com:irish315/Datumbox-Python-Wrapper.git
$ cd Datumbox-Python-Wrapper
$ python
>>> from DatumBox import DatumBox
>>> datum_box = DatumBox(API_KEY)
>>> datum_box.twitter_sentiment_analysis("I love my cat")
u'positive'
</code>```

Body:
You have to use this wrapper: https://github.com/irish315/Datumbox-Python-Wrapper

$ git clone git@github.com:irish315/Datumbox-Python-Wrapper.git
$ cd Datumbox-Python-Wrapper
$ python
>>> from DatumBox import DatumBox
>>> datum_box = DatumBox(API_KEY)
>>> datum_box.twitter_sentiment_analysis("I love my cat")
u'positive'


问:
Generating a CSR with Security framework on iPhone app?
Anyone know how to generate a CSR from within an iPhone app to send to the CA?

If its not part of the security framework, then how is iPhone suppose to get certificate that authenticate it against a CA?

Thanks much!

答: I use developer.apple.com to manage these settings to app store/ provisioning profiles. </p>


问:
Javascript - How to use promises with multiple .then()
I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

```<code>-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)
</code>```

And my code is this:

```<code>var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });
</code>```

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then()
I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

Thank you

答:
You got it wrong.

First promise.prototype.then  resolve with just one Argument. Please  check     docs

And second thing promise return a promise, so you are just calling a query resolving there only, so no change in first resolved data and while chaining it will just pass the first data as it is

You can do this with two ways

First  One : By taking a global variable :

const $Vals = {};
function A() {
  return new Promise((resolve, reject) => {
    resolve([1, 2, 3])
  })
}

function B() {
  return new Promise((resolve, reject) => {
    resolve([4, 5, 6])
  })
}

A().then((dt) => {
  $Vals.A = dt;
  return B();
}).then((dt) => {
  $Vals.B = dt;
  console.log('%j', $Vals);
})
```

<p>output: {"A":[1,2,3],"B":[4,5,6]}</p>

<ul>
<li>Second which is more suitable by passing a custom promise :</li>
</ul>

<pre class="lang-js prettyprint-override"><code>A().then((dt) => new Promise((resolve) => {
  B().then((bData) => {
    resolve({
      A:dt,
      B:bData,
    })
  })
})).then((combined) => {
  console.log('%j', combined);
})

Output: {"A":[1,2,3],"B":[4,5,6]}
</code>```

Body:
I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)

And my code is this:

var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then()
I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

Thank you

Body:
You got it wrong.

First promise.prototype.then  resolve with just one Argument. Please  check     docs

And second thing promise return a promise, so you are just calling a query resolving there only, so no change in first resolved data and while chaining it will just pass the first data as it is

You can do this with two ways

First  One : By taking a global variable :

const $Vals = {};
function A() {
  return new Promise((resolve, reject) => {
    resolve([1, 2, 3])
  })
}

function B() {
  return new Promise((resolve, reject) => {
    resolve([4, 5, 6])
  })
}

A().then((dt) => {
  $Vals.A = dt;
  return B();
}).then((dt) => {
  $Vals.B = dt;
  console.log('%j', $Vals);
})

output: {"A":[1,2,3],"B":[4,5,6]}

Second which is more suitable by passing a custom promise :

A().then((dt) => new Promise((resolve) => {
  B().then((bData) => {
    resolve({
      A:dt,
      B:bData,
    })
  })
})).then((combined) => {
  console.log('%j', combined);
})

Output: {"A":[1,2,3],"B":[4,5,6]}


问:
Selenium: Wait for element's width to be greater than X
I have a page that does some processing and displays a progress bar.

I want to press the cancel button when the filling of the progress bar has at least 50% width.

How can I create a custom wait condition ?

```<code>    driver.findElement(By.id('bar')).then(function (stateEl) {
      // driver.wait(until. ?? By.xpath?
    }).then(done);
</code>```

答:
You can use explicit driver.wait functionality, where you return true or false value to release or hold the driver.

http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html#wait

You can do something like:

```<code>  driver.wait(function() {
    return Promise.all([
      driver.findElement(progressBarWrapper).getSize(),
      driver.findElement(progressBar).getSize()
    ]).then(function(sizes) {
      return (sizes[0].width / 2) <= sizes[1].width;
    });
  }, timeout);
</code>```

I assumed, that you have a wrapper (a box for your progress bar, its width is max width of progress bar) and the actual progress bar.

Body:
I have a page that does some processing and displays a progress bar.

I want to press the cancel button when the filling of the progress bar has at least 50% width.

How can I create a custom wait condition ?

    driver.findElement(By.id('bar')).then(function (stateEl) {
      // driver.wait(until. ?? By.xpath?
    }).then(done);

Body:
You can use explicit driver.wait functionality, where you return true or false value to release or hold the driver.

http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html#wait

You can do something like:

  driver.wait(function() {
    return Promise.all([
      driver.findElement(progressBarWrapper).getSize(),
      driver.findElement(progressBar).getSize()
    ]).then(function(sizes) {
      return (sizes[0].width / 2) <= sizes[1].width;
    });
  }, timeout);

I assumed, that you have a wrapper (a box for your progress bar, its width is max width of progress bar) and the actual progress bar.


问:
SystemJS will not load angular2 from node_modules
I am trying to add Angular2 to my current Angular 1.X projects. I am using yo angular project, with TypeScript enabled.

I installed everything (using npm install):

```<code><script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/node_modules/rxjs/bundles/Rx.js"></script>
<script src="/node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="/node_modules/angular2/bundles/http.dev.js"></script>
<script src="/node_modules/angular2/bundles/router.dev.js"></script>
</code>```

And I added the following config:

```<code>     <script>
        System.config({
          packages: {
            app: {
              format: 'cjs',
              defaultExtension: 'js'
            }
          },
          paths: {
            'angular2/upgrade': '../node_modules/angular2/upgrade'
          }

        });

         System.import('scripts/bootstrap.js').then(null, console.error.bind(console));

    </script>
</code>```

Now, inside my Bootstrap.ts I use:

```<code>import {UpgradeAdapter} from 'angular2/upgrade';
</code>```

Typescript knows how to transpile it, into my .tmp:

```<code>var upgrade_1 = require('angular2/upgrade');
</code>```

But SystemJS doesn't know how to load the import. I am getting 404 error:

```<code>GET http://localhost:9000/node_modules/angular2/upgrade 404 (Not Found)
</code>```

My directory structure:

```<code>root
- .tmp
- node_modules
- app
|-- index.html
|-- scripts
</code>```

What am I missing here?

答:
Consider the approach taken by the Angular2 quickstart project as best practice.

Here we see in index.html they, using script tags, load ..

```<code><script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
</code>```

This ensures all dependencies and shims are in place. Everything else should be loaded on demand using SystemJS.

This ensures that NOT everything is loaded up front but is instead loaded as needed. That way the initial app load is much faster since less must be loaded. Modules such as RxJS, etc are then loaded when used.

The SystemJS code for loading ng2 is found in systemjs.config.js as listed here for ease of reference ..

```<code>/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js',
        meta: {
          './*.js': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

Don't forget files referenced in systemjs.config.js such as systemjs-angular-loader.js

Of course, these days we have the option of using Angular CLI to kick off our project for us without these headaches, Angular CLI uses Webpack. Despite this, I remain a staunch SystemJS fan because it implements a W3 standard that will remain with us! Webpack may be superceded by a newcomer at any time.

Body:
I am trying to add Angular2 to my current Angular 1.X projects. I am using yo angular project, with TypeScript enabled.

I installed everything (using npm install):

And I added the following config:

Now, inside my Bootstrap.ts I use:

import {UpgradeAdapter} from 'angular2/upgrade';

Typescript knows how to transpile it, into my .tmp:

var upgrade_1 = require('angular2/upgrade');

But SystemJS doesn't know how to load the import. I am getting 404 error:

GET http://localhost:9000/node_modules/angular2/upgrade 404 (Not Found)

My directory structure:

root
- .tmp
- node_modules
- app
|-- index.html
|-- scripts

What am I missing here?

Body:
Consider the approach taken by the Angular2 quickstart project as best practice.

Here we see in index.html they, using script tags, load ..

<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>

This ensures all dependencies and shims are in place. Everything else should be loaded on demand using SystemJS.

This ensures that NOT everything is loaded up front but is instead loaded as needed. That way the initial app load is much faster since less must be loaded. Modules such as RxJS, etc are then loaded when used.

The SystemJS code for loading ng2 is found in systemjs.config.js as listed here for ease of reference ..

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js',
        meta: {
          './*.js': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

Don't forget files referenced in systemjs.config.js such as systemjs-angular-loader.js

Of course, these days we have the option of using Angular CLI to kick off our project for us without these headaches, Angular CLI uses Webpack. Despite this, I remain a staunch SystemJS fan because it implements a W3 standard that will remain with us! Webpack may be superceded by a newcomer at any time.


问:
Button onClick event
For a study  Project I try to make a sidebar for an interactive map.

I have a button which trigger an onClick() Event which Shows
a
 with an form Input.

So far I have 3 questions.

1) Can I check if the button was already clicked so I can hide my additional Content again? If so, how can I achieve that?

2) At the Moment I only display the content but I would like to have  an Animation. Again, you may give me some Infos to do this or provide an link / tutorial.

3) Is there a better Solution for my Problem, if so. May you give me a hint?

function showDropdown(x) {
  let id = x;

  if (id == 1) {
    document.getElementById("1").style.display = "block";
    console.log(id);
  }

  if (id == 2) {
    document.getElementById("2").style.display = "block";
    console.log(id);
  }

  if (id == 3) {
    document.getElementById("3").style.display = "block";
    console.log(id);
  } else {
    console.log(id);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-sidebar>ul {
  display: none;
}</code>```

        <button type="button" onclick="showDropdown(1)" class="dropdown-header">Einwohner</button>

Feld 1:<input type="text" Placeholder="a" size="2"

Feld 2:<input type="text" Placeholder="b" size="2"

Feld 3:<input type="text" Placeholder="c" size="2"

```

答:
Use a data attribute and jQuery slidetoggle as I suggested in my comment.

Please note I do not like numeric IDs so I prefixed the ID with a u.

$(function() {
  $(".dropdown-header").on("click", function() {
    var id = $(this).attr("data-id");
    $("#" + id).slideToggle()
    console.log(id);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-sidebar>ul {
  display: none;
}</code>```

        <button type="button" data-id="u1" class="dropdown-header">Einwohner</button>

Feld 1: <input type="text" Placeholder="a" size="2" />

Feld 2: <input type="text" Placeholder="b" size="2" />

Feld 3: <input type="text" Placeholder="c" size="2" />

```

Title: Button onClick event

Body:
For a study  Project I try to make a sidebar for an interactive map.

I have a button which trigger an onClick() Event which Shows
a
 with an form Input.

So far I have 3 questions.

1) Can I check if the button was already clicked so I can hide my additional Content again? If so, how can I achieve that?

2) At the Moment I only display the content but I would like to have  an Animation. Again, you may give me some Infos to do this or provide an link / tutorial.

3) Is there a better Solution for my Problem, if so. May you give me a hint?

function showDropdown(x) {
  let id = x;

  if (id == 1) {
    document.getElementById("1").style.display = "block";
    console.log(id);
  }

  if (id == 2) {
    document.getElementById("2").style.display = "block";
    console.log(id);
  }

  if (id == 3) {
    document.getElementById("3").style.display = "block";
    console.log(id);
  } else {
    console.log(id);
  }
}

.nav-sidebar>ul {
  display: none;
}

        <button type="button" onclick="showDropdown(1)" class="dropdown-header">Einwohner</button>

Feld 1:<input type="text" Placeholder="a" size="2"

Feld 2:<input type="text" Placeholder="b" size="2"

Feld 3:<input type="text" Placeholder="c" size="2"

Body:
Use a data attribute and jQuery slidetoggle as I suggested in my comment.

Please note I do not like numeric IDs so I prefixed the ID with a u.

$(function() {
  $(".dropdown-header").on("click", function() {
    var id = $(this).attr("data-id");
    $("#" + id).slideToggle()
    console.log(id);
  });
});

.nav-sidebar>ul {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col-sm-3 col-md-2 sidebar">
      <div class="nav nav-sidebar">
        <button type="button" data-id="u1" class="dropdown-header">Einwohner</button>
        <ul class="dropdown-item" id="u1">
          <li>
            <p>Feld 1:&nbsp;<input type="text" Placeholder="a" size="2" /></p>
          </li>
          <li>
            <p>Feld 2:&nbsp;<input type="text" Placeholder="b" size="2" /></p>
          </li>
          <li>
            <p>Feld 3:&nbsp;<input type="text" Placeholder="c" size="2" /></p>
          </li>
        </ul>
      </div>
    </div>


问:
How to delay jquery step function response
I m using jQuery-step library with a form combining the formvalidation.js . i want to delay below method response until ajax complete.

i want to send return true/false when ajax complete.

```<code>onStepChanging: function (e, currentIndex, newIndex) {

    var fv = $stepForm.data('formValidation'), // FormValidation instance
        // The current step container
        $container = $stepForm.find('section[data-step="' + currentIndex + '"]');

    // Validate the container
    fv.validateContainer($container);
    var isValidStep = fv.isValidContainer($container);
    if (isValidStep === false || isValidStep === null) {
        // Do not jump to the next step
        return false;
    }
    if (isValidStep === true) {
        //call ajax here
        //wait for ajax to complete then move to next or keep
    }
    return true; //-> i want to delay this

},
</code>```

答:
I have done by setting property in javascript window then wrap the return in setTimeout function

Step 1:

```<code>$(document).ready(function(){ window.flag = ''; });
</code>```

Step 2

```<code>function submitForm($stepForm) {
    $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        success: function (data) {
          window.flag = true;
        }
}
</code>```

Step 3:

```<code>onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
                submitForm($stepForm);
  }
 .... code
  setTimeout(function () {
     return window.flag;
  }, 2000);
}
</code>```

Body:
I m using jQuery-step library with a form combining the formvalidation.js . i want to delay below method response until ajax complete.

i want to send return true/false when ajax complete.

onStepChanging: function (e, currentIndex, newIndex) {

    var fv = $stepForm.data('formValidation'), // FormValidation instance
        // The current step container
        $container = $stepForm.find('section[data-step="' + currentIndex + '"]');

    // Validate the container
    fv.validateContainer($container);
    var isValidStep = fv.isValidContainer($container);
    if (isValidStep === false || isValidStep === null) {
        // Do not jump to the next step
        return false;
    }
    if (isValidStep === true) {
        //call ajax here
        //wait for ajax to complete then move to next or keep
    }
    return true; //-> i want to delay this

},

Body:
I have done by setting property in javascript window then wrap the return in setTimeout function

Step 1:

$(document).ready(function(){ window.flag = ''; });

Step 2

function submitForm($stepForm) {
    $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        success: function (data) {
          window.flag = true;
        }
}

Step 3:

onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
                submitForm($stepForm);
  }
 .... code
  setTimeout(function () {
     return window.flag;
  }, 2000);
}


问:
Move a selectedNode Up and Down in Treelist By clicking Buttons
How to move selectedNode up and down when click the Up and down button. selectedNode always visible in treelist control. so that Treelist can scroll up and down.</p>

答:
Try this code, It might be helpful

```<code> if(mainTreelist.FocusedNode.Expanded)
            {
                mainTreelist.MoveNode(mainTreelist.FocusedNode, mainTreelist.FocusedNode.NextVisibleNode, true);
                mainTreelist.MakeNodeVisible(mainTreelist.FocusedNode);
            }
</code>```

Which moves the selected node to next node.

Body:
Try this code, It might be helpful

 if(mainTreelist.FocusedNode.Expanded)
            {
                mainTreelist.MoveNode(mainTreelist.FocusedNode, mainTreelist.FocusedNode.NextVisibleNode, true);
                mainTreelist.MakeNodeVisible(mainTreelist.FocusedNode);
            }

Which moves the selected node to next node.


问:
Angular2 QuickStart npm start is not working correctly

I know Angular2 beta has just been released but I can't reproduce the steps from their official site tutorial ( https://angular.io/guide/quickstart ). Maybe someone has had similar issues and knows what to do in order to fix the this? When I try to start the application with npm start command I get output like this:

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'node', '/usr/local/bin/npm', 'start' ]
2 info using npm@2.7.4
3 info using node@v0.12.2
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart angular2-quickstart@1.0.0
6 info start angular2-quickstart@1.0.0
7 verbose unsafe-perm in lifecycle true
8 info angular2-quickstart@1.0.0 Failed to exec start script
9 verbose stack Error: angular2-quickstart@1.0.0 start: `concurrent "npm run tsc:w" "npm run lite" `
9 verbose stack Exit status 127
9 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:213:16)
9 verbose stack     at EventEmitter.emit (events.js:110:17)
9 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:14:12)
9 verbose stack     at ChildProcess.emit (events.js:110:17)
9 verbose stack     at maybeClose (child_process.js:1015:16)
9 verbose stack     at Process.ChildProcess._handle.onexit (child_process.js:1087:5)
10 verbose pkgid angular2-quickstart@1.0.0
11 verbose cwd /Users/tmrovsky/Documents/angular2/angular2-quickstart
12 error Darwin 13.4.0
13 error argv "node" "/usr/local/bin/npm" "start"
14 error node v0.12.2
15 error npm  v2.7.4
16 error code ELIFECYCLE
17 error angular2-quickstart@1.0.0 start: `concurrent "npm run tsc:w" "npm run lite" `
17 error Exit status 127
18 error Failed at the angular2-quickstart@1.0.0 start script 'concurrent "npm run tsc:w" "npm run lite" '.
18 error This is most likely a problem with the angular2-quickstart package,
18 error not with npm itself.
18 error Tell the author that this fails on your system:
18 error     concurrent "npm run tsc:w" "npm run lite"
18 error You can get their info via:
18 error     npm owner ls angular2-quickstart
18 error There is likely additional logging output above.
19 verbose exit [ 1, true ]
</code>```

I had:
typescript 1.7.5 version
node 0.12.2 version

Maybe someone could help solve the problem :) ?

package.json:

```<code>{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.1",
    "typescript": "^1.7.3"
  }
}
</code>```

index.html:

```<code><html>

<head>
    <title>Angular 2 QuickStart</title>

    <!-- 1. Load libraries -->
    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/boot')
                .then(null, console.error.bind(console));
    </script>

</head>

<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>

</html>
</code>```

app.components.ts:

```<code>import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>',
})

export class AppComponent {}
</code>```

boot.js:

```<code>import {bootstrap} from 'angular2/platform/browser'
import  {AppComponent} from './app.component'

bootstrap(AppComponent);
</code>```

答: In my case ,I just needed to add a dummy .ts file.So I created a test.ts file with no contents and ran npm start to solve the problem.</p>

Body:
I know Angular2 beta has just been released but I can't reproduce the steps from their official site tutorial ( https://angular.io/guide/quickstart ). Maybe someone has had similar issues and knows what to do in order to fix the this? When I try to start the application with npm start command I get output like this:

0 info it worked if it ends with ok
1 verbose cli [ 'node', '/usr/local/bin/npm', 'start' ]
2 info using npm@2.7.4
3 info using node@v0.12.2
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart angular2-quickstart@1.0.0
6 info start angular2-quickstart@1.0.0
7 verbose unsafe-perm in lifecycle true
8 info angular2-quickstart@1.0.0 Failed to exec start script
9 verbose stack Error: angular2-quickstart@1.0.0 start: `concurrent "npm run tsc:w" "npm run lite" `
9 verbose stack Exit status 127
9 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:213:16)
9 verbose stack     at EventEmitter.emit (events.js:110:17)
9 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:14:12)
9 verbose stack     at ChildProcess.emit (events.js:110:17)
9 verbose stack     at maybeClose (child_process.js:1015:16)
9 verbose stack     at Process.ChildProcess._handle.onexit (child_process.js:1087:5)
10 verbose pkgid angular2-quickstart@1.0.0
11 verbose cwd /Users/tmrovsky/Documents/angular2/angular2-quickstart
12 error Darwin 13.4.0
13 error argv "node" "/usr/local/bin/npm" "start"
14 error node v0.12.2
15 error npm  v2.7.4
16 error code ELIFECYCLE
17 error angular2-quickstart@1.0.0 start: `concurrent "npm run tsc:w" "npm run lite" `
17 error Exit status 127
18 error Failed at the angular2-quickstart@1.0.0 start script 'concurrent "npm run tsc:w" "npm run lite" '.
18 error This is most likely a problem with the angular2-quickstart package,
18 error not with npm itself.
18 error Tell the author that this fails on your system:
18 error     concurrent "npm run tsc:w" "npm run lite"
18 error You can get their info via:
18 error     npm owner ls angular2-quickstart
18 error There is likely additional logging output above.
19 verbose exit [ 1, true ]

I had:
typescript 1.7.5 version
node 0.12.2 version

Maybe someone could help solve the problem :) ?

package.json:

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.1",
    "typescript": "^1.7.3"
  }
}

index.html:

    <title>Angular 2 QuickStart</title>

<my-app>Loading...</my-app>

app.components.ts:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '
My First Angular 2 App
',
})

export class AppComponent {}

boot.js:

import {bootstrap} from 'angular2/platform/browser'
import  {AppComponent} from './app.component'

bootstrap(AppComponent);


问:
Is it worth to migrate from Angular 2 to Angular 4?
Hello SO community and Angularians!

So, I am midway developing a huge platform in Angular 2. And I realized that many external libraries and dependencies for Angular 2 are migrating to the new Angular 4. Giving me many errors, obviously.

I could fork these libraries and use the forked versions and subscribe to main library development or, I could just upgrade to Angular 4 my project.

Questions to be answered in order to determinate if it's worth for me to migrate:

Compatibility with Angular 2.4

I have found some adaptations to ensure compatibility with legacy, like this: https://github.com/angular/angular/commit/e99d721

Changes app wide

Do I have to go through my whole app and start fixing things?

I mean, are main functionalities reworked in such way that I will have to review many of them?

Or, are there many build/core incompatibilities that will keep me days occupied fixing compile errors/warnings instead of developing?

I am not asking for someone to do the research for me, I am asking people that maybe already went through this process or simply know well both versions in order to give me some experience tips, clarifications, etc.

At the moment, I am doing my research here:

https://github.com/angular/angular/blob/master/CHANGELOG.md

http://angularjs.blogspot.it/2017/03/angular-400-now-available.html

https://learninglaravel.net/angular-4-new-features-and-improvements

UPDATE

I just migrated to Angular 4. The link that @PierreDuc put in his answer is a very nice tool to have a decent guideline in the migration process.

I would recommend:

Read new features and update yourself with Angular 4. This was specially useful: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html

Follow Angular's guideline and modify your project: https://angular-update-guide.firebaseapp.com/

I would also recommend to commit your current project, create a new branch in your dev repository and proceed with migration in that branch.

An issue that I encountered:

Input, Output and ContentChild will be imported from a wrong path.

My case:

```<code>import { Component, OnInit, OnDestro } from '@angular/core';
import { Input, ContentChild } from "@angular/core/src/metadata/directives";
</code>```

Solution:

```<code>import { Component, OnInit, OnDestroy, Input, ContentChild } from '@angular/core';
</code>```

答:
If you check the changelog there are a couple things you need to keep in mind:

Before updating

Ensure you don't use extends OnInit, or use extends with any lifecycle event. Instead use implements <lifecycle event>.

Stop using DefaultIterableDiffer, KeyValueDiffers#factories, or IterableDiffers#factories

Stop using deep imports, these symbols are now marked with ɵ and are
not part of our public API.

Stop using Renderer.invokeElementMethod as this method has been
removed. There is not currently a replacement.

During the update

Update all of your dependencies to version 4 and the latest typescript.

If you are using Linux/Mac, you can use: npm install
@angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@4.0.0
typescript@latest --save

If you use animations in your application, you should import
BrowserAnimationsModule from @angular/platform-browser/animations in
your App NgModule.

Replace RootRenderer with RendererFactory2.

Replace Renderer with Renderer2.

After the update

Rename your template tags to ng-template.

Replace OpaqueTokens with InjectionTokens.

If you call DifferFactory.create(...) remove the ChangeDetectorRef
argument.

Replace ngOutletContext with ngTemplateOutletContext.

Replace CollectionChangeRecord with IterableChangeRecord

source

Body:
Hello SO community and Angularians!

So, I am midway developing a huge platform in Angular 2. And I realized that many external libraries and dependencies for Angular 2 are migrating to the new Angular 4. Giving me many errors, obviously.

I could fork these libraries and use the forked versions and subscribe to main library development or, I could just upgrade to Angular 4 my project.

Questions to be answered in order to determinate if it's worth for me to migrate:

Compatibility with Angular 2.4

I have found some adaptations to ensure compatibility with legacy, like this: https://github.com/angular/angular/commit/e99d721

Changes app wide

Do I have to go through my whole app and start fixing things?

I mean, are main functionalities reworked in such way that I will have to review many of them?

Or, are there many build/core incompatibilities that will keep me days occupied fixing compile errors/warnings instead of developing?

I am not asking for someone to do the research for me, I am asking people that maybe already went through this process or simply know well both versions in order to give me some experience tips, clarifications, etc.

At the moment, I am doing my research here:

https://github.com/angular/angular/blob/master/CHANGELOG.md

http://angularjs.blogspot.it/2017/03/angular-400-now-available.html

https://learninglaravel.net/angular-4-new-features-and-improvements

UPDATE

I just migrated to Angular 4. The link that @PierreDuc put in his answer is a very nice tool to have a decent guideline in the migration process.

I would recommend:

Read new features and update yourself with Angular 4. This was specially useful: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html

Follow Angular's guideline and modify your project: https://angular-update-guide.firebaseapp.com/

I would also recommend to commit your current project, create a new branch in your dev repository and proceed with migration in that branch.

An issue that I encountered:

Input, Output and ContentChild will be imported from a wrong path.

My case:

import { Component, OnInit, OnDestro } from '@angular/core';
import { Input, ContentChild } from "@angular/core/src/metadata/directives";

Solution:

import { Component, OnInit, OnDestroy, Input, ContentChild } from '@angular/core';