问:
How to use a ProgressBar on a basic themed Splash Screen?
I'd like to replace ProgressDialog (which is deprecated) by ProgressBar in my Xamarin.Android application.

I have a Splash Screen which is a simple AppCompat Activity:

```<code>[Activity(Theme = "@style/MainTheme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/favicon", ScreenOrientation = ScreenOrientation.Portrait)]
public partial class SplashActivity : AppCompatActivity
{
   ProgressDialog m_loginProgress;
}
</code>```

With the following theme:

```<code><style name="MainTheme.Splash" parent ="Theme.AppCompat.Light">
    <item name="android:windowBackground">@drawable/splash_screen</item>
    <item name="android:windowNoTitle">true</item>
</style>
</code>```

OnCreate in the activity:

```<code>protected override async void OnCreate(Android.OS.Bundle savedInstanceState)
{
   base.OnCreate(savedInstanceState);

   m_loginProgress = ProgressDialog.Show(this, Resources.GetString(Resource.String.connecting), Resources.GetString(Resource.String.please_wait), true);
   await SomeCallAsync().ContinueWith(() => m_loginProgress.Dismiss());
}
</code>```

ProgressDialog was like "it just works". By that I mean:

The dialog is automatically centered on the screen

It has a title and a text.

User interactions are automatically disabled (not sure about that though)

Dismiss() would run on the UI thread automatically

Now I'm trying to use ProgressBar instead.

The code is a little trickier:

It seems that the underlying layout of the splash screen is of type ContentFrameLayout

I don't know how to center the ProgressBar because I can't have a Rule Added to a ContentFrameLayout.LayoutParams. I would need a RelativeLayout at a minimum.

I don't know how to add a simple text that is aligned with the progress bar

This is the code I have so far, and of course it does not work.

```<code>ContentFrameLayout layout = FindViewById<ContentFrameLayout>(Android.Resource.Id.Content);
var p1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
p1.AddRule(LayoutRules.CenterInParent);
m_loginProgress = new ProgressBar(this, null, Android.Resource.Attribute.ProgressBarStyleLarge);

m_loginProgress.Id = View.GenerateViewId();
m_loginProgress.LayoutParameters = p1;

layout.AddView(m_loginProgress);
var p2 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);

TextView tv = new TextView(this);

tv.LayoutParameters = p2;
tv.Text = Resources.GetString(Resource.String.please_wait);

// Disable user interactions
Window.SetFlags(WindowManagerFlags.NotTouchable, WindowManagerFlags.NotTouchable);
// Show the progress bar
m_loginProgress.Visibility = ViewStates.Visible;
</code>```

I'd like to know if I'm stuck and should create a content view for my splash screen.
If ProgressDialog works, ProgressBar should work too?

EDIT: OMG, I'm discovering that ProgressBar is not a dialog ! It is just the spinning circle. Everywhere I've red that ProgressDialog could be replaced by ProgressBar, but obviously this is more complicated than that.

The solution is to create a horizontal LinearLayout with the TextView and ProgressBar as children. Then add this linear layout as a child of the FrameLayout

答:
Please try to below link to set progress bar and change progress bar color using colorAccent in color.xml :-

https://www.javatpoint.com/android-progressbar-example

Body:
I'd like to replace ProgressDialog (which is deprecated) by ProgressBar in my Xamarin.Android application.

I have a Splash Screen which is a simple AppCompat Activity:

[Activity(Theme = "@style/MainTheme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/favicon", ScreenOrientation = ScreenOrientation.Portrait)]
public partial class SplashActivity : AppCompatActivity
{
   ProgressDialog m_loginProgress;
}

With the following theme:

OnCreate in the activity:

protected override async void OnCreate(Android.OS.Bundle savedInstanceState)
{
   base.OnCreate(savedInstanceState);

   m_loginProgress = ProgressDialog.Show(this, Resources.GetString(Resource.String.connecting), Resources.GetString(Resource.String.please_wait), true);
   await SomeCallAsync().ContinueWith(() => m_loginProgress.Dismiss());
}

ProgressDialog was like "it just works". By that I mean:

The dialog is automatically centered on the screen

It has a title and a text.

User interactions are automatically disabled (not sure about that though)

Dismiss() would run on the UI thread automatically

Now I'm trying to use ProgressBar instead.

The code is a little trickier:

It seems that the underlying layout of the splash screen is of type ContentFrameLayout

I don't know how to center the ProgressBar because I can't have a Rule Added to a ContentFrameLayout.LayoutParams. I would need a RelativeLayout at a minimum.

I don't know how to add a simple text that is aligned with the progress bar

This is the code I have so far, and of course it does not work.

ContentFrameLayout layout = FindViewById<ContentFrameLayout>(Android.Resource.Id.Content);
var p1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
p1.AddRule(LayoutRules.CenterInParent);
m_loginProgress = new ProgressBar(this, null, Android.Resource.Attribute.ProgressBarStyleLarge);

m_loginProgress.Id = View.GenerateViewId();
m_loginProgress.LayoutParameters = p1;

layout.AddView(m_loginProgress);
var p2 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);

TextView tv = new TextView(this);

tv.LayoutParameters = p2;
tv.Text = Resources.GetString(Resource.String.please_wait);

// Disable user interactions
Window.SetFlags(WindowManagerFlags.NotTouchable, WindowManagerFlags.NotTouchable);
// Show the progress bar
m_loginProgress.Visibility = ViewStates.Visible;

I'd like to know if I'm stuck and should create a content view for my splash screen.
If ProgressDialog works, ProgressBar should work too?

EDIT: OMG, I'm discovering that ProgressBar is not a dialog ! It is just the spinning circle. Everywhere I've red that ProgressDialog could be replaced by ProgressBar, but obviously this is more complicated than that.

The solution is to create a horizontal LinearLayout with the TextView and ProgressBar as children. Then add this linear layout as a child of the FrameLayout


来源: stackexchange

问:
Display MySQL Results vertically in terminal
Is there a way to show data from the table in a more clean way?
For example:
SHOW COLUMNS FROM my_table; shows a clean display of each column with the type of data it contains and this information is displayed vertically.

SELECT * FROM my_table WHERE uid=99999;
However, when I select one record from this table, the results are jumbled because the screen is not wide enough for a clean view. Is it possible to display the columns on the left instead when just looking at one row?

Thanks!

答:
The \G modifier in the MySQL command line client

A little publicized, but exceedingly useful feature of the MySQL command line client is the \G modifier. It formats the query output nicely, so you can read through it easier. To use it, you just replace the semi-colon at the end of the query with \G.

For example,

```<code>mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000193 |     7061 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

mysql> SHOW MASTER STATUS\G
*************************** 1. row ***************************
            File: mysql-bin.000193
        Position: 7061
    Binlog_Do_DB:
Binlog_Ignore_DB:
1 row in set (0.00 sec)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The \G modifier in the MySQL command line client

A little publicized, but exceedingly useful feature of the MySQL command line client is the \G modifier. It formats the query output nicely, so you can read through it easier. To use it, you just replace the semi-colon at the end of the query with \G.

For example,

mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000193 |     7061 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

mysql> SHOW MASTER STATUS\G
*************************** 1. row ***************************
            File: mysql-bin.000193
        Position: 7061
    Binlog_Do_DB:
Binlog_Ignore_DB:
1 row in set (0.00 sec)


问:
Table row onclick String value shows error in jquery
I have populated table from database in Ajax using json. But on click edit button only number field are passed to java script function. But when i want to pass  string like name, base64Encoding String not passed
Here is the java script code

```<code>'<a href="javascript:void(0)" onclick="doGet('+item.pohto+','+item.name+')" > <i class="fas fa-pencil-alt"></i> </a>';
</code>```

When I click on edit icon it shows bellow error

```<code>SyntaxError: missing ) after argument list
</code>```

But when I use only number value it is working.

Please help me to pass string value like image , name

答:
probably item.pohto or item.name is empty. therefor the function will look like doGet('value',) or doGet(,'value').

This will be interpreted as wrong Javascript syntax.

You should set a breakpoint in the console and check how the actual values look like.
Even better: make a function wich will take the full item value and check the existance of the needed attributes in the object for your self like this:

function performDoGet(item) {
  if (item['pohto'] && item['name']) {
    doGet(item.pohto, item.name);
  }
  else {
    console.log("Values are missing");
  }
}
```

<p>and change your clicklistener to following:</p>

<pre class="lang-js prettyprint-override"><code>'<i class="fas fa-pencil-alt"></i>';
</code>```

Body:
I have populated table from database in Ajax using json. But on click edit button only number field are passed to java script function. But when i want to pass  string like name, base64Encoding String not passed
Here is the java script code

'  ';

When I click on edit icon it shows bellow error

SyntaxError: missing ) after argument list

But when I use only number value it is working.

Please help me to pass string value like image , name

Body:
probably item.pohto or item.name is empty. therefor the function will look like doGet('value',) or doGet(,'value').

This will be interpreted as wrong Javascript syntax.

You should set a breakpoint in the console and check how the actual values look like.
Even better: make a function wich will take the full item value and check the existance of the needed attributes in the object for your self like this:

function performDoGet(item) {
  if (item['pohto'] && item['name']) {
    doGet(item.pohto, item.name);
  }
  else {
    console.log("Values are missing");
  }
}

and change your clicklistener to following:

'<a href="javascript:void(0)" onclick="performDoGet(' + item + ')"><i class="fas fa-pencil-alt"></i></a>';


问:
Unexpected behavior of generated bison parser
I created parser via Flex/Bison, which unexpectedly fails during parsing. Here is simplified sample which shows problem

Lexer.l:

```<code>%{
#include "Parser.h"
%}
%option noyywrap nodefault

%%
"foo"               {   return FOO;                          }
"bar"               {   return BAR;                          }
"("                 {   return OP;                           }
")"                 {   return CP;                           }
[ \t\n]+            {   /*    DO NOTHING  */                 }
.                   {   YY_FATAL_ERROR("unknown character"); }
%%
</code>```

And Parser.y (with enabled tracing and verbosity):

```<code>%{
#include <stdio.h>
int yylex();
void yyerror (char const *s);
%}

%debug
%verbose
%error-verbose
%token FOO BAR OP CP

%%
program_expr :   foo_expr bar_expr   {}
;
foo_expr :   /*  NOTHING  */  {}
    |   OP FOO CP           {}
;
bar_expr :   /*  NOTHING  */  {}
    |   OP BAR CP           {}
;
%%

int main(int argc, char** argv)
{
    yydebug = 1;
    yyparse();
    return 0;
}

void yyerror (char const *s) {  fprintf(stderr, "%s\n", s); }
</code>```

But generated parser will fail if I specify input like (bar) - parse tree in that case should contain foo expression which is empty. It reports:

Starting parse

Entering state 0

Reading a token: Next token is token OP ()

Shifting token OP ()

Entering state 1

Reading a token: Next token is token BAR ()

syntax error, unexpected BAR, expecting FOO

Error: popping token OP ()

Stack now 0

Cleanup: discarding lookahead token BAR ()

Stack now 0

Here is piece of text from generated description of shift/reduce automata:

```<code>state 0
    0 $accept: . program_expr $end
    OP  shift, and go to state 1
    OP        [reduce using rule 2 (foo_expr)]
    $default  reduce using rule 2 (foo_expr)
    program_expr  go to state 2
    foo_expr      go to state 3

state 1
    3 foo_expr: OP . FOO CP
    FOO  shift, and go to state 4
state 2
    0 $accept: program_expr . $end
    $end  shift, and go to state 5
state 3
    1 program_expr: foo_expr . bar_expr
    OP  shift, and go to state 6
    $default  reduce using rule 4 (bar_expr)
    bar_expr  go to state 7
</code>```

But I cannot understand meaning/syntax of such states. What's problem with my grammar/parser?

答:
If you want to accept just (bar) as input, you could use the following:

```<code>program_expr :   foo_expr bar_expr   {}
    |            bar_expr            {}
;
</code>```

instead of this:

```<code>program_expr :   foo_expr bar_expr   {}
;
</code>```

Test output:

```<code>> echo "(bar)" | ./Parser
Starting parse
Entering state 0
Reading a token: Next token is token OP ()
Shifting token OP ()
Entering state 1
Reading a token: Next token is token BAR ()
Shifting token BAR ()
Entering state 6
Reading a token: Next token is token CP ()
Shifting token CP ()
Entering state 11
Reducing stack by rule 6 (line 20):
   $1 = token OP ()
   $2 = token BAR ()
   $3 = token CP ()
-> $$ = nterm bar_expr ()
Stack now 0
Entering state 4
Reducing stack by rule 2 (line 14):
   $1 = nterm bar_expr ()
-> $$ = nterm program_expr ()
Stack now 0
Entering state 2
Reading a token: Now at end of input.
....
</code>```

Body:
I created parser via Flex/Bison, which unexpectedly fails during parsing. Here is simplified sample which shows problem

Lexer.l:

%{
#include "Parser.h"
%}
%option noyywrap nodefault

%%
"foo"               {   return FOO;                          }
"bar"               {   return BAR;                          }
"("                 {   return OP;                           }
")"                 {   return CP;                           }
[ \t\n]+            {   /*    DO NOTHING  */                 }
.                   {   YY_FATAL_ERROR("unknown character"); }
%%

And Parser.y (with enabled tracing and verbosity):

%{
#include <stdio.h>
int yylex();
void yyerror (char const *s);
%}

%debug
%verbose
%error-verbose
%token FOO BAR OP CP

%%
program_expr :   foo_expr bar_expr   {}
;
foo_expr :   /*  NOTHING  */  {}
    |   OP FOO CP           {}
;
bar_expr :   /*  NOTHING  */  {}
    |   OP BAR CP           {}
;
%%

int main(int argc, char** argv)
{
    yydebug = 1;
    yyparse();
    return 0;
}

void yyerror (char const *s) {  fprintf(stderr, "%s\n", s); }

But generated parser will fail if I specify input like (bar) - parse tree in that case should contain foo expression which is empty. It reports:

Starting parse

Entering state 0

Reading a token: Next token is token OP ()

Shifting token OP ()

Entering state 1

Reading a token: Next token is token BAR ()

syntax error, unexpected BAR, expecting FOO

Error: popping token OP ()

Stack now 0

Cleanup: discarding lookahead token BAR ()

Stack now 0

Here is piece of text from generated description of shift/reduce automata:

state 0
    0 $accept: . program_expr $end
    OP  shift, and go to state 1
    OP        [reduce using rule 2 (foo_expr)]
    $default  reduce using rule 2 (foo_expr)
    program_expr  go to state 2
    foo_expr      go to state 3

state 1
    3 foo_expr: OP . FOO CP
    FOO  shift, and go to state 4
state 2
    0 $accept: program_expr . $end
    $end  shift, and go to state 5
state 3
    1 program_expr: foo_expr . bar_expr
    OP  shift, and go to state 6
    $default  reduce using rule 4 (bar_expr)
    bar_expr  go to state 7

But I cannot understand meaning/syntax of such states. What's problem with my grammar/parser?

Body:
If you want to accept just (bar) as input, you could use the following:

program_expr :   foo_expr bar_expr   {}
    |            bar_expr            {}
;

instead of this:

program_expr :   foo_expr bar_expr   {}
;

Test output:

> echo "(bar)" | ./Parser
Starting parse
Entering state 0
Reading a token: Next token is token OP ()
Shifting token OP ()
Entering state 1
Reading a token: Next token is token BAR ()
Shifting token BAR ()
Entering state 6
Reading a token: Next token is token CP ()
Shifting token CP ()
Entering state 11
Reducing stack by rule 6 (line 20):
   $1 = token OP ()
   $2 = token BAR ()
   $3 = token CP ()
-> $$ = nterm bar_expr ()
Stack now 0
Entering state 4
Reducing stack by rule 2 (line 14):
   $1 = nterm bar_expr ()
-> $$ = nterm program_expr ()
Stack now 0
Entering state 2
Reading a token: Now at end of input.
....


问:
Gradient color in CSS with percentage
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

```<code> .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }
</code>```

答:
Eveyrone is giving the to bottom solution but the trivial solution is to consider to top and keep the percentage values you are using in the picture:

```<code>linear-gradient(to top, #mycolor3 10%, #mycolor2 45%, #mycolor1 85%);
</code>```

example:

body {
  background: linear-gradient(to top, red 10%, purple 45%, blue 85%);
  margin: 0;
  height: 100vh;
}```
</div>
</div>
</p>

<p>Concerning the percentage between (50% and 30%), they are <em>probably</em> the color hints (also called color interpolation hints). From the new specification</p>

<blockquote>
  <p>Between two color stops there can be a <strong>color interpolation hint</strong>, which specifies how the colors of the two color stops on either side should be interpolated in the space between them (by default, they interpolate linearly). There can only be at most one color interpolation hint between any two given color stops; using more than that makes the function invalid.</p>
</blockquote>

<p>example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background:
   /* First gradient with hints*/
   linear-gradient(to top, red 10%, purple 45%, blue 85%) left /45% 100%,
   /* Second gradient with hints*/
   linear-gradient(to top, red 10%,27.5% ,purple 45%, 57% ,blue 85%) right/45% 100%;

  background-repeat:no-repeat;
  margin: 0;
  height: 100vh;
}</code>```

Title: Gradient color in CSS with percentage

Body:
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

 .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }

Body:
Eveyrone is giving the to bottom solution but the trivial solution is to consider to top and keep the percentage values you are using in the picture:

linear-gradient(to top, #mycolor3 10%, #mycolor2 45%, #mycolor1 85%);

example:

body {
  background: linear-gradient(to top, red 10%, purple 45%, blue 85%);
  margin: 0;
  height: 100vh;
}

Concerning the percentage between (50% and 30%), they are probably the color hints (also called color interpolation hints). From the new specification

Between two color stops there can be a color interpolation hint, which specifies how the colors of the two color stops on either side should be interpolated in the space between them (by default, they interpolate linearly). There can only be at most one color interpolation hint between any two given color stops; using more than that makes the function invalid.

example:

body {
  background:
   /* First gradient with hints*/
   linear-gradient(to top, red 10%, purple 45%, blue 85%) left /45% 100%,
   /* Second gradient with hints*/
   linear-gradient(to top, red 10%,27.5% ,purple 45%, 57% ,blue 85%) right/45% 100%;

  background-repeat:no-repeat;
  margin: 0;
  height: 100vh;
}


问:
What's the best way to track unique visits to a page?
I want to log unique visits to a particular page on my site. What is a pretty accurate yet simple way to do this? Simply by IP? Suggestions?

Let me clarify a bit:

I have a list of articles on my site. Every article is actually the same page like article.aspx. However the content is different based on thee article being viewed. I want to track unique views of a particular article.

Thanks!

答: Use a combination of cookies and IP addresses. If you use only cookies then a user (or robot) with cookies turned off can run up your page views. If you use only IP then you block all computers on a proxy.</p>

OwnerDisplayName: Micah

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Micah

OwnerDisplayName: Lucas Aardvark


问:
How to shutdown and reboot the emulator through code in android?
I have implemented the code like:

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);
</code>```

it get the error(runtime):

```<code>java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***
</code>```

答:
In android SDK documents, I see a note about the Intent.ACTION_REBOOt. It says, "This is a protected intent that can only be sent by the system".
I think you don't have the  privilege to use this intent to reboot the device for security reason.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have implemented the code like:

Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);

it get the error(runtime):

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***


问:
Loading application context via annotation in benchmark
Let's assume I want to write a benchmark for the class which can be autowired thus I need to load application context.

My test has annotation @org.openjdk.jmh.annotations.State(Scope.Benchmark) and main method

```<code>public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(MyBenchmark.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();
    }
</code>```

And of course I have some benchmarks like this:

```<code>@Benchmark
public void countAllObjects() {
    Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}
</code>```

Now, the question is how do I inject myAutowiredService?

Possible solution

Load manually the context in @Setup method.

```<code>ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);
</code>```

But I don't like this solution. I would prefer that my test just have annotation

```<code>@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })
</code>```

and then I just inject my bean like

```<code>@Autowired
private MyAutowiredService myAutowiredService;
</code>```

but this does not work. The reason, I assume, is that I have no annotation that my test should run with Spring:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
</code>```

However there is no point of doing this because I also don't have any @Test annotated methods, thus I will get No runnable methods exception.

Can I achieve loading the context via annotations in this case?

答:
```<code>@State(Scope.Benchmark)
public static class SpringState {

    AnnotationConfigApplicationContext context;

    @Setup(Level.Trial)
    public void setup() {
        context = new AnnotationConfigApplicationContext();
        context.register(CLASSNAME.class);
        context.register(ANOTHER_CLASSNAME_TO_BE_LOADED.class);
        context.refresh();
    }

    @TearDown(Level.Trial)
    public void tearDown() {
        context.close();
    }
}
</code>```

Body:
Let's assume I want to write a benchmark for the class which can be autowired thus I need to load application context.

My test has annotation @org.openjdk.jmh.annotations.State(Scope.Benchmark) and main method

public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(MyBenchmark.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();
    }

And of course I have some benchmarks like this:

@Benchmark
public void countAllObjects() {
    Assert.assertEquals(OBJECT_COUNT, myAutowiredService.count());
}

Now, the question is how do I inject myAutowiredService?

Possible solution

Load manually the context in @Setup method.

ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/application-context.xml");
context.getAutowireCapableBeanFactory().autowireBean(this);

But I don't like this solution. I would prefer that my test just have annotation

@ContextConfiguration(locations = { "classpath:META-INF/application-context.xml" })

and then I just inject my bean like

@Autowired
private MyAutowiredService myAutowiredService;

but this does not work. The reason, I assume, is that I have no annotation that my test should run with Spring:

@RunWith(SpringJUnit4ClassRunner.class)

However there is no point of doing this because I also don't have any @Test annotated methods, thus I will get No runnable methods exception.

Can I achieve loading the context via annotations in this case?


问:
Inserting multiple records in mySQL with NodeJS preventing injection and getting each record's ID
I have an ajax request that adds one or multiple records to a table (the following code is server side):

```<code>app.post('/saveLesson',function(req, res) {

    let sections = JSON.parse(req.body.sections);

    let sql = 'INSERT INTO sections (title, content, duration) VALUES ';

    for (let i = 0; i < sections.length; i++) {

        if (i == sections.length-1) {
            sql += '("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '");';
        } else {
            sql += '("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '"),';
        }
    }
    connection.query(sql,
        function (error, result) {
            if (error) throw error;
    });

});
</code>```

I want to prevent SQL injection, but I'm not sure how to do it for multiple records.

Generally I know that I would have to build my sql statement as follows:

```<code>connection.query("SELECT * FROM bank_accounts WHERE dob = ? AND bank_account = ?",
    [
     req.body.dob,
     req.body.account_number
    ],
    function(error, results) {

    }
);
</code>```

But I'm not sure how to achieve this with multiple records (not knowing how many they are). Is the .query parameter just a regular array?

Also, I need to store somewhere the created IDs and send them back to the client page. How can I achieve this? Thank you.

***************************** UPDATE *****************************

Although someone posted a solution, I thought this might be useful. With the following code you can add multiple records preventing SQL injections.

```<code>app.post('/saveLesson',function(req, res) {

    let sections = JSON.parse(req.body.sections);

    console.log(sections);

    let sql = 'INSERT INTO sections (title, duration, content) VALUES ';

    // I make a new array to pass the list of values to the query
    let sectionsParamList = [];

    for (let i = 0; i < sections.length; i++) {

        if (i == sections.length-1) {
            sql += '(?,?,?);';
        } else {
            sql += '(?,?,?),';
        }

        sectionsParamList.push(sections[i].title);
        sectionsParamList.push(sections[i].duration);
        sectionsParamList.push(sections[i].content);
    }

    connection.query(sql, sectionsParamList,
        function (error, result) {
            if (error) throw error;
    });

});
</code>```

答:
The way MySQL works, when you perform a multi-row INSERT operation like the one you propose, you only get back the automatically generated unique id of the last row inserted. It shows up in your result object as result.insertId. Don't try to guess the id values of the other rows, by subtraction for example, because there's no guarantee of that.

The fact that you need that id for every row you insert means you should not use a multi-row insert, but rather a sequence of single row inserts.  That neatly solves your SQL injection issue too.

But you will have to figure out how to do a sequence of INSERT operations. You may want to do it with an async  / await / promise setup. Something like this, not debugged.

```<code>/* do one insert with a Promise so you can await it */
function doInsert (section, connection) {
   const values = [section.title, section.content, section.duration];
   return new Promise( function ( resolve, reject ) {
      const sql = "INSERT INTO sections (title, content, duration) VALUES (?,?,?);"
      connection.query (sql, values, function ( error, result ) {
         if (error) reject (error)
         resolve (result.insertId)
      } )
   } )
}

/* do all the inserts, awaiting each one */
async function doInserts (sections, connection) {
  let ids = []
  for (let i = 0; i < sections.length; i++) {
     const id = await doInsert (sections[i], connection)
     ids.push(id)
  }
  return ids
}
</code>```

```<code>/* handle your post */
app.post('/saveLesson',function(req, res) {
  let sections = JSON.parse(req.body.sections)
  /* get the result back from an async function with .then / .catch */
  doInserts (sections, connection)
  .then (function (resultIds) {
     /* respond with the id values in a JSON object */
     res.status(200).json(resultIds)
  } )
  .catch ( function (error) {
     /* respond with an error */
     res.status(500).json(error)
  } )
} )
</code>```

These async / await and Promise language constructions are really worth your trouble to learn, if you don't already know them.

Body:
I have an ajax request that adds one or multiple records to a table (the following code is server side):

app.post('/saveLesson',function(req, res) {

    let sections = JSON.parse(req.body.sections);

    let sql = 'INSERT INTO sections (title, content, duration) VALUES ';

    for (let i = 0; i < sections.length; i++) {

        if (i == sections.length-1) {
            sql += '("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '");';
        } else {
            sql += '("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '"),';
        }
    }
    connection.query(sql,
        function (error, result) {
            if (error) throw error;
    });

});

I want to prevent SQL injection, but I'm not sure how to do it for multiple records.

Generally I know that I would have to build my sql statement as follows:

connection.query("SELECT * FROM bank_accounts WHERE dob = ? AND bank_account = ?",
    [
     req.body.dob,
     req.body.account_number
    ],
    function(error, results) {

    }
);

But I'm not sure how to achieve this with multiple records (not knowing how many they are). Is the .query parameter just a regular array?

Also, I need to store somewhere the created IDs and send them back to the client page. How can I achieve this? Thank you.

***************************** UPDATE *****************************

Although someone posted a solution, I thought this might be useful. With the following code you can add multiple records preventing SQL injections.

app.post('/saveLesson',function(req, res) {

    let sections = JSON.parse(req.body.sections);

    console.log(sections);

    let sql = 'INSERT INTO sections (title, duration, content) VALUES ';

    // I make a new array to pass the list of values to the query
    let sectionsParamList = [];

    for (let i = 0; i < sections.length; i++) {

        if (i == sections.length-1) {
            sql += '(?,?,?);';
        } else {
            sql += '(?,?,?),';
        }

        sectionsParamList.push(sections[i].title);
        sectionsParamList.push(sections[i].duration);
        sectionsParamList.push(sections[i].content);
    }

    connection.query(sql, sectionsParamList,
        function (error, result) {
            if (error) throw error;
    });

});

Body:
The way MySQL works, when you perform a multi-row INSERT operation like the one you propose, you only get back the automatically generated unique id of the last row inserted. It shows up in your result object as result.insertId. Don't try to guess the id values of the other rows, by subtraction for example, because there's no guarantee of that.

The fact that you need that id for every row you insert means you should not use a multi-row insert, but rather a sequence of single row inserts.  That neatly solves your SQL injection issue too.

But you will have to figure out how to do a sequence of INSERT operations. You may want to do it with an async  / await / promise setup. Something like this, not debugged.

/* do one insert with a Promise so you can await it */
function doInsert (section, connection) {
   const values = [section.title, section.content, section.duration];
   return new Promise( function ( resolve, reject ) {
      const sql = "INSERT INTO sections (title, content, duration) VALUES (?,?,?);"
      connection.query (sql, values, function ( error, result ) {
         if (error) reject (error)
         resolve (result.insertId)
      } )
   } )
}

/* do all the inserts, awaiting each one */
async function doInserts (sections, connection) {
  let ids = []
  for (let i = 0; i < sections.length; i++) {
     const id = await doInsert (sections[i], connection)
     ids.push(id)
  }
  return ids
}

/* handle your post */
app.post('/saveLesson',function(req, res) {
  let sections = JSON.parse(req.body.sections)
  /* get the result back from an async function with .then / .catch */
  doInserts (sections, connection)
  .then (function (resultIds) {
     /* respond with the id values in a JSON object */
     res.status(200).json(resultIds)
  } )
  .catch ( function (error) {
     /* respond with an error */
     res.status(500).json(error)
  } )
} )

These async / await and Promise language constructions are really worth your trouble to learn, if you don't already know them.


问:
Animation bag with some ImageViews
I have problem with my android animation. When I click the first time on my ImageView, my image have a rotation but when click the second time on my ImageView, rotation don't work. Why is it happened?

My rotation method in Java code:

```<code>private boolean tomIsInvisible = false;

public void eraseTom(View view) {
    ImageView tom = findViewById(R.id.tom);
    ImageView jerry = findViewById(R.id.jerry);

    if (tomIsInvisible) {

        tom.animate()
                .rotation(3600)
                .scaleX(1)
                .scaleY(1)
                .alpha(1)
                .setDuration(3000);

        jerry.animate()
                .rotation(3600)
                .scaleX(0)
                .scaleY(0)
                .alpha(0)
                .setDuration(3000);

        tomIsInvisible = false;

    } else if(!tomIsInvisible) {

        tom.animate()
                .rotation(3600)
                .scaleX(0)
                .scaleY(0)
                .alpha(0)
                .setDuration(3000);

        jerry.animate()
                .rotation(3600)
                .alpha(1)
                .scaleX(1)
                .scaleY(1)
                .setDuration(3000);

        tomIsInvisible = true;
    }
}
</code>```

Others methods on my ImageView work correctly.

答:
When you call rotation(3600) first time it animates rotation from 0 to 3600. (default view rotation is 0). After first animation rotation is 3600 (ViewPropertyAnimator changes actual value of property while it animate things). So when you call rotation(3600) second time rotation of your view is already 3600 and you try to animate it to 3600. Thats why there is no visual changes. There is rotationBy method which apply specified value to view rotation, try to use it.

```<code>view.animate().rotationBy(3600)
</code>```

Another solution is to animate from 0 to 360 and in the animation end reset view rotation to 0.

Title: Animation bag with some ImageViews

Body:
I have problem with my android animation. When I click the first time on my ImageView, my image have a rotation but when click the second time on my ImageView, rotation don't work. Why is it happened?

My rotation method in Java code:

private boolean tomIsInvisible = false;

public void eraseTom(View view) {
    ImageView tom = findViewById(R.id.tom);
    ImageView jerry = findViewById(R.id.jerry);

    if (tomIsInvisible) {

        tom.animate()
                .rotation(3600)
                .scaleX(1)
                .scaleY(1)
                .alpha(1)
                .setDuration(3000);

        jerry.animate()
                .rotation(3600)
                .scaleX(0)
                .scaleY(0)
                .alpha(0)
                .setDuration(3000);

        tomIsInvisible = false;

    } else if(!tomIsInvisible) {

        tom.animate()
                .rotation(3600)
                .scaleX(0)
                .scaleY(0)
                .alpha(0)
                .setDuration(3000);

        jerry.animate()
                .rotation(3600)
                .alpha(1)
                .scaleX(1)
                .scaleY(1)
                .setDuration(3000);

        tomIsInvisible = true;
    }
}

Others methods on my ImageView work correctly.

Body:
When you call rotation(3600) first time it animates rotation from 0 to 3600. (default view rotation is 0). After first animation rotation is 3600 (ViewPropertyAnimator changes actual value of property while it animate things). So when you call rotation(3600) second time rotation of your view is already 3600 and you try to animate it to 3600. Thats why there is no visual changes. There is rotationBy method which apply specified value to view rotation, try to use it.

view.animate().rotationBy(3600)

Another solution is to animate from 0 to 360 and in the animation end reset view rotation to 0.


问:
How to make a jquery tab contain an html form that redirects inside the tab?
currently I have a section of my page with jquery tabs. The tabs reference html pages, and each contain a form for someone to enter their details. On clicking the submit button, ideally, their details should be submitted to a mySQL database, and they should then be redirected to a javascript form. I'm not bothered what happens after that, but everything there should happen inside the tab.

I've managed to get the mySQL submit working, and I've verified that it inserts the data into the database. However, it loads the php submit for the form as a whole new page, rather than staying in the tabs. It also doesn't redirect, although I may have mistyped something.

I've got links to work in the tabs, in that, I placed a link in there and got it to load inside the tab when I clicked on it. I just can't seem to work out this part though :S

For the form submit, I'm using a php page, which contains the php for writing to the database, followed by a javascript redirect in  tags.

Can anyone help? Thanks!

AWESOME guys, thanks loads! It's finally working. :)

If anyone's interested, this tutorial was pretty helpful. http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form

答:
I guess what you did was that you did a regular post instead of a XHR post. If you do a regular post, the whole page is going to be replaced by whatever the post does, but with XHR post, you can send it in the background without having to refresh the page. read Jquery AJAX documentations for more information.

http://api.jquery.com/category/ajax/


问:
Using margin in @media
I have some css which is perfect in mobile but I'm trying make work in desktop @media min-width 768px. I'm trying to get two pieces of text closer together and moved down the page around 50px. Whatever I try though, I can't seem to move it.

Here it is, and what I want to move is find an event and post an event.

@media (min-width: 768px) {
  .event_wrapper {
    display: grid;
    grid-template-columns: 1 fr 1 fr 1 fr;
    grid-template-rows: auto;
    grid-template-areas: 'a b c d e f';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lasvegas">Events</div>
<div class="findanevent" />
<div class="event_wrapper">

    <span id="findanevent" class="event">Find an Event</span>.

    <span id="postanevent" class="event">Post an Event</span>

</div></code>```

答:
Remove space before fr unit:

```<code>grid-template-columns: 1fr 1fr 1fr;
</code>```

Title: Using margin in @media

Body:
I have some css which is perfect in mobile but I'm trying make work in desktop @media min-width 768px. I'm trying to get two pieces of text closer together and moved down the page around 50px. Whatever I try though, I can't seem to move it.

Here it is, and what I want to move is find an event and post an event.

@media (min-width: 768px) {
  .event_wrapper {
    display: grid;
    grid-template-columns: 1 fr 1 fr 1 fr;
    grid-template-rows: auto;
    grid-template-areas: 'a b c d e f';
  }
}

Events

    Find an Event.

    Post an Event

Body:
Remove space before fr unit:

grid-template-columns: 1fr 1fr 1fr;


问:
Columns appending is troublesome with Pandas
Here is what I have tried and what error I received:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> df
   A  B  C  D
0  1  5  0  1
1  2  4  0  1
2  3  3  0  1
3  4  2  0  1
4  5  1  0  1
>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> first = [2,2,2,2,2,2,2,2,2,2,2,2]
>>> first = pd.DataFrame(first).T
>>> first.index = [2]
>>> df = df.join(first)
>>> df
   A  B  C  D    0    1    2    3    4    5    6    7    8    9   10   11
0  1  5  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2  3  3  0  1  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
3  4  2  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
>>> second = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
>>> second = pd.DataFrame(second).T
>>> second.index = [1]
>>> df = df.join(second)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6815, in join
    rsuffix=rsuffix, sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6830, in _join_compat
    suffixes=(lsuffix, rsuffix), sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 48, in merge
    return op.get_result()
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 552, in get_result
    rdata.items, rsuf)
  File "C:\Python35\lib\site-packages\pandas\core\internals\managers.py", line 1972, in items_overlap_with_suffix
    '{rename}'.format(rename=to_rename))
ValueError: columns overlap but no suffix specified: Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype='object')
</code>```

I am trying to create new list with the extra columns which I have to add at specific indexes of the main dataframe df.

When i tried the first it worked and you can see the output. But when I tried the same way with second I received the above mentioned error.

Kindly, let me know what I can do in this situation and achieve the goal I am expecting.

答:
Yes this is expected behaviour because join works much like an SQL join, meaning that it will join on the provided index and concatenate all the columns together. The problem arises from the fact that pandas does not accept two columns to have the same name. Hence, if you have 2 columns in each dataframe with the same name, it will first look for a suffix to add to those columns to avoid name clashes. This is controlled with the lsuffix and rsuffix arguments in the join method.

Conclusion: 2 ways to solve this:

Either provide a suffix so that pandas is able to resolve the name clashes; or

Make sure that you don't have overlapping columns

Body:
Here is what I have tried and what error I received:

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> df
   A  B  C  D
0  1  5  0  1
1  2  4  0  1
2  3  3  0  1
3  4  2  0  1
4  5  1  0  1
>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> first = [2,2,2,2,2,2,2,2,2,2,2,2]
>>> first = pd.DataFrame(first).T
>>> first.index = [2]
>>> df = df.join(first)
>>> df
   A  B  C  D    0    1    2    3    4    5    6    7    8    9   10   11
0  1  5  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2  3  3  0  1  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
3  4  2  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
>>> second = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
>>> second = pd.DataFrame(second).T
>>> second.index = [1]
>>> df = df.join(second)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6815, in join
    rsuffix=rsuffix, sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6830, in _join_compat
    suffixes=(lsuffix, rsuffix), sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 48, in merge
    return op.get_result()
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 552, in get_result
    rdata.items, rsuf)
  File "C:\Python35\lib\site-packages\pandas\core\internals\managers.py", line 1972, in items_overlap_with_suffix
    '{rename}'.format(rename=to_rename))
ValueError: columns overlap but no suffix specified: Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype='object')

I am trying to create new list with the extra columns which I have to add at specific indexes of the main dataframe df.

When i tried the first it worked and you can see the output. But when I tried the same way with second I received the above mentioned error.

Kindly, let me know what I can do in this situation and achieve the goal I am expecting.


问:
Stripe does not let a charge be associated with a customer with one-time source
As the title says, I am trying to make a payment using a one-time source (credit card) that is not being saved in the customer's profile. I still want to be able to record that charge on the customer's profile on Stripe.

According to the docs, this can be done by passing the customer's id in customer key in the payload sent to Stripe.customers.createCharge. However, on doing that, I receive an error stating the card is not linked with the customer (which obviously is not, and I don't want it to be).

Customer cus_*** does not have card with ID tok_visa

To get around this, temporarily I have applied the fix mentioned in this answer which basically involves creating a temporary card for the payment and then deleting it.

I was wondering how does the API not work when it is clearly documented otherwise, hope someone experienced with Stripe chimes in on the same.

Here is the code I'm trying to get to run:

```<code>await stripeService.charges.create({
    source: token, // temporary token received from Checkout
    customer: user.stripeCustomerId, // the Stripe customer ID from my database
    amount,
    currency: 'usd',
    description: 'Test charge'
});
</code>```

答:
I was able to achieve this by creating the source first followed by the charge where you specify the customerId and sourceId as below:</p>

```<code>            //Create the source first
            var options = new SourceCreateOptions
            {
                Type = SourceType.Card,
                Card = new CreditCardOptions
                {
                    Number = Number,
                    ExpYear = ExpYear,
                    ExpMonth = ExpMonth,
                    Cvc = Cvc
                },
                Currency = "gbp"
            };

            var serviceSource = new SourceService();
            Source source = serviceSource.Create(options);

            //Now do the payment
            var optionsCharge = new ChargeCreateOptions
            {
                Amount = 500,
                Currency = "gbp",
                Description = "Your description",
                SourceId = source.Id,
                CustomerId = "yourcustomerid"
            };
            var service = new ChargeService();
            service.Create(optionsCharge);

            result = "success";
</code>```

Body:
As the title says, I am trying to make a payment using a one-time source (credit card) that is not being saved in the customer's profile. I still want to be able to record that charge on the customer's profile on Stripe.

According to the docs, this can be done by passing the customer's id in customer key in the payload sent to Stripe.customers.createCharge. However, on doing that, I receive an error stating the card is not linked with the customer (which obviously is not, and I don't want it to be).

Customer cus_*** does not have card with ID tok_visa

To get around this, temporarily I have applied the fix mentioned in this answer which basically involves creating a temporary card for the payment and then deleting it.

I was wondering how does the API not work when it is clearly documented otherwise, hope someone experienced with Stripe chimes in on the same.

Here is the code I'm trying to get to run:

await stripeService.charges.create({
    source: token, // temporary token received from Checkout
    customer: user.stripeCustomerId, // the Stripe customer ID from my database
    amount,
    currency: 'usd',
    description: 'Test charge'
});

Body:
I was able to achieve this by creating the source first followed by the charge where you specify the customerId and sourceId as below:

            //Create the source first
            var options = new SourceCreateOptions
            {
                Type = SourceType.Card,
                Card = new CreditCardOptions
                {
                    Number = Number,
                    ExpYear = ExpYear,
                    ExpMonth = ExpMonth,
                    Cvc = Cvc
                },
                Currency = "gbp"
            };

            var serviceSource = new SourceService();
            Source source = serviceSource.Create(options);

            //Now do the payment
            var optionsCharge = new ChargeCreateOptions
            {
                Amount = 500,
                Currency = "gbp",
                Description = "Your description",
                SourceId = source.Id,
                CustomerId = "yourcustomerid"
            };
            var service = new ChargeService();
            service.Create(optionsCharge);

            result = "success";


问:
How to drop a specific Django table which uses PostgreSQL?
I want to delete a Django UserModel table and then recreate it.

Or delete user field and recreate it with a new user by python manage.py createsuperuser

[NOTE]:

My DB is PostgreSQL on a docker container.

答:
connect to psql or using pgAdmin
connect to your databese
execute the query:
DROP TABLE IF EXISTS  CASCADE;</p>


问:
vertical centering of list items
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

```<code><div id = "main">
    <ul>
        <li>
            <img src="test.jpg" alt="#" />
            <p>Lorem ipsum</p>
        </li>
    </ul>
</div>

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}
</code>```

答:
Here's a simple solution. I've added borders to make the result easier to see.</p>

```<code>    #main {
        margin: 60px auto;
        height:600px;
        display: table-cell;
        vertical-align: middle;
        border:1px solid #d0d0d0
    }

    #main ul li {
        display: block;
        margin: 0 13px 72px 22px;
        height: 100px;
        border:1px solid #ff0000;
}
</code>```

Title: vertical centering of list items

Body:
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

Lorem ipsum

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}

Body:
Here's a simple solution. I've added borders to make the result easier to see.

    #main {
        margin: 60px auto;
        height:600px;
        display: table-cell;
        vertical-align: middle;
        border:1px solid #d0d0d0
    }

    #main ul li {
        display: block;
        margin: 0 13px 72px 22px;
        height: 100px;
        border:1px solid #ff0000;
}


问:
Error related to decoding while combining pandas and shutil
I am trying to copy a bunch of directories with shutil.copytree and pandas (apply function). While checking the log I noticed that some files could not be copied due to the following error: [Errno 2] No such file or directory:PATH. Even though the path name was valid. Upon further inspection it appeared the Í character was changed in \xb4, which explains why the file could not be found.

I have tried following the advice in this post:
Pandas convert object column to str - column contains unicode, float etc
by trying to convert the column to unicode. However, this lead to the following error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 20: ordinal not in range(128)

```<code>import pandas as pd
import shutil

def copy_files(row):
    try:
        shutil.copy(row['1'], row['2'])
        return 'DONE'
    except Exception as e:
        return str(e)

df = pd.DataFrame({'1':['Y:\project\Test\1\RAÍ.pdf'],'2':
['Y:\project\Test\2\RAÍ.pdf']})

df['errors'] = df.apply(copy_files, axis=1)

print(df['errors'][0])
</code>```

I expected that the string 'DONE' would be printed but instead I got the error message:

[Errno 2] No such file or directory: 'Y:\project\Test\x01\RAI\xcc\x81.pdf'

EDIT:

If use raw string literals like so:

```<code>df = pd.DataFrame({r'1':[r'Y:\project\Test\1'],
              '2':[r'Y:\project\Test\2']})

def copy_files(row):
    try:
        shutil.copytree(row['1'], row['2'])
        return 'DONE'
    except Exception as e:
        return str(e)

df['errors'] = df.apply(copy_files, axis=1)

print(df['errors'][0])
</code>```

I still get the following result:

[('Y:\project\Test\1\RAI\xb4i.pdf',
  'Y:\project\Test\2\RAI\xb4i.pdf', "[Errno 2] No such file or
  directory: 'Y:\\project\\Test\\1\\RAI\xb4i.pdf'")]

答:
Where did you get those characters? It looks that your name contains a 'LATIN CAPITAL LETTER I WITH ACUTE'. The problem is that UNICODE (independently of the encoding) allows more than one representation. It can be (Normal Form C or Canonical Composition) U+00CD or '\xcd' or (Normal Form D or Canonical Decomposition) U+0049 followed with U+0301 or 'I\u0301'. This NFD form read as LATIN CAPITAL LETTER I followed with COMBINING ACUTE ACCENT.

It is impossible to distinguish those 2 forms on a printed or displayed characters, but unfortunately they are different strings for both Python and the filesystem...

How to fix: avoid non ascii characters in filenames. You now know why...

Workarounds:

Your source contains the NFD form. It is likely that the filesystem contains the NFC form, so you could try:

```<code>df = pd.DataFrame({'1':['Y:\project\Test\1\RAI\xcd.pdf'],'2':
['Y:\project\Test\2\RAI\xcd.pdf']})
</code>```

The bulletproof way is to ask the filesystem what string actually is the filename:

```<code>l = glob.glob('Y:\project\Test\1\RAI*.pdf')
for name in l:
    print(name, [hex(ord(i)) for i in name])
</code>```

(notice the * and not a ? because in NFD form a single glyph could correspond to more than one character) That would dump the unicode codepoints of all characters as known by the file system. Provided you later use the exact same representation thing should go fine.

Refences:

unicodedata — Unicode Database — Python 3.7.3 documentation

Unicode Normalization Forms

Body:
I am trying to copy a bunch of directories with shutil.copytree and pandas (apply function). While checking the log I noticed that some files could not be copied due to the following error: [Errno 2] No such file or directory:PATH. Even though the path name was valid. Upon further inspection it appeared the Í character was changed in \xb4, which explains why the file could not be found.

I have tried following the advice in this post:
Pandas convert object column to str - column contains unicode, float etc
by trying to convert the column to unicode. However, this lead to the following error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 20: ordinal not in range(128)

import pandas as pd
import shutil

def copy_files(row):
    try:
        shutil.copy(row['1'], row['2'])
        return 'DONE'
    except Exception as e:
        return str(e)

df = pd.DataFrame({'1':['Y:\project\Test\1\RAÍ.pdf'],'2':
['Y:\project\Test\2\RAÍ.pdf']})

df['errors'] = df.apply(copy_files, axis=1)

print(df['errors'][0])

I expected that the string 'DONE' would be printed but instead I got the error message:

[Errno 2] No such file or directory: 'Y:\project\Test\x01\RAI\xcc\x81.pdf'

EDIT:

If use raw string literals like so:

df = pd.DataFrame({r'1':[r'Y:\project\Test\1'],
              '2':[r'Y:\project\Test\2']})

def copy_files(row):
    try:
        shutil.copytree(row['1'], row['2'])
        return 'DONE'
    except Exception as e:
        return str(e)

df['errors'] = df.apply(copy_files, axis=1)

print(df['errors'][0])

I still get the following result:

[('Y:\project\Test\1\RAI\xb4i.pdf',
  'Y:\project\Test\2\RAI\xb4i.pdf', "[Errno 2] No such file or
  directory: 'Y:\\project\\Test\\1\\RAI\xb4i.pdf'")]

Body:
Where did you get those characters? It looks that your name contains a 'LATIN CAPITAL LETTER I WITH ACUTE'. The problem is that UNICODE (independently of the encoding) allows more than one representation. It can be (Normal Form C or Canonical Composition) U+00CD or '\xcd' or (Normal Form D or Canonical Decomposition) U+0049 followed with U+0301 or 'I\u0301'. This NFD form read as LATIN CAPITAL LETTER I followed with COMBINING ACUTE ACCENT.

It is impossible to distinguish those 2 forms on a printed or displayed characters, but unfortunately they are different strings for both Python and the filesystem...

How to fix: avoid non ascii characters in filenames. You now know why...

Workarounds:

Your source contains the NFD form. It is likely that the filesystem contains the NFC form, so you could try:

df = pd.DataFrame({'1':['Y:\project\Test\1\RAI\xcd.pdf'],'2':
['Y:\project\Test\2\RAI\xcd.pdf']})

The bulletproof way is to ask the filesystem what string actually is the filename:

l = glob.glob('Y:\project\Test\1\RAI*.pdf')
for name in l:
    print(name, [hex(ord(i)) for i in name])

(notice the * and not a ? because in NFD form a single glyph could correspond to more than one character) That would dump the unicode codepoints of all characters as known by the file system. Provided you later use the exact same representation thing should go fine.

Refences:

unicodedata — Unicode Database — Python 3.7.3 documentation

Unicode Normalization Forms


问:
Why isn't the code working (here) when I try to change values of a list using 'for' loop?
Let's say there's this random list:

```<code>st=['smthg','xyz','random','000','666']
</code>```

I want to change the values of the indices 1 to 3 using this for loop:

```<code>for anythg in st:
      st[1:3]='whtevr'
</code>```

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

```<code>'t','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',
</code>```

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

```<code>for i in range(1,4):
    st[i]='whtevr'
</code>```

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

答:
because you are keep changing the list, you are iterating through list and then keep modifying it again and again and iterationg over that list

so in first iteration your list become

```<code>['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']
</code>```

see length of st changes

now for second iteration on above modifed list , it becomes

```<code>['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']
</code>```

again length increase, and so on.. so iterate is not able to reach at end and it
keep changing and changing and you are reached in that situation
 value of

Body:
Let's say there's this random list:

st=['smthg','xyz','random','000','666']

I want to change the values of the indices 1 to 3 using this for loop:

for anythg in st:
      st[1:3]='whtevr'

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

't','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

for i in range(1,4):
    st[i]='whtevr'

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
because you are keep changing the list, you are iterating through list and then keep modifying it again and again and iterationg over that list

so in first iteration your list become

['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']

see length of st changes

now for second iteration on above modifed list , it becomes

['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']

again length increase, and so on.. so iterate is not able to reach at end and it
keep changing and changing and you are reached in that situation
 value of


答:
You have to specify the suffixes since the column names are the same. Assuming you are trying to add the second values as new columns horizontally:

```<code>df = df.join(second, lsuffix='first', rsuffix='second')

   A  B  C  D  0first  1first  2first  3first  4first  5first  ...  10second  11second   12   13   14   15   16   17   18   19
0  1  5  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       3.0       3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
2  3  3  0  1     2.0     2.0     2.0     2.0     2.0     2.0  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
3  4  2  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
</code>```

Title: Columns appending is troublesome with Pandas

Body:
You have to specify the suffixes since the column names are the same. Assuming you are trying to add the second values as new columns horizontally:

df = df.join(second, lsuffix='first', rsuffix='second')

   A  B  C  D  0first  1first  2first  3first  4first  5first  ...  10second  11second   12   13   14   15   16   17   18   19
0  1  5  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       3.0       3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
2  3  3  0  1     2.0     2.0     2.0     2.0     2.0     2.0  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
3  4  2  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1     NaN     NaN     NaN     NaN     NaN     NaN  ...       NaN       NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN


答:
Is this what you want?

```<code>select max(case when rank = 1 then value end) as value_a,
       max(case when rank = 2 then value end) as value_b,
       name
where rank in (1, 2)
group by name
having count(*) = 2;
</code>```

If you want the first column as well, just add row_number() over (order by (select null)).

Title: Pivot over rank'ed table

Body:
Trying to effectively convert an existing table with a rank over partition column, into a columnar only when there is a rank of 1 and more.  Here's my data:

   -------------------------------------
   | Id | Value  | Name          | rank|
   -------------------------------------
   | 1  | 1234   | John          |1    |
   | 2  | 3456   | John          |2    |
   | 3  | 9999   | Chris         |1    |
   | 4  | 9801   | Joe           |1    |
   | 5  | 1287   | Joe           |2    |
   _____________________________________

What I'm trying to arrive at:

   -------------------------------------
   |       ValA  | ValB     | Name     |
   -------------------------------------
   | 1  | 1234   | 3456    | John      |
   | 2  | 9801   | 1287    | Joe       |
   -------------------------------------

Tried a few versions of pivot but I feel like I'm missing something.  The key is dropping any rows where rank is only 1, and if I have a 1 & 2, to convert those.

Body:
Is this what you want?

select max(case when rank = 1 then value end) as value_a,
       max(case when rank = 2 then value end) as value_b,
       name
where rank in (1, 2)
group by name
having count(*) = 2;

If you want the first column as well, just add row_number() over (order by (select null)).


问:
Why isn't my css applied unless i clean browser cache?
I'm making a simple website for a school project. It was going well until i added php to the code. Now it doesn't want to apply my css changes every time for some reason. I validated html, css and php on some sites and everything seems to be clean. Then i came across a article that said i have to clear the cache for the css to get applied. It worked (using chrome) though now i have to clean it after every css change or it wont get applied. Only thing that is coming to my mind is that I'm working in PhpStorm but checking the code using xampp and not the PhpStorm built-in browsers, though it worked perfectly until the php. Is there a better way out then clearing cache after every single css change?</p>

答:
In Chrome, I suggest you disable the cache while the developer tools are open.

To do this, open Chrome's developer tools (press F12) then open the Settings (press F1). Find the checkbox labeled Disable cache (while DevTools is open) under the Network heading.

Once this is turned on, keep the dev tools window open while you do your development work and Chrome will no longer cache your CSS files and always load the latest version.


问:
Develop an application on 2 different machine
I would like to develop a web application (Django 1.11, python 2.7) on 2 different machines: the morning developping on a computer and the evening on another computer. currently I copy the entire folder from one machine to another
Is there another way?</p>

答:
You can use a version control software to do so.
Here are 15 best software to do the job.

Using these you can push your code from one machine and take the latest pull on another machine and start working from where you left  and then push it again


问:
How do I sequentially fill a big range of cells in Google Sheets?
I want to fill an entire column of Google Sheets with numbers from -4000 to 4000, but I can't find an easy way of doing it.

I'm aware of the auto-fill solution of google sheets that allows you to write two sequential numbers and then select them and use the drag-and-drop approach, but for big numbers, this is not a feasible approach.

Is there a way of automating it using some formula or some built-in option?

答:
Please try (in Row1 of a big enough sheet):</p>

```<code>=ArrayFormula(ROW(A1:A8001)-4001)
</code>```

Body:
Please try (in Row1 of a big enough sheet):

=ArrayFormula(ROW(A1:A8001)-4001)


问:
Searching for literal string with Select-String and extracting part of string
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

```<code> Select-String -Path C:\file.inf -Pattern "$DeviceID"
</code>```

But it won't take the string as is, it's having a problem with the "\V":

```
Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand
```

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

答:
PowerShell is trying to do a regular expression match. Add the -SimpleMatch switch to look for the literal string in $DeviceID, without regex.

```<code>Select-String -Path C:\file.inf -Pattern $DeviceID -SimpleMatch
</code>```

Body:
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

 Select-String -Path C:\file.inf -Pattern "$DeviceID"

But it won't take the string as is, it's having a problem with the "\V":

Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

Body:
PowerShell is trying to do a regular expression match. Add the -SimpleMatch switch to look for the literal string in $DeviceID, without regex.

Select-String -Path C:\file.inf -Pattern $DeviceID -SimpleMatch


问:
What is the most appropriate HTTP response from a backend service when attempting to remove an entry that no longer exists in the Database?
My team is developing a simple backend service that provides the operations ADD, GET and REMOVE a very simple item. All are triggered by an http request and they do not much besides adding, getting and removing the item from a database.

Regarding the specific scenario in which a REMOVE operation is triggered on a item that is not present in the DB (e.g. was removed before), our question is what should be the response of the service? We having been debating options like 200 + some specific message, 410 - resource gone, amongst other 2XX and 4XX possibilities, but we haven't reached a consensus.

I hope this is not Bikeshedding.

Thank you for your help.

答:
What should be the response of the service?

It's important to highlight that status codes are meant to indicate the result of the server's attempt to understand and satisfy the client request. Having said that, 2xx status codes are unsuitable for this situation and should be avoided:

The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.

The most suitable status code would be in the 4xx range:

The 4xx (Client Error) class of status code indicates that the client seems to have erred.  Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

The 404 status code seems to be what you are looking for, as it indicates that the server can't find the requested resource:

6.5.4.  404 Not Found

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.  A 404 status code does not indicate whether this lack of representation is temporary or permanent; [...]

If you are concerned on how the client will understand the 404 reponse, you could provide them with a payload stating that such resource is no longer available.

And just bear in mind that ADD and REMOVE are not standard HTTP methods. Hopefully that was a typo and you are using POST (or PUT) and DELETE to express operations over your resources.


问:
Pyspark : How to pick the values till last from the first occurrence in an array based on the matching values in another column
I have an dataframe where I need to search a value present in one column i.e., StringType in another column i.e., ArrayType but I want to pick the values from the second column till last value in array from the first occurences of the first column.

Explained below with examples :

Input DF is below :

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]
</code>```

Output DF Should look like as below:

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]
</code>```

Body:
I have an dataframe where I need to search a value present in one column i.e., StringType in another column i.e., ArrayType but I want to pick the values from the second column till last value in array from the first occurences of the first column.

Explained below with examples :

Input DF is below :

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]

Output DF Should look like as below:

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]

Body:
This is what you want i think, i have implemented it on dummy data also:

import pyspark.sql.types as T
import pyspark.sql.functions as F

df = sqlContext.createDataFrame([['E101',["E101", "E102", "E103", "E104", "E105"]]],["eid", "mapped_eid"])
df.persist()
df.show(truncate = False)

+----+------------------------------+
|eid |mapped_eid                    |
+----+------------------------------+
|E101|[E101, E102, E103, E104, E105]|
+----+------------------------------+

@F.udf(returnType=T.ArrayType(T.StringType()))
def find_element(element,temp_list):
    count = 0
    res = []
    for i in range(len(temp_list)):
        if (count == 0) and (temp_list[i] != element):
            count = 1
            res.append(temp_list[i])
        elif count == 1:
            res.append(temp_list[i])
    return res

df.withColumn(
    "res_col",
    find_element(F.col("eid"), F.col("mapped_eid"))
).show(truncate = False)

+----+------------------------------+------------------------+
|eid |mapped_eid                    |res_col                 |
+----+------------------------------+------------------------+
|E101|[E101, E102, E103, E104, E105]|[E102, E103, E104, E105]|
+----+------------------------------+------------------------+

let me know if this works for you.


答:
Use DataFrame.combine_first instead join if need assign to same columns created before, last DataFrame.reindex by list of columns for expected ordering:

```<code>df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
orig = df.columns.tolist()

first = [2,2,2,2,2,2,2,2,2,2,2,2]
first = pd.DataFrame(first).T
first.index = [2]
df = df.combine_first(first)

second = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
second = pd.DataFrame(second).T
second.index = [1]
df = df.combine_first(second)

df = df.reindex(orig + first.columns.tolist(), axis=1)
print (df)
   A  B  C  D    0    1    2    3    4    5    6    7    8    9   10   11
0  1  5  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
2  3  3  0  1  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
3  4  2  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
</code>```

Body:
Here is what I have tried and what error I received:

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> df
   A  B  C  D
0  1  5  0  1
1  2  4  0  1
2  3  3  0  1
3  4  2  0  1
4  5  1  0  1
>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
>>> first = [2,2,2,2,2,2,2,2,2,2,2,2]
>>> first = pd.DataFrame(first).T
>>> first.index = [2]
>>> df = df.join(first)
>>> df
   A  B  C  D    0    1    2    3    4    5    6    7    8    9   10   11
0  1  5  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2  3  3  0  1  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
3  4  2  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
>>> second = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
>>> second = pd.DataFrame(second).T
>>> second.index = [1]
>>> df = df.join(second)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6815, in join
    rsuffix=rsuffix, sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 6830, in _join_compat
    suffixes=(lsuffix, rsuffix), sort=sort)
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 48, in merge
    return op.get_result()
  File "C:\Python35\lib\site-packages\pandas\core\reshape\merge.py", line 552, in get_result
    rdata.items, rsuf)
  File "C:\Python35\lib\site-packages\pandas\core\internals\managers.py", line 1972, in items_overlap_with_suffix
    '{rename}'.format(rename=to_rename))
ValueError: columns overlap but no suffix specified: Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype='object')

I am trying to create new list with the extra columns which I have to add at specific indexes of the main dataframe df.

When i tried the first it worked and you can see the output. But when I tried the same way with second I received the above mentioned error.

Kindly, let me know what I can do in this situation and achieve the goal I am expecting.

Body:
Use DataFrame.combine_first instead join if need assign to same columns created before, last DataFrame.reindex by list of columns for expected ordering:

df = pd.DataFrame({"A":[1,2,3,4,5],"B":[5,4,3,2,1],"C":[0,0,0,0,0],"D":[1,1,1,1,1]})
orig = df.columns.tolist()

first = [2,2,2,2,2,2,2,2,2,2,2,2]
first = pd.DataFrame(first).T
first.index = [2]
df = df.combine_first(first)

second = [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
second = pd.DataFrame(second).T
second.index = [1]
df = df.combine_first(second)

df = df.reindex(orig + first.columns.tolist(), axis=1)
print (df)
   A  B  C  D    0    1    2    3    4    5    6    7    8    9   10   11
0  1  5  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  2  4  0  1  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
2  3  3  0  1  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
3  4  2  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
4  5  1  0  1  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN


问:
JavaScript: Traversing and Reversing Singly-Linked Lists and Converting Between SLLs and Numbers
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

```<code>/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};

</code>```

答:
One way to do step 8 of your plan is to use the reduce method of Array.

Like this:

```<code>function ListNode(val)
{
   this.val = val;
   this.next = null;
}

const array2List = function(list, nextValue)
{
   let node = new ListNode(parseInt(nextValue));
   node.next = list;

   return node;
}

let numberArray = Array.from('807');

let list = numberArray.reduce(array2List, null);

console.log(list);
</code>```

Or change your plan and do something like:

```<code>const addTwoNumbers = function(l1, l2)
{
   let sumList = new ListNode(0);
   let node    = sumList;
   let carry   = 0;

   while (node)
   {
      let l1Value = (l1) ? parseInt(l1.val) : 0;
      let l2Value = (l2) ? parseInt(l2.val) : 0;

      let sum  = carry + l1Value + l2Value;

      node.val = sum % 10;
      carry    = (sum - node.val)/10;

      if (l1) { l1 = l1.next }
      if (l2) { l2 = l2.next }

      node.next = (l1 || l2 || carry) ? new ListNode(0) : null;
      node      = node.next;
   }

   return sumList;
}
</code>```

Body:
INTRO
Today, while doing a mock interview with a Facebook JavaScript problem, I blanked out on how to handle singly-linked lists.  The code I had so far is simply a function that takes 2 linked lists and returns another linked list.  My plan is below.

QUESTION
You are given two non-empty linked lists of arbitrary length representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
  342 + 465 = 807.

PLAN

Copy each number from the first linked list into an array in order.

Reverse the array.

Convert the array to a string then to an integer and store this in a variable.

Repeat this for the second linked list.

Sum the two numbers and store this value in a variable.

Convert this sum into a string.

Use Array.from on this string to convert it into an array then reverse the array.

?

Return the new linked list.

/*
 * Definition for singly-linked list.
 * function ListNode(val)
 * {
 *  this.val = val;
 *  this.next = null;
 * }
 */

/* Expected input and output.
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

var addTwoNumbers = function(l1, l2)
{

};

Body:
One way to do step 8 of your plan is to use the reduce method of Array.

Like this:

function ListNode(val)
{
   this.val = val;
   this.next = null;
}

const array2List = function(list, nextValue)
{
   let node = new ListNode(parseInt(nextValue));
   node.next = list;

   return node;
}

let numberArray = Array.from('807');

let list = numberArray.reduce(array2List, null);

console.log(list);

Or change your plan and do something like:

const addTwoNumbers = function(l1, l2)
{
   let sumList = new ListNode(0);
   let node    = sumList;
   let carry   = 0;

   while (node)
   {
      let l1Value = (l1) ? parseInt(l1.val) : 0;
      let l2Value = (l2) ? parseInt(l2.val) : 0;

      let sum  = carry + l1Value + l2Value;

      node.val = sum % 10;
      carry    = (sum - node.val)/10;

      if (l1) { l1 = l1.next }
      if (l2) { l2 = l2.next }

      node.next = (l1 || l2 || carry) ? new ListNode(0) : null;
      node      = node.next;
   }

   return sumList;
}