问:
app:srcCompat - Vector drawable shows up in design preview, but doesn't show up in app
drawable/information.xml

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0,0 0,2 12A10,10 0,0 0,12 22A10,10 0,0 0,22 12A10,10 0,0 0,12 2Z"/>
</vector>
</code>```

LayoutofCardView.xml

```<code><ImageView
    android:layout_width="24dp"
    android:background="#f00"
    android:layout_height="24dp"
    android:id="@+id/informationImageView"
    app:srcCompat="@drawable/information"
    tools:src="@drawable/information"
    />
</code>```

build.gradle

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.company"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        generatedDensities = []

    }
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
}
</code>```

The image shows up correctly in the design pane of android studio. But when I run the app, the image doesn't show up. The image is in cardView, which is in recyclerviewfragment. other items render correctly only vector drawbles don't render.

Also, Lint error shows up in the layout file

```<code>unexpected namespace prefix "app" found for tag ImageView app:srcCompat
</code>```

答:
I found this answer when I have your problem.
Quick answer is you should use android.support.v7.widget.AppCompatImageView and app:srcCompat

this link explain it.

Body:
drawable/information.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0,0 0,2 12A10,10 0,0 0,12 22A10,10 0,0 0,22 12A10,10 0,0 0,12 2Z"/>
</vector>

LayoutofCardView.xml

<ImageView
    android:layout_width="24dp"
    android:background="#f00"
    android:layout_height="24dp"
    android:id="@+id/informationImageView"
    app:srcCompat="@drawable/information"
    tools:src="@drawable/information"
    />

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.company"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        generatedDensities = []

    }
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
}

The image shows up correctly in the design pane of android studio. But when I run the app, the image doesn't show up. The image is in cardView, which is in recyclerviewfragment. other items render correctly only vector drawbles don't render.

Also, Lint error shows up in the layout file

unexpected namespace prefix "app" found for tag ImageView app:srcCompat


来源: stackexchange

问:
How to use Dockerfile to link main container to a db container?
Docker has a quite convenient way to link the main container to a db container with a command like:

```<code>docker run --link db:db user/main
</code>```

This is very convenient already. However, I believe it's still clumsy compared to a command like:

```<code>docker run user/ultra
</code>```

where ultra is a container that is already linking the main container to the db container.

Is that possible that I can achieve this by writing a good Dockerfile.

I suppose I can start the Dockerfile with

```<code>FROM user/main
</code>```

but how do I get the second container involved and then link them with Dockerfile?

Thanks.

答:
```<code>FROM user/main
</code>```

That would create an image (build time) based on user/main, which is not at all the same as linking at runtime two containers together.

Plus, --link is now obsolete: see "Legacy container links"

Warning: The --link flag is a deprecated legacy feature of Docker. It may eventually be removed.

Unless you absolutely need to continue using it, we recommend that you use user-defined networks to facilitate communication between two containers instead of using --link

Use instead the links directive in a docker-compose.yml file.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified

You can make sure the containers are launched in the proper order with the depends_on directive.

Then a simple docker-compose up will launch the containers and link them on the same network.

ContentLicense: CC BY-SA 3.0

Body:
Docker has a quite convenient way to link the main container to a db container with a command like:

docker run --link db:db user/main

This is very convenient already. However, I believe it's still clumsy compared to a command like:

docker run user/ultra

where ultra is a container that is already linking the main container to the db container.

Is that possible that I can achieve this by writing a good Dockerfile.

I suppose I can start the Dockerfile with

FROM user/main

but how do I get the second container involved and then link them with Dockerfile?

Thanks.

Body:
FROM user/main

That would create an image (build time) based on user/main, which is not at all the same as linking at runtime two containers together.

Plus, --link is now obsolete: see "Legacy container links"

Warning: The --link flag is a deprecated legacy feature of Docker. It may eventually be removed.

Unless you absolutely need to continue using it, we recommend that you use user-defined networks to facilitate communication between two containers instead of using --link

Use instead the links directive in a docker-compose.yml file.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified

You can make sure the containers are launched in the proper order with the depends_on directive.

Then a simple docker-compose up will launch the containers and link them on the same network.

ContentLicense: CC BY-SA 4.0


问:
Hovering effect over image link is overextending the div it is surrounded in
So for some reason when I hover over specific points below an image link I have that is wrapped in a div, it will trigger the hovering effect for the image link that I have created through CSS. I have tried multiple things (overflow:hidden, display:inline-block) but nothing seems to work. I will post my code and a jsfiddle link. Thanks in advance.

HTML:

```<code><div class="div_for_projects">
 <div class="project_inner_divs">
  <div id="portfolio_project">
    <div id="portfolio_project_child">
      <a href="index.html">
        <!--
        Image Source:
        http://www.connectwithchildlife.com/2015/10/child-life-portfolio.html
        -->
        <img class="portfolio_page_projects"
        src="http://www.vandelaydesign.com/wp-content/uploads/portfolio2.jpg"
        alt="portfolio_image">
      </a>
      <p>
        <a href="index.html"
        class="text_align project_description">
          PROJECT
        </a>
      </p>
      <a href="#">
        <img class="portfolio_sm_links"
        src="https://maxcdn.icons8.com/Share/icon/Editing//arrow_filled1600.png"
        alt="Portfolio Image Link">
      </a>
   </div>
  </div>
 </div>
</div>
</code>```

CSS:

```<code>.div_for_projects {
  width: 100%;
  height: 420px;
}
.project_inner_divs {
  float: left;
  width: 35%;
}
#portfolio_project {
  position: relative;
  width: 426px;
  height: 420px;
  pointer-events: none;
  transition-duration: 0.4s;
}
#portfolio_project_child {
  pointer-events: auto;
  width: 100%;
  height: 100%;
}
#portfolio_project:hover {
  -webkit-filter: brightness(70%);
}
#portfolio_project:hover .project_description {
  visibility: visible;
  opacity: 1;
}
#portfolio_project:hover .portfolio_sm_links {
  visibility: visible;
  opacity: 1;
}
.portfolio_page_projects {
  width: 426px;
  height: 420px;
}
.project_description {
  position: relative;
  bottom: 250px;
  visibility: hidden;
  opacity: 0;
  transition-duration: 0.4s;
  font-size: 18px;
  font-family: Tahoma, Geneva, sans-serif;
  color: rgb(50, 50, 50);
  display: inline-block;
  left: 170px;
 }
.text_align {
  text-align: center;
}
.portfolio_sm_links {
  width: 40px;
  height: 40px;
  position: relative;
  bottom: 130px;
  left: 350px;
  visibility: hidden;
  display: inline-block;
  opacity: 0;
}
.portfolio_sm_links:hover {
  background-color: grey;
}
</code>```

jsfiddle link: https://jsfiddle.net/26vutwz9/

答:
The paragraph tag is your issue. You can solve it by taking it out of the normal html flow with a position absolute, like</p>

```<code>#portfolio_project_child p { position: absolute; top: 0; left:0 }
</code>```

Body:
So for some reason when I hover over specific points below an image link I have that is wrapped in a div, it will trigger the hovering effect for the image link that I have created through CSS. I have tried multiple things (overflow:hidden, display:inline-block) but nothing seems to work. I will post my code and a jsfiddle link. Thanks in advance.

HTML:

          PROJECT

CSS:

.div_for_projects {
  width: 100%;
  height: 420px;
}
.project_inner_divs {
  float: left;
  width: 35%;
}
#portfolio_project {
  position: relative;
  width: 426px;
  height: 420px;
  pointer-events: none;
  transition-duration: 0.4s;
}
#portfolio_project_child {
  pointer-events: auto;
  width: 100%;
  height: 100%;
}
#portfolio_project:hover {
  -webkit-filter: brightness(70%);
}
#portfolio_project:hover .project_description {
  visibility: visible;
  opacity: 1;
}
#portfolio_project:hover .portfolio_sm_links {
  visibility: visible;
  opacity: 1;
}
.portfolio_page_projects {
  width: 426px;
  height: 420px;
}
.project_description {
  position: relative;
  bottom: 250px;
  visibility: hidden;
  opacity: 0;
  transition-duration: 0.4s;
  font-size: 18px;
  font-family: Tahoma, Geneva, sans-serif;
  color: rgb(50, 50, 50);
  display: inline-block;
  left: 170px;
 }
.text_align {
  text-align: center;
}
.portfolio_sm_links {
  width: 40px;
  height: 40px;
  position: relative;
  bottom: 130px;
  left: 350px;
  visibility: hidden;
  display: inline-block;
  opacity: 0;
}
.portfolio_sm_links:hover {
  background-color: grey;
}

jsfiddle link: https://jsfiddle.net/26vutwz9/

Body:
The paragraph tag is your issue. You can solve it by taking it out of the normal html flow with a position absolute, like

#portfolio_project_child p { position: absolute; top: 0; left:0 }


问:
How i solve memory leak problem?
I developing an simple application in which design or make code in which i creating and instance object of UIImage. When i swip on Ipad screen it make up an image of the sreen and that image i render into UIImage object after that this image i set into UIImageView object and UIimage object is released.
Every time i swipe on the screen and above process is does again and again. But it give me leak in renderImage = [[UIImage alloc] init];.

Code,

```<code>_renderImage = [[UIImage alloc] init];

_textImageV = [[UIImageView alloc] init];

[self renderIntoImage];

-(void)renderIntoImage
{

    UIGraphicsBeginImageContext(bgTableView.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    _renderImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

 _textImageV.image = _renderImage;
[_renderImage release];
</code>```

after completing the process of swipe i also releasing _textImageV.

How i solve the memory leak problem in UIImage *_renderImage?

答:
On this line:

```<code>_renderImage = UIGraphicsGetImageFromCurrentImageContext();
</code>```

UIGraphicsGetImageFromCurrentImageContext() returns a new autoreleased UIImage and points the _renderImage ivar to it. The previously allocated UIImage is never actually released, the variable to it is just repointed to somewhere else.

This abandoned UIImage causes/is the memory leak. You should either release it before pointing _renderImage to something else, or you could just not allocate it in the first place.

ContentLicense: CC BY-SA 2.5

Title: How i solve memory leak problem?

Body:
I developing an simple application in which design or make code in which i creating and instance object of UIImage. When i swip on Ipad screen it make up an image of the sreen and that image i render into UIImage object after that this image i set into UIImageView object and UIimage object is released.
Every time i swipe on the screen and above process is does again and again. But it give me leak in renderImage = [[UIImage alloc] init];.

Code,

_renderImage = [[UIImage alloc] init];

_textImageV = [[UIImageView alloc] init];

[self renderIntoImage];

-(void)renderIntoImage
{

    UIGraphicsBeginImageContext(bgTableView.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    _renderImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

 _textImageV.image = _renderImage;
[_renderImage release];

after completing the process of swipe i also releasing _textImageV.

How i solve the memory leak problem in UIImage *_renderImage?

Body:
On this line:

_renderImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsGetImageFromCurrentImageContext() returns a new autoreleased UIImage and points the _renderImage ivar to it. The previously allocated UIImage is never actually released, the variable to it is just repointed to somewhere else.

This abandoned UIImage causes/is the memory leak. You should either release it before pointing _renderImage to something else, or you could just not allocate it in the first place.


问:
Value of type String cannot be converted to JSONObject
I'm struggling with an error that tells me that it cannot convert a String value to JSONObject. I'm trying to pass a CSRFToken as a parameter to my JSONObjectRequest. I have no clue if this is the right way to even go about it.

I'm getting the error message: org.json.JSONException: Value inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2 of type java.lang.String cannot be converted to JSONObject

Relevant code is below.

HashMap<String, String> params = new HashMap<>();
params.put("_token", ((TestApplication) getApplication()).getCSRFToken());

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        Log.i("response", response.toString());
        alertDialog.setMessage(response.toString());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(error.getMessage());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
});

queue.add(stringRequest);
```

Does anyone know what I may have done wrong and how to rectify the issue?

答:
I've figured it out. JsonObjectRequest doesn't send any accept headers. After adding an accept header I was able to get the response I was after.

Final code:

```<code>HashMap<String, String> params = new HashMap<>();

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        // ...
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        //alertDialog.setMessage(error.toString());
        alertDialog.setMessage(new String(error.networkResponse.data));
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put("X-CSRF-TOKEN", ((TestApplication) getApplication()).getCSRFToken());
        params.put("Accept", "application/json");
        return params;
    }
};

queue.add(stringRequest);
</code>```

Body:
I'm struggling with an error that tells me that it cannot convert a String value to JSONObject. I'm trying to pass a CSRFToken as a parameter to my JSONObjectRequest. I have no clue if this is the right way to even go about it.

I'm getting the error message: org.json.JSONException: Value inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2 of type java.lang.String cannot be converted to JSONObject

Relevant code is below.

HashMap<String, String> params = new HashMap<>();
params.put("_token", ((TestApplication) getApplication()).getCSRFToken());

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        Log.i("response", response.toString());
        alertDialog.setMessage(response.toString());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(error.getMessage());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
});

queue.add(stringRequest);

Does anyone know what I may have done wrong and how to rectify the issue?

Body:
I've figured it out. JsonObjectRequest doesn't send any accept headers. After adding an accept header I was able to get the response I was after.

Final code:

HashMap<String, String> params = new HashMap<>();

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        // ...
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        //alertDialog.setMessage(error.toString());
        alertDialog.setMessage(new String(error.networkResponse.data));
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put("X-CSRF-TOKEN", ((TestApplication) getApplication()).getCSRFToken());
        params.put("Accept", "application/json");
        return params;
    }
};

queue.add(stringRequest);


问:
Try Catch doesnt try the second condition
i have 2 condition inside try which is ||. The first condition will not try to catch. But the second one, it does.

```<code>    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        try
        {
            if (fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)
            {
                SearchingPhoto();
            }
        }
        catch(NullReferenceException)
        { return; }
    }
</code>```

Method in try will run if and only if fbd[0].SelectedPath is not equal to null.

case 1: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)OK

case 2: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)not OK

case 3: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)OK

case 4: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)not OK

//i want to run a method inside case 2:

答:
here is my final method</p>

```<code>    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        if (fbd[0]?.SelectedPath != null || fbd[1]?.SelectedPath != null)
        {
            SearchingPhoto();
        }
    }
</code>```

Body:
i have 2 condition inside try which is ||. The first condition will not try to catch. But the second one, it does.

    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        try
        {
            if (fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)
            {
                SearchingPhoto();
            }
        }
        catch(NullReferenceException)
        { return; }
    }

Method in try will run if and only if fbd[0].SelectedPath is not equal to null.

case 1: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)OK

case 2: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)not OK

case 3: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)OK

case 4: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)not OK

//i want to run a method inside case 2:

Body:
here is my final method

    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        if (fbd[0]?.SelectedPath != null || fbd[1]?.SelectedPath != null)
        {
            SearchingPhoto();
        }
    }


问:
Custom alert dialog is shown different in older Api's
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

```<code>final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);
</code>```

What should I do?

答:
Just add the below line. It will solve your problem.

```<code>dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

Actually, you have to hide the title place of the dialog.

Body:
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);

What should I do?

Body:
Just add the below line. It will solve your problem.

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

Actually, you have to hide the title place of the dialog.


问:
Convert base64string to downloadable file using javascript
I want to download the file while clicking on the link.

```<code><a href="javascript:download(375,untitled.png,image/x-png,*base64bytestring*)" >untitled.png</a>
</code>```

javascript code

```<code>function download(id,name,contenttype,filebyte)
{

}
</code>```

答:
You can use this simple download function , pass to it the url , file name you want and the type.</p>

```<code> function download(url, filename, mimeType){
        return (fetch(url)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], filename, {type:mimeType});})
        );
    }

    download('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt', 'text/plain')
    .then(function(file){
        console.log(file);
    })
</code>```

Body:
I want to download the file while clicking on the link.

untitled.png

javascript code

function download(id,name,contenttype,filebyte)
{

}

Body:
You can use this simple download function , pass to it the url , file name you want and the type.

 function download(url, filename, mimeType){
        return (fetch(url)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], filename, {type:mimeType});})
        );
    }

    download('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt', 'text/plain')
    .then(function(file){
        console.log(file);
    })


问:
How to resize background image on Safari?
In Chrome

In Chrome, it works just like the picture above.

In Safari

However, in Safari, it does not work as shown above.

The CSS code is as follows:

```<code>background-image: url(rendyhome.png);
background-size: auto 66vh;
background-repeat: no-repeat;
background-position: right;
</code>```

How do I fix it?

答:
Look here:
https://www.w3schools.com/cssref/css3_pr_background-size.asp

I would look at using

```<code>background-size: cover;
</code>```

Scale the background image to be as large as possible so that the
  background area is completely covered by the background image. Some
  parts of the background image may not be in view within the background
  positioning area

Body:
In Chrome

In Chrome, it works just like the picture above.

In Safari

However, in Safari, it does not work as shown above.

The CSS code is as follows:

background-image: url(rendyhome.png);
background-size: auto 66vh;
background-repeat: no-repeat;
background-position: right;

How do I fix it?

Body:
Look here:
https://www.w3schools.com/cssref/css3_pr_background-size.asp

I would look at using

background-size: cover;

Scale the background image to be as large as possible so that the
  background area is completely covered by the background image. Some
  parts of the background image may not be in view within the background
  positioning area


问:
how to learn EXTJS
I know jquery and javascript but never worked on other frameworks like EXTJS.
can somebody tell me the best way to quickly learn EXTJS? and also what is the process to configure EXTJS? Is it in the same way like we configure jquery (by just adding a standard js file)? or something else.

Thanks

答:
Quite a few tutorials on this website:

http://www.sencha.com/learn/Tutorials

Or have a look at the answer to this question

https://stackoverflow.com/questions/2001112/ext-js-tutorial-or-videos

Try Garcia's book 'Ext JS in action'
http://www.manning.com/garcia/

Title: how to learn EXTJS


问:
sony xperia z5 camera 60 fps
We work with a Sony Xperia Z5 device and have encountered difficulties retrieving a 60fps video stream (VGA or HD) from the front (and back) camera using Android APIs.  We don't use the media recorder, we want to do live image processing and therefore don't need to save the images. We used the getHighSpeedVideoFpsRanges() Method but didn't get any results. This is somehow a strange behaviour. It would be great to use the front camera for this.
Is there any other way to access the camera via the Android APIs with 60fps (or more)?
Are there other (Sony) devices that allow retrieving 60fps streams for third party apps via the Android APIs?
Empty result - getHighSpeedVideoFpsRanges() </p>

答:
Checking the internet forums, e.g. Reddit or Xperia Support, this device does not have full camera2 implementation. It seems that Sony only provides legacy camera2 hardware level.

In some cases, you can achieve more through the deprecated hardware.Camera API. I am not sure if specifically for Sony Xperia Z5, it is possible to receive reliable 60 fps video stream with the old API, but the big question is whether it is worthwhile to invest in such R&D effort.

Title: sony xperia z5 camera 60 fps


问:
error TS6044: Compiler option 'types' expects an argument
i'm facing with the following error error TS6044: Compiler option 'types' expects an argument. when trying to set "types": [] in tsconfig.json.

We are using grunt-ts

This is recommended by official TS documentation in order to get rid of the following errors: node_modules/@types/angular/index.d.ts(14,9): error TS2403

Here is the link to TS documentation

Specify "types": [] to disable automatic inclusion of @types packages.

But instead of disabling automatic inclusion of @types i see error error TS6044: Compiler option 'types' expects an argument.

Can someone help me?

答:
Finally i've solved my problem specifying jasmine in types
 "types" : ["jasmine"]</p>


问:
Prevent Serialization of parent class Java
Is there a way where I can prevent the parent class to be serialized?

When we do a serialization of the subclass all the way up till the parent class the serialization is performed.

Can I restrict the serialization of the parent classes and serialize the only sub class I am working on?

答:
Whilst it is technically possible to fine tune each level of inheritance on its own - even to the extent of excluding super class fields - you might want to step back here.

Basically there are two cases:

The super class does not have any fields / state. Then you have nothing to exclude anyway.

The super class has state, represented by fields of that class.

So how do you think to meaningfully address the second part? You see when you allow deserialisation without the data for the super class fields - that means that you might have to do a lot of additional testing. To make sure that super class methods don't throw exceptions - because all of a sudden fields are null instead of being initialized.

In other words: it is possible that "leaving out" all these values - you are creating objects which behave completely different. Are you prepared for handling all the effects of that?

Meanung: skipping super class fields requires you to interfere with serialization code. It might require a lot of additional testing effort. And what do you gain? A few bytes less of data transfer at runtime.

Beyond that: what is the purpose of an inheretance hierarchy that has 4 levels - but where the super class state is irrelevant?

So my non-answer: carefully consider if your idea is really the best OO design to solve the underlying requirements.


问:
C++ header file with default arguments in C program
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

```<code>#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif
</code>```

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?

答:
Rather than macro hackery to work around the fact that C does not support default arguments, I'd introduce a layer of indirection.

First a C++ specific header that your C++ code uses (which I arbitrarily name interface.h.

```<code> double my_function_caller(double x, double abs_error = 1E-3);
</code>```

and a C specific header (which I arbitrarily name the_c_header.h)

```<code> double my_function(double x, double abs_error);

 /*  all other functions that have a C interface here */
</code>```

In practice, one would probably want include guards in both headers.

The next step is a C++ compilation unit (which I arbitrarily name interface.cpp) that actually interfaces to mathematica

```<code> #include "interface.h"

 extern "C"     //  this is C++, so we don't need to test __cplusplus
 {
      #include "the_c_header.h"
 }

 double my_function_caller(double x, double error)
 {
      return my_function(x, error);
 }
</code>```

Then there is just the question of how to call the function.  If the caller is C++, then all it needs to do is

```<code>  #include "interface.h"

  //   and later in some code

       double result = my_function_caller(x);
       double another_result = my_function_caller(x, 1E-6);
</code>```

If the caller is C (built with a C compiler) it simply does

```<code>  #include "the_c_header.h"

  /*  and later */

       result = my_function(x, 1E-3);
       another result = my_function(x, 1E-6);
</code>```

There are obviously advantages and disadvantages of this, compared with a macro-based solution, including;

None of the traditional disadvantages of macros (not respecting scope, no unintended interactions with other macros, running afoul of some C++ development guidelines that forbid usage of macros for anything except include guards).

Clear separation of which code is C and which is C++: Only interface.cpp needs to take care to have both #include "the_c_header.h" and #include "interface.h" and worry about the mechanics of interfacing of C++ to C.   Otherwise, C compilation units (compiled with a C compiler) only need #include "the_c_header.h" and C++ compilation units only need to #include "interface.h".

interface.h can use any C++ language features (not just default arguments).  For example, all the functions it declares may be placed in a namespace named mathematica if you wish.   C++ developers using your functions need not care that there is actually an interface to C code buried away within that call.

If you decide in future to re-implement my_function() using something other than mathematica you can.   Simply drop in the replacements of the_c_header.h and interface.cpp, and rebuild.  The separation of concerns means that it is unnecessary to change interface.h, that all C++ callers will not even need to be recompiled in an incremental build (unless, of course, you change interface.h for some other reason).

Practically, the build process will detect mistaken usage of both header files.  A C compiler will choke on interface.h because it uses C++-specific features.   A C++ compiler will accept contents of the_c_header.h outside of an extern "C" context, but the result will be a linker error if any C++ code ever calls my_function() directly (linking will require a name-mangled definition).

In short, this takes a little more effort to set up than the macro approach, but is easier to maintain in the long run.

Body:
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?

Body:
Rather than macro hackery to work around the fact that C does not support default arguments, I'd introduce a layer of indirection.

First a C++ specific header that your C++ code uses (which I arbitrarily name interface.h.

 double my_function_caller(double x, double abs_error = 1E-3);

and a C specific header (which I arbitrarily name the_c_header.h)

 double my_function(double x, double abs_error);

 /*  all other functions that have a C interface here */

In practice, one would probably want include guards in both headers.

The next step is a C++ compilation unit (which I arbitrarily name interface.cpp) that actually interfaces to mathematica

 #include "interface.h"

 extern "C"     //  this is C++, so we don't need to test __cplusplus
 {
      #include "the_c_header.h"
 }

 double my_function_caller(double x, double error)
 {
      return my_function(x, error);
 }

Then there is just the question of how to call the function.  If the caller is C++, then all it needs to do is

  #include "interface.h"

  //   and later in some code

       double result = my_function_caller(x);
       double another_result = my_function_caller(x, 1E-6);

If the caller is C (built with a C compiler) it simply does

  #include "the_c_header.h"

  /*  and later */

       result = my_function(x, 1E-3);
       another result = my_function(x, 1E-6);

There are obviously advantages and disadvantages of this, compared with a macro-based solution, including;

None of the traditional disadvantages of macros (not respecting scope, no unintended interactions with other macros, running afoul of some C++ development guidelines that forbid usage of macros for anything except include guards).

Clear separation of which code is C and which is C++: Only interface.cpp needs to take care to have both #include "the_c_header.h" and #include "interface.h" and worry about the mechanics of interfacing of C++ to C.   Otherwise, C compilation units (compiled with a C compiler) only need #include "the_c_header.h" and C++ compilation units only need to #include "interface.h".

interface.h can use any C++ language features (not just default arguments).  For example, all the functions it declares may be placed in a namespace named mathematica if you wish.   C++ developers using your functions need not care that there is actually an interface to C code buried away within that call.

If you decide in future to re-implement my_function() using something other than mathematica you can.   Simply drop in the replacements of the_c_header.h and interface.cpp, and rebuild.  The separation of concerns means that it is unnecessary to change interface.h, that all C++ callers will not even need to be recompiled in an incremental build (unless, of course, you change interface.h for some other reason).

Practically, the build process will detect mistaken usage of both header files.  A C compiler will choke on interface.h because it uses C++-specific features.   A C++ compiler will accept contents of the_c_header.h outside of an extern "C" context, but the result will be a linker error if any C++ code ever calls my_function() directly (linking will require a name-mangled definition).

In short, this takes a little more effort to set up than the macro approach, but is easier to maintain in the long run.


问:
Rethinkdb: Query to get items from the last 24 hours from a big table
I have a table in RethinkDB consisting of 3 millions tweets. Each field has an epoch time, when it was inserted. What javascript query could I make to get quickly the tweets from the last 24 hours (roughly about 50k) sorted by keyword? I tried something below, but it is really slow. </p>

```<code>`r.db('twitter').table('tweets')
  .group('keyword')
  .filter((row) => {
    return row('epoch_time').gt(r.now().sub(86400));
  })
  .orderBy(r.desc('time'))
  .pluck('url', 'text') `
</code>```

答:
A bit late for you I imagine, but may help others who find this in their search results.

group('keyword') returns a reduction so won't have an 'epoch_time'

if you know that you only want tweet from the last 24 hours then put that filter first. There is no query optimiser in RethinkDB.

if performance is still an issue after that, consider putting an index on 'epoch_time' and change your filter (does a table scan) to getAll...

if still an issue after that, index by 'keyword'

Body:
I have a table in RethinkDB consisting of 3 millions tweets. Each field has an epoch time, when it was inserted. What javascript query could I make to get quickly the tweets from the last 24 hours (roughly about 50k) sorted by keyword? I tried something below, but it is really slow.

`r.db('twitter').table('tweets')
  .group('keyword')
  .filter((row) => {
    return row('epoch_time').gt(r.now().sub(86400));
  })
  .orderBy(r.desc('time'))
  .pluck('url', 'text') `


问:
palindrome or not what logical error in this
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome</p>

```<code>     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}
</code>```

答:
Logical error because you are working with references.
Try this:</p>

```<code>package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());

        String original = sbuffer.toString();
        sbuffer.reverse();

        if(original.equals(sbuffer.toString()){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");
        }
        input.close();
    }

}
</code>```

Body:
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome

     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}

Body:
Logical error because you are working with references.
Try this:

package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());

        String original = sbuffer.toString();
        sbuffer.reverse();

        if(original.equals(sbuffer.toString()){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");
        }
        input.close();
    }

}


问:
How do I use rugged to check if there are uncommited changes in my git repository?
How do I use rugged to check whether there are uncommitted changes in my git repo?

Much like How do I programmatically determine if there are uncommited changes?

答:
You can get something similar to git status using Repository#status.

If you'd just like to check if there are any unstaged changes:

```<code>repository.to_enum(:status).any?
</code>```

Body:
You can get something similar to git status using Repository#status.

If you'd just like to check if there are any unstaged changes:

repository.to_enum(:status).any?


问:
Cloning string in ruby

My question is: how's work cloning in ruby?

When exactly does cloning happen?

So, all I have are function cur_memory, which returns current used memory in Gb , string s1 that contain long text and s2 that is cloned of prev:

```<code>def cur_memory
  %x(free).split("\n")[1].split(' ')[2].to_f / 10**6
end
</code>```

Pay attention, it takes 3 gigabytes of memory! (or you can replace 9 by 8 below)

```<code>m = cur_memory              # snapshot
s1 = '0'*10**9              # create long string

p (cur_memory - m).round 3  # 1st output
s2 = s1.clone
p (cur_memory - m).round 3  # 2nd output
s1[0] = '2'
p (cur_memory - m).round 3  # 3rd output
s2[0] = '1'
p (cur_memory - m).round 3  # 4th output
</code>```

output:

```<code>0.978
0.978
1.957
2.936
</code>```

First output is okay!

Why nothing changed after 1st output?

Okay, maybe ruby smart, maybe it's sort of lazy cloning. (but anyway, I would like to know)

But WTF now? 3 gigabytes instead of 2?

P.S. Tested on Ruby 2.1.0 and 2.4.0

答:
I tested this in MRI 2.4 and JRuby 9.1.2 on MacOS X. In both, MRI and JRuby I found that they behave similarly when run as a script. The memory is allocated for the clone when either the original or copy is modified, i.e. they no longer match each other.

```<code>def cur_memory
  pid = Process.pid
  `ps -p#{pid} -o rss=`.to_f / 1024
end

def diff(m)
  (cur_memory - m).round 3
end

m = cur_memory              # snapshot

s1 = '0'*10**8              # create long string
p "1st output #{diff(m)} MB"

s2 = s1.clone
p "2nd output #{diff(m)} MB"

s2[0] = '2'
p "3rd output #{diff(m)} MB"

s1[0] = '1'
p "4th output #{diff(m)} MB"

s2[0] = '1'
p "5th output #{diff(m)} MB"

s1[0] = '2'
p "6th output #{diff(m)} MB"
</code>```

Output:

```<code>"1st output 95.379 MB"
"2nd output 95.41 MB"
"3rd output 190.781 MB"
"4th output 286.152 MB"
"5th output 286.152 MB"
"6th output 286.152 MB"
</code>```

In JRuby, we can observe how the heap memory is allocated. It shows that once the clone is allocated modifications do not increase the heap usage.

```<code>require 'java'

java_import 'java.lang.System'
java_import 'java.lang.management.ManagementFactory'

def cur_heap
  ManagementFactory.getMemoryMXBean.getHeapMemoryUsage.getUsed.to_f / (1024 * 1024)
end

def cur_memory
  pid = Process.pid
  `ps -p#{pid} -o rss=`.to_f / 1024
end

def diff_mem(m)
  (cur_memory - m).round 3
end

def diff_heap(m)
  (cur_heap - m).round 3
end

System.gc
m = cur_memory              # snapshot
h = cur_heap

s1 = '0'*10**8              # create long string
System.gc
p "1st output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2 = s1.clone
System.gc
p "2nd output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2[0] = '2'
System.gc
p "3rd output #{diff_heap(h)}/#{diff_mem(m)} MB"

s1[0] = '1'
System.gc
p "4th output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2[0] = '1'
System.gc
p "5th output #{diff_heap(h)}/#{diff_mem(m)} MB"

s1[0] = '2'
System.gc
p "6th output #{diff_heap(h)}/#{diff_mem(m)} MB"
</code>```

Output:

```<code>"1st output 95.392/103.844 MB"
"2nd output 94.503/101.262 MB"
"3rd output 189.871/200.262 MB"
"4th output 189.876/299.277 MB"
"5th output 189.877/299.328 MB"
"6th output 189.878/299.41 MB"
</code>```

Note: The MRI behavior is slightly different when using IRB. It shows increased memory usage as soon as the clone is created.

Title: Cloning string in ruby

Body:
My question is: how's work cloning in ruby?

When exactly does cloning happen?

So, all I have are function cur_memory, which returns current used memory in Gb , string s1 that contain long text and s2 that is cloned of prev:

def cur_memory
  %x(free).split("\n")[1].split(' ')[2].to_f / 10**6
end

Pay attention, it takes 3 gigabytes of memory! (or you can replace 9 by 8 below)

m = cur_memory              # snapshot
s1 = '0'*10**9              # create long string

p (cur_memory - m).round 3  # 1st output
s2 = s1.clone
p (cur_memory - m).round 3  # 2nd output
s1[0] = '2'
p (cur_memory - m).round 3  # 3rd output
s2[0] = '1'
p (cur_memory - m).round 3  # 4th output

output:

0.978
0.978
1.957
2.936

First output is okay!

Why nothing changed after 1st output?

Okay, maybe ruby smart, maybe it's sort of lazy cloning. (but anyway, I would like to know)

But WTF now? 3 gigabytes instead of 2?

P.S. Tested on Ruby 2.1.0 and 2.4.0

Body:
I tested this in MRI 2.4 and JRuby 9.1.2 on MacOS X. In both, MRI and JRuby I found that they behave similarly when run as a script. The memory is allocated for the clone when either the original or copy is modified, i.e. they no longer match each other.

def cur_memory
  pid = Process.pid
  `ps -p#{pid} -o rss=`.to_f / 1024
end

def diff(m)
  (cur_memory - m).round 3
end

m = cur_memory              # snapshot

s1 = '0'*10**8              # create long string
p "1st output #{diff(m)} MB"

s2 = s1.clone
p "2nd output #{diff(m)} MB"

s2[0] = '2'
p "3rd output #{diff(m)} MB"

s1[0] = '1'
p "4th output #{diff(m)} MB"

s2[0] = '1'
p "5th output #{diff(m)} MB"

s1[0] = '2'
p "6th output #{diff(m)} MB"

Output:

"1st output 95.379 MB"
"2nd output 95.41 MB"
"3rd output 190.781 MB"
"4th output 286.152 MB"
"5th output 286.152 MB"
"6th output 286.152 MB"

In JRuby, we can observe how the heap memory is allocated. It shows that once the clone is allocated modifications do not increase the heap usage.

require 'java'

java_import 'java.lang.System'
java_import 'java.lang.management.ManagementFactory'

def cur_heap
  ManagementFactory.getMemoryMXBean.getHeapMemoryUsage.getUsed.to_f / (1024 * 1024)
end

def cur_memory
  pid = Process.pid
  `ps -p#{pid} -o rss=`.to_f / 1024
end

def diff_mem(m)
  (cur_memory - m).round 3
end

def diff_heap(m)
  (cur_heap - m).round 3
end

System.gc
m = cur_memory              # snapshot
h = cur_heap

s1 = '0'*10**8              # create long string
System.gc
p "1st output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2 = s1.clone
System.gc
p "2nd output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2[0] = '2'
System.gc
p "3rd output #{diff_heap(h)}/#{diff_mem(m)} MB"

s1[0] = '1'
System.gc
p "4th output #{diff_heap(h)}/#{diff_mem(m)} MB"

s2[0] = '1'
System.gc
p "5th output #{diff_heap(h)}/#{diff_mem(m)} MB"

s1[0] = '2'
System.gc
p "6th output #{diff_heap(h)}/#{diff_mem(m)} MB"

Output:

"1st output 95.392/103.844 MB"
"2nd output 94.503/101.262 MB"
"3rd output 189.871/200.262 MB"
"4th output 189.876/299.277 MB"
"5th output 189.877/299.328 MB"
"6th output 189.878/299.41 MB"

Note: The MRI behavior is slightly different when using IRB. It shows increased memory usage as soon as the clone is created.


问:
Loading config files producing null in Java
I'm trying to load a config file in a custom way from a path. When I load the file, I get no errors, but when I reference loaded values I get null and when I attempt to close the file I get a NullPointerException. Here's everything:

Main Class

ConfigHandler Class

File to load:

```<code>test:one
hello:two
world:three
</code>```

Console output:

```<code>nullnullnullnull
Exception in thread "main" java.lang.NullPointerException
    at config.ConfigHandler.closeConfig(ConfigHandler.java:54)
    at main.Main.main(Main.java:13)
</code>```

Anyone got any idea what is going wrong?

答: the ready boolean is never set true so the file is never initialized(its initialized null) in the constructor of ConfigHandler.Is there a reason for using the ready flag?If yes then write something to make it true as your code uses it at multiple places</p>

Body:
I'm trying to load a config file in a custom way from a path. When I load the file, I get no errors, but when I reference loaded values I get null and when I attempt to close the file I get a NullPointerException. Here's everything:

Main Class

ConfigHandler Class

File to load:

test:one
hello:two
world:three

Console output:

nullnullnullnull
Exception in thread "main" java.lang.NullPointerException
    at config.ConfigHandler.closeConfig(ConfigHandler.java:54)
    at main.Main.main(Main.java:13)

Anyone got any idea what is going wrong?


问:
Programmatically cause onBlur to trigger in react
I use onBlur to close a dropdown, but I also want to handle a click handler of an li which is render within, setState won't work here, the behavior is broken when user try to open the dropdown again, try it here:

http://jsfiddle.net/ur1rbcrz

My code:

```<code>toggleDropdown = () => {
    this.setState({
        openDropdown: !this.state.openDropdown
    })
  }

  render() {
    return (
      <div>
        <div tabIndex="0" onFocus={this.toggleDropdown} onBlur={this.toggleDropdown}>
          MyList
        <ul className={this.state.openDropdown ? 'show' : 'hide'}>
          <li>abc</li>
          <li>123</li>
          <li onClick={()=> this.setState({openDropdown:false})}>xyz</li> {/* not working */}
        </ul>
      </div>
      </div>
    );
  }
</code>```

答:
Your code is not working because, even though you click li, a div container with onBlur event still is focused.

We add to your list container ref, after that we can call .blur(). We use it in your onClick li event handler.

```<code>this.dropDownList.blur()
</code>```

See working example jsfiddle.

Or run this snippet:

class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
      isDropdownVisible: false
    }

    this.toggleDropdown = this.toggleDropdown.bind(this);
  }

  toggleDropdown() {
   this.setState({
     isDropdownVisible: !this.state.isDropdownVisible
    })
  }

  render() {
    return (

 this.dropDownList = c}
        onFocus={this.toggleDropdown}
        onBlur={this.toggleDropdown}>
          MyList

abc

123

 this.dropDownList.blur()}>xyz
 {/* not working */}

    );
  }
}

ReactDOM.render(
  <Hello initialName="World"/>,
  document.getElementById('container')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none
}

.show {
  display: block !important;
}

div:focus {
  border: 1px solid #000;
}

div:focus {
  outline: none;
 }</code>```

```

Body:
I use onBlur to close a dropdown, but I also want to handle a click handler of an li which is render within, setState won't work here, the behavior is broken when user try to open the dropdown again, try it here:

http://jsfiddle.net/ur1rbcrz

My code:

toggleDropdown = () => {
    this.setState({
        openDropdown: !this.state.openDropdown
    })
  }

  render() {
    return (

          MyList

abc

123

 this.setState({openDropdown:false})}>xyz
 {/* not working */}

    );
  }

Body:
Your code is not working because, even though you click li, a div container with onBlur event still is focused.

We add to your list container ref, after that we can call .blur(). We use it in your onClick li event handler.

this.dropDownList.blur()

See working example jsfiddle.

Or run this snippet:

class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
      isDropdownVisible: false
    }

    this.toggleDropdown = this.toggleDropdown.bind(this);
  }

  toggleDropdown() {
   this.setState({
     isDropdownVisible: !this.state.isDropdownVisible
    })
  }

  render() {
    return (
      <div>
        <div
        tabIndex="0"
        ref={c => this.dropDownList = c}
        onFocus={this.toggleDropdown}
        onBlur={this.toggleDropdown}>
          MyList
        <ul
        className={this.state.isDropdownVisible ? 'show' : 'hide'}>
          <li>abc</li>
          <li>123</li>
          <li onClick={() => this.dropDownList.blur()}>xyz</li> {/* not working */}
        </ul>
      </div>
      </div>
    );
  }
}

ReactDOM.render(
  <Hello initialName="World"/>,
  document.getElementById('container')
);

.hide {
  display: none
}

.show {
  display: block !important;
}

div:focus {
  border: 1px solid #000;
}

div:focus {
  outline: none;
 }

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>


问:
when i run my client program it doesn't connect with my server
this client and server program compiles successfully. run the server it waits for client connection.
but when i run this client program it always shows "connection failed..."
i don't understand why...

server.c

```<code>int main()
{

  struct sockaddr_in main_server, cli_1_server, cli_2_server;
  int main_sock, cli_1_sock, cli_2_sock;
  int Len;
  char arv_msg[MAXSZ];
  //char client_name[20];
 // FILE *fp;
  //short int RcvByte_1 = 0, RcvByte_2 = 0;

  if( ( main_sock = socket(AF_INET, SOCK_STREAM, 0) ) < 0 )
  {
    printf("socket creation failed...\n");
    exit(-1);
  }

  main_server.sin_family = AF_INET;
  main_server.sin_addr.s_addr = inet_addr("127.0.0.1");
  main_server.sin_port = htons(10000);

  if( ( bind( main_sock, (SA *)&main_server, sizeof(main_server) ) ) < 0)
  {
    printf("binding failed...\n");
    exit(-1);
  }

  printf("Listining...\n");
  listen(main_sock, WAITING);
  Len = sizeof(cli_1_server);

  if( ( cli_1_sock = accept( main_sock, (SA *)&cli_1_server, &Len ) ) <0)
  {
    printf("Client 1 request failed...\n");
    exit(-1);
  }

  printf("client 1 connected...\n");

}
</code>```

client.c

```<code>int main()
{

  struct sockaddr_in main_server;
  int cli_1_sock;
  char snd_msg[MAXSZ], rcv_msg[MAXSZ];
  int n = 0;

  if( ( cli_1_sock = (AF_INET, SOCK_STREAM, 0) ) == -1 )
  {
    printf("socket creation failed...\n");
    exit(-1);
  }

  main_server.sin_family = AF_INET;
  main_server.sin_addr.s_addr = inet_addr("127.0.0.1");
  main_server.sin_port = htons(10000);

  if( ( connect(cli_1_sock, (SA *)&main_server,sizeof(main_server)))==-1)
  {
    printf("connection failed...\n");
    exit(-1);
  }

  printf("connected\n");

}
</code>```

this is my server and client..program

答:
change   </p>

```<code>cli_1_sock = (AF_INET, SOCK_STREAM, 0)
</code>```

<p>to </p>

```<code>cli_1_sock = socket(AF_INET, SOCK_STREAM, 0)
</code>```

Body:
this client and server program compiles successfully. run the server it waits for client connection.
but when i run this client program it always shows "connection failed..."
i don't understand why...

server.c

int main()
{

  struct sockaddr_in main_server, cli_1_server, cli_2_server;
  int main_sock, cli_1_sock, cli_2_sock;
  int Len;
  char arv_msg[MAXSZ];
  //char client_name[20];
 // FILE *fp;
  //short int RcvByte_1 = 0, RcvByte_2 = 0;

  if( ( main_sock = socket(AF_INET, SOCK_STREAM, 0) ) < 0 )
  {
    printf("socket creation failed...\n");
    exit(-1);
  }

  main_server.sin_family = AF_INET;
  main_server.sin_addr.s_addr = inet_addr("127.0.0.1");
  main_server.sin_port = htons(10000);

  if( ( bind( main_sock, (SA *)&main_server, sizeof(main_server) ) ) < 0)
  {
    printf("binding failed...\n");
    exit(-1);
  }

  printf("Listining...\n");
  listen(main_sock, WAITING);
  Len = sizeof(cli_1_server);

  if( ( cli_1_sock = accept( main_sock, (SA *)&cli_1_server, &Len ) ) <0)
  {
    printf("Client 1 request failed...\n");
    exit(-1);
  }

  printf("client 1 connected...\n");

}

client.c

int main()
{

  struct sockaddr_in main_server;
  int cli_1_sock;
  char snd_msg[MAXSZ], rcv_msg[MAXSZ];
  int n = 0;

  if( ( cli_1_sock = (AF_INET, SOCK_STREAM, 0) ) == -1 )
  {
    printf("socket creation failed...\n");
    exit(-1);
  }

  main_server.sin_family = AF_INET;
  main_server.sin_addr.s_addr = inet_addr("127.0.0.1");
  main_server.sin_port = htons(10000);

  if( ( connect(cli_1_sock, (SA *)&main_server,sizeof(main_server)))==-1)
  {
    printf("connection failed...\n");
    exit(-1);
  }

  printf("connected\n");

}

this is my server and client..program

Body:
change

cli_1_sock = (AF_INET, SOCK_STREAM, 0)

to

cli_1_sock = socket(AF_INET, SOCK_STREAM, 0)


问:
menu are ID based so open in one page just scrolling down the page, how can I go the the page id from separate page
I have menu in the website most of them are ID based so open in one page just scrolling down the page, but I have made couples pages which has different page so, how can I go the the page id which which will scroll down to the id when I click the menu from the different page? Let me be specific, Here is the project which I am working for http://pasalnepal.com.np/yadavbhatta/ so the forum is separate page in the menu, so when I click on education, it should go to education part of the page. </p>

答: This is due to some JavaScript code of your project. If I disable JavaScript in my browser and open http://pasalnepal.com.np/yadavbhatta/#education it will jump to the education anchor like its supposed to. But if JavaScript is enabled it jumps to the anchor and goes to the top of the page immediately.</p>


问:
Cordova or ionic chat bot implementation
we developed the cordova mobile application using angular js, we are trying to add the chat bot (chat service) feature in our application any one have implemented same feature in the cordova or hybrid mobile application please let me know the best way to implement</p>

答:
You can use api.ai or wit.ai they both have a lot of libraries so you can integrate it with your platform of choice , in your case you can use http .
You can also have a look on this github repo it contains a sample that uses api.ai to create a chatbot in an apache cordova app</p>


问:
twig symfony - read jquery inside {{path()}}
I have a project using Symfony 3

I'm trying to dynamically generate the following URL with the appropriate parameters

```<code>http://127.0.0.1/add/{id}/{price}
</code>```

I want to do something like this (it's indented for clarity):

```<code>window.open(
    "{{
         path('add_family'
            , {'id': $(this).data("myid"),
               'relation': $('#my-select').val()
         })
     }}"
);
</code>```

these two instructions are good and give the correct result

$(this).data("myid")

$('#my-select').val()

My question is, how can I get them to work inside twig, meaning inside the {{ path() }} function ?

答:
There are two ways to do it:

From your twig page, create a script and set the link in it.

```<code><script>
    var the_link = "{{path("link_name", {'id': "ID", 'relation':  "RELATION"})}}";

    the_link = the_link.replace("ID", $(this).data("myid"));
    //etc
</script>
</code>```

Using FosJsBundle

Body:
I have a project using Symfony 3

I'm trying to dynamically generate the following URL with the appropriate parameters

http://127.0.0.1/add/{id}/{price}

I want to do something like this (it's indented for clarity):

window.open(
    "{{
         path('add_family'
            , {'id': $(this).data("myid"),
               'relation': $('#my-select').val()
         })
     }}"
);

these two instructions are good and give the correct result

$(this).data("myid")

$('#my-select').val()

My question is, how can I get them to work inside twig, meaning inside the {{ path() }} function ?

Body:
There are two ways to do it:

From your twig page, create a script and set the link in it.

<script>
    var the_link = "{{path("link_name", {'id': "ID", 'relation':  "RELATION"})}}";

    the_link = the_link.replace("ID", $(this).data("myid"));
    //etc
</script>

Using FosJsBundle


问:
Share image and text using android share dialog
is it possible to share image and text to facebook, instagram and whatsapp using android share dialog? i am trying for 2 weeks to do this with no success. the only thing i can do is to write some code foreach media without using the share dialog. this is some code that work with whatsapp but not with insta and facebook</p>

```<code>String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    OutputStream fOut = null;
                    Uri outputFileUri;
                    try {
                        File root = new File(Environment.getExternalStorageDirectory() + File.separator + "FoodMana" + File.separator);
                        root.mkdirs();
                        File sdImageMainDirectory = new File(root, "myPicName.jpg");
                        fOut = new FileOutputStream(sdImageMainDirectory);
                    } catch (Exception e) {Toast.makeText(getApplicationContext(), "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();}

                    try {
                        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (Exception e) {
                    }

                        Intent waIntent = new Intent(android.content.Intent.ACTION_SEND);
                        waIntent.setType("image/*");
                        waIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory()
                                + File.separator + "FoodMana" + File.separator + "myPicName.jpg"));
                        waIntent.putExtra(Intent.EXTRA_TEXT, "I am going to eat that dish!!!!!" + "\n" + "what do you think? check out");
                        startActivity(Intent.createChooser(waIntent, "Share with"));

                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");

                }
            });
</code>```

答:
OK i found the solution</p>

```<code>String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
                    String path = null;
                    path = MediaStore.Images.Media.insertImage(getContentResolver(), bm, "", null);
                    Uri screenshotUri = Uri.parse(path);
                    intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
                    intent.setType("image/*");
                    startActivity(Intent.createChooser(intent, "Share image via..."));
                }
                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }
                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");
                }
            });
</code>```

Body:
is it possible to share image and text to facebook, instagram and whatsapp using android share dialog? i am trying for 2 weeks to do this with no success. the only thing i can do is to write some code foreach media without using the share dialog. this is some code that work with whatsapp but not with insta and facebook

String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    OutputStream fOut = null;
                    Uri outputFileUri;
                    try {
                        File root = new File(Environment.getExternalStorageDirectory() + File.separator + "FoodMana" + File.separator);
                        root.mkdirs();
                        File sdImageMainDirectory = new File(root, "myPicName.jpg");
                        fOut = new FileOutputStream(sdImageMainDirectory);
                    } catch (Exception e) {Toast.makeText(getApplicationContext(), "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();}

                    try {
                        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (Exception e) {
                    }

                        Intent waIntent = new Intent(android.content.Intent.ACTION_SEND);
                        waIntent.setType("image/*");
                        waIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory()
                                + File.separator + "FoodMana" + File.separator + "myPicName.jpg"));
                        waIntent.putExtra(Intent.EXTRA_TEXT, "I am going to eat that dish!!!!!" + "\n" + "what do you think? check out");
                        startActivity(Intent.createChooser(waIntent, "Share with"));

                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");

                }
            });

Body:
OK i found the solution

String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
                    String path = null;
                    path = MediaStore.Images.Media.insertImage(getContentResolver(), bm, "", null);
                    Uri screenshotUri = Uri.parse(path);
                    intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
                    intent.setType("image/*");
                    startActivity(Intent.createChooser(intent, "Share image via..."));
                }
                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }
                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");
                }
            });


问:
Recurring background task in Xamarin.Android
I would like to write a silence/vibration scheduler for Android 6.

I need therefore a background task that sets sound/vibration/silence according to a schedule defined in the UI app which is done and ready.

How can I add such a service to my application to run in the background? (recurring service that checks/sets ringtone status on a minute basis)

I can use the AudioManager to read/set the value, but I do not know how to schedule the task.

答:
You need to add a broadcast receiver for these. Set Android.Content.Intent to ActionTimeTick so that android os will broadcast message(an android intent) whenever time is changed.

```<code>[BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionTimeTick })]
    public class GridStartBroadcastReceiver : BroadcastReceiver
    {
        public static readonly string GRID_STARTED = "GRID_STARTED";
        public override void OnReceive(Context context, Intent intent)
        {
           if (intent.Action == GRID_STARTED)
            {
         //your logic
            }
        }
    }
</code>```

you need to register the broadcast receiver first.
Add these code to oncreate method to register broadcast receiver.

IntentFilter filter = new IntentFilter(GridStartBroadcastReceiver.GRID_STARTED);
            filter.AddCategory(Intent.CategoryDefault);
            _receiver = new GridStartBroadcastReceiver();
            RegisterReceiver(_receiver, filter);

Next send the broadcast to the broadcast receiver.

```<code>//calling
                    Intent BroadcastIntent = new Intent(this, typeof(MainActivity.GridStartBroadcastReceiver));
                    BroadcastIntent.SetAction(MainActivity.GridStartBroadcastReceiver.GRID_STARTED);
                    BroadcastIntent.AddCategory(Intent.CategoryDefault);
                    SendBroadcast(BroadcastIntent);
</code>```

Body:
You need to add a broadcast receiver for these. Set Android.Content.Intent to ActionTimeTick so that android os will broadcast message(an android intent) whenever time is changed.

[BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionTimeTick })]
    public class GridStartBroadcastReceiver : BroadcastReceiver
    {
        public static readonly string GRID_STARTED = "GRID_STARTED";
        public override void OnReceive(Context context, Intent intent)
        {
           if (intent.Action == GRID_STARTED)
            {
         //your logic
            }
        }
    }

you need to register the broadcast receiver first.
Add these code to oncreate method to register broadcast receiver.

IntentFilter filter = new IntentFilter(GridStartBroadcastReceiver.GRID_STARTED);
            filter.AddCategory(Intent.CategoryDefault);
            _receiver = new GridStartBroadcastReceiver();
            RegisterReceiver(_receiver, filter);

Next send the broadcast to the broadcast receiver.

//calling
                    Intent BroadcastIntent = new Intent(this, typeof(MainActivity.GridStartBroadcastReceiver));
                    BroadcastIntent.SetAction(MainActivity.GridStartBroadcastReceiver.GRID_STARTED);
                    BroadcastIntent.AddCategory(Intent.CategoryDefault);
                    SendBroadcast(BroadcastIntent);


问:
404 with spring 3
hi
I am going through my first lessons with spring 3.I created a dynamic web app in eclipse with the following structure.

```<code>spring3mvc \src\my.spring.HelloWorldController.java
                \WebContent
                   |
                   |-----WEB-INF\jsp\hello.jsp
                   |-----index.jsp
                   |-----WEB-INF\web.xml
                   |-----WEB-INF\spring-servlet.xml
                   |-----WEB-INF\lib\...*.jar files
</code>```

I created the spring-servlet.xml as below

```<code> <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/context
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                 <mvc:annotation-driven/>

        <context:component-scan base-package="my.spring" />
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp">

          <property name="contentType" value="text/html; charset=utf-8" />
        </bean>
      </beans>
</code>```

and coded the controller

```<code>package my.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 @RequestMapping("/hello")
 public ModelAndView helloWorld() {
  String message = "Hello World, Spring 3.0!";
  return new ModelAndView("hello", "message", message);
 }
}
</code>```

index.jsp has a link to hello view

```<code><html>
<body>
<a href="hello.html">Say Hello</a>

</body>
</html>
</code>```

finally in hello.jsp I have put

```<code><html>
<body>
${message}
</body>
</html>
</code>```

My web.xml has

```<code><display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</code>```

When I run the app on Tomcat6 server( thru eclipse),I can see the index page at
http://localhost:8080/Spring3MVC/ .It displays the link to hello page.When I click on it(http://localhost:8080/Spring3MVC/hello.html),I get a 404 error.

```<code>message /Spring3MVC/hello.html
description The requested resource (/Spring3MVC/hello.html) is not available.
</code>```

Any idea how I can solve this?

thanks

mark.

答:
I belive the problem is not the View resolver (it would print other exceptions).

Read the error message carfully, it tells what the problem is:

```<code>message /Spring3MVC/hello.html description
The requested resource (/Spring3MVC/hello.html) is not available.
</code>```

It is that the hello .html (handler) can not be found, not the jsp. -- But I don't know what the exact problem it. -- I tryed to reproduce the error, but I did not get exact the same error message.

added -- find the problem

When you start the Server it prints all mappings to the controller in the log file. In your case there must by something like

```<code>INFO : org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/hallo] onto handler 'halloController'
</code>```

If you don't have such a statement, then something is wrong with your context scan, or you have forget to enable the annotation driven MVC @Controller programming model. This can be enabled by adding:

```<code><!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
</code>```

Title: 404 with spring 3

Body:
hi
I am going through my first lessons with spring 3.I created a dynamic web app in eclipse with the following structure.

spring3mvc \src\my.spring.HelloWorldController.java
                \WebContent
                   |
                   |-----WEB-INF\jsp\hello.jsp
                   |-----index.jsp
                   |-----WEB-INF\web.xml
                   |-----WEB-INF\spring-servlet.xml
                   |-----WEB-INF\lib\...*.jar files

I created the spring-servlet.xml as below

 <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/context
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                 <mvc:annotation-driven/>

        <context:component-scan base-package="my.spring" />
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp">

          <property name="contentType" value="text/html; charset=utf-8" />
        </bean>
      </beans>

and coded the controller

package my.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 @RequestMapping("/hello")
 public ModelAndView helloWorld() {
  String message = "Hello World, Spring 3.0!";
  return new ModelAndView("hello", "message", message);
 }
}

index.jsp has a link to hello view

Say Hello

finally in hello.jsp I have put

${message}

My web.xml has

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

When I run the app on Tomcat6 server( thru eclipse),I can see the index page at
http://localhost:8080/Spring3MVC/ .It displays the link to hello page.When I click on it(http://localhost:8080/Spring3MVC/hello.html),I get a 404 error.

message /Spring3MVC/hello.html
description The requested resource (/Spring3MVC/hello.html) is not available.

Any idea how I can solve this?

thanks

mark.

Body:
I belive the problem is not the View resolver (it would print other exceptions).

Read the error message carfully, it tells what the problem is:

message /Spring3MVC/hello.html description
The requested resource (/Spring3MVC/hello.html) is not available.

It is that the hello .html (handler) can not be found, not the jsp. -- But I don't know what the exact problem it. -- I tryed to reproduce the error, but I did not get exact the same error message.

added -- find the problem

When you start the Server it prints all mappings to the controller in the log file. In your case there must by something like

INFO : org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapped URL path [/hallo] onto handler 'halloController'

If you don't have such a statement, then something is wrong with your context scan, or you have forget to enable the annotation driven MVC @Controller programming model. This can be enabled by adding:

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />


问:
In Selenium, how to log in website on the popup window with python?
I would like to log in the website using selenium.
This site has link( members login ) and when I click this link, popup window appears.

The website URL is http://affiliates.888.com/

I wrote the code as follows.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480").click()
# so far popup appears.
eight88.switch_to_alert()
eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")
</code>```

When I run this script, NoSuchElementException occurs.

```<code>raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"userName"}
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)
</code>```

I don't know how to go to the popup and find element there.

How can I log in this website on popup.

答:
Authorization form is located inside an iframe, not alert. To be able to handle elements inside iframe you should switch to it first:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480")
loginForm.click()

wait(eight88, 10).until(EC.frame_to_be_available_and_switch_to_it(eight.find_element_by_xpath('//iframe[contains(@src, "Auth/Login")]')))

eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")
</code>```

Body:
I would like to log in the website using selenium.
This site has link( members login ) and when I click this link, popup window appears.

The website URL is http://affiliates.888.com/

I wrote the code as follows.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480").click()
# so far popup appears.
eight88.switch_to_alert()
eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")

When I run this script, NoSuchElementException occurs.

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"userName"}
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)

I don't know how to go to the popup and find element there.

How can I log in this website on popup.

Body:
Authorization form is located inside an iframe, not alert. To be able to handle elements inside iframe you should switch to it first:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480")
loginForm.click()

wait(eight88, 10).until(EC.frame_to_be_available_and_switch_to_it(eight.find_element_by_xpath('//iframe[contains(@src, "Auth/Login")]')))

eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")


问:
Jquery Trigger is firing the wrong table column
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

```<code>    if (discountProductGroupBuyer != null)
    {
    sb.Append("<td><input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') ></td>");
    }
</code>```

****onclick of generated checkboxes

```<code>   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
</code>```

}

*** Check all code

```<code>$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});
</code>```

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

```<code>$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});
</code>```

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

答:
Here you go with the solution https://jsfiddle.net/d9x95q2q/1/

$(document).on("click", ".checkAll", function () {
     var cbody = $(this);
     var theader = cbody.parent();
     var column = theader.index() + 1;
   $('.col' + column ).prop('checked', $(this).is(':checked'));
});   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

<thead>
  <tr>
    <th>
      col 1 <input type="checkbox" class="checkAll" />
    </th>
    <th>
      col 2 <input type="checkbox" class="checkAll" />
    </th>
    <th>
      col 3 <input type="checkbox" class="checkAll" />
    </th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
</tbody>
</table></code>```

Body:
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

    if (discountProductGroupBuyer != null)
    {
    sb.Append("<input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') >	");
    }

****onclick of generated checkboxes

   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}

}

*** Check all code

$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

Body:
Here you go with the solution https://jsfiddle.net/d9x95q2q/1/

$(document).on("click", ".checkAll", function () {
     var cbody = $(this);
     var theader = cbody.parent();
     var column = theader.index() + 1;
   $('.col' + column ).prop('checked', $(this).is(':checked'));
});

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

<thead>
  <tr>
    <th>
      col 1 <input type="checkbox" class="checkAll" />
    </th>
    <th>
      col 2 <input type="checkbox" class="checkAll" />
    </th>
    <th>
      col 3 <input type="checkbox" class="checkAll" />
    </th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="col1" />
    </td>
    <td>
      <input type="checkbox" class="col2" />
    </td>
    <td>
      <input type="checkbox" class="col3" />
    </td>
  </tr>
</tbody>
</table>


问:
Regex - Select the entire file that contains an word in textcrawler
I need to select and delete all content of those files that contains word "MY_WORD".

```<code>blah blagh
tata MY_WORD ppp
mother id 787
</code>```

I try this regex (?s)(.*?MY_WORD).*$ or  [^"]+(MY_WORD)[^"]+  and works in notepad++, but doesn't work in TextCrawler.

答:
You can just try this approach:

```<code>.*MY_WORD.*
</code>```

and also need to check "Dot matches newline".

Body:
I need to select and delete all content of those files that contains word "MY_WORD".

blah blagh
tata MY_WORD ppp
mother id 787

I try this regex (?s)(.*?MY_WORD).*$ or  [^"]+(MY_WORD)[^"]+  and works in notepad++, but doesn't work in TextCrawler.

Body:
You can just try this approach:

.*MY_WORD.*

and also need to check "Dot matches newline".