问:
classes not visible to gradle task swagger when using kongchen swagger-maven-plugin
When performing gradle clean and then gradle swagger a ClassNotFoundException is thrown. If gradle swagger is then run again (basically after the api build is done in previous run), it works fine.

build.gradle looks as below:

```<code>buildscript {
    repositories {
        maven { url hydraMavenRepo }
        maven { url hydraPluginsRepo }
    }
    dependencies {
        classpath "com.github.kongchen:swagger-maven-plugin:3.1.4"
    }
}

apply plugin: 'java'

configurations {
    addclasspath
}

dependencies {
    addclasspath files(project(':api:desktop-api').configurations['runtime'].files)
    addclasspath files(project(':api:desktop-api').sourceSets['main'].output)
    addclasspath files(project(':api:desktop-api').sourceSets.main.output.classesDir)

    runtime project(':api:desktop-api')
}

sourceSets {
    main {
        runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output)
        runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output.classesDir)
        runtimeClasspath += files(project(':api:desktop-api').configurations['runtime'].files)
    }
}

import com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo
import com.github.kongchen.swagger.docgen.mavenplugin.ApiSource
import io.swagger.models.Info

task swagger(dependsOn: [':api:desktop-api:build']) {
    doLast {
        logger.info 'Swagger GenDoc...'
        project.file(reportsDir).mkdirs()

        // a trick to have all needed classes in the classpath
        def customClassLoader = new GroovyClassLoader()

        buildscript.configurations.classpath.each {
            //println it.toURI().toURL()
            customClassLoader.addURL(it.toURI().toURL())
        }

        configurations.addclasspath.each {
            customClassLoader.addURL(it.toURI().toURL())
        }

        // the same settings as in the swagger-maven-example/pom.xml
        final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo', true, customClassLoader).newInstance(
                apiSources: [
                        new ApiSource(
                                springmvc: false,
                                locations: ['com/vmware/vdi/hydra'],
                                schemes: ['http', 'https'],
                                host: 'vmware.com',
                                basePath: '/api',
                                info: new Info(
                                        title: "Hydra DS-REST API's",
                                        version: 'v100',
                                        description: "Hydra DS-REST API's",
                                ),
                                swaggerDirectory: reportsDir
                        )
                ]
        )
        mavenTask.execute()
        logger.info 'Swagger GenDoc task is completed'
    }
}
</code>```

答:
You have several flaws in your build script.

You should not depend on built things in build script dependencies. This is a hen and egg problem. You need to execute the build to get the classes that are necessary to execute the build. This cannot work reliably, if at all.

Instead you should declare them as dependencies outside the buildscript block. The buildscript block is only for dependencies that are needed by your build script to run itself, like Gradle Tasks and Gradle Plugins or classes you use during the build, like the swagger-maven-plugin stuff which is correct in the buildscript block.

Besides that, you execute part of your swagger stuff (the instanciation, execution and printing) during the configuration phase instead of during the execution phase. Everything you do in a task closure, but outside any doFirst or doLast blocks is run during the configuration phase, when the build is configured and thus always, no matter what tasks you actually want to execute and no matter whether the task may already be up-to-date or not. For the up-to-date check to work and save your time you need to declare all inputs like files and properties that might change between executions and all outputs that you generate, then Gradle can do its magic to only execute the task when actually necessary.

Also you should not use println in build scripts. That is like using System.out.println in Java programs. Instead you should use the provided logging facility directly, e. g. doing logger.info 'Swagger GenDoc task is completed'.

Body:
When performing gradle clean and then gradle swagger a ClassNotFoundException is thrown. If gradle swagger is then run again (basically after the api build is done in previous run), it works fine.

build.gradle looks as below:

buildscript {
    repositories {
        maven { url hydraMavenRepo }
        maven { url hydraPluginsRepo }
    }
    dependencies {
        classpath "com.github.kongchen:swagger-maven-plugin:3.1.4"
    }
}

apply plugin: 'java'

configurations {
    addclasspath
}

dependencies {
    addclasspath files(project(':api:desktop-api').configurations['runtime'].files)
    addclasspath files(project(':api:desktop-api').sourceSets['main'].output)
    addclasspath files(project(':api:desktop-api').sourceSets.main.output.classesDir)

    runtime project(':api:desktop-api')
}

sourceSets {
    main {
        runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output)
        runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output.classesDir)
        runtimeClasspath += files(project(':api:desktop-api').configurations['runtime'].files)
    }
}

import com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo
import com.github.kongchen.swagger.docgen.mavenplugin.ApiSource
import io.swagger.models.Info

task swagger(dependsOn: [':api:desktop-api:build']) {
    doLast {
        logger.info 'Swagger GenDoc...'
        project.file(reportsDir).mkdirs()

        // a trick to have all needed classes in the classpath
        def customClassLoader = new GroovyClassLoader()

        buildscript.configurations.classpath.each {
            //println it.toURI().toURL()
            customClassLoader.addURL(it.toURI().toURL())
        }

        configurations.addclasspath.each {
            customClassLoader.addURL(it.toURI().toURL())
        }

        // the same settings as in the swagger-maven-example/pom.xml
        final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo', true, customClassLoader).newInstance(
                apiSources: [
                        new ApiSource(
                                springmvc: false,
                                locations: ['com/vmware/vdi/hydra'],
                                schemes: ['http', 'https'],
                                host: 'vmware.com',
                                basePath: '/api',
                                info: new Info(
                                        title: "Hydra DS-REST API's",
                                        version: 'v100',
                                        description: "Hydra DS-REST API's",
                                ),
                                swaggerDirectory: reportsDir
                        )
                ]
        )
        mavenTask.execute()
        logger.info 'Swagger GenDoc task is completed'
    }
}


来源: stackexchange

问:
Determine Windows as 32- or 64bit
This is the code I have so far:

```<code>#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a " & $arc & "bit one.")
</code>```

It will say my computer is 32bit when it is 64. So I had a look at the path and made new code:

```<code>#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
$path = @HomeDrive & "\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a " & $arc & "bit one.")
</code>```

This shows the path and seems to be OK. Where am I going wrong?

答:
Try this :

```<code>#include <MsgBoxConstants.au3>
if FileExists (@HomeDrive&"\Program Files (x86)") then
   $arc=64
Else
   $arc=32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a "&$arc&"bit one.")
</code>```

Or this :

```<code>#include <MsgBoxConstants.au3>
if FileExists (@HomeDrive&"\Program Files (x86)") then
   $arc=64
Else
   $arc=32
EndIf
$path=@HomeDrive&"\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a "&$arc&"bit one.")
</code>```

Your code didn't work because you didn't put backslash check.

ContentLicense: CC BY-SA 3.0

Title: Determine Windows as 32- or 64bit

Body:
This is the code I have so far:

#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a " & $arc & "bit one.")

It will say my computer is 32bit when it is 64. So I had a look at the path and made new code:

#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
$path = @HomeDrive & "\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a " & $arc & "bit one.")

This shows the path and seems to be OK. Where am I going wrong?

Body:
Try this :

#include <MsgBoxConstants.au3>
if FileExists (@HomeDrive&"\Program Files (x86)") then
   $arc=64
Else
   $arc=32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a "&$arc&"bit one.")

Or this :

#include <MsgBoxConstants.au3>
if FileExists (@HomeDrive&"\Program Files (x86)") then
   $arc=64
Else
   $arc=32
EndIf
$path=@HomeDrive&"\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a "&$arc&"bit one.")

Your code didn't work because you didn't put backslash check.

ContentLicense: CC BY-SA 4.0


问:
Can we do server side html rendering using jQuery?
I have a client side JS library(call it lib.js) which uses jQuery. The library fires an API using ajax and renders html based on the json response received.

Due to SEO concerns, I want to create another nodejs based API, which does all the client side work that lib.js does and creates html on the server side and responds with this html. The catch is that I want to use the same client side library(lib.js) on the server side too so that any changes made to lib.js affects the html response of my backend API too.

So, basically I am looking to execute client side JS on the server without doing too many changes to client side JS library.

I went through node modules of jquery and jsdom but could not find a conclusive way to approach this solution. Are there any better node modules to do this ? Is there any good article that targets this problem ?

答: I am not sure that there is a way to do that and it is hard to tell which library/program is capable of all that. One thing might be the use of phantom and export the resulting html after page load there. Another thing could be jsdom, which tells from itself that is it capable of executing scripts, and use the resulting html from there. But both options have the downside that all attached event listeners will be lost if you just use the html from there. Also the onload event will be triggered again, so your scripts might go crazy, if the dom already exists. All in all I doubt that this will work good, but it also depends on the scripts and what they are doing.


问:
Not able to set label text in asp.net master page controls from content page
I am trying to change the text of label in master page which is inside modal and from content page i am trying to set the text.
This is my master page:

```<code><%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1 maximum-
    scale=1, user-scalable=no" />
    <link href="../Content/bootstrap.min.css" rel="stylesheet" />
    <link href="../Style/StyleSheet.css" rel="stylesheet" />
    <link href="../Content/font-awesome.min.css" rel="stylesheet" />
    <link href="http://fonts.googleapis.com/css?
    family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet"
    type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/jquery-1.9.1.min.js"></script>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
</head>
    <body>
    <div id="header">
        <form id="Form1" runat="server">
            <header>
            </header>
            <div class="container-fluid" id="body">
                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>
                <div class="modal fade" id="myModal">
                    <div class="modal-dialog">
                        <div class="modal-content" style="width: 400px;margin: 0 auto;">
                            <div class="modal-header" runat="server">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span></button>
                                <h4 class="modal-title"><asp:Label ID="lblMasterMessage" runat="server" Text="Label"></asp:Label> </h4>
                            </div>
                            <div class="modal-body">
                                <asp:Label ID="lblMasterbodyMessage" runat="server" Text="gh" />
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <footer class="panel-footer white">
                <div class="row">
                </div>
            </footer>
        </form>
    </div>
    <script src="../Scripts/bootstrap.min.js"></script>
    </body>
</html>
</code>```

script in child page which opens modal:

```<code><script type="text/javascript">
     function openModal(message) {
          $('#myModal').modal('show');
      }
 </script>
</code>```

code behind child page calling the script and changing text of label in modalpopup

```<code>    ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
    Label lblMaster = (Label)Master.FindControl("lblMasterbodyMessage");
    string message = "something";
    lblMaster.Text = message;
</code>```

i also tried the second approach by setting properties in master page but text in the popup is not getting updated. any help will be appreciated

答:
Specify your master page class name in TypeName attribute of MasterType directive.

```<code><%@ MasterType TypeName="MasterPageClassName" %>
</code>```

Now you can access your public properties as this.Master.propertyname

Also try by moving your code from page load event to PreRenderComplete event of page.

That'll solve you're problem

Body:
I am trying to change the text of label in master page which is inside modal and from content page i am trying to set the text.
This is my master page:

<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1 maximum-
    scale=1, user-scalable=no" />
    <link href="../Content/bootstrap.min.css" rel="stylesheet" />
    <link href="../Style/StyleSheet.css" rel="stylesheet" />
    <link href="../Content/font-awesome.min.css" rel="stylesheet" />
    <link href="http://fonts.googleapis.com/css?
    family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet"
    type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>

        <form id="Form1" runat="server">

                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>

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

<asp:Label ID="lblMasterMessage" runat="server" Text="Label"></asp:Label>

                                <asp:Label ID="lblMasterbodyMessage" runat="server" Text="gh" />

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

        </form>

script in child page which opens modal:

code behind child page calling the script and changing text of label in modalpopup

    ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);
    Label lblMaster = (Label)Master.FindControl("lblMasterbodyMessage");
    string message = "something";
    lblMaster.Text = message;

i also tried the second approach by setting properties in master page but text in the popup is not getting updated. any help will be appreciated

Body:
Specify your master page class name in TypeName attribute of MasterType directive.

<%@ MasterType TypeName="MasterPageClassName" %>

Now you can access your public properties as this.Master.propertyname

Also try by moving your code from page load event to PreRenderComplete event of page.

That'll solve you're problem


问:
Laravel API returning different model user
I have 2 models Admin and User i am able to grant access_token for both models by modifying UserRepository and PasswordGrant by referring https://github.com/laravel/passport/issues/161

every thing is fine in granting access_token but when request the user details
http://localhost:8000/api/user i'm getting the user details for User model.

```<code>{
    "id": 2,
    "name": "App User",
    "email": "appuser@gmail.com",
    "created_at": "2017-07-04 10:01:52",
    "updated_at": "2017-07-04 10:01:52"
}

//but i should be getting the user details of `admin` model
{
    "id": 1,
    "name": "Admin",
    "email": "admin@gmail.com",
    "created_at": "2017-07-04 10:01:52",
    "updated_at": "2017-07-04 10:01:52"
}
</code>```

I guess when requesting the user is referring to User model not theAdmin model

my auth.php

```<code>'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'passport',
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
],
</code>```

i'm just returning the user in my routes/api.php route

```<code>Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
</code>```

looking forward for much needed help

thank you

答:
By default laravel uses the web guard. You can use the api guard like

```<code>\Auth::guard('api')->user()
</code>```

To access the user

Body:
I have 2 models Admin and User i am able to grant access_token for both models by modifying UserRepository and PasswordGrant by referring https://github.com/laravel/passport/issues/161

every thing is fine in granting access_token but when request the user details
http://localhost:8000/api/user i'm getting the user details for User model.

{
    "id": 2,
    "name": "App User",
    "email": "appuser@gmail.com",
    "created_at": "2017-07-04 10:01:52",
    "updated_at": "2017-07-04 10:01:52"
}

//but i should be getting the user details of `admin` model
{
    "id": 1,
    "name": "Admin",
    "email": "admin@gmail.com",
    "created_at": "2017-07-04 10:01:52",
    "updated_at": "2017-07-04 10:01:52"
}

I guess when requesting the user is referring to User model not theAdmin model

my auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'passport',
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
],

i'm just returning the user in my routes/api.php route

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

looking forward for much needed help

thank you

Body:
By default laravel uses the web guard. You can use the api guard like

\Auth::guard('api')->user()

To access the user


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答: With the controlled variable you would be able to handle exit conditions (code after the while) before exiting the function.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?


问:
how to restrict horizontal strech of css flex
I am having a div with 3 child divs. I am using CSS flex for dynamically set the height of div. With 3 divs it's working fine.

But there may be a scenario where I will be having 2 child divs. Here child divs are stretching and taking full width of the page. How can I restrict this stretch using only CSS. Check its behaviour by removing div 3.

html, body {
    height: 100%;
}

body {
    margin: 0;
}

.flex-container .row {
    display: flex;
}

.flex-item {
    flex: 1;
    display: inline-block;
    background: yellow;
    margin: 10px;
    height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
    <div class="row">
        <div class="flex-item">DIV 1</div>
        <div class="flex-item">DIV 2</div>
        <div class="flex-item">DIV 3</div>
    </div>
</div></code>```

2 child divs streching like this

答:
Using flex-basis might be an option

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex-basis: calc(33.33% - 20px);
  background: yellow;
  margin: 10px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
  </div>
</div></code>```

Another option is to set flex-grow to a number smaller than 1

So i.e. achieve the same result as with flex-basis, you need to set flex-shrink to 0 and add an extra element inside the flex items to handle the margin's.

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex: 0.333 0;
}
.flex-item div {
  background: yellow;
  margin: 10px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
    <div class="flex-item"><div>3</div></div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
  </div>
</div></code>```

Body:
I am having a div with 3 child divs. I am using CSS flex for dynamically set the height of div. With 3 divs it's working fine.

But there may be a scenario where I will be having 2 child divs. Here child divs are stretching and taking full width of the page. How can I restrict this stretch using only CSS. Check its behaviour by removing div 3.

html, body {
    height: 100%;
}

body {
    margin: 0;
}

.flex-container .row {
    display: flex;
}

.flex-item {
    flex: 1;
    display: inline-block;
    background: yellow;
    margin: 10px;
    height: 100px;
}

DIV 1

DIV 2

DIV 3

2 child divs streching like this

Body:
Using flex-basis might be an option

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex-basis: calc(33.33% - 20px);
  background: yellow;
  margin: 10px;
  height: 100px;
}

<div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
  </div>
</div>

Another option is to set flex-grow to a number smaller than 1

So i.e. achieve the same result as with flex-basis, you need to set flex-shrink to 0 and add an extra element inside the flex items to handle the margin's.

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex: 0.333 0;
}
.flex-item div {
  background: yellow;
  margin: 10px;
  height: 100px;
}

<div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
    <div class="flex-item"><div>3</div></div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
  </div>
</div>


问:
Using AndroidStudio + gradle + NDK to build Library for Android and Linux
I want to build a shared library with different variants / versions that I can use on Android and in Linux applications.

Therefor, I set up an Android Project consisting of an app module and a (native C/C++) library module as outlined in the official Android Studio documentation*, so that my complete build tool chain for the library consists of**:

Android Studio

gradle / build.gradle

cmake / CMakeLists.txt

ninja

clang

My code is actually portable, e.g. I used #ifdef __ANDROID__ around Android specific code paths, and I can compile a working Linux shared object by hand, that is, by invoking the compiler from the command line.

Is there a nice way to use the above tool chain to create both the .so files for Android and Linux, without maintaining two redundant sets of build configuration files?

* I followed the documentation from May 2017, which is almost identical to this archive.org snapshot from February 2017.

** I do not use Android.mk and ndk-build, so that this related question does not apply for me, even though the purpose is the same.

答:
As it turns out, it's easier than I thought. In this case, Gradle is not needed for the Linux version, and the Cmake configuration is mostly portable across Android and Linux. So theoretically, you can just:

```<code>cd $AndroidProject/librarymodule/build
cmake -G "Unix Makefiles" .. && make
</code>```

As said before, this circumvents gradle, meaning that the configurations in the build.gradle are nerver applied.

The easiest fix is to add those settings to CMakeLists.txt like this:

```<code># (...) Common defintions for both platforms here (...)

if (ANDROID)
    find_library( log-lib log )
    target_link_libraries( librarymodule ${log-lib} )
else ( )
    find_package( OpenCV REQUIRED )
    target_compile_definitions ( librarymodule PUBLIC ENABLE_DEBUG_LOGGING linux HAVE_LIBUDEV)
    target_include_directories ( librarymodule PRIVATE  src/main/cpp ../otherlib/src/main/cpp )
    target_compile_options ( librarymodule PRIVATE -Wall -Wno-unknown-pragmas -O0 -g -std=c++11 -fexceptions )
    target_link_libraries( librarymodule pthread ${OpenCV_LIBS} )
)
</code>```

Theres a disadvantage in having identical / similar settings scattered across build.grade for Android and CMakeLists.txt for Linux. Possible solutions:

Move all those settings into CMakeLists.txt. Should be trivial.

Try to use Gradle as a wrapper for both Android and Linux and move all settings to build.gradle. Could be complex.

Body:
As it turns out, it's easier than I thought. In this case, Gradle is not needed for the Linux version, and the Cmake configuration is mostly portable across Android and Linux. So theoretically, you can just:

cd $AndroidProject/librarymodule/build
cmake -G "Unix Makefiles" .. && make

As said before, this circumvents gradle, meaning that the configurations in the build.gradle are nerver applied.

The easiest fix is to add those settings to CMakeLists.txt like this:

# (...) Common defintions for both platforms here (...)

if (ANDROID)
    find_library( log-lib log )
    target_link_libraries( librarymodule ${log-lib} )
else ( )
    find_package( OpenCV REQUIRED )
    target_compile_definitions ( librarymodule PUBLIC ENABLE_DEBUG_LOGGING linux HAVE_LIBUDEV)
    target_include_directories ( librarymodule PRIVATE  src/main/cpp ../otherlib/src/main/cpp )
    target_compile_options ( librarymodule PRIVATE -Wall -Wno-unknown-pragmas -O0 -g -std=c++11 -fexceptions )
    target_link_libraries( librarymodule pthread ${OpenCV_LIBS} )
)

Theres a disadvantage in having identical / similar settings scattered across build.grade for Android and CMakeLists.txt for Linux. Possible solutions:

Move all those settings into CMakeLists.txt. Should be trivial.

Try to use Gradle as a wrapper for both Android and Linux and move all settings to build.gradle. Could be complex.


问:
How to use msdeploy to rebind website to new subfolder
I want to deploy new releases to separate subfolders and then rebind the same application to the new subfolder.

I already know how to deploy content to specific folder:
msdeploy -verb:sync -source:package=C:\agent_work\r11\a\projectX\website-package.zip -dest:contentPath=\server\projectX$\releaseXYZ

Now I only need to notify IIS to rebind the app to the new subfolder.
How can I do that?

答:
The answer is:

```<code>C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy" -verb:sync -source:apphostconfig="DestSiteName",computername=myserveraddress -dest:auto,computername=myserveraddress -setParam:type=DestinationVirtualDirectory,scope="DestSiteName",value=D:\destiantionPath -disableLink:ContentExtension
</code>```

This will change destination dir without deploying files

Body:
The answer is:

C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy" -verb:sync -source:apphostconfig="DestSiteName",computername=myserveraddress -dest:auto,computername=myserveraddress -setParam:type=DestinationVirtualDirectory,scope="DestSiteName",value=D:\destiantionPath -disableLink:ContentExtension

This will change destination dir without deploying files


问:
Interpreting SymPy.solveset() piecewise results
Really impressed with Sympy's handling the solution of a quartic equation with particularly ugly coefficients.

The quartic was solved on a variable I called Tb and the solution had the general form Tb = f(Tc)

I did not find much detail in the Sympy docs about the piecewise results solveset() returned (I will try to contribute to the docs on this where needed once I trudge through resolving my own answers here).

There were 4 piecewise sections headed by "{Piecewise(( ..." (reasonable for a quartic solution).

However, each Piecewise section was apparently divided into "chunks" with a seperating comma apparently indicating a special subcase.

For example, one piecewise had one chunk of three (truncated here for brevity),

(-sqrt(1.68483078787199*Tc**2 - 3.36390287324716*Tc - 2*(-(-15738.9526511382*Tc >+ .... + 5.04585430987074*Tc + 6222.41209283579)**3/108)**(1/3) - >8296.54945711438)/2 + 0.998291014581918,

followed by another "chunk" (again seperated by a comma),

Eq(-1.81898940354586e-12*Tc - (-2.52724618180798*Tc**2 + 5.04585430987074*Tc + 6222.41209283579)**2/12 + 14816961.9123814, 0)),

with the last "chunk" followed up by

...  + 5.04585430987074*Tc + 6222.41209283579)**3/216)**(1/3) - >8296.54945711438)/2 +
  0.998291014581918, True)),

There were two questions concerning the above:

Do I correctly interpret that the ", True))," at the tail end of the last chunk implies that I simply have the general solution Tb = f(Tc) for two of the 3 special case chunks and the Eq simply means Tb = f(Tc) = 0?

Are there Sympy methods to programatically isolate and extract these (assumed) special cases for further processing? I could have missed it in the Sympy docs.

答:
The general format of Piecewise arguments is Piecewise((expr1, cond1), (expr2, cond2), ... [, (exprn, True)]). If a condition is True it applies if no condition preceding it applies. I believe the quartic solution is returned with the conditions under which various expressions apply. There is no "general solution" of a general quartic because the form of the solution depends on the values of the coefficients. So one way to dissect your result would be to just look at the conditions:

```<code>for arg in piecewise.args:
    print(arg.cond)  # or arg[1]
</code>```

Body:
The general format of Piecewise arguments is Piecewise((expr1, cond1), (expr2, cond2), ... [, (exprn, True)]). If a condition is True it applies if no condition preceding it applies. I believe the quartic solution is returned with the conditions under which various expressions apply. There is no "general solution" of a general quartic because the form of the solution depends on the values of the coefficients. So one way to dissect your result would be to just look at the conditions:

for arg in piecewise.args:
    print(arg.cond)  # or arg[1]


问:
Simulation from a customised distribution in R
Does anyone know how to simulate random variables from the following probability density function (pdf):

where g(x) is the pdf for standard normal distribution N(0,1).
I understand that simulating random variables from customised distribution involves finding the cumulative density function and using the uniform distribution (as there were similar questions on this topic in this platform also). However, the pdf I have here looks a bit more complicated than the other examples I came across before. For example, I would imagine that finding the cumulative density function (need to integrate) is not so straight forward. Can anyone give me advice on how to solve this? Or is there another simpler method to simulate from the above distribution?
Look forward to your advice. Thanks!

答:
You can do this using sample...

```<code>#define some x values
x <- seq(-5, 5, 0.001)
#define the pdf as above
f <- function(x) {
  if (x <= -1) {
    y <- dnorm(x)/(1+exp(-x-1))
  } else if (x >= 1) {
    y <- dnorm(x)/(1+exp(-x+1))
  } else {
    y <- dnorm(x)/2
  }
  return(y)
}
#calculate values of pdf for all x
fx <- f(x)
#create sample using these probabilities
samp <- sample(x, size=10000, replace=TRUE, prob=fx)

hist(samp, breaks=50)
</code>```

Body:
You can do this using sample...

#define some x values
x <- seq(-5, 5, 0.001)
#define the pdf as above
f <- function(x) {
  if (x <= -1) {
    y <- dnorm(x)/(1+exp(-x-1))
  } else if (x >= 1) {
    y <- dnorm(x)/(1+exp(-x+1))
  } else {
    y <- dnorm(x)/2
  }
  return(y)
}
#calculate values of pdf for all x
fx <- f(x)
#create sample using these probabilities
samp <- sample(x, size=10000, replace=TRUE, prob=fx)

hist(samp, breaks=50)


问:
How to add support for 10.5 inch iPad Pro
I've just downloaded the latest Xcode 8.3.3 update from the MAS. I was wondering how to add support for the new 10.5-inch iPad Pro?

I'm using storyboards with auto-layout, a launch screen storyboard and all app icon sizes are added to the xcassets.

答:
The workaround for now seems to be to go back to using individual launch images rather than a launch screen storyboard.

(This thread on Twitter had the answer. Also I took a look at the Info.plist file for Linea, and that seems to be exactly how they've achieved it).


答:
The only difference between these two approaches is that in the second approach you can still do something after you exit the while loop, while in the first approach, you're returning from the function itself; you can do nothing after the while.

However, I would suggest this simple code : instead of maintaining a variable, you can also use break like this:

```<code>while (true)
{
       //your code

       if (UserChoice == "exit")
            break;

       //your code
}
</code>```

The variable ShouldExit is not needed anymore!

Title: Infinite Loops and Early Return Statements

Body:
The only difference between these two approaches is that in the second approach you can still do something after you exit the while loop, while in the first approach, you're returning from the function itself; you can do nothing after the while.

However, I would suggest this simple code : instead of maintaining a variable, you can also use break like this:

while (true)
{
       //your code

       if (UserChoice == "exit")
            break;

       //your code
}

The variable ShouldExit is not needed anymore!


问:
Scrapy: TypeError: __init__() missing 1 required positional argument: 'settings'
I have a Scrapy middleware:

```<code>class ProxyMiddleware(object):
    def __init__(self, settings):
        self.proxy_file = settings.get('PROXY_FILE')
        fin = open(self.proxy_file)
        self.proxy_list = list()
        for line in fin.readlines():
            parts = line.strip().split()
            proxy = parts[2] + '://' + parts[0] + ':' + parts[1]
            self.proxy_list.append(proxy)

    def process_request(self, request, spider):
        request.meta['proxy'] = random.choice(self.proxy_list)
</code>```

But an error occurred when running, what's the settings?

答:
If you need a settings object to initialize your middleware, you need to define a from_crawler() class method, otherwise scrapy initializes the middleware without arguments.

Take a look at the built-in middleware for inspiration, for example HttpErrorMiddleware

```<code>class HttpErrorMiddleware(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.handle_httpstatus_all = settings.getbool('HTTPERROR_ALLOW_ALL')
        self.handle_httpstatus_list = settings.getlist('HTTPERROR_ALLOWED_CODES')
</code>```

In your case it would be something like:

```<code>class ProxyMiddleware(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.proxy_file = settings.get('PROXY_FILE')
        fin = open(self.proxy_file)
        self.proxy_list = list()
        for line in fin.readlines():
            parts = line.strip().split()
            proxy = parts[2] + '://' + parts[0] + ':' + parts[1]
            self.proxy_list.append(proxy)

    def process_request(self, request, spider):
        request.meta['proxy'] = random.choice(self.proxy_list)
</code>```

Body:
I have a Scrapy middleware:

class ProxyMiddleware(object):
    def __init__(self, settings):
        self.proxy_file = settings.get('PROXY_FILE')
        fin = open(self.proxy_file)
        self.proxy_list = list()
        for line in fin.readlines():
            parts = line.strip().split()
            proxy = parts[2] + '://' + parts[0] + ':' + parts[1]
            self.proxy_list.append(proxy)

    def process_request(self, request, spider):
        request.meta['proxy'] = random.choice(self.proxy_list)

But an error occurred when running, what's the settings?

Body:
If you need a settings object to initialize your middleware, you need to define a from_crawler() class method, otherwise scrapy initializes the middleware without arguments.

Take a look at the built-in middleware for inspiration, for example HttpErrorMiddleware

class HttpErrorMiddleware(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.handle_httpstatus_all = settings.getbool('HTTPERROR_ALLOW_ALL')
        self.handle_httpstatus_list = settings.getlist('HTTPERROR_ALLOWED_CODES')

In your case it would be something like:

class ProxyMiddleware(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.proxy_file = settings.get('PROXY_FILE')
        fin = open(self.proxy_file)
        self.proxy_list = list()
        for line in fin.readlines():
            parts = line.strip().split()
            proxy = parts[2] + '://' + parts[0] + ':' + parts[1]
            self.proxy_list.append(proxy)

    def process_request(self, request, spider):
        request.meta['proxy'] = random.choice(self.proxy_list)


问:
How to achieve speed more than 1000 msg/sec to SQS?
I have the following code that sends a batch message to SQS.
My goal is to send 1000 msg/sec in while true loop.

I have a bottleneck - select random ids from CSV file. How can I improve the algorithm to achieve the goal?

```<code>async def send_to_sqs(file_path, loop):
    ids = load_file_to_list(file_path)
    while True:
        messages = []
        for id in ids:
            message = {'Id': id}
            messages.append(message)

        for i in range(0, 10000, 10): #butch size is 10
            messages_batch = messages[i:i+10]

            entries = []
            for message in messages_batch:
                entries.append({'Id': str(message['Id']),
                'MessageBody': json.dumps(message)})
            await sqs.send_message_batch(QueueUrl=sqs_url, Entries=entries)

def load_file_to_list(file_path):
   with open(file_path, 'r') as f:
     reader = csv.reader(f)
     return list(reader)
</code>```

答:
Why dont you use UUIDs? This is far more likely to be unique than random ID from a file you pre-created

To solve your code more directly, without taking a step back, I'd consider leaving the file open as persistent in the background, rather than opening it everytime you call your function.

Body:
I have the following code that sends a batch message to SQS.
My goal is to send 1000 msg/sec in while true loop.

I have a bottleneck - select random ids from CSV file. How can I improve the algorithm to achieve the goal?

async def send_to_sqs(file_path, loop):
    ids = load_file_to_list(file_path)
    while True:
        messages = []
        for id in ids:
            message = {'Id': id}
            messages.append(message)

        for i in range(0, 10000, 10): #butch size is 10
            messages_batch = messages[i:i+10]

            entries = []
            for message in messages_batch:
                entries.append({'Id': str(message['Id']),
                'MessageBody': json.dumps(message)})
            await sqs.send_message_batch(QueueUrl=sqs_url, Entries=entries)

def load_file_to_list(file_path):
   with open(file_path, 'r') as f:
     reader = csv.reader(f)
     return list(reader)


问:
How to debug typescript in Ionic2
I use typescript in my Ionic 2 project . How to debug my typescript files ? I try to without webpack file  , But it is not a good solution for that !!Can you help me ?</p>

答:
WebStorm / InteliJ Supports Typescript debugging. it is using a chrome extension and allow you to put breakpoints in the IDE.
This blog post also covers it</p>

Title: How to debug typescript in Ionic2


问:
Multi udp sockets for multi ethernet ports
I have linux running on a device with multiethernet ports and i have set each of them up now i have my udp echo server running on my linux. I have sent packets from packetsender application and received them back from the same port. It is as follows:

192.168.1.100

192.168.1.101

192.168.1.102

192.168.1.103 are the 4 ethernet ports

When I send packets to 192.168.1.100 and i get an echo back from this port and when I set my network up for the second port up and send the packets to 192.168.1.101 then I am getting an echo from 192.168.1.100 though they are delivered at 192.168.1.101 and I understood that the socket was binded to the first port by the kernel and if I want my multiport to have each socket binded to the port.What is to be done?Here is the code for the single port binding of the socket. Should i use select() and do the same binding stating the ip addresses of each port?Kernel is assigning the socket binded of its own choice.

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

int main(int argc, char **argv)
{
    printf("Hello World!\n");

    return 0;
}
*/

#include <stdio.h>      /* standard C i/o facilities */
#include <stdlib.h>     /* needed for atoi() */
#include <unistd.h>     /* defines STDIN_FILENO, system calls,etc */
#include <sys/types.h>  /* system data type definitions */
#include <sys/socket.h> /* socket specific definitions */
#include <netinet/in.h> /* INET constants and stuff */
#include <arpa/inet.h>  /* IP address conversion stuff */
#include <netdb.h>      /* gethostbyname */

/* this routine echos any messages (UDP datagrams) received */

#define MAXBUF 1024*1024

void echo( int sd ) {
    int len,n;
    char bufin[MAXBUF];
    struct sockaddr_in remote;

    /* need to know how big address struct is, len must be set before the
       call to recvfrom!!! */

    len = sizeof(remote);

    while (1) {
      /* read a datagram from the socket (put result in bufin) */
      n=recvfrom(sd,bufin,MAXBUF,0,(struct sockaddr *)&remote,&len);

      /* print out the address of the sender */
      printf("Got a datagram from %s port %d\n",
             inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));

      if (n<0) {
        perror("Error receiving data");
      } else {
        printf("GOT %d BYTES\n",n);
    printf("%s\n",bufin);
        /* Got something, just send it back */

        sendto(sd,bufin,n,0,(struct sockaddr *)&remote,len);
    // ClUSTERING
      }
    }
}

/* server main routine */

int main() {
  int ld;
  struct sockaddr_in skaddr;
  int length;

  /* create a socket
     IP protocol family (PF_INET)
     UDP protocol (SOCK_DGRAM)
  */

  if ((ld = socket( PF_INET, SOCK_DGRAM, 0 )) < 0) {
    printf("Problem creating socket\n");
    exit(1);
  }

  /* establish our address
     address family is AF_INET
     our IP address is INADDR_ANY (any of our IP addresses)
     the port number is assigned by the kernel
  */

  skaddr.sin_family = AF_INET;
  skaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  skaddr.sin_port = htons(0);

  if (bind(ld, (struct sockaddr *) &skaddr, sizeof(skaddr))<0) {
    printf("Problem binding\n");
    exit(0);
  }

  /* find out what port we were assigned and print it out */

  length = sizeof( skaddr );
  if (getsockname(ld, (struct sockaddr *) &skaddr, &length)<0) {
    printf("Error getsockname\n");
    exit(1);
  }

  /* port number's are network byte order, we have to convert to
     host byte order before printing !
  */
  printf("The server UDP port number is %d\n",ntohs(skaddr.sin_port));

  /* Go echo every datagram we get */
  echo(ld);
  return(0);
}
</code>```

答: You bound your socket to INADDR_ANY, which means any IP address. If that's not what you want, bind it to a specific IP address. But that way you need multiple sockets. The way you have it now, you don't.</p>

Body:
I have linux running on a device with multiethernet ports and i have set each of them up now i have my udp echo server running on my linux. I have sent packets from packetsender application and received them back from the same port. It is as follows:

192.168.1.100

192.168.1.101

192.168.1.102

192.168.1.103 are the 4 ethernet ports

When I send packets to 192.168.1.100 and i get an echo back from this port and when I set my network up for the second port up and send the packets to 192.168.1.101 then I am getting an echo from 192.168.1.100 though they are delivered at 192.168.1.101 and I understood that the socket was binded to the first port by the kernel and if I want my multiport to have each socket binded to the port.What is to be done?Here is the code for the single port binding of the socket. Should i use select() and do the same binding stating the ip addresses of each port?Kernel is assigning the socket binded of its own choice.

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("Hello World!\n");

    return 0;
}
*/

#include <stdio.h>      /* standard C i/o facilities */
#include <stdlib.h>     /* needed for atoi() */
#include <unistd.h>     /* defines STDIN_FILENO, system calls,etc */
#include <sys/types.h>  /* system data type definitions */
#include <sys/socket.h> /* socket specific definitions */
#include <netinet/in.h> /* INET constants and stuff */
#include <arpa/inet.h>  /* IP address conversion stuff */
#include <netdb.h>      /* gethostbyname */

/* this routine echos any messages (UDP datagrams) received */

#define MAXBUF 1024*1024

void echo( int sd ) {
    int len,n;
    char bufin[MAXBUF];
    struct sockaddr_in remote;

    /* need to know how big address struct is, len must be set before the
       call to recvfrom!!! */

    len = sizeof(remote);

    while (1) {
      /* read a datagram from the socket (put result in bufin) */
      n=recvfrom(sd,bufin,MAXBUF,0,(struct sockaddr *)&remote,&len);

      /* print out the address of the sender */
      printf("Got a datagram from %s port %d\n",
             inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));

      if (n<0) {
        perror("Error receiving data");
      } else {
        printf("GOT %d BYTES\n",n);
    printf("%s\n",bufin);
        /* Got something, just send it back */

        sendto(sd,bufin,n,0,(struct sockaddr *)&remote,len);
    // ClUSTERING
      }
    }
}

/* server main routine */

int main() {
  int ld;
  struct sockaddr_in skaddr;
  int length;

  /* create a socket
     IP protocol family (PF_INET)
     UDP protocol (SOCK_DGRAM)
  */

  if ((ld = socket( PF_INET, SOCK_DGRAM, 0 )) < 0) {
    printf("Problem creating socket\n");
    exit(1);
  }

  /* establish our address
     address family is AF_INET
     our IP address is INADDR_ANY (any of our IP addresses)
     the port number is assigned by the kernel
  */

  skaddr.sin_family = AF_INET;
  skaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  skaddr.sin_port = htons(0);

  if (bind(ld, (struct sockaddr *) &skaddr, sizeof(skaddr))<0) {
    printf("Problem binding\n");
    exit(0);
  }

  /* find out what port we were assigned and print it out */

  length = sizeof( skaddr );
  if (getsockname(ld, (struct sockaddr *) &skaddr, &length)<0) {
    printf("Error getsockname\n");
    exit(1);
  }

  /* port number's are network byte order, we have to convert to
     host byte order before printing !
  */
  printf("The server UDP port number is %d\n",ntohs(skaddr.sin_port));

  /* Go echo every datagram we get */
  echo(ld);
  return(0);
}


问:
How to check if HTTP request is originating from AWS API Gateway?
I use AWS API Gateway that proxies HTTP queries to my services. How could my services check that HTTP requests are originating from AWS API Gateway?</p>

答:
You can use client-side certificates to authenticate requests between API-Gateway and your server.

http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-client-side-ssl-authentication.html

You can use API Gateway to generate an SSL certificate and use its public key in the backend to verify that HTTP requests to your backend system are from API Gateway. This allows your HTTP backend to control and accept only requests originating from Amazon API Gateway, even if the backend is publicly accessible.

The SSL certificates that are generated by API Gateway are self-signed and only the public key of a certificate is visible in the API Gateway console or through the APIs.


问:
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text=""?
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text="" ?</p>

答: Are you talking about a server-side button click event?  If so, then you can register javascript to run after the page is loaded, but you cannot execute javascript on the server in the context of the browser.</p>


问:
Dynamically changing a style in Polymer 2.0
I'm writing a proof of concept Polymer 2.0 web component where I want to change the colour of a piece of text depending on the user input.

I've tried using Polymer 2.0's this.updateStyles({...}) and Polymer.updateStyles({...}) but neither is updating the text which is output.

e.g.

```<code>Polymer.updateStyles({'--tool-colour': 'green'});
</code>```

I've written a plunker which demonstrates the problem here.

I'm probably missing something simple, can someone help me out?

答:
As Jordan Running commented, the problem was due to missing dependencies. I'd written code in an online editor (Plunker) assuming that all I needed to get polymer working was a reference to 'webcomponents-loader.js' and links to the other web components my bespoke component was using (doh!).

To get my Polymer element working I used the Polymer CLI facility provided by the Polymer team (specifically I used this for creating a Polymer element template project).

When I then used:

```<code>polymer serve
</code>```

To run a local webserver to "serve" the app which was using my Polymer element, the dependencies then got resolved properly and the element worked.

Body:
I'm writing a proof of concept Polymer 2.0 web component where I want to change the colour of a piece of text depending on the user input.

I've tried using Polymer 2.0's this.updateStyles({...}) and Polymer.updateStyles({...}) but neither is updating the text which is output.

e.g.

Polymer.updateStyles({'--tool-colour': 'green'});

I've written a plunker which demonstrates the problem here.

I'm probably missing something simple, can someone help me out?

Body:
As Jordan Running commented, the problem was due to missing dependencies. I'd written code in an online editor (Plunker) assuming that all I needed to get polymer working was a reference to 'webcomponents-loader.js' and links to the other web components my bespoke component was using (doh!).

To get my Polymer element working I used the Polymer CLI facility provided by the Polymer team (specifically I used this for creating a Polymer element template project).

When I then used:

polymer serve

To run a local webserver to "serve" the app which was using my Polymer element, the dependencies then got resolved properly and the element worked.


问:
NSURLConnection gets time out after multiple Requests
My code is having like below
1) For each streaming request we will process request in separate thread.

2) For blow streaming if i create separate exe works fine. Problem with single exe. Meance if i create separate for url connecting streaming works fine.

```<code>-(void)processRequest:(NSDictionary*)jsonObject
{
   // [NSThread detachNewThreadSelector:@selector(putHttpRequest:) toTarget:self withObject:jsonObject];
    NSInvocationOperation *invocationOP = [[NSInvocationOperation alloc] initWithTarget:myObj selector:@selector(putHttpRequest:) object:jsonObject] ;
    [rpcEventQueue addOperation:invocationOP];
    [invocationOP release];

}

-(void)putHttpRequest:(NSDictionary*)jsonObject
{
    [NSThread detachNewThreadSelector:@selector(databaseQueryForStreaming:) toTarget:self withObject:dict];
}

-(void)databaseQueryForStreaming:(NSDictionary*)dict
{
    [self performHttpPUTRequestForStreamingModifiedOne:dict];
}

-(void)performHttpPUTRequestForStreamingModifiedOne:(NSDictionary*)requestDict
{

NSString *url =@"http://asia.remotepc.com/proxy/host_put_response";
    NSMutableURLRequest * theRequest = (NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    [theRequest setHTTPMethod:@"PUT"];
    [theRequest addValue:request_id forHTTPHeaderField:@"request_id"];
    [theRequest addValue:@"200" forHTTPHeaderField:@"X-StatusCode"];
    [theRequest addValue:[NSString stringWithFormat:@"%ld", responseSize]  forHTTPHeaderField:@"X-ResposeSize"];

        [theRequest addValue:[NSString stringWithFormat:@"%@",fileSize] forHTTPHeaderField:@"X-FileSize"];
    [theRequest addValue:[NSString stringWithFormat:@"%@",lmd] forHTTPHeaderField:@"X-FileLMD"];
    [theRequest setValue:@"video/mp4" forHTTPHeaderField:@"Content-Type"];
    [theRequest setValue:@"chunked" forHTTPHeaderField:@"Transfer-Encoding"];

      NSOperationQueue *senderQueue = [[[NSOperationQueue alloc] init] autorelease];
    RPCStreamReader *stream =[[RPCStreamReader alloc]initWithFileAtPath:filepath];
    [stream setProperty:[NSNumber numberWithLong:start] forKey:NSStreamFileCurrentOffsetKey];
    if (end==1)
    {
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filepath];
        NSData *fileData = [handle readDataOfLength:30000];
        [theRequest setHTTPBodyStream:[NSInputStream inputStreamWithData:fileData]];
        [handle closeFile];
    }
    else
    {
     [theRequest setHTTPBodyStream:stream];
    }

[NSURLConnection sendAsynchronousRequest:theRequest queue:senderQueue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                                   NSLog(@"Finished with status code: %i and response:%@", [(NSHTTPURLResponse *)response statusCode],[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *)response statusCode]]);
                                   NSLog(@"error:%@",error);
                                   if(error)
                                       NSLog(@"Request id:%@ failed",request_id);
                                   else
                                       NSLog(@"Request id:%@ succeeded",request_id);
                               }
         ];

}
</code>```

答:
1) Reduced NSMutableURLRequest time out to 10 sec instead of 60 sec

2) NSMutableURLRequest sending modified from asynchronous to Syncronous

issue resolved working fine.

Body:
My code is having like below
1) For each streaming request we will process request in separate thread.

2) For blow streaming if i create separate exe works fine. Problem with single exe. Meance if i create separate for url connecting streaming works fine.

-(void)processRequest:(NSDictionary*)jsonObject
{
   // [NSThread detachNewThreadSelector:@selector(putHttpRequest:) toTarget:self withObject:jsonObject];
    NSInvocationOperation *invocationOP = [[NSInvocationOperation alloc] initWithTarget:myObj selector:@selector(putHttpRequest:) object:jsonObject] ;
    [rpcEventQueue addOperation:invocationOP];
    [invocationOP release];

}

-(void)putHttpRequest:(NSDictionary*)jsonObject
{
    [NSThread detachNewThreadSelector:@selector(databaseQueryForStreaming:) toTarget:self withObject:dict];
}

-(void)databaseQueryForStreaming:(NSDictionary*)dict
{
    [self performHttpPUTRequestForStreamingModifiedOne:dict];
}

-(void)performHttpPUTRequestForStreamingModifiedOne:(NSDictionary*)requestDict
{

NSString *url =@"http://asia.remotepc.com/proxy/host_put_response";
    NSMutableURLRequest * theRequest = (NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    [theRequest setHTTPMethod:@"PUT"];
    [theRequest addValue:request_id forHTTPHeaderField:@"request_id"];
    [theRequest addValue:@"200" forHTTPHeaderField:@"X-StatusCode"];
    [theRequest addValue:[NSString stringWithFormat:@"%ld", responseSize]  forHTTPHeaderField:@"X-ResposeSize"];

        [theRequest addValue:[NSString stringWithFormat:@"%@",fileSize] forHTTPHeaderField:@"X-FileSize"];
    [theRequest addValue:[NSString stringWithFormat:@"%@",lmd] forHTTPHeaderField:@"X-FileLMD"];
    [theRequest setValue:@"video/mp4" forHTTPHeaderField:@"Content-Type"];
    [theRequest setValue:@"chunked" forHTTPHeaderField:@"Transfer-Encoding"];

      NSOperationQueue *senderQueue = [[[NSOperationQueue alloc] init] autorelease];
    RPCStreamReader *stream =[[RPCStreamReader alloc]initWithFileAtPath:filepath];
    [stream setProperty:[NSNumber numberWithLong:start] forKey:NSStreamFileCurrentOffsetKey];
    if (end==1)
    {
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filepath];
        NSData *fileData = [handle readDataOfLength:30000];
        [theRequest setHTTPBodyStream:[NSInputStream inputStreamWithData:fileData]];
        [handle closeFile];
    }
    else
    {
     [theRequest setHTTPBodyStream:stream];
    }

[NSURLConnection sendAsynchronousRequest:theRequest queue:senderQueue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                                   NSLog(@"Finished with status code: %i and response:%@", [(NSHTTPURLResponse *)response statusCode],[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *)response statusCode]]);
                                   NSLog(@"error:%@",error);
                                   if(error)
                                       NSLog(@"Request id:%@ failed",request_id);
                                   else
                                       NSLog(@"Request id:%@ succeeded",request_id);
                               }
         ];

}


问:
Symfony 3.3.3 Generating missing files via the command assets:install
Since the new version of symfony 3.3.3, the command : php bin/console assets:install do not create anymore file in the directory web/bundles/.

You have an idea to solve concerns ?
For the moment, I copy last there the contents of the missing files... :)

I'm use Windows OS

答:
Solution is comming...

Reference : https://github.com/symfony/symfony/commit/6298e69f29b7ef8bdde357a2ce87e8f4843d1fd8

---

UPDATE

New minor version available : http://symfony.com/blog/symfony-3-3-4-released


问:
Cassandra Connection with Groovy Script In SoapUI
thanks for the time. I am trying to access a remote Cassandra DB in order to complete my assertions. I see that the Server is running:
Cassandra V 3.0.8.1293
Driver Type: Cassandra CQL
Datastax Java Driver for Apache Cassandra - Core [3.0.5]

So, I am trying with the following simple code to access the DB

```<code>import com.datastax.driver.core.*

Cluster cluster = null;
try {
cluster = Cluster.builder().addContactPoint("x.x.x.x").withCredentials("xxxxxxx", "xxxxxx").withPort(9042).build()

Session session = cluster.connect();

ResultSet rs = session.execute("select * from TABLE");
Row row = rs.one();
} finally {
if (cluster != null) cluster.close();
}
</code>```

when I use the cassandra-driver-core-2.0.1.jar I am getting the error :

ERROR:com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /x.x.x.x(null))

Read the documentation and a lot of posts here and on other blogs and I saw that there may be an incompatibility with the driver version so I tried to upgrade the driver to many versions (cassandra-driver-core-2.5,cassandra-driver-core-3,cassandra-driver-core-3.2), but on that I am getting the following:

ERROR:java.lang.ExceptionInInitializerError

Have also tried to connect using JDBC, but to no avail, using the configuration proposed at this thread
SoapUI JDBC connection with Apache Cassandra

Actually I am running out of ideas. Can anyone propose or point to some direction on how to actually achieve this, either by pointing me to some tutorial or any idea.
Thank you very much

答:
I think you haven't enable remote access to cassandra.

Try enabling remote access using below configuration -

File Path /etc/cassandra/default.conf/cassandra.yaml

```<code>rpc_address: 0.0.0.0

broadcast_rpc_address: <serverIPAddress>
</code>```

After that, restart cassandra service.

Body:
thanks for the time. I am trying to access a remote Cassandra DB in order to complete my assertions. I see that the Server is running:
Cassandra V 3.0.8.1293
Driver Type: Cassandra CQL
Datastax Java Driver for Apache Cassandra - Core [3.0.5]

So, I am trying with the following simple code to access the DB

import com.datastax.driver.core.*

Cluster cluster = null;
try {
cluster = Cluster.builder().addContactPoint("x.x.x.x").withCredentials("xxxxxxx", "xxxxxx").withPort(9042).build()

Session session = cluster.connect();

ResultSet rs = session.execute("select * from TABLE");
Row row = rs.one();
} finally {
if (cluster != null) cluster.close();
}

when I use the cassandra-driver-core-2.0.1.jar I am getting the error :

ERROR:com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /x.x.x.x(null))

Read the documentation and a lot of posts here and on other blogs and I saw that there may be an incompatibility with the driver version so I tried to upgrade the driver to many versions (cassandra-driver-core-2.5,cassandra-driver-core-3,cassandra-driver-core-3.2), but on that I am getting the following:

ERROR:java.lang.ExceptionInInitializerError

Have also tried to connect using JDBC, but to no avail, using the configuration proposed at this thread
SoapUI JDBC connection with Apache Cassandra

Actually I am running out of ideas. Can anyone propose or point to some direction on how to actually achieve this, either by pointing me to some tutorial or any idea.
Thank you very much

Body:
I think you haven't enable remote access to cassandra.

Try enabling remote access using below configuration -

File Path /etc/cassandra/default.conf/cassandra.yaml

rpc_address: 0.0.0.0

broadcast_rpc_address: <serverIPAddress>

After that, restart cassandra service.


问:
Swift: Argument labels naming convention?
Suppose I want to hide/show an UI element using one function. What is the correct way to name it?

```<code>func changeRefreshControlVisibilityTo(_ isVisible: Bool) {}
</code>```

or

```<code>func changeRefreshControlVisibility(to isVisible: Bool) {}
</code>```

Do people have thoughts and/or references for this? Thanks!

答:
I personally wouldn't go with neither of these. The change part seems redundant to me, especially taking into account the fact, that it might not really change anything - let's say, that current visibility is false and you still can set false as the argument of this method.

So if you want to stick to word change, maybe something like that:

```<code>func changeRefreshControlVisibility() {}
</code>```

or to me, even better one:

```<code>func toggleRefreshControlVisibility() {}
</code>```

would be sufficient?

And if you want to openly communicate what value will the visibility have after using this method, why not simply:

```<code>func setRefreshControlVisible(_ isVisible: Bool) {}
</code>```

Anyway, the API design guidelines for Swift are rather brief:

https://swift.org/documentation/api-design-guidelines/

So my general impression is that you should go with whatever suits you/your team best.

Body:
Suppose I want to hide/show an UI element using one function. What is the correct way to name it?

func changeRefreshControlVisibilityTo(_ isVisible: Bool) {}

or

func changeRefreshControlVisibility(to isVisible: Bool) {}

Do people have thoughts and/or references for this? Thanks!

Body:
I personally wouldn't go with neither of these. The change part seems redundant to me, especially taking into account the fact, that it might not really change anything - let's say, that current visibility is false and you still can set false as the argument of this method.

So if you want to stick to word change, maybe something like that:

func changeRefreshControlVisibility() {}

or to me, even better one:

func toggleRefreshControlVisibility() {}

would be sufficient?

And if you want to openly communicate what value will the visibility have after using this method, why not simply:

func setRefreshControlVisible(_ isVisible: Bool) {}

Anyway, the API design guidelines for Swift are rather brief:

https://swift.org/documentation/api-design-guidelines/

So my general impression is that you should go with whatever suits you/your team best.


问:
Custom Code Panels preview in InstallAnywhere?
Is there a way to preview custom code panels in InstallAnywhere? Non-custom code panels can be previewed using the InstallAnywhere IDE. I'm wondering if there is a way to do this for these panels. Any suggestion will be greatly appreciated. Thanks :)</p>

答:
Just got InstallAnywhere 2017; according to Flexera's SP1 release note they are supporting custom panels preview (IOJ-1759620):
http://helpnet.flexerasoftware.com/installanywhere2017/IAReleaseNotes_en.htm

In case you're using older IA versions, you may implement your custom panels on any java swing editor such as eclipse or netbeans (I prefer netbeans since it has an oobt support for swing editor).


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
Depends on the language. If you're writing in C, then the "one entry, one exit" philosophy makes sense -- you want one place where you're cleaning up resources used by a function so that you don't have a chance of forgetting later. If you're in C++, then you should be using RAII for cleanup anyway, in which case I completely disagree with your teacher. Use returns as needed in order to make the code as clear as possible.

(Though I would use for (;;) instead of while (true) in C++ to generate the infinite loop)

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?


问:
Font change onmouseover onmouseout
what would be the code for this: Insert a link. When mouse is over, the link font turns bold and underlined, when mouse is out, it comes back to the initial form</p>

答:
you can change the font on hover whic will get back to its original font when mouseout

```<code>a:hover{
    font-weight:600;
    text-decoration: underline;
    color:#000;
}
</code>```

Title: Font change onmouseover onmouseout

Body:
you can change the font on hover whic will get back to its original font when mouseout

a:hover{
    font-weight:600;
    text-decoration: underline;
    color:#000;
}


问:
Multiple $scope.$watch not working in Angular JS
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)</p>

```<code>$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});
</code>```

答:
To watch multiple scope in the same controller, you can use:</p>

```<code>$scope.$watchGroup(['search', 'id'], function(newValues, oldValues) {

 newValues[0] -> $scope.search
 newValues[1] -> $scope.id

// Then perform your operations.

});
</code>```

Body:
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)

$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});

Body:
To watch multiple scope in the same controller, you can use:

$scope.$watchGroup(['search', 'id'], function(newValues, oldValues) {

 newValues[0] -> $scope.search
 newValues[1] -> $scope.id

// Then perform your operations.

});


问:
Pandas replace, to lowercase and else option [Python]
I am trying to replace dataframe values in columns: Professional Status Activity and Professional Status Activity Type with numbers but before that, I want to be sure each value in map is compared with the lowercase value in thr dataframe and, if there is no value in map, put value = 2.

```<code>mapping_dict = {
    "Professional Status Activity": {
        "full time employed": 1,
        "pension": 1,
        "student": 2,
        "part time employed": 2,
        "other": 2,
        "unemployed": 3

    },
    "Professional Status Activity Type":{
        "civil servant": 1,
        "judge": 1,
        "army officer": 1,
        "worker": 2,
        "insurance officer": 2,
        "notary": 2,
        "lawyer": 2,
        "consultant": 3,
        "chief l": 3
    }
}

df = df.replace(mapping_dict)
</code>```

So this is the logic I need:
for example if in df column Professional Status Activity first row = Full Time Employed then lowercase it and compare it with full time employed in map object so result will be 1 from map.
And if in df column Professional Status Activity first row = Something not have in map result will be 2

答:
so the question is not completely clear and a minimal complete example would help. But I think you want something like this:

```<code>df["status"].apply(lambda x: mapping_dict["Professional Status Activity"].get(x.lower(),2))
</code>```

This gows through a column of your dataframe (which I've called "status" since you haven't given an example of your actual dataframe) and applies a function on each element. First it calls .lower() for the element, which turns a string into its lower-case form. Then it checks for this value in the "Professional Status Activity"dict from the mapping_dict, using get(). Get allows you to specify a default value, which in this case I have set as 2, so if the key is not in the dictionary, it will return 2.

If you want to replace your column with this transformed version, you would do

```<code>df["status"] = df["status"].apply(lambda x: mapping_dict["Professional Status Activity"].get(x.lower(),2))
</code>```

Body:
I am trying to replace dataframe values in columns: Professional Status Activity and Professional Status Activity Type with numbers but before that, I want to be sure each value in map is compared with the lowercase value in thr dataframe and, if there is no value in map, put value = 2.

mapping_dict = {
    "Professional Status Activity": {
        "full time employed": 1,
        "pension": 1,
        "student": 2,
        "part time employed": 2,
        "other": 2,
        "unemployed": 3

    },
    "Professional Status Activity Type":{
        "civil servant": 1,
        "judge": 1,
        "army officer": 1,
        "worker": 2,
        "insurance officer": 2,
        "notary": 2,
        "lawyer": 2,
        "consultant": 3,
        "chief l": 3
    }
}

df = df.replace(mapping_dict)

So this is the logic I need:
for example if in df column Professional Status Activity first row = Full Time Employed then lowercase it and compare it with full time employed in map object so result will be 1 from map.
And if in df column Professional Status Activity first row = Something not have in map result will be 2

Body:
so the question is not completely clear and a minimal complete example would help. But I think you want something like this:

df["status"].apply(lambda x: mapping_dict["Professional Status Activity"].get(x.lower(),2))

This gows through a column of your dataframe (which I've called "status" since you haven't given an example of your actual dataframe) and applies a function on each element. First it calls .lower() for the element, which turns a string into its lower-case form. Then it checks for this value in the "Professional Status Activity"dict from the mapping_dict, using get(). Get allows you to specify a default value, which in this case I have set as 2, so if the key is not in the dictionary, it will return 2.

If you want to replace your column with this transformed version, you would do

df["status"] = df["status"].apply(lambda x: mapping_dict["Professional Status Activity"].get(x.lower(),2))


问:
Determine device public ip
Does anyone know how I could get the public ip address of an android device?

I am trying to run a server socket (just experimenting with simple p2p).

This requires informing the local and remote users of each others public ip. I did find this thread How to get IP address of the device from code? which contains a link to an article (http://www.droidnova.com/get-the-ip-address-of-your-device,304.html) that shows how to get the IP. However this returns the local ip when connected through a router and I would like to get the actual public IP instead.

TIA

答:
```<code> public class getIp extends AsyncTask<String, String, String> {
        String result;

        @Override
        protected String doInBackground(String... strings) {
            CustomHttpClient client = new CustomHttpClient();
            try {
                result = client.executeGet("http://checkip.amazonaws.com/");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }
</code>```

and call in anywhere

```<code>try {
            ip = new getIp().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
</code>```

CustomHttpClient.java

```<code>import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class CustomHttpClient {
    private static HttpClient custHttpClient;
    public static final int MAX_TOTAL_CONNECTIONS = 1000;
    public static final int MAX_CONNECTIONS_PER_ROUTE = 1500;
    public static final int TIMEOUT_CONNECT = 150000;
    public static final int TIMEOUT_READ = 150000;
    public static HttpClient getHttpClient() {
    if (custHttpClient == null) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
            HttpParams connManagerParams = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(connManagerParams, MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams, new ConnPerRouteBean(MAX_CONNECTIONS_PER_ROUTE));
            HttpConnectionParams.setConnectionTimeout(connManagerParams, TIMEOUT_CONNECT);
            HttpConnectionParams.setSoTimeout(connManagerParams, TIMEOUT_READ);
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
            custHttpClient = new DefaultHttpClient(cm, null);
            HttpParams para = custHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(para, (30 * 10000));
            HttpConnectionParams.setSoTimeout(para, (30 * 10000));
            ConnManagerParams.setTimeout(para, (30 * 10000));
        }
        return custHttpClient;
    }
    public static String executePost(String urlPostFix,ArrayList<NameValuePair> postedValues)
    throws Exception {
        String url = urlPostFix;
        BufferedReader in = null;
        try {
            System.setProperty("http.keepAlive", "false");
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postedValues);
            formEntity.setContentType("application/json");
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
    public static String executeGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                BufferedReader in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet( url);
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    HttpResponse response = client.execute(request);
                    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line + NL);
                    }
                    in.close();
                    String result = sb.toString();
                    return result;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
    public static Bitmap executeImageGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                InputStream in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet(url);
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                    in = bufHttpEntity.getContent();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                    return bitmap;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                }
                }
    }
}
</code>```

Title: Determine device public ip

Body:
 public class getIp extends AsyncTask<String, String, String> {
        String result;

        @Override
        protected String doInBackground(String... strings) {
            CustomHttpClient client = new CustomHttpClient();
            try {
                result = client.executeGet("http://checkip.amazonaws.com/");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

and call in anywhere

try {
            ip = new getIp().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

CustomHttpClient.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class CustomHttpClient {
    private static HttpClient custHttpClient;
    public static final int MAX_TOTAL_CONNECTIONS = 1000;
    public static final int MAX_CONNECTIONS_PER_ROUTE = 1500;
    public static final int TIMEOUT_CONNECT = 150000;
    public static final int TIMEOUT_READ = 150000;
    public static HttpClient getHttpClient() {
    if (custHttpClient == null) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
            HttpParams connManagerParams = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(connManagerParams, MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams, new ConnPerRouteBean(MAX_CONNECTIONS_PER_ROUTE));
            HttpConnectionParams.setConnectionTimeout(connManagerParams, TIMEOUT_CONNECT);
            HttpConnectionParams.setSoTimeout(connManagerParams, TIMEOUT_READ);
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
            custHttpClient = new DefaultHttpClient(cm, null);
            HttpParams para = custHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(para, (30 * 10000));
            HttpConnectionParams.setSoTimeout(para, (30 * 10000));
            ConnManagerParams.setTimeout(para, (30 * 10000));
        }
        return custHttpClient;
    }
    public static String executePost(String urlPostFix,ArrayList<NameValuePair> postedValues)
    throws Exception {
        String url = urlPostFix;
        BufferedReader in = null;
        try {
            System.setProperty("http.keepAlive", "false");
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postedValues);
            formEntity.setContentType("application/json");
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
    public static String executeGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                BufferedReader in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet( url);
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    HttpResponse response = client.execute(request);
                    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line + NL);
                    }
                    in.close();
                    String result = sb.toString();
                    return result;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
    public static Bitmap executeImageGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                InputStream in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet(url);
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                    in = bufHttpEntity.getContent();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                    return bitmap;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                }
                }
    }
}


问:
xslt transformation to copy from xml to xml specific nodes omly
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

```<code><?xml version="1.0"?>
<root>
  <a id="A">
    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>
  </a>
  <a id="B">
    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>
  </a>
</root>
</code>```

desired output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
   <a id="A">
      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>
   </a>
   <a id="B">
      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>
   </a>
</root>
</code>```

Currently I use follwonf xslt:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

But I would like to have shorter list something like that:

```<code> root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()
</code>```

So how to create xslt transformation for that short list?

答:
I would get more specific:

XSLT

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="a">
    <xsl:copy>
        <xsl:apply-templates select="@id|bb|cc"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="cc">
    <xsl:copy>
        <xsl:apply-templates select="bbb"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

<?xml version="1.0"?>
<root>

    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>

    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>

</root>

desired output:

<?xml version="1.0" encoding="UTF-8"?>
<root>

      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>

      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>

</root>

Currently I use follwonf xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

But I would like to have shorter list something like that:

 root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()

So how to create xslt transformation for that short list?

Body:
I would get more specific:

XSLT

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="a">
    <xsl:copy>
        <xsl:apply-templates select="@id|bb|cc"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="cc">
    <xsl:copy>
        <xsl:apply-templates select="bbb"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>