问:
Modal dimmed and nothing clickable on it
I'm trying to make a Bootstrap Modal open when a button is clicked, it does open but the whole screen including the modal is dimmed and I can not click on any of the buttons on it. Any idea what I am doing wrong? I am using Bootstrap 4 beta 2

    <meta charset="utf-8" />
    <meta name="viewport"
     content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />

    <title>My site</title>

    <link rel="stylesheet"
     href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
     integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
     crossorigin="anonymous" />

       Home
       <button class="navbar-toggler" type="button" data-toggle="collapse"
        data-target="#navbarResponsive" aria-controls="navbarResponsive"
        aria-expanded="false" aria-label="Toggle navigation">

       </button>
       <button type="button" class="btn btn-danger" data-toggle="modal"
        data-target="#myModal">Upload</button>

Home
           (current)

About

Contact

Modal title

          <button type="button" class="close" data-dismiss="modal"
           aria-label="Close">
           ×
          </button>

...

          <button type="button" class="btn btn-secondary"
           data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save
           changes</button>

Copyright © MySite
        2017

    ```

答:
```<code>.modal-backdrop.show{
  z-index:1;
}
</code>```

This will bring modal on the top.

.modal-backdrop.show {
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head th:fragment="head">
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta name="description" content="" />
  <meta name="author" content="" />

  <title>My site</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />

  <script>
    $('#myModal').on('shown.bs.modal', function() {
      $('#myInput').focus()
    })
  </script>
</head>

<body>

  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">

    <div class="container">
      Home
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
       </button>
      <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal">Upload</button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">Home
           <span class="sr-only">(current)</span>
         </li>
          <li class="nav-item">About</li>
          <li class="nav-item">Contact
          </li>
        </ul>
      </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="5" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           <span aria-hidden="true">×</span>
          </button>
          </div>
          <div class="modal-body">...</div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save
           changes</button>
          </div>
        </div>
      </div>
    </div>

  </nav>

  <!-- Footer -->
  <footer class="py-5 bg-dark">
    <div class="container">
      <p class="m-0 text-center text-white">Copyright © MySite 2017
      </p>
    </div>
    <!-- /.container -->

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

    <!--modal-->
    <script>
      $(document).ready(function() {
        $("#myModal").modal();
      });
    </script>
  </footer>
</body>

</html></code>```

Body:
.modal-backdrop.show{
  z-index:1;
}

This will bring modal on the top.

.modal-backdrop.show {
  z-index: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head th:fragment="head">
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta name="description" content="" />
  <meta name="author" content="" />

  <title>My site</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />

  <script>
    $('#myModal').on('shown.bs.modal', function() {
      $('#myInput').focus()
    })
  </script>
</head>

<body>

  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">

    <div class="container">
      <a class="navbar-brand" href="/">Home</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
       </button>
      <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal">Upload</button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active"><a class="nav-link" href="#">Home
           <span class="sr-only">(current)</span>
         </a></li>
          <li class="nav-item"><a class="nav-link" href="#">About</a></li>
          <li class="nav-item"><a class="nav-link" href="#">Contact</a>
          </li>
        </ul>
      </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="5" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           <span aria-hidden="true">&times;</span>
          </button>
          </div>
          <div class="modal-body">...</div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save
           changes</button>
          </div>
        </div>
      </div>
    </div>

  </nav>

  <!-- Footer -->
  <footer class="py-5 bg-dark">
    <div class="container">
      <p class="m-0 text-center text-white">Copyright &copy; MySite 2017
      </p>
    </div>
    <!-- /.container -->

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

    <!--modal-->
    <script>
      $(document).ready(function() {
        $("#myModal").modal();
      });
    </script>
  </footer>
</body>

</html>


来源: stackexchange

问:
Basic split screen with css /html
I'm attempting to create two separate divs, one covering the left half of the screen and one covering the right. Why does my code create only one div covering the left half of the page when I have included float:left and float:right? And how can I solve it?

#col-1 {
  position: fixed;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: fixed;
  width: 50%;
  float: right;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="col-1">
  <h1>This is half of a page</h1>
</div>
<div id="col-2">
  <h1>This is another half of a page</h1>
</div></code>```

View on JSFiddle

答:
Edit - My description of the problem wasn't fully correct, but the solution works none the less. Floats don't work well with position: fixed

#col-1 {
  position: fixed;
  width: 50%;
  left: 0;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: fixed;
  width: 50%;
  left: 50%;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="col-1">
  <h1>This is half of a page</h1>
</div>
<div id="col-2">
  <h1>This is another half of a page</h1>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Basic split screen with css /html

Body:
I'm attempting to create two separate divs, one covering the left half of the screen and one covering the right. Why does my code create only one div covering the left half of the page when I have included float:left and float:right? And how can I solve it?

#col-1 {
  position: fixed;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: fixed;
  width: 50%;
  float: right;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}

This is half of a page

This is another half of a page

View on JSFiddle

Body:
Edit - My description of the problem wasn't fully correct, but the solution works none the less. Floats don't work well with position: fixed

#col-1 {
  position: fixed;
  width: 50%;
  left: 0;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: fixed;
  width: 50%;
  left: 50%;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}

<div id="col-1">
  <h1>This is half of a page</h1>
</div>
<div id="col-2">
  <h1>This is another half of a page</h1>
</div>


问:
Entity Framework .First() Caches Query Data
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

```<code>  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }
</code>```

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

答:
Your TransactionScope must be inside your context and begin a transaction

you have no open transaction in your context if you declare them like you did

using information such as Celso Livero said => MSDN Page

```<code>using (var context = new SekhavatDBEntities())
{
    using (var dbContextTransaction = context.Database.BeginTransaction())
    {
        var account = context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;
        context.SaveChanges();

        dbContextTransaction.Rollback();
    }
}
</code>```

use another context to check the data

```<code>using (var context = new SekhavatDBEntities())
{
    var account2 = context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
}
</code>```

First() or Find() is not your problem with the transaction.
and like Erk said,  see there is already entity with the same key in context

the data is caching in your context, not because you are using First() or Find()

Body:
According to Entity Framework documents, Entity Framework will only cache data when using .Find() to query data.

In the following sample I got query data cached when using .First():

  static void Main(string[] args)
    {
        var trxScope = new TransactionScope();
        var context = new SekhavatDBEntities();

        //the value of Balance is Zero
        var account =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;

        context.SaveChanges();
        trxScope.Dispose();

        var trxScope2 = new TransactionScope();
        var account2 =
            context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));

        //Balance of account2 Is 50 Now!
        trxScope2.Dispose();
    }

Why is account2's Balance 50? According to my considerations, it should be 0.

Thanks in advance

Body:
Your TransactionScope must be inside your context and begin a transaction

you have no open transaction in your context if you declare them like you did

using information such as Celso Livero said => MSDN Page

using (var context = new SekhavatDBEntities())
{
    using (var dbContextTransaction = context.Database.BeginTransaction())
    {
        var account = context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
        account.Balance = 50;
        context.SaveChanges();

        dbContextTransaction.Rollback();
    }
}

use another context to check the data

using (var context = new SekhavatDBEntities())
{
    var account2 = context.Accounts.First(acc => acc.Id == new Guid("79B7AAC6-AD2D-4824-907E-16ADB4C41EE1"));
}

First() or Find() is not your problem with the transaction.
and like Erk said,  see there is already entity with the same key in context

the data is caching in your context, not because you are using First() or Find()


问:
how to remove spaces in a list that has a specific character
how do you get a list to fix the spaces in the list m.

```<code>m = ['m, a \n', 'l, n \n', 'c, l\n']
for i in m:
    if (' ') in i:
        i.strip(' ')
</code>```

I got:

```<code>'m, a \n'
'l, n \n'
'c, l\n'
</code>```

and I want it to return:

```<code>['m, a\n', 'l, n\n', 'c, l\n']
</code>```

答:
Your code wouldn't be useful in a script; you are just seeing the REPL displaying the result of the expression i.strip(' '). In a script, that value would just be ignored.

To create a list, use a list comprehension:

```<code>result = [i.strip(' ') for i in m if ' ' in i]
</code>```

Note, however, strip only removes the requested character from either end; in your data, the space precedes the newline. You'll need to do something like removing the newline as well, then put it back:

```<code>    result = ["%s\n" % i.strip() for i in m if ' ' in i]
</code>```

Body:
how do you get a list to fix the spaces in the list m.

m = ['m, a \n', 'l, n \n', 'c, l\n']
for i in m:
    if (' ') in i:
        i.strip(' ')

I got:

'm, a \n'
'l, n \n'
'c, l\n'

and I want it to return:

['m, a\n', 'l, n\n', 'c, l\n']

Body:
Your code wouldn't be useful in a script; you are just seeing the REPL displaying the result of the expression i.strip(' '). In a script, that value would just be ignored.

To create a list, use a list comprehension:

result = [i.strip(' ') for i in m if ' ' in i]

Note, however, strip only removes the requested character from either end; in your data, the space precedes the newline. You'll need to do something like removing the newline as well, then put it back:

    result = ["%s\n" % i.strip() for i in m if ' ' in i]


问:
How to check if url exist synchronously in NodeJs ?
I would like to know if there is a way to check whether an URL exists synchronously. In fact I am downloading files so I need to make sure these URLs exists before trying to download them. Here is the package I am using to check if these URLs are valid https://github.com/boblauer/url-exists</p>

答:
In short, you can't.

You can't force an async request to be synchronous.

You have a couple different syntactical approaches (Promises, async/await, events via Node.js http, callbacks, etc), but it's all going to boil down to being async in some way.

The async/await pattern will look the most synchronous, but it will still be async.

The package you're using specifically uses the callback pattern, so you'll need to adjust your other code to be async. You can mix and match these approaches.

My personal preference is to wrap non-Promise patterns into a Promise pattern, then use async/await syntax throughout. Again, this look synchronous, but keep in mind it isn't and deal with it accordingly.

You can wrap callback syntax as a Promise like this:

```<code>const urlExistsPromise = url => new Promise((resolve, reject) =>
    urlExists(url, (err, exists) => err ? reject(err) : resolve(exists));
</code>```

And you can use it like this:

```<code>urlExistsPromise(url).then(exists => console.log(exists));
</code>```

or as await (inside a function labeled async):

```<code>const exists = await urlExistsPromise(url);
</code>```

Body:
In short, you can't.

You can't force an async request to be synchronous.

You have a couple different syntactical approaches (Promises, async/await, events via Node.js http, callbacks, etc), but it's all going to boil down to being async in some way.

The async/await pattern will look the most synchronous, but it will still be async.

The package you're using specifically uses the callback pattern, so you'll need to adjust your other code to be async. You can mix and match these approaches.

My personal preference is to wrap non-Promise patterns into a Promise pattern, then use async/await syntax throughout. Again, this look synchronous, but keep in mind it isn't and deal with it accordingly.

You can wrap callback syntax as a Promise like this:

const urlExistsPromise = url => new Promise((resolve, reject) =>
    urlExists(url, (err, exists) => err ? reject(err) : resolve(exists));

And you can use it like this:

urlExistsPromise(url).then(exists => console.log(exists));

or as await (inside a function labeled async):

const exists = await urlExistsPromise(url);


问:
Generated aws gateway android sdk with cognito authorization not having authorisation paramenter
I created AWS gateway API using chalice, using Cognito as the authorizer.

I am able to successfully login to the app using Cognito.

I am trying to access the APIs from the android app using generated AWS gateway SDK. But the generated client doesn't have param in the method (@Parameter( name = "Authorization", location = "header"))

I am able to call the APIs using postman by manually adding Authorization key and token(from the android app) in the header.

In this question, its mentioned that by adding some missing configuration we can generate the SDK properly. But I am not able to find the missing config.

答:
You can add Authorization as one of the parameters in the Method, then deploy the API to a stage. After you deploy the API, you can generate the Android SDK from the stage.

In the new generated Android SDK, you should be able to have param in the method (@Parameter( name = "Authorization", location = "header")).

How to add a parameters in the Method

```<code>aws apigateway put-method --rest-api-id <value> \
                          --resource-id <value> \
                          --http-method <value> \
                          --api-key-required \
                          --request-parameters "method.request.header.Authorization=true"
</code>```

Body:
You can add Authorization as one of the parameters in the Method, then deploy the API to a stage. After you deploy the API, you can generate the Android SDK from the stage.

In the new generated Android SDK, you should be able to have param in the method (@Parameter( name = "Authorization", location = "header")).

How to add a parameters in the Method

aws apigateway put-method --rest-api-id <value> \
                          --resource-id <value> \
                          --http-method <value> \
                          --api-key-required \
                          --request-parameters "method.request.header.Authorization=true"


问:
How to replace a string with the array and index of an array as a string?
Consider

```<code>var arr = ["a","b","c"];
var string = "Hello {1} is a friend of {2} and {3}";
</code>```

so replacing {1} with "a", {2} with "b", and {3} with "c"

How do we do using JavaScript?

答:
You are looking for template strings in ES6.

```<code>const arr = ['a', 'b', 'c'];

const string = `Hello ${arr[0]} is a friend of ${arr[1]} and ${arr[2]}`;
</code>```

Addind some destructuring

```<code>const [
  a,
  b
  c,
] = ['a', 'b', 'c'];

const string = `Hello ${a} is a friend of ${b} and ${c}`;
</code>```

@EDIT in ES5, the good old

```<code>var arr = ['a', 'b', 'c'];

var string = 'Hello ' + arr[0] + ' is a friend of ' + arr[1] + ' and ' + arr[2];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider

var arr = ["a","b","c"];
var string = "Hello {1} is a friend of {2} and {3}";

so replacing {1} with "a", {2} with "b", and {3} with "c"

How do we do using JavaScript?

Body:
You are looking for template strings in ES6.

const arr = ['a', 'b', 'c'];

const string = `Hello ${arr[0]} is a friend of ${arr[1]} and ${arr[2]}`;

Addind some destructuring

const [
  a,
  b
  c,
] = ['a', 'b', 'c'];

const string = `Hello ${a} is a friend of ${b} and ${c}`;

@EDIT in ES5, the good old

var arr = ['a', 'b', 'c'];

var string = 'Hello ' + arr[0] + ' is a friend of ' + arr[1] + ' and ' + arr[2];


问:
Need help finding an error in my C project
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

```<code>#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}
</code>```

答:
I dont know why you are using command line argument, if the requirement of your project is to use four functions . I have given the following code which will work for your project.
There is no need of writing two seperate functions for forward data and reverse data. You can do it by using same function for both. Just passing tha value will be reverse.
dont use semicolon in the first line of function definition.</p>

Body:
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}


问:
Merging panel data in python using loop
I'm trying to merging the panel dataframes by idcode and do a sorting process by 'idcode' in my dataframes.

My data variable names are wave68, wave69...., wave71.

Overall, I have two problems:

First, I want to sort the dataframes by using a loop, but I don't know how to assign the looping file names, i.e. wave+i?

Second, I don't know how to make the loop algorithm to merge the dataframes correctly.

The final result that I want is wide form Panel data sorted by 'idcode' by wave68,69,70.. by using loop.

```<code>import pandas as pd
import numpy as np

wave68 = pd.read_csv('panel_data/wave68.csv')
wave69 = pd.read_csv('panel_data/wave69.csv')
wave70 = pd.read_csv('panel_data/wave70.csv')
wave71 = pd.read_csv('panel_data/wave71.csv')

df = [wave68,wave69,wave70,wave71]

def my_sorter(file_name,var):
    for i in file_name:
        file_name[i].sort_values(by=[var])

wave68 = wave68.sort_values(by=['idcode'])
wave69 = wave69.sort_values(by=['idcode'])
wave70 = wave70.sort_values(by=['idcode'])

merged = pd.merge(wave68, wave69, on='idcode')
merged = pd.merge(merged, wave70, on='idcode')
merged = pd.merge(merged, wave71, on='idcode')

merged.head(20)
</code>```

答:
For merging across multiple dfs, consider the chain merge with reduce. Alternatively, if using one column, run horizontal merge with pd.concat() setting axis=1 but prior to that set the index of each dataframe to the join column. Afterwards, you can then sort on your final dataframe only once.

Do note: unlike other data analytics tools, in pandas you do not need to sort pior to merging.

Merge with reduce (only matched idcodes across all dfs will be kept, otherwise use a left join)

```<code>from functools import reduce
...
dfList = [wave68, wave69, wave70, wave71]

finaldf = reduce(lambda left, right: pd.merge(left, right, on=['idcode']), dfList).sort_values(['idcode'])
</code>```

Merge with pd.concat (any unmatched idcodes will retain NaNs)

```<code>dfList = [wave68, wave69, wave70, wave71]

finaldf = pd.concat([df.set_index('idcode') for df in dfList], axis=1).sort_index()
</code>```

Title: Merging panel data in python using loop

Body:
I'm trying to merging the panel dataframes by idcode and do a sorting process by 'idcode' in my dataframes.

My data variable names are wave68, wave69...., wave71.

Overall, I have two problems:

First, I want to sort the dataframes by using a loop, but I don't know how to assign the looping file names, i.e. wave+i?

Second, I don't know how to make the loop algorithm to merge the dataframes correctly.

The final result that I want is wide form Panel data sorted by 'idcode' by wave68,69,70.. by using loop.

import pandas as pd
import numpy as np

wave68 = pd.read_csv('panel_data/wave68.csv')
wave69 = pd.read_csv('panel_data/wave69.csv')
wave70 = pd.read_csv('panel_data/wave70.csv')
wave71 = pd.read_csv('panel_data/wave71.csv')

df = [wave68,wave69,wave70,wave71]

def my_sorter(file_name,var):
    for i in file_name:
        file_name[i].sort_values(by=[var])

wave68 = wave68.sort_values(by=['idcode'])
wave69 = wave69.sort_values(by=['idcode'])
wave70 = wave70.sort_values(by=['idcode'])

merged = pd.merge(wave68, wave69, on='idcode')
merged = pd.merge(merged, wave70, on='idcode')
merged = pd.merge(merged, wave71, on='idcode')

merged.head(20)

Body:
For merging across multiple dfs, consider the chain merge with reduce. Alternatively, if using one column, run horizontal merge with pd.concat() setting axis=1 but prior to that set the index of each dataframe to the join column. Afterwards, you can then sort on your final dataframe only once.

Do note: unlike other data analytics tools, in pandas you do not need to sort pior to merging.

Merge with reduce (only matched idcodes across all dfs will be kept, otherwise use a left join)

from functools import reduce
...
dfList = [wave68, wave69, wave70, wave71]

finaldf = reduce(lambda left, right: pd.merge(left, right, on=['idcode']), dfList).sort_values(['idcode'])

Merge with pd.concat (any unmatched idcodes will retain NaNs)

dfList = [wave68, wave69, wave70, wave71]

finaldf = pd.concat([df.set_index('idcode') for df in dfList], axis=1).sort_index()


问:
Accessing the outer scope in Python 2.6
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

```
def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456
```

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.

答:
This is not how nonlocal works. It doesn't provide dynamic scoping (which is just a huge PITA waiting to happen and even more rarely useful than your average "evil" feature). It just fixes up lexical scoping.

Anyway, you can't do what you have in mind (and I would say that this is a good thing). There's not even a dirty but easy hack (and while we're at it: such hacks are not discouraged because they generally perform a bit worse!). Just forget about it and solve the real problem properly (you didn't name it, so we can't say anything on this).

The closest you could get is defining some object that carries everything you want to share and pass that around explicitly (e.g. make a class and use self, as suggested in another answer). But that's relatively cumbersome to do everywhere, and still hackery (albeit better than dynamic scoping, because "explicit is better than implicit").

ContentLicense: CC BY-SA 2.5

Title: Accessing the outer scope in Python 2.6

Body:
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.


问:
QBWC1048: QuickBooks Web Connector could not verify the web application server certificate. QBWC1051: The new application was not added
We use web connector(2.1.0.30)  to add an aplication, but we get
 QBWC1048 and QBWC1051 error messages.

Anyone have any suggestions on how to solve this problem?

Here is our log file:

> 20151026.03:13:41 UTC : QWCReader.ParseQWC() : Contents of QWC file: -
> <QBWCXML>    <AppName>200Connect </AppName> <AppID></AppID>
> <AppURL>https://www.jframework.cn:4431/Areas/JOBOP/QBWebConnector/ExportToQuick.asmx</AppURL>
> <AppDescription>A short description for ExportToQuick</AppDescription>
> <AppSupport>https://www.jframework.cn:4431</AppSupport>
> <UserName>donet||lowes@pasasoft.com</UserName>
> <OwnerID>{230A7DC2-E8EF-7946-738A-000EC198A2D2}</OwnerID>
> <FileID>{230A7DC2-E8EF-7946-738A-000EC198A2D2}</FileID>
> <QBType>QBFS</QBType>
> <Scheduler>  <RunEveryNMinutes>15</RunEveryNMinutes>    </Scheduler>
> </QBWCXML>
> 20151026.03:13:41 UTC : QBWebConnector.WebServiceManager.ReadQWC(QWCReader QWC) : Parsing
> application configuration xml file to load its content to variables
> 20151026.03:13:41 UTC :  : QBWC1048: QuickBooks Web Connector could not verify the web application server certificate.
>
>
> Certificate URL:
> https://www.jframework.cn:4431/Areas/JOBOP/QBWebConnector/ExportToQuick.asmxStackTrace:
> at System.Net.HttpWebRequest.GetResponse()    at
> QBWebConnector.QWCReader.CheckCertURL()
>
> Message (description of the exception): The underlying connection was
> closed: An unexpected error occurred on a receive.
>
> Source (name of application or object that caused the exception):
> System
>
> TargetSite (method that threw the exception): System.Net.WebResponse
> GetResponse()
>
> InnerException: System.ArgumentOutOfRangeException: Length cannot be
> less than zero. Parameter name: length    at
> QBWebConnector.myCertPolicy.CheckValidationResult(ServicePoint
> srvPoint, X509Certificate cert, WebRequest request, Int32
> certificateProblem)    at System.Net.PolicyWrapper.CheckErrors(String
> hostName, X509Certificate certificate, X509Chain chain,
> SslPolicyErrors sslPolicyErrors)    at
> System.Net.CertPolicyValidationCallback.Callback(Object state)    at
> System.Threading.ExecutionContext.RunInternal(ExecutionContext
> executionContext, ContextCallback callback, Object state, Boolean
> preserveSyncCtx)    at
> System.Threading.ExecutionContext.Run(ExecutionContext
> executionContext, ContextCallback callback, Object state, Boolean
> preserveSyncCtx)    at
> System.Threading.ExecutionContext.Run(ExecutionContext
> executionContext, ContextCallback callback, Object state)    at
> System.Net.CertPolicyValidationCallback.Invoke(String hostName,
> ServicePoint servicePoint, X509Certificate certificate, WebRequest
> request, X509Chain chain, SslPolicyErrors sslPolicyErrors)    at
> System.Net.ServicePoint.HandshakeDoneProcedure.CertValidationCallback(String
> hostName, X509Certificate certificate, X509Chain chain,
> SslPolicyErrors sslPolicyErrors)    at
> System.Net.Security.SecureChannel.VerifyRemoteCertificate(RemoteCertValidationCallback
> remoteCertValidationCallback)    at
> System.Net.Security.SslState.CompleteHandshake()    at
> System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
> message, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
> readBytes, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
> AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
> message, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
> readBytes, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
> AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
> message, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
> readBytes, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
> AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
> message, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
> count, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,
> Byte[] buffer, AsyncProtocolRequest asyncRequest)    at
> System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult
> lazyResult)    at
> System.Net.TlsStream.CallProcessAuthentication(Object state)    at
> System.Threading.ExecutionContext.RunInternal(ExecutionContext
> executionContext, ContextCallback callback, Object state, Boolean
> preserveSyncCtx)    at
> System.Threading.ExecutionContext.Run(ExecutionContext
> executionContext, ContextCallback callback, Object state, Boolean
> preserveSyncCtx)    at
> System.Threading.ExecutionContext.Run(ExecutionContext
> executionContext, ContextCallback callback, Object state)    at
> System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
> at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
> at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32
> size)    at System.Net.ConnectStream.WriteHeaders(Boolean async)
>
>
> 20151026.03:13:42 UTC : QBWebConnector.WebServiceManager.ReadQWC(QWCReader QWC) : QBWC1048:
> QuickBooks Web Connector could not verify the web application server
> certificate.
>
> QBWC1051: The new application was not added. ```

答: This error could occured, If your QuickBooks Web Connect application is not updated.Or may be SSL certificate issue with Internet Explorer. Please follow this link to fix this error code. </p>


问:
How to add security on my node.js web pages?

Beginner NodeJs here.

I have created a registration and login page using nodejs and mysql.

It is just a basic setup wherein:

I have a form which submit to nodejs to register (will add a row in mysql database with email and password) and login/authenticate (which will just do a lookup in mysql and search for equivalent email and password).

I can register and login no problem.

The steps I followed are from here:
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example

I have also edited the code a little that if It login successfully, it will redirect to a page via this code..

```<code>    if (password==results[0].password){
                // res.json({
                //     status:true,
                //     message: 'successfully authenticated'
                // });
                var sample = req.body.email;
                var newsample = sample.split('@')[0];
                return res.redirect('/users/1/?username=' + newsample);
</code>```

and I also have this route in my users.js

```<code>    router.get('/1/*', function(req, res, next) {
      var q = url.parse(req.url, true).query;
      var txt = "Welcome" + q.username;
      res.send(txt);
     });
</code>```

it works fine.

What I want to accomplish is that, I can only access the link

http://localhost:3000/users/1/?username=*

if I came from the login page and have authenticated.

Hope you can guide me on how to do about it or a hint on how it is done.

I have search but only found links which uses a different library or authentication which i find hard to understand. Pardon my being noob.

A working example would be very helpful for me.

Thank you.

答:
I think you handle user authentication in a hard way, you can use passport.js it will help you a lot

but you can use the session to save what is necessary to check if the user is logged in like user id and check this session in a custom middleware

Body:
Beginner NodeJs here.

I have created a registration and login page using nodejs and mysql.

It is just a basic setup wherein:

I have a form which submit to nodejs to register (will add a row in mysql database with email and password) and login/authenticate (which will just do a lookup in mysql and search for equivalent email and password).

I can register and login no problem.

The steps I followed are from here:
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example

I have also edited the code a little that if It login successfully, it will redirect to a page via this code..

    if (password==results[0].password){
                // res.json({
                //     status:true,
                //     message: 'successfully authenticated'
                // });
                var sample = req.body.email;
                var newsample = sample.split('@')[0];
                return res.redirect('/users/1/?username=' + newsample);

and I also have this route in my users.js

    router.get('/1/*', function(req, res, next) {
      var q = url.parse(req.url, true).query;
      var txt = "Welcome" + q.username;
      res.send(txt);
     });

it works fine.

What I want to accomplish is that, I can only access the link

http://localhost:3000/users/1/?username=*

if I came from the login page and have authenticated.

Hope you can guide me on how to do about it or a hint on how it is done.

I have search but only found links which uses a different library or authentication which i find hard to understand. Pardon my being noob.

A working example would be very helpful for me.

Thank you.


问:
using $emit to pass a function from child to parent in angularJS
I want to send the result of a function to a parent controller from a child.

Here is my file structure

```<code>-submission.controller.js
--calculate.controller.js
</code>```

In calculate.controller.js i have a function that looks like:

```<code>function validForm() {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
}
</code>```

and i want to send the results of this function to the parent (submission.controller.js) and use it as an argument in a function.

```<code>showValidZip() {
  if (validForm() === true) {
    return false;
  }
  return true;
};
</code>```

So far i've tried to use $emit and $on to send validForm from calculate to submission but havent had much luck in doing so.

for example:

```<code>$scope.$emit('validForm', function () {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
});
</code>```

and

```<code>$scope.showValidZip = function () {
  if ($scope.$on('validForm') === true) {
    return false;
  }
  return true;
};
</code>```

but it's not really working as intended.

答:
Assuming the controllers are used in such a way that they are parent-child of each other, you have two issues with the code you have provided:

$scope.$emit expects arguments next to event name so if you want to pass a function's result, you can have a seperate function and then call it from there like $scope.$emit('validForm', myFunctionCall())

Also, you can't use $scope.$on like that since it doesn't return anything. If you want to access the values sent from $emit, you can do that inside the listener function (second argument) i.e. something like this:

```<code>$scope.$on('validForm', function(event, argument1) {
  // argument1 is the same as return value of myFunctionCall()
});
</code>```

Body:
I want to send the result of a function to a parent controller from a child.

Here is my file structure

-submission.controller.js
--calculate.controller.js

In calculate.controller.js i have a function that looks like:

function validForm() {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
}

and i want to send the results of this function to the parent (submission.controller.js) and use it as an argument in a function.

showValidZip() {
  if (validForm() === true) {
    return false;
  }
  return true;
};

So far i've tried to use $emit and $on to send validForm from calculate to submission but havent had much luck in doing so.

for example:

$scope.$emit('validForm', function () {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
});

and

$scope.showValidZip = function () {
  if ($scope.$on('validForm') === true) {
    return false;
  }
  return true;
};

but it's not really working as intended.

Body:
Assuming the controllers are used in such a way that they are parent-child of each other, you have two issues with the code you have provided:

$scope.$emit expects arguments next to event name so if you want to pass a function's result, you can have a seperate function and then call it from there like $scope.$emit('validForm', myFunctionCall())

Also, you can't use $scope.$on like that since it doesn't return anything. If you want to access the values sent from $emit, you can do that inside the listener function (second argument) i.e. something like this:

$scope.$on('validForm', function(event, argument1) {
  // argument1 is the same as return value of myFunctionCall()
});


答:
You can use regex:

```<code>import re
m = ['m, a \n', 'l, n \n', 'c, l\n']
final_m = [re.sub('(?<=[a-zA-Z])\s+(?=\n)', '', i) for i in m]
</code>```

Output:

```<code>['m, a\n', 'l, n\n', 'c, l\n']
</code>```

Title: how to remove spaces in a list that has a specific character

Body:
You can use regex:

import re
m = ['m, a \n', 'l, n \n', 'c, l\n']
final_m = [re.sub('(?<=[a-zA-Z])\s+(?=\n)', '', i) for i in m]

Output:

['m, a\n', 'l, n\n', 'c, l\n']


问:
Turning a 2D array into a sparse array of arrays
I have an array of x=[[3,1],[2,2]] and I want to turn it into x[3][1]=1 and x[2][2]=1. The code should also work for longer arrays like x=[[3,1],[2,12],[3,3]].

答:
You can use array#reduce to iterate through your array and check if the array exist corresponding to first value, in case it's not initialise with [] and then assign the value to that index.

var x=[[3,1],[2,12],[3,3]];
var result = x.reduce((r,[a,b]) => {
  r[a] = r[a] || [];
  r[a][b] = 1;
  return r;
},[]);
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You can use array#reduce to iterate through your array and check if the array exist corresponding to first value, in case it's not initialise with [] and then assign the value to that index.

var x=[[3,1],[2,12],[3,3]];
var result = x.reduce((r,[a,b]) => {
  r[a] = r[a] || [];
  r[a][b] = 1;
  return r;
},[]);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


答: Your Code also includes a fixed positioning of each div, taking each out of the normal flow of the page, thus stacking them on top of each other. </p>

Title: Basic split screen with css /html

Body:
I'm attempting to create two separate divs, one covering the left half of the screen and one covering the right. Why does my code create only one div covering the left half of the page when I have included float:left and float:right? And how can I solve it?

#col-1 {
  position: fixed;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: fixed;
  width: 50%;
  float: right;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}

This is half of a page

This is another half of a page

View on JSFiddle


问:
import XMindDocument to create MINDMAP
I'm tring to import XMindDocument from mekk.xmind but I've gotten the error:

"ImportError: No module named mekk.xmind"

I've used pip to install mekk.xmind

```<code>pip install mekk.xmind
</code>```

error: command '"C:\Users\frank\AppData\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe"' failed with exit status 2

Can anyone help?

答:
The module is broken.

I ended up manually copying the files cp -r <location>/mekk/xmind mekkxmind (where <location> can be found via pip show mekk.xmind) to my working directory and import it from there:

```<code>from mekkxmind import XMindDocument

xmind = XMindDocument.create(u"First sheet title", u"Root subject")
first_sheet = xmind.get_first_sheet()
root_topic = first_sheet.get_root_topic()

root_topic.add_subtopic(u"First item")
root_topic.add_subtopic(u"Second item")
t = root_topic.add_subtopic(u"Third item")
t.add_subtopic(u"Second level - 1")
t.add_subtopic(u"Second level - 2")
root_topic.add_subtopic(u"Detached topic", detached = True)
t.add_subtopic(u"Another detached", detached = True)
t.add_marker("flag-red")
root_topic.add_subtopic(u"Link example").set_link("https://stackoverflow.com/questions/42896645/import-xminddocument-to-create-mindmap")
root_topic.add_subtopic(u"With note").set_note(u"""This is just some dummy note.""")

xmind.pretty_print()
# xmind.save('test.xmind')
</code>```

Title: import XMindDocument to create MINDMAP

Body:
I'm tring to import XMindDocument from mekk.xmind but I've gotten the error:

"ImportError: No module named mekk.xmind"

I've used pip to install mekk.xmind

pip install mekk.xmind

error: command '"C:\Users\frank\AppData\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe"' failed with exit status 2

Can anyone help?

Body:
The module is broken.

I ended up manually copying the files cp -r <location>/mekk/xmind mekkxmind (where <location> can be found via pip show mekk.xmind) to my working directory and import it from there:

from mekkxmind import XMindDocument

xmind = XMindDocument.create(u"First sheet title", u"Root subject")
first_sheet = xmind.get_first_sheet()
root_topic = first_sheet.get_root_topic()

root_topic.add_subtopic(u"First item")
root_topic.add_subtopic(u"Second item")
t = root_topic.add_subtopic(u"Third item")
t.add_subtopic(u"Second level - 1")
t.add_subtopic(u"Second level - 2")
root_topic.add_subtopic(u"Detached topic", detached = True)
t.add_subtopic(u"Another detached", detached = True)
t.add_marker("flag-red")
root_topic.add_subtopic(u"Link example").set_link("https://stackoverflow.com/questions/42896645/import-xminddocument-to-create-mindmap")
root_topic.add_subtopic(u"With note").set_note(u"""This is just some dummy note.""")

xmind.pretty_print()
# xmind.save('test.xmind')


答:
Your options are to use global variables,

```<code>s = None
n = None

def outer(self):
    global s
    global n
    s = 'qwerty'
    n = 123
    modify()

def modify(self):
    global s
    global n
    s = 'abcd'
    n = 456
</code>```

or define those as methods and use a class or instance variable.

```<code>class Foo(object):
    def __init__(self):
        self.s = None
        self.n = None

    def outer(self):
        self.s = 'qwerty'
        self.n = 123
        self.modify()

    def modify(self):
        self.s = 'abcd'
        self.n = 456
</code>```

Title: Accessing the outer scope in Python 2.6

Body:
Your options are to use global variables,

s = None
n = None

def outer(self):
    global s
    global n
    s = 'qwerty'
    n = 123
    modify()

def modify(self):
    global s
    global n
    s = 'abcd'
    n = 456

or define those as methods and use a class or instance variable.

class Foo(object):
    def __init__(self):
        self.s = None
        self.n = None

    def outer(self):
        self.s = 'qwerty'
        self.n = 123
        self.modify()

    def modify(self):
        self.s = 'abcd'
        self.n = 456


问:
How can I have this program add the user input into my linked list?
```<code>import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}
</code>```

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

答:
just change it :</p>

```<code>LinkedList<String> linky = new LinkedList<String>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();
    linky.add(0, name);
    System.out.println("Enter gender ");
    gender=input.nextLine();
    linky.add(1, gender);
    System.out.println("Enter hair color ");
    hairColor=input.nextLine();
linky.add(2, hairColor);
</code>```

Body:
import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

Body:
just change it :

LinkedList<String> linky = new LinkedList<String>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();
    linky.add(0, name);
    System.out.println("Enter gender ");
    gender=input.nextLine();
    linky.add(1, gender);
    System.out.println("Enter hair color ");
    hairColor=input.nextLine();
linky.add(2, hairColor);


答:
#col-1 {
  position: relative;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: relative;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="col-1">
  <h1>This is half of a page</h1>
</div>
<div id="col-2">
  <h1>This is another half of a page</h1>
</div></code>```

This worked for me. I changed position: fixed to relative. Also, they should both be float:left. The one on the right will become scattered if you do float:right for it, they should both be left.

Also, just a suggestion from me, that I like to do on my pages - I'm a big fan of tables, when used appropriately. Tables tend to put things right next to each other, with equal measurements and alignments. It does a lot of the styling work for you. Try doing something with
,
, and
 tags.

Title: Basic split screen with css /html

Body:
#col-1 {
  position: relative;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #282828;
  z-index: 1010101010
}

#col-2 {
  position: relative;
  width: 50%;
  float: left;
  height: 100%;
  background-color: #0080ff;
  z-index: 1010101010
}

<div id="col-1">
  <h1>This is half of a page</h1>
</div>
<div id="col-2">
  <h1>This is another half of a page</h1>
</div>

This worked for me. I changed position: fixed to relative. Also, they should both be float:left. The one on the right will become scattered if you do float:right for it, they should both be left.

Also, just a suggestion from me, that I like to do on my pages - I'm a big fan of tables, when used appropriately. Tables tend to put things right next to each other, with equal measurements and alignments. It does a lot of the styling work for you. Try doing something with <table>, <tbody>, and <thead> tags.


问:
Can't change the keystore format
I'm trying to make some keystores using keytool from the latest JRE (version 1.8.0_151). When I create the keystore using this command keytool -genkey -alias serverprivate -keystore server.private -keyalg rsa -storepass apassword -keypass apassword it shows me this warning:

```<code>Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate
to  PKCS12 which is an industry standard format using "keytool
-importkeystore -srckeystore server.private -destkeystore server.private
-deststoretype pkcs12".
</code>```

So I type the command, and it says it's done and the old keystore was saved in server.private_old. But when I run keytool -list -keystore server.private and type the password, it is still listed as JKS instead of PKCS12. Why is this?

update

It's not silently changed to pkcs12 either, because when I use KeyStore store = KeyStore.getInstance("pkcs12"); in java it throws an error, while it works fine when using getInstance("JKS");

update 2

And when using keytool -genkey -alias serverprivate -keystore server.private -storetype PKCS12 -keyalg rsa it doesn't show me a warning, but still shows as a JKS keystore when using keytool -list server.private.

答:
It seems to be a bug in what keytool displays rather than what it does. Consider the following experiments.

(EDIT: bug report filed)

First, my jdk version is 1.8.0_152:

excalibur:~ ronan$ java -version
java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)
```

<p>Now, create the keystore as you specified:</p>

<pre class="lang-none prettyprint-override"><code>excalibur:~ ronan$ keytool -genkey -alias serverprivate -keystore server.private -keyalg rsa -storepass apassword -keypass apassword
What is your first and last name?
  [Unknown]:  Art Vandelay
What is the name of your organizational unit?
  [Unknown]:  Export/Import
What is the name of your organization?
  [Unknown]:  Vandelay Industries
What is the name of your City or Locality?
  [Unknown]:  New York
What is the name of your State or Province?
  [Unknown]:  New York
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Art Vandelay, OU=Export/Import, O=Vandelay Industries, L=New York, ST=New York, C=US correct?
  [no]:  yes

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore server.private -destkeystore server.private -deststoretype pkcs12".
</code>```

Now, following the instructions given:

excalibur:~ ronan$ keytool -importkeystore -srckeystore server.private -destkeystore server.private -deststoretype pkcs12
Enter source keystore password:
Entry for alias serverprivate successfully imported.
Import command completed:  1 entries successfully imported, 0 entries failed or cancelled

Warning:
Migrated "server.private" to Non JKS/JCEKS. The JKS keystore is backed up as "server.private.old".
```

<p>But when we list it with keytool it still says JKS.</p>

<pre class="lang-none prettyprint-override"><code>excalibur:~ ronan$ keytool -list -keystore server.private
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

serverprivate, Dec 4, 2017, PrivateKeyEntry,
Certificate fingerprint (SHA1): 16:E8:C6:12:7A:F1:7A:B8:64:98:EC:12:C4:07:9E:67:06:BD:DD:BD
</code>```

However, openssl can parse it as pkcs12 just fine.

excalibur:~ ronan$ openssl pkcs12 -in server.private
Enter Import Password:
MAC verified OK
Bag Attributes
    friendlyName: serverprivate
    localKeyID: 54 69 6D 65 20 31 35 31 32 34 31 33 32 30 38 31 38 32
Key Attributes: <No Attributes>
Enter PEM pass phrase:
Bag Attributes
    friendlyName: serverprivate
    localKeyID: 54 69 6D 65 20 31 35 31 32 34 31 33 32 30 38 31 38 32
subject=/C=US/ST=New York/L=New York/O=Vandelay Industries/OU=Export/Import/CN=Art Vandelay
issuer=/C=US/ST=New York/L=New York/O=Vandelay Industries/OU=Export/Import/CN=Art Vandelay
-----BEGIN CERTIFICATE-----
MIIDoTCCAomgAwIBAgIEKSoRITANBgkqhkiG9w0BAQsFADCBgDELMAkGA1UEBhMC
VVMxETAPBgNVBAgTCE5ldyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazEcMBoGA1UE
ChMTVmFuZGVsYXkgSW5kdXN0cmllczEWMBQGA1UECxMNRXhwb3J0L0ltcG9ydDEV
MBMGA1UEAxMMQXJ0IFZhbmRlbGF5MB4XDTE3MTIwNDE4NDM1NVoXDTE4MDMwNDE4
NDM1NVowgYAxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazERMA8GA1UE
BxMITmV3IFlvcmsxHDAaBgNVBAoTE1ZhbmRlbGF5IEluZHVzdHJpZXMxFjAUBgNV
BAsTDUV4cG9ydC9JbXBvcnQxFTATBgNVBAMTDEFydCBWYW5kZWxheTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAIwVIy24Hws6ffaEQGhYEyaw2JC4UPLH
wtSXpJaZf3lrdtbktbLC+zKJ93fFVfoukX5vpnZKxv+f724duAszkVWN3bBrnAwb
6sh445tXiRhT2eS+z0rHtXwiPWUKOAPOxGUP1Lhfl5ZCPR4bmohyh/daSX1ppT3P
k6//lf1y2RdsS5hZ5Ltx9dr99/txsv4a1D8uuPDHIf8dvWfOqGb7ywIAlrbh5JsA
4IWjMVFMpDQ2WM/C+v48y2W7AdgxGD0J/nNC6t4QfAgwhvVyXbiu9IbAR+ivn59E
VqC83qv4bBkffB3yYk6WSHSl7YloJueWalVAoudf4uHeaNZBLCvbNsMCAwEAAaMh
MB8wHQYDVR0OBBYEFNOc6gJkUFCSgyHCDFGJmZwtPLgIMA0GCSqGSIb3DQEBCwUA
A4IBAQAVyc6j9U+va5U02MxsjDE6LWDPg+0FaqpTAQlU6xhVrZlKWuX+Dup4PF6S
s4oqhInb7XcGOjbLkVTnuEY5mwfHnyGqNhmyyUwJOVrWZJWBZADvhdcZi0w/jclg
jAb7dP1VssR4Ozgsd1XkGxnS7P8e344xpjQd1krPc1Od7qhFSF6FufTDvgEcrmx/
qrHpLpwoYPTyuv+NtD+7KlWINqWq5PT1olydd6ki8O+bTsgDuy8rnvqd/jJ7dsuv
VLNc+IDEEMO26hS8d1WkppTTuLrayE07LCV8df68WHv6KumDSc5Mb0zOUdLqZUDQ
Wmxbt0kEAAG6jgbpACBpGEqtAtTs
-----END CERTIFICATE-----
```

<p>and the following Java snippet can also parse it.</p>

<pre class="lang-java prettyprint-override"><code>import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Collections;

public class Main {
    public static void main(String[] args) throws Exception {
        KeyStore pkcs12 = KeyStore.getInstance("PKCS12");
        pkcs12.load(new FileInputStream("../../../server.private"), "apassword".toCharArray());
        for (String alias : Collections.list(pkcs12.aliases())) {
            System.out.println(alias);
        }
    }
}
</code>```

and the output is

serverprivate

Title: Can't change the keystore format

Body:
I'm trying to make some keystores using keytool from the latest JRE (version 1.8.0_151). When I create the keystore using this command keytool -genkey -alias serverprivate -keystore server.private -keyalg rsa -storepass apassword -keypass apassword it shows me this warning:

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate
to  PKCS12 which is an industry standard format using "keytool
-importkeystore -srckeystore server.private -destkeystore server.private
-deststoretype pkcs12".

So I type the command, and it says it's done and the old keystore was saved in server.private_old. But when I run keytool -list -keystore server.private and type the password, it is still listed as JKS instead of PKCS12. Why is this?

update

It's not silently changed to pkcs12 either, because when I use KeyStore store = KeyStore.getInstance("pkcs12"); in java it throws an error, while it works fine when using getInstance("JKS");

update 2

And when using keytool -genkey -alias serverprivate -keystore server.private -storetype PKCS12 -keyalg rsa it doesn't show me a warning, but still shows as a JKS keystore when using keytool -list server.private.

Body:
It seems to be a bug in what keytool displays rather than what it does. Consider the following experiments.

(EDIT: bug report filed)

First, my jdk version is 1.8.0_152:

excalibur:~ ronan$ java -version
java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)

Now, create the keystore as you specified:

excalibur:~ ronan$ keytool -genkey -alias serverprivate -keystore server.private -keyalg rsa -storepass apassword -keypass apassword
What is your first and last name?
  [Unknown]:  Art Vandelay
What is the name of your organizational unit?
  [Unknown]:  Export/Import
What is the name of your organization?
  [Unknown]:  Vandelay Industries
What is the name of your City or Locality?
  [Unknown]:  New York
What is the name of your State or Province?
  [Unknown]:  New York
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Art Vandelay, OU=Export/Import, O=Vandelay Industries, L=New York, ST=New York, C=US correct?
  [no]:  yes

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore server.private -destkeystore server.private -deststoretype pkcs12".

Now, following the instructions given:

excalibur:~ ronan$ keytool -importkeystore -srckeystore server.private -destkeystore server.private -deststoretype pkcs12
Enter source keystore password:
Entry for alias serverprivate successfully imported.
Import command completed:  1 entries successfully imported, 0 entries failed or cancelled

Warning:
Migrated "server.private" to Non JKS/JCEKS. The JKS keystore is backed up as "server.private.old".

But when we list it with keytool it still says JKS.

excalibur:~ ronan$ keytool -list -keystore server.private
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

serverprivate, Dec 4, 2017, PrivateKeyEntry,
Certificate fingerprint (SHA1): 16:E8:C6:12:7A:F1:7A:B8:64:98:EC:12:C4:07:9E:67:06:BD:DD:BD

However, openssl can parse it as pkcs12 just fine.

excalibur:~ ronan$ openssl pkcs12 -in server.private
Enter Import Password:
MAC verified OK
Bag Attributes
    friendlyName: serverprivate
    localKeyID: 54 69 6D 65 20 31 35 31 32 34 31 33 32 30 38 31 38 32
Key Attributes: <No Attributes>
Enter PEM pass phrase:
Bag Attributes
    friendlyName: serverprivate
    localKeyID: 54 69 6D 65 20 31 35 31 32 34 31 33 32 30 38 31 38 32
subject=/C=US/ST=New York/L=New York/O=Vandelay Industries/OU=Export/Import/CN=Art Vandelay
issuer=/C=US/ST=New York/L=New York/O=Vandelay Industries/OU=Export/Import/CN=Art Vandelay
-----BEGIN CERTIFICATE-----
MIIDoTCCAomgAwIBAgIEKSoRITANBgkqhkiG9w0BAQsFADCBgDELMAkGA1UEBhMC
VVMxETAPBgNVBAgTCE5ldyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazEcMBoGA1UE
ChMTVmFuZGVsYXkgSW5kdXN0cmllczEWMBQGA1UECxMNRXhwb3J0L0ltcG9ydDEV
MBMGA1UEAxMMQXJ0IFZhbmRlbGF5MB4XDTE3MTIwNDE4NDM1NVoXDTE4MDMwNDE4
NDM1NVowgYAxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazERMA8GA1UE
BxMITmV3IFlvcmsxHDAaBgNVBAoTE1ZhbmRlbGF5IEluZHVzdHJpZXMxFjAUBgNV
BAsTDUV4cG9ydC9JbXBvcnQxFTATBgNVBAMTDEFydCBWYW5kZWxheTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAIwVIy24Hws6ffaEQGhYEyaw2JC4UPLH
wtSXpJaZf3lrdtbktbLC+zKJ93fFVfoukX5vpnZKxv+f724duAszkVWN3bBrnAwb
6sh445tXiRhT2eS+z0rHtXwiPWUKOAPOxGUP1Lhfl5ZCPR4bmohyh/daSX1ppT3P
k6//lf1y2RdsS5hZ5Ltx9dr99/txsv4a1D8uuPDHIf8dvWfOqGb7ywIAlrbh5JsA
4IWjMVFMpDQ2WM/C+v48y2W7AdgxGD0J/nNC6t4QfAgwhvVyXbiu9IbAR+ivn59E
VqC83qv4bBkffB3yYk6WSHSl7YloJueWalVAoudf4uHeaNZBLCvbNsMCAwEAAaMh
MB8wHQYDVR0OBBYEFNOc6gJkUFCSgyHCDFGJmZwtPLgIMA0GCSqGSIb3DQEBCwUA
A4IBAQAVyc6j9U+va5U02MxsjDE6LWDPg+0FaqpTAQlU6xhVrZlKWuX+Dup4PF6S
s4oqhInb7XcGOjbLkVTnuEY5mwfHnyGqNhmyyUwJOVrWZJWBZADvhdcZi0w/jclg
jAb7dP1VssR4Ozgsd1XkGxnS7P8e344xpjQd1krPc1Od7qhFSF6FufTDvgEcrmx/
qrHpLpwoYPTyuv+NtD+7KlWINqWq5PT1olydd6ki8O+bTsgDuy8rnvqd/jJ7dsuv
VLNc+IDEEMO26hS8d1WkppTTuLrayE07LCV8df68WHv6KumDSc5Mb0zOUdLqZUDQ
Wmxbt0kEAAG6jgbpACBpGEqtAtTs
-----END CERTIFICATE-----

and the following Java snippet can also parse it.

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Collections;

public class Main {
    public static void main(String[] args) throws Exception {
        KeyStore pkcs12 = KeyStore.getInstance("PKCS12");
        pkcs12.load(new FileInputStream("../../../server.private"), "apassword".toCharArray());
        for (String alias : Collections.list(pkcs12.aliases())) {
            System.out.println(alias);
        }
    }
}

and the output is

serverprivate


问:
Making John, john and JOHN mean the same variable in python lists?
My question is this.

How do I make it so users can not make a new user_name John if JOHN or john are already in use.

Can I make user_name.upper() = user_name.lower() or something like that.

These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms.

Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.

答:
Use the code below

```<code>existing_users = ["John","tilak","RAMESH","SidDDu"]
while True:
    name = raw_input("Enter a name: ")

    for i in existing_users:
        if name.lower() == i.lower():
            print "Name Already exists!Please choose another"
        else:
            existing_users.append(name)
</code>```

Body:
Use the code below

existing_users = ["John","tilak","RAMESH","SidDDu"]
while True:
    name = raw_input("Enter a name: ")

    for i in existing_users:
        if name.lower() == i.lower():
            print "Name Already exists!Please choose another"
        else:
            existing_users.append(name)


答:
You can achieve this with array reduction and string replacement.

var arr = ["a","b","c"];
var s = "Hello {1} is a friend of {2} and {3}";

var result = arr.reduce((str, replacement, idx) => {
  return str.replace(`{${idx + 1}}`, replacement)
}, s);

console.log(result);```

Title: How to replace a string with the array and index of an array as a string?

Body:
Consider

var arr = ["a","b","c"];
var string = "Hello {1} is a friend of {2} and {3}";

so replacing {1} with "a", {2} with "b", and {3} with "c"

How do we do using JavaScript?


问:
Adding Custom Columns to Union Table - Oracle SQL
enter image description here

I'm dealing with the following union between two different tables in an Oracle Database.

the first query refers to vessels that are part of the current fleet of the payer_no. The second query refers to all vessels transacted with at some time.

If an item appears only in the first query, I want a custom column that says "current fleet" and if an item only appears in the second query, I want a column that says "past fleet."

Output would look like this:

enter image description here

答:
Pending clarification of what should happen if an "item" appears in both members of the UNION:

The usual way to do what you need is to add a column with hard-coded values and with the same name to both members of the union. It doesn't matter if one or both members is/are the result of a join, or whatever other simple or complicated computation.

```<code>select col_1, col_2, ... , col_n, 'Current Fleet' as status
from   ( big join or whatever here; do prefix columns with table aliases in a join! )
UNION    --  Or UNION ALL  !
select col_1, col_2, ... , col_n, 'Past Fleet'    as status
from   .........
</code>```

Body:
Pending clarification of what should happen if an "item" appears in both members of the UNION:

The usual way to do what you need is to add a column with hard-coded values and with the same name to both members of the union. It doesn't matter if one or both members is/are the result of a join, or whatever other simple or complicated computation.

select col_1, col_2, ... , col_n, 'Current Fleet' as status
from   ( big join or whatever here; do prefix columns with table aliases in a join! )
UNION    --  Or UNION ALL  !
select col_1, col_2, ... , col_n, 'Past Fleet'    as status
from   .........


问:
ClickOnce Deployment with a Database as a Prerequisite
I have a Winforms application that I want to publish using ClickOnce. This application comes with an initial database, which must be installed once on a per-machine basis. After much ado, I have landed on the idea of using a custom pre-requisite to install the .sdf file. I have used Bootstrapper Manifest Generator (BMG) to create a package for the .cmd file I want to run, and I have included the .sdf file as an "additional file."

My expectation was that the two files would end up in the same directory, and I would be able to copy the .sdf file to the place where I want it (They do end up in the same directory.) The pre-requisite shows up in Visual Studio just fine. It get's deployed to the client system just fine, and the setup program kicks off the prerequisite just fine.

The only problem is that the current working directory that the .cmd file is executing is C:\Documents and Settings\\Desktop!

Neither of the two files (.cmd or .sdf) are located there - they were downloaded elsewhere, e.g., "C:\Documents and Settings\drogers\Local Settings\Temp\VSD5A.tmp". So, although I know where to xcopy to, I have no idea where to xcopy from.

How can I resolve this?

Here is the .cmd file:

```<code>REM Modify this file to reflect your manufacturer name [FHCRC] and product name [ClickOnceSharedDataDemo].
SET TargetBase=%ALLUSERSPROFILE%
IF NOT "%TargetBase%"=="C:\ProgramData" SET TargetBase=%ALLUSERSPROFILE%\Application Data
REM We only want to do this copy for the first user!
if exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" GOTO EXIT
if not exist "%TargetBase%\FHCRC" mkdir "%TargetBase%\FHCRC"
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo" mkdir "%TargetBase%\FHCRC\ClickOnceSharedDataDemo"
CACLS "%TargetBase%\FHCRC\ClickOnceSharedDataDemo" /E /T /C /G "Users":C
xcopy shareddata.sdf "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\"
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" PAUSE
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" exit /B -1
:EXIT
PAUSE
exit /B 0
</code>```

Thanks,
David

答:
Did you try MSDeploy? It is able to fulfil all your needs.

Cheers!

Body:
I have a Winforms application that I want to publish using ClickOnce. This application comes with an initial database, which must be installed once on a per-machine basis. After much ado, I have landed on the idea of using a custom pre-requisite to install the .sdf file. I have used Bootstrapper Manifest Generator (BMG) to create a package for the .cmd file I want to run, and I have included the .sdf file as an "additional file."

My expectation was that the two files would end up in the same directory, and I would be able to copy the .sdf file to the place where I want it (They do end up in the same directory.) The pre-requisite shows up in Visual Studio just fine. It get's deployed to the client system just fine, and the setup program kicks off the prerequisite just fine.

The only problem is that the current working directory that the .cmd file is executing is C:\Documents and Settings\\Desktop!

Neither of the two files (.cmd or .sdf) are located there - they were downloaded elsewhere, e.g., "C:\Documents and Settings\drogers\Local Settings\Temp\VSD5A.tmp". So, although I know where to xcopy to, I have no idea where to xcopy from.

How can I resolve this?

Here is the .cmd file:

REM Modify this file to reflect your manufacturer name [FHCRC] and product name [ClickOnceSharedDataDemo].
SET TargetBase=%ALLUSERSPROFILE%
IF NOT "%TargetBase%"=="C:\ProgramData" SET TargetBase=%ALLUSERSPROFILE%\Application Data
REM We only want to do this copy for the first user!
if exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" GOTO EXIT
if not exist "%TargetBase%\FHCRC" mkdir "%TargetBase%\FHCRC"
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo" mkdir "%TargetBase%\FHCRC\ClickOnceSharedDataDemo"
CACLS "%TargetBase%\FHCRC\ClickOnceSharedDataDemo" /E /T /C /G "Users":C
xcopy shareddata.sdf "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\"
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" PAUSE
if not exist "%TargetBase%\FHCRC\ClickOnceSharedDataDemo\shareddata.sdf" exit /B -1
:EXIT
PAUSE
exit /B 0

Thanks,
David


问:
Base64 jpg to base64 Png in Ruby
I'm working with base64 files and i would like to convert a base64jpg image in a base64png image. Is there a way to do it?

The reason is i'm using rsvg-convert to convert svg files into png files, but when i have a base64jpg in my svg, it's not working, But it works with base64 files.

Title: Base64 jpg to base64 Png in Ruby

Body:
In ImageMagick, this works for me.

Create JPG base 64 file:

convert rose: rose.jpg

convert rose.jpg inline:rose_base64jpg

The text file rose_base64jpg shows:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAuAEYDAREAAhEBAxEB/8QAHAAAAgIDAQEAAAAAAAAAAAAABgcEBQMICQEC/8QANRAAAQMCBAMGBAUFAQAAAAAAAQIDBAURAAYSIQcxQQgTIlFhcRQygcEjQlJikRUWJDOx0f/EABwBAAIDAQEBAQAAAAAAAAAAAAUGAwQHCAIBAP/EADARAAIBAwQABAQGAgMAAAAAAAECAwAEEQUSITEGQVFhExQigQcjMnGhwRWxQlLh/9oADAMBAAIRAxEAPwDSvuJ6W7toJA9MRHaTUiFsVh/yS4UrZN/UY+lVFetzY5qzgKmsIU6GlJSNuWIHCH6akjB7o4yVnJ6nT22FpUEqGySLgn/3AbULIMN690/+D9ffS5RHns5HVFlczAmY8t5KShKkgBKuYsN8BVtGX9VP+reIf8jK0nWfKpuRqLJq+YGYcpKowKwHO9SUlAPUg++2Lgtg4wTileTXBpjGQoWZQcKBliceg59/2oM42cM6tkqsS6kww9JpTr6rPlNyi5vY2wxW0qYCA9Vj/wA81/KzScOxJ6r77OUhL+e1QJTrzNPfhvd8tCfCF6bIubbc/rbF+K9j02eO7dd23PANSy3MkNo8YP0t/VNnPeS6RkXL0aFCzhUq3HM5ZabUwhttsKSSSALqvcW3NvTFOfURfyGRE20JgvmlYnFa/wBNYlRZJiT2trEpUBzx5kl+klaMpGQcGnzP7Kb9fyPT83ZJzImRIlxW33IElmyioi6tKh98OaeEvj26T28nLAHnr7VUN7hijjqlqxwozVpkwqoY9JdiL7styblbqr8kpTfp1NsJV2YNPleO4kAdfIZOfvTro3hLWtchSa2ixE5wGYhR9h2fbiiSm0dUWO1BC0spZbDaAEpud7lSrc7nck+2E25vXlcuxOPStu0bw2kFutsAF2DHQyTnkk4yeas2o8cMlae5kKSrUAUAlKvMX+3LFE3MxOIjinDTtGsVib4iq7qcjIGc+o/upxky49L71lLZWp4JfdIClWTa1/Mb2/jntieO4kMYBPVC2sE0u9lvbZAk743N5gDyHlz54ovyytqssrQxIW+ln/YjWVAb2BsenP6YMafcjlXOaKi+tLwZljXf5kqP94pwdmrhVwrqvE+qUDM+U0fHVimGfFLRUholl3S9sk2Fw417kE9cGrFknf8AMUEe9c8fiVp+m294HtMZYBigBAx1n7nyGOqe/E3smcP+IT8GJDhqokentkp+GA0ulRtv1uLdf1YtT/DTC4xWaNDG6gr/ABXLNuG9JeQhDJdWshKEpFySfLFJFeRgijJNFztUZNbCcMMn8R6tlKrQ3kVF+DAZIbVEUpXcaUk7qTtt5bn/AJhyvL6/0TSCtw6q54QEncR0dvuKk0FNIuNVj/yIJh/5EcY/89aCKsmopnsRShy4C3SpXhW9ttYne539TbGRyM5LbiSTzz2a6puLmP8AIkiIMPH1L0fIddcVFjxEOyVGO74n0hTaHVWJP6QeR35efvigPzGx50c023is2aaY8cc991P/ALdmLQiAzTyKsvU6lEhxKGEN2+a/Un7YvGBGAXH1Y9a+306FPi2sKkLwONuSfXHtUFTLjTzaY7zTbNwqSgOKUlVvmHS4Nvby2xXIVTweKHR29xOmwYXzOf6PrRDwu+EgZuZaeBEedGfDoWbjUhBcSffwkfXE9jIZJdpqvqukpYLFJbZy/B/eirJXEysU3PFal5drq6XIhshlT0dDZf0PEKU2FKBsmyG+XW+DEkj2mGU4rnP8YbxBrqwQHmOJUYj/ALZLfxkUz09o6dlOCBXMyTJHeueBtUhJc1WJUu6t7Hb649affMWbfzWY6bfSW+5MZFaX8N3qvAmIj5gSqO2taUGU2nUttsnxEeRI2vhx0W9tLK8WWcHHWfSi8qzSJtp21Xi/FpVAkZQy3WpAbdQplDDZLbakkW1k/mOGXX9f02ZD8uu9+gSOqjtbdoz9fX+6E015wZUXliZFD0hDqVokOklbKbhVkHnvyPT64xTVJw0hAGT61014GsLiPRlW4O0jpfUHo469uKpg6uUHGg4VuMuJQEFW4SAd9/pgeA3Bpq+L8ctAnOD15/vVkh9K1JjzaksPJaShDYJUSlOwA6ee5P8AOJgzHJejdpcxaa4hI3SMQcHyrHJWhiI666rSEpNrnEezf+mpL67S3jknlwD6V5l2rPOw51Qp0b4qYhKo0SMn53VkXUB5X2Tf9xwR021+C5kk6pF1Dxxb2VnJdyjc0Y+hfVsdn2HdQclu5Yor7VKqNaXW881mepUxcSRriQY6QpRZC0+FxZUd7XA02HLchfh5omlVcIMYz3+9coaveT6pJJdzHJYliT2STz9vT2o/VQmJhMueENJvpurffmBc+mAwnK8LQH4uzgUu0pttbDhmnIMDTL4W9lfNHaJpVWm0Sr06lM0g92l+QslS3ym4QEp3CfMnEqQts+IOKhmZGOw1TZW4YcV63xAlcFlcNXf67lxlZfebkBTaWgm6NTirApVbwG9yTgJNpXzQMsZyfQ1rPhv8Q7e1jjsbqLZGgwGBLfwRnB/fiq+t0VygTKjSZlJcpdVZCmpLT7Sm3mlAclBW4+4wIaMxsFI68q1dLi0uIHnsnB3j9QPtStcmykOlaZC0rve4PK2CQhR+NtZf87cRPvEh3DzzmotSzDPmptIkrdKOVziSOzRP0ior3Xrm+4mcmpbecaXQaC1GWhT8yQ2VOR7J2Cifn1AgXHpexxfitSw44zSTruqgQm2jOWbs+g9PvVXkasJHESgzY0ZpppyUmO20hISlpKrp0n2BJv1xJdQF7ZkJyaR5OYmX0p31zN0SRqdTIbEdl3uWtR2tvv7m1/a2F2G1ZRgUGSInqhpsX0qPXfDSpzTZG24bq6H9l6U1QuzfBlFoJd7yS5qYSEqVZRUNRFifK+LU7FLdAPSqUWXJHvTayFl+hMR3s5xqWy3VswJS/OlBP4jthZKSrqABYYkhjESADzqxIBuxVDxi4DcPOM0JDOaYDkepIToi1WEEolMg38JUQQtH7VAjysd8V7uzhvsBhg+tFtH1290eQm2b6T2p5U/b1965zdqTsxvdneXRivOTdejV9UgM3gGO4wG9HzfiKCr6+luWBksfy7bG5okfEJnzIUx7A8UjoEJsykEAKS0S4+lXVsW+X93Pntyx+c+VC5tZnuH2J9IoezVHdn16dNmvanJTpdunaw/KLegAH0wTgbKD2oPMhQ5Y5zVMmBMiESocqw1DYkg/yMWGAI5qA4PdE1cVVzREUuRJTpakIc1JWb7tkAXsLgDFGIop3Ad1Vyuc4r//2Q==

Convert from base 64 JPG to base 64 PNG:

cat rose_base64jpg | convert inline:- PNG:- | convert - inline:rose_base64png

The text file rose_base64png show:

data:image/png;base64,[encoded data, 9532 characters]


问:
BottomSheetDialogFragment sets wrong background color for Dark theme
I have recently added BottomSheetDialogFragment to my app, but it shows background color for Material Dark theme as white. Even when I use </p>

```<code>android:background="?android:attr/colorBackground"
</code>```

<p>for the root layout of the dialog, it is still white (but this attr is ok outside of the dialog). Has anyone ever had this problem? </p>

答:
I just hit this problem. I used attribute you mentioned in the root layout of the dialog and it helped me.</p>

```<code>android:background="?android:attr/colorBackground"
</code>```

Body:
I have recently added BottomSheetDialogFragment to my app, but it shows background color for Material Dark theme as white. Even when I use

android:background="?android:attr/colorBackground"

for the root layout of the dialog, it is still white (but this attr is ok outside of the dialog). Has anyone ever had this problem?

Body:
I just hit this problem. I used attribute you mentioned in the root layout of the dialog and it helped me.

android:background="?android:attr/colorBackground"


问:
Maven clean install failed to execute goal on project
I am developing a spring boot project which has few modules. I have on entry point module which has main class, the other module dependencis i have added in entry point module pom.xml. When i give command mvn clean install it throws an error saying `

Failed to execute goal on project api: Could not resolve dependencies
  for project com.nikesh:api:jar:1.0.0: The following artifacts could
  not be resolved: com.nikesh:lib:jar:1.0.0, com.nikesh:repo:jar:1.0.0,
  com.nikesh:entity:jar:1.0.0, com.nikesh:dto:jar:1.0.0,
  com.nikesh:service:jar:1.0.0, com.nikesh:common:jar:1.0.0: Failure to
  find com.nikesh:lib:jar:1.0.0 in https://repo.maven.apache.org/maven2
  was cached in the local repository, resolution will not be reattempted
  until the update interval of central has elapsed or updates are forced
  -`

This is my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nikesh</groupId>
<artifactId>api</artifactId>
<version>1.0.0</version>
<description>api module</description>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
    <start-class>com.nikesh.api.MultiModuleApp</start-class>
</properties>

<dependencies>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>lib</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>repo</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>entity</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>dto</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>service</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>common</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

Please help me out resolving this issue.

答:
You need to make sure that all sub modules are built in proper order before the main module build.

Guide to Working with Multiple Modules

The Reactor

The mechanism in Maven that handles multi-module projects is referred to as the reactor. This part of the Maven core does the following:

Collects all the available modules to build

Sorts the projects into the correct build order

Builds the selected projects in order

Because modules within a multi-module build can depend on each other, it is important that The reactor sorts all the projects in a way that guarantees any project is built before it is required.

The following relationships are honoured when sorting projects:

a project dependency on another module in the build

a plugin declaration where the plugin is another modules in the build

a plugin dependency on another module in the build

a build extension declaration on another module in the build

the order declared in the  element (if no other rule
applies)

Note that only "instantiated" references are used - dependencyManagement and pluginManagement elements will not cause a change to the reactor sort order

for more info. You can refer this link for a sample multi module maven project.

Body:
I am developing a spring boot project which has few modules. I have on entry point module which has main class, the other module dependencis i have added in entry point module pom.xml. When i give command mvn clean install it throws an error saying `

Failed to execute goal on project api: Could not resolve dependencies
  for project com.nikesh:api:jar:1.0.0: The following artifacts could
  not be resolved: com.nikesh:lib:jar:1.0.0, com.nikesh:repo:jar:1.0.0,
  com.nikesh:entity:jar:1.0.0, com.nikesh:dto:jar:1.0.0,
  com.nikesh:service:jar:1.0.0, com.nikesh:common:jar:1.0.0: Failure to
  find com.nikesh:lib:jar:1.0.0 in https://repo.maven.apache.org/maven2
  was cached in the local repository, resolution will not be reattempted
  until the update interval of central has elapsed or updates are forced
  -`

This is my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nikesh</groupId>
<artifactId>api</artifactId>
<version>1.0.0</version>
<description>api module</description>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
    <start-class>com.nikesh.api.MultiModuleApp</start-class>
</properties>

<dependencies>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>lib</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>repo</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>entity</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>dto</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>service</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.nikesh</groupId>
        <artifactId>common</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Please help me out resolving this issue.


问:
Best way to load distant data
I'm currently developping an iPhone app and need your opinion.

First, I am developping it for a Football (soccer) Club. It contains many tabs (at least these ones) :

News (Where I am displaying last news posted, obviously)

Shop (Where the user can buy stadium seats, and maybe various goodies)

Don't know yet exactly (But it will be related to Facebook/Twitter or stuff like that)

For every of theses tabs, I need to download XML data (using initWithContentOfURL). Right. But, that's where my problem is. Should I :

Load every needed xml pages at application start-up, and display a nice loading screen ?

Load every needed xml pages at the exact instant the user needs it in the application ?

In the first case, I get a slower application startup, but then, a faster navigation between tabs.

In the second case, my application starts relatively faster (still needs to load News XML, that's the welcome tab), but switching between tabs won't be as fluent as the first case (only the first time the tab is opened, of course).

Any advice?

答: Take a look at ASIHttpRequest which does provide some pre built caching mechanisms for you that may be appropriate and generally make interacting with web services easier</p>

Title: Best way to load distant data