问:
Firebase authentication registration Error occured
I'am try to register a user in my android app with using Google Firebase authentication option, but i am getting error and my Toast handle my error in this code line Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();

I think my SHA-1 and firebase connection was linked right. Firebase console image attached below

I'm here add my source code and also xml file.

```<code>package com.example.anu.activityone;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class RegistrationActivity extends AppCompatActivity {

private EditText txtEmail, txtPassword;
private Button btnRegister;

private FirebaseAuth mAuth;
/*
    public abstract class FirebaseAuth extends Object
    The entry point of the Firebase Authentication SDK.
 */
private FirebaseAuth.AuthStateListener FirebaseAuthStateListener;
/*  FirebaseAuth.AuthStateListener  is a interface,
    that Listener called when there is a change in the authentication state.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);

    // method called when user logged in or logged out
    mAuth = FirebaseAuth.getInstance();
    FirebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if(user != null){
                Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
    };

    txtEmail = (EditText)findViewById(R.id.email);
    txtPassword = (EditText)findViewById(R.id.password);
    btnRegister = (Button)findViewById(R.id.register);

    // Register a new user
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String email = txtEmail.getText().toString();
            final String password = txtPassword.getText().toString();
            /*
                Support User Registration
                With password-based authentication, new users must register themselves by providing
                a unique email address and a password. To add this functionality to your app,
                you can use the createUserWithEmailAndPassword() method of the FirebaseAuth class.
                As its name suggests, the method expects an email address and a password as its arguments.
             */
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
                /*
                    public interface OnCompleteListener
                    Listener called when a Task completes.
                 */
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            /*
                To be able to determine the result of the createUserWithEmailAndPassword() method,
                you must add an OnCompleteListener to it using the addOnCompleteListener() method.
             */
        }
    });
}
// To start Firebase authentication
@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(FirebaseAuthStateListener);
}
// To stop Firebase authentication when app pause
@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(FirebaseAuthStateListener);
}
}
</code>```

XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anu.activityone.RegistrationActivity"
android:orientation="vertical">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="email"
    android:id="@+id/email"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:id="@+id/password"/>

<Button
    android:id="@+id/register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Registration" />
</LinearLayout>
</code>```

答:
I found the error and i also print it using Toast by using this code line</p>

```<code>Toast.makeText(LoginActivity.this, "User Authentication Failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
</code>```

Body:
I'am try to register a user in my android app with using Google Firebase authentication option, but i am getting error and my Toast handle my error in this code line Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();

I think my SHA-1 and firebase connection was linked right. Firebase console image attached below

I'm here add my source code and also xml file.

package com.example.anu.activityone;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class RegistrationActivity extends AppCompatActivity {

private EditText txtEmail, txtPassword;
private Button btnRegister;

private FirebaseAuth mAuth;
/*
    public abstract class FirebaseAuth extends Object
    The entry point of the Firebase Authentication SDK.
 */
private FirebaseAuth.AuthStateListener FirebaseAuthStateListener;
/*  FirebaseAuth.AuthStateListener  is a interface,
    that Listener called when there is a change in the authentication state.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);

    // method called when user logged in or logged out
    mAuth = FirebaseAuth.getInstance();
    FirebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if(user != null){
                Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
    };

    txtEmail = (EditText)findViewById(R.id.email);
    txtPassword = (EditText)findViewById(R.id.password);
    btnRegister = (Button)findViewById(R.id.register);

    // Register a new user
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String email = txtEmail.getText().toString();
            final String password = txtPassword.getText().toString();
            /*
                Support User Registration
                With password-based authentication, new users must register themselves by providing
                a unique email address and a password. To add this functionality to your app,
                you can use the createUserWithEmailAndPassword() method of the FirebaseAuth class.
                As its name suggests, the method expects an email address and a password as its arguments.
             */
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
                /*
                    public interface OnCompleteListener
                    Listener called when a Task completes.
                 */
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            /*
                To be able to determine the result of the createUserWithEmailAndPassword() method,
                you must add an OnCompleteListener to it using the addOnCompleteListener() method.
             */
        }
    });
}
// To start Firebase authentication
@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(FirebaseAuthStateListener);
}
// To stop Firebase authentication when app pause
@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(FirebaseAuthStateListener);
}
}

XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anu.activityone.RegistrationActivity"
android:orientation="vertical">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="email"
    android:id="@+id/email"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:id="@+id/password"/>

<Button
    android:id="@+id/register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Registration" />
</LinearLayout>

Body:
I found the error and i also print it using Toast by using this code line

Toast.makeText(LoginActivity.this, "User Authentication Failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();


来源: stackexchange

问:
How to remove the category from the page url?
Is there any way to remove the "Project" term from the below permalink/url?
www.fourmanteam.com/project/camping

I want the url in below order.
www.fourmanteam.com/camping

I tried the custom structure. But, no help.

Thanks.

答:
I assume that, "Project" is your custom taxonomy.

So while registering your taxonomy you need to pass following rewrite rule:

```<code>$args = array(
            'hierarchical'      => true,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => '/' ),
        );
register_taxonomy( 'Project', array( [custom_post_type_slug] ), $args, array( 'rewrite' => array ('slug'=>'/')));
</code>```

After applying this code, you need to flush rewrite rules. For that you just need to save permalink setting again.

ContentLicense: CC BY-SA 3.0

Body:
I assume that, "Project" is your custom taxonomy.

So while registering your taxonomy you need to pass following rewrite rule:

$args = array(
            'hierarchical'      => true,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => '/' ),
        );
register_taxonomy( 'Project', array( [custom_post_type_slug] ), $args, array( 'rewrite' => array ('slug'=>'/')));

After applying this code, you need to flush rewrite rules. For that you just need to save permalink setting again.


问:
WinForms: Is there a concept of associating a label with a textbox?
I'm using Visual Studio 2010 with C#.  Is there a concept in Windows Forms development of somehow linking a label with is text box?  Something so that they move together as a unit?  In the ASP.NET world, there is the AssociatedControlId property of the label control.  I also think I remember MS Access form designer having some way of associating (or linking) labels with controls.  Does this feature even exist in Visual Studio world?

If not, how do you group labels with controls such that if you move a text box you don't have to manually move the label also?

答: i think the best bet would be to use a GroupBox.</p>

ContentLicense: CC BY-SA 2.5


问:
Laravel: get a model through another table
I have gotten a model called User. in this model i have a function called UserActivity where i return this:

```<code>return $this->hasMany('App\UserActivity', 'userid');
</code>```

After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:

```<code>public function Activity() {
      return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}
</code>```

And in my view i want to use this like this:

```<code>$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());
</code>```

But then i get an error saying this:

```<code>Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)
</code>```

I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:

Users: pk: id

user_activities: pk: userid, activityid

activities: pk: id

Thank you in advance!

答:
You can try using eager loading.

So something like:

```<code>$activiteiten = \App\User::with('UserActivity.Activity')->find(Auth::user()->id);
dd($activiteiten->UserActivity->Activity);
</code>```

Edit: So then you can do something like this:

```<code>foreach($activiteiten->UserActivity as $user_activity) {
  foreach($user_activity->Activity as $activity) {
    print_r($activity);
  }
}
</code>```

Shows how you can loop through the relationships.

Body:
I have gotten a model called User. in this model i have a function called UserActivity where i return this:

return $this->hasMany('App\UserActivity', 'userid');

After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:

public function Activity() {
      return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}

And in my view i want to use this like this:

$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());

But then i get an error saying this:

Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)

I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:

Users: pk: id

user_activities: pk: userid, activityid

activities: pk: id

Thank you in advance!

Body:
You can try using eager loading.

So something like:

$activiteiten = \App\User::with('UserActivity.Activity')->find(Auth::user()->id);
dd($activiteiten->UserActivity->Activity);

Edit: So then you can do something like this:

foreach($activiteiten->UserActivity as $user_activity) {
  foreach($user_activity->Activity as $activity) {
    print_r($activity);
  }
}

Shows how you can loop through the relationships.


问:
Javascript - Why does the JavaScript I wrote inside a TypeScript file not function correctly?
I have an ionic project that I created. I added JavaScript code inside the type script of the ionic project, but I found that the function is not working.

problem.html

```<code>  </ion-col>
  <ion-col col-7 style="text-align:center;">
    <div class="center-block">
      <!--<input type="file" id="view" accept="image/*" multiple="multiple">-->
      <!--<input type="file" accept="image/*" multiple="multiple" onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">-->
      <article>
        <input id="files" type="file" accept="image/*" multiple/>
        <button ion-button (click)="imageUpload()"> Here ! </button>
      </article>
    </div>
  </ion-col>

 <p style="text-align:center;">
    <output id="result">
      <div>
      </div>
    </output>
</code>```

Inside my problem.ts file:

```<code>imageUpload(){

  window.onload = function () {
console.log("hihi");
    //Check File API support zzzz
    (<any>$('#files')).live("change", function (event) {
      var files = event.target.files; //FileList object
      var output = document.getElementById("result");
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        //Only pics
        // if(!file.type.match('image'))
        if (file.type.match('image.*')) {
          if (this.files[0].size < 2097152) {
            // continue;
            var picReader = new FileReader();
            picReader.addEventListener("load", function (event) {
              var picFile = <FileReader>event.target;
              var div = document.createElement("div");
              div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                "title='preview image'>";
              output.insertBefore(div, null);
            });
            //Read the image
            $('#clear, #result').show();
            picReader.readAsDataURL(file);
          } else {
            alert("Image Size is too big. Minimum size is 2MB.");
            $(this).val("");
          }
        } else {
          alert("You can only upload image file.");
          $(this).val("");
        }
      }
    });
    (<any>$('#files')).live("click", function () {
      $('.thumbnail').parent().remove();
      $('result').hide();
      $(this).val("");
    });

    (<any>$('#clear')).live("click", function () {
      $('.thumbnail').parent().remove();
      $('#result').hide();
      $('#files').val("");
      $(this).hide();
    });

  }
}
</code>```

This is all of my code. After I implemented it, no errors were returned, but I found that my JavaScript, the imageUpload() function specifically, is not working. I console.log and nothing is returned in my console.

Anyone know what the problem is? Thanks.

答:
The obvious thing to check is, do you have a valid window object when this method is called? Is window.onLoad() ever called? I don't remember ever using window.onLoad() in an ionic app.

Where is this method imageUpload() called? I'll probably get a hold of a valid window object first (e.g., in a component or service), and pass it into this method. And, I'd suggest changing your code so that your "onload" function is called within one of the Angular/Ionic component lifecycle methods. The way your code looks, I doubt that it'll ever run in an Angular/Ionic app.

Body:
I have an ionic project that I created. I added JavaScript code inside the type script of the ionic project, but I found that the function is not working.

problem.html

  </ion-col>
  <ion-col col-7 style="text-align:center;">

        <input id="files" type="file" accept="image/*" multiple/>
        <button ion-button (click)="imageUpload()"> Here ! </button>

  </ion-col>

    <output id="result">

    </output>

Inside my problem.ts file:

imageUpload(){

  window.onload = function () {
console.log("hihi");
    //Check File API support zzzz
    (<any>$('#files')).live("change", function (event) {
      var files = event.target.files; //FileList object
      var output = document.getElementById("result");
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        //Only pics
        // if(!file.type.match('image'))
        if (file.type.match('image.*')) {
          if (this.files[0].size < 2097152) {
            // continue;
            var picReader = new FileReader();
            picReader.addEventListener("load", function (event) {
              var picFile = <FileReader>event.target;
              var div = document.createElement("div");
              div.innerHTML = "";
              output.insertBefore(div, null);
            });
            //Read the image
            $('#clear, #result').show();
            picReader.readAsDataURL(file);
          } else {
            alert("Image Size is too big. Minimum size is 2MB.");
            $(this).val("");
          }
        } else {
          alert("You can only upload image file.");
          $(this).val("");
        }
      }
    });
    (<any>$('#files')).live("click", function () {
      $('.thumbnail').parent().remove();
      $('result').hide();
      $(this).val("");
    });

    (<any>$('#clear')).live("click", function () {
      $('.thumbnail').parent().remove();
      $('#result').hide();
      $('#files').val("");
      $(this).hide();
    });

  }
}

This is all of my code. After I implemented it, no errors were returned, but I found that my JavaScript, the imageUpload() function specifically, is not working. I console.log and nothing is returned in my console.

Anyone know what the problem is? Thanks.


问:
Swift Sandbox User In app Purchases Loop
Im using a sandbox user to test In app Purchases in my app, it was working well a few days ago, but today, when im testing In app Purchase I need to sign in, my user and password are correct, and then I click buy and then nothing happens, and the sign in view appears again, and the process get repeated. I have sign out of any Apple ID in my physical iPhone, as recommended. </p>

答:
Do the following thing to resolve your problem:

Remove your personal Apple ID from Settings.

Crash the app.

Sign In to iTunes Store using Sandbox ID.

Launch the app and try to buy again.

I have tested this because I was facing the same issue. Let me know if problem still persists.

P.S. Give a restart also in case if it doesn't works.


问:
Save image path to core data, then use the path in a eureka row to show the image
I am trying to save an images path to core data that I can later use to display the image in a row created using Eureka Forms: The below code saves the URL, but I cannot get the file name. Here is what is currently being saved.

file:///Users/myName/Library/Developer/CoreSimulator/Devices/21A03F39-026C-417F-8E51-16C5E4BE2FC8/data/Containers/Data/Application/4A7CAE46-5004-4A2E-93A6-A3581F853576/Documents/

```<code>@IBAction func btnSave(_ sender: UIButton) {

    UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)

     let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first

    let url = URL(fileURLWithPath: documentDirectories!)

    print ("STARTS HERE \(url) ENDS")
</code>```

答:
Try this code for saving an image to document directory with an image name. After saving you will get the file URL that will work in future use. </p>

```<code>let documentsDirectoryURL = try!
NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask,
  appropriateForURL: nil, create: true)
// create a name for your image
let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("Image1.jpg")

if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
    if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) {
        print("file saved")
    } else {
        print("error saving file")
    }
} else {
    print("file already exists")
}
print ("STARTS HERE \(fileURL) ENDS")
</code>```

Body:
I am trying to save an images path to core data that I can later use to display the image in a row created using Eureka Forms: The below code saves the URL, but I cannot get the file name. Here is what is currently being saved.

file:///Users/myName/Library/Developer/CoreSimulator/Devices/21A03F39-026C-417F-8E51-16C5E4BE2FC8/data/Containers/Data/Application/4A7CAE46-5004-4A2E-93A6-A3581F853576/Documents/

@IBAction func btnSave(_ sender: UIButton) {

    UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)

     let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first

    let url = URL(fileURLWithPath: documentDirectories!)

    print ("STARTS HERE \(url) ENDS")

Body:
Try this code for saving an image to document directory with an image name. After saving you will get the file URL that will work in future use.

let documentsDirectoryURL = try!
NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask,
  appropriateForURL: nil, create: true)
// create a name for your image
let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("Image1.jpg")

if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
    if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) {
        print("file saved")
    } else {
        print("error saving file")
    }
} else {
    print("file already exists")
}
print ("STARTS HERE \(fileURL) ENDS")


问:
jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered?
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});```
<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>
<input type='text' id='price'></code>```

答:
Use keypress for that instead of keydown

then

the keyCode of 0 to 9 are 48 to 57 so use this condition

```<code>if (event.keyCode < 48 || event.keyCode > 57) {
   event.preventDefault();
}
</code>```

this condition returns true if you enter keys that are not 0, 1, 2, 3, 4, 5, 6, 7 ,8 and 9 or not numbers

So your code would be like this

$(document).ready(function() {
  $('#price').keypress(function(event) {
       if (event.keyCode < 48 || event.keyCode > 57) {
           event.preventDefault();
       }
    });
});```
<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>
<input type='text' id='price'></code>```

Body:
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});

<input type='text' id='price'>

Body:
Use keypress for that instead of keydown

then

the keyCode of 0 to 9 are 48 to 57 so use this condition

if (event.keyCode < 48 || event.keyCode > 57) {
   event.preventDefault();
}

this condition returns true if you enter keys that are not 0, 1, 2, 3, 4, 5, 6, 7 ,8 and 9 or not numbers

So your code would be like this

$(document).ready(function() {
  $('#price').keypress(function(event) {
       if (event.keyCode < 48 || event.keyCode > 57) {
           event.preventDefault();
       }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>


问:
HTML and Apache2 dont play mp4 video
I have problem with playing mp4 video in web-brower on localhost on Debian 8...I use Apache 2 with html....
This is my index.html in /var/www/html

```<code><!DOCTYPE html>
<html>
<body>

<video width="320" height="240" controls>
    <source src="150927_NOAA2422_0750_0758_C2.1_ca.mp4" type="video/mp4">

</video>

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

In the same path is video file too.

I used .htaccess in /var/www/html with this configuration:

```<code>AddType video/mp4 .mp4
</code>```

and change in apache2.conf AllowOverride None to All

```<code><Directory /var/www/>
    Options Indexes FollowSymlinks
    AllowOverride All
    Require all granted
</Directory>
</code>```

Then service apache2 restart...

Now when I type 127.0.0.1 to browser I get window of video but with "No video with supported format and MIME type found"

Any suggestion?

Thanks

答:
I had the same issue on my Raspberry PI and it turns out it was a case sensitive issue in the path of the URL.

http://www.vallisoftware.com/SpeechEditor/shared/SpeechEditorReview.mp4

http://www.vallisoftware.com/SpeechEditor/Shared/SpeechEditorReview.mp4

The top link didn't work but the bottom link did because the folder was named Shared not shared.

I didn't need a .htaccess or didn't need to modify the a .conf file either.

Title: HTML and Apache2 dont play mp4 video

Body:
I have problem with playing mp4 video in web-brower on localhost on Debian 8...I use Apache 2 with html....
This is my index.html in /var/www/html

<!DOCTYPE html>

<video width="320" height="240" controls>
    <source src="150927_NOAA2422_0750_0758_C2.1_ca.mp4" type="video/mp4">

</video>

In the same path is video file too.

I used .htaccess in /var/www/html with this configuration:

AddType video/mp4 .mp4

and change in apache2.conf AllowOverride None to All

<Directory /var/www/>
    Options Indexes FollowSymlinks
    AllowOverride All
    Require all granted
</Directory>

Then service apache2 restart...

Now when I type 127.0.0.1 to browser I get window of video but with "No video with supported format and MIME type found"

Any suggestion?

Thanks


问:
joomla setRedirect
How to prevent executing code after setRedirect?

I've place setRedirect in controller, it does redirect to different controller but still executing rest of the code in first controller.

答: Use php die() function after setRedirect, it's equivalent to exit()</p>

Title: joomla setRedirect


问:
Two anchor.hash properties differ, but js disagrees
In a html page I'm trying to compare the hash property of two anchor elements, but even when the strings are different, javascript still returns true.

HTML

  link0
  link1
  link2
  link3
  link4

<button onclick="myFunction()">Click</button>

```

<h2>JS</h2>

<pre class="lang-js prettyprint-override"><code>let currPg = 0;

function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash); {
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}
</code>```

I've been fiddling with it, here: https://jsfiddle.net/danobdgz/1/

答:
There's a semicolon in the end of this line:

```<code>if (location.hash == pages[i].hash);
</code>```

:)

Body:
In a html page I'm trying to compare the hash property of two anchor elements, but even when the strings are different, javascript still returns true.

HTML

  link0
  link1
  link2
  link3
  link4

<button onclick="myFunction()">Click</button>

JS

let currPg = 0;

function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash); {
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}

I've been fiddling with it, here: https://jsfiddle.net/danobdgz/1/

Body:
There's a semicolon in the end of this line:

if (location.hash == pages[i].hash);

:)


问:
Firebase - How do I make a new table/structure?
So I am currently developing an API which gets data from Firebase and depending on that data the button changes its color. However, when I tried to make a new structure for my buttons. It won't let me make one.

I tried the answers here: How to insert data of two tables in Firebase? and here: How can I create an empty table from android app in Firebase? but neither did work for me.

Here's my sample code:

```<code>public class Normal extends AppCompatActivity {

    Button suite, normal, room1;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private DatabaseReference mFirebaseDatabase1;
    private FirebaseDatabase mFirebaseInstance;

    //FIREBASE AUTH FIELDS

    DatabaseReference mSearchedLocationReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal);

        mFirebaseInstance = FirebaseDatabase.getInstance();

        //FIREBASE
        mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
        mSearchedLocationReference = mFirebaseDatabase1.child("Room1").child("RoomStatus");

        //ASSIGN ID's

        room1 = (Button) findViewById(R.id.room2);

        room1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
                startActivity(new Intent(Normal.this, room2.class));
            }
        });

        mSearchedLocationReference.addValueEventListener(new ValueEventListener() { //attach listener

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location); //log
                    if ( location.equals("Green")){
                        room1.setBackgroundColor(Color.GREEN);
                    }else if ( location.equals("Red")){
                        room1.setBackgroundColor(Color.RED);

                    }
                    else{
                        room1.setBackgroundColor(Color.YELLOW);

                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.

            }
        });

    }
}
</code>```

PS: I created the User structure (which is for my login) on another class.

答:
I think you should make a new structure at firebase you can do it by clicking the "+" beside your DB Name, here's an example:

Implement your methods and it should work. Then Connect again your firebase database.

Body:
So I am currently developing an API which gets data from Firebase and depending on that data the button changes its color. However, when I tried to make a new structure for my buttons. It won't let me make one.

I tried the answers here: How to insert data of two tables in Firebase? and here: How can I create an empty table from android app in Firebase? but neither did work for me.

Here's my sample code:

public class Normal extends AppCompatActivity {

    Button suite, normal, room1;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private DatabaseReference mFirebaseDatabase1;
    private FirebaseDatabase mFirebaseInstance;

    //FIREBASE AUTH FIELDS

    DatabaseReference mSearchedLocationReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal);

        mFirebaseInstance = FirebaseDatabase.getInstance();

        //FIREBASE
        mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
        mSearchedLocationReference = mFirebaseDatabase1.child("Room1").child("RoomStatus");

        //ASSIGN ID's

        room1 = (Button) findViewById(R.id.room2);

        room1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
                startActivity(new Intent(Normal.this, room2.class));
            }
        });

        mSearchedLocationReference.addValueEventListener(new ValueEventListener() { //attach listener

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location); //log
                    if ( location.equals("Green")){
                        room1.setBackgroundColor(Color.GREEN);
                    }else if ( location.equals("Red")){
                        room1.setBackgroundColor(Color.RED);

                    }
                    else{
                        room1.setBackgroundColor(Color.YELLOW);

                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.

            }
        });

    }
}

PS: I created the User structure (which is for my login) on another class.


答:
Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.

This is a link if you want to build it yourself.

```<code>  $(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});
</code>```

NOTE: If your webpage uses HTML5, you can use the built-in <input type="number"> and use the min and max properties to control the minimum and maximum value.

```<code>$(function() {
  $('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
    <input id="child" type="textarea" />
</div>
</code>```

I coppied from it on here

If its help for you.Please  vote first writer .

Title: jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered?

Body:
Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.

This is a link if you want to build it yourself.

  $(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

NOTE: If your webpage uses HTML5, you can use the built-in <input type="number"> and use the min and max properties to control the minimum and maximum value.

$(function() {
  $('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
    <input id="child" type="textarea" />
</div>

I coppied from it on here

If its help for you.Please  vote first writer .


问:
Three.js Image is not power of two warning
I have a problem with this warning I'm getting from three.js. The warning is: THREE.WebGLRenderer: image is not power of two (600x480). Resized to 512x512
I have tried adding THREE.LinearFilter, but it does nothing.

```<code>var texture = new THREE.TextureLoader().load(data[i]['image']);
texture.minFilter = THREE.LinearFilter;
            var paintingGeometry = new THREE.BoxGeometry(1, 1, 1);
            var paintingMaterial = new THREE.MeshPhongMaterial({
                map: texture
            });
            var painting = new THREE.Mesh(paintingGeometry, paintingMaterial);
</code>```

What are your suggestions? Thanks.

答: There isn't a problem here - all textures need power of two images. If you're having issues with how the texture is scaled and applied to your geometry you should check out the docs for THREE.Texture, specifically the wrap and repeat properties.

Body:
I have a problem with this warning I'm getting from three.js. The warning is: THREE.WebGLRenderer: image is not power of two (600x480). Resized to 512x512
I have tried adding THREE.LinearFilter, but it does nothing.

var texture = new THREE.TextureLoader().load(data[i]['image']);
texture.minFilter = THREE.LinearFilter;
            var paintingGeometry = new THREE.BoxGeometry(1, 1, 1);
            var paintingMaterial = new THREE.MeshPhongMaterial({
                map: texture
            });
            var painting = new THREE.Mesh(paintingGeometry, paintingMaterial);

What are your suggestions? Thanks.


问:
How can I omit a "Cout" statement for a specific "if-else" statement?

I'm trying to avoid a cout statement. Specifically,

```<code>cout<< "Enter integer 2: \n"

cin>> i
</code>```

I've tried utilizing the cin.ignore(j) in various places of the 8th if-else statement. That is, option 8 from the user selections.

I want to accomplish this with the last complicated method. I'm in "Introduction to C++" and well, I'm not too familiar with advanced methods.

The goal here is to create a calculator with the given functions under the prototype section.

```<code>#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = " << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}
</code>```

答:
You create a separate if-else statement which accepts second input in cases other than factorial condition. So, if a user only selects operation like factorial/square/square root your calculator asks for only one input from the user. You can do that simply like:

```<code>if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    if (choice == 8)
    {
        cout << i << ", factorial = 8" << factorial(i) << endl;
        return 0;
    }
    else
    {
        cout << "Enter integer 2: \n";
        cin >> j;
    }

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

        return 0;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to avoid a cout statement. Specifically,

cout<< "Enter integer 2: \n"

cin>> i

I've tried utilizing the cin.ignore(j) in various places of the 8th if-else statement. That is, option 8 from the user selections.

I want to accomplish this with the last complicated method. I'm in "Introduction to C++" and well, I'm not too familiar with advanced methods.

The goal here is to create a calculator with the given functions under the prototype section.

#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = " << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}

Body:
You create a separate if-else statement which accepts second input in cases other than factorial condition. So, if a user only selects operation like factorial/square/square root your calculator asks for only one input from the user. You can do that simply like:

if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    if (choice == 8)
    {
        cout << i << ", factorial = 8" << factorial(i) << endl;
        return 0;
    }
    else
    {
        cout << "Enter integer 2: \n";
        cin >> j;
    }

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

        return 0;


问:
Can a React App run on AWS S3
I am creating a React App that doesn't have a database connection for the moment, am just trying to get the frontend UI working before I get the database up. I have been trying to host the application on AWS S3 as a static website but not having much luck. I have linked up the React CDN to an index.html page but when I run it nothing seems to be rendering.

Question is, is it even possible to have a React App running on S3? Or do I need to have a Node server running?

答:
Yes, hosting a react app on S3 is possible. All you need to do is create a build of your project and upload those files on s3 as a static website.

The build just creates a bundle of all your js files and dependency which can just be hosted. I found a great detailed article on how you can setup s3 and build and deploy your react app.

Ref: [https://www.fullstackreact.com/articles/deploying-a-react-app-to-s3/]

Title: Can a React App run on AWS S3


问:
Automapper Compile Mappings
We use automapper with ASP.NET Core 2.0.

We like to create a mapping configuration once, which will be used from each mapper. We create a mapper per request that we will not have problems because I read once automapper is not thread safe.

We like to precompile the mappingconfiguration at application startup (See in Code MapperConfigruation.CompileMappings();

If I measure the time how long the mapping takes, i see that the first mapping need more time than the other mappings. Is there a reason for that or do I have bug?

Code

In ConfigureService of Startup class:

```<code> services.AddSingleton<MyMapperConfiguration>();
 services.AddScoped<IObjectMapper, MyMapper>();
</code>```

Mapperconfiguration

```<code>public class MyMapperConfiguration
    {
        public MapperConfiguration MapperConfiguration { get; private set; }

        public MappingDefinition MappingDefinition { get; }

        public MapperConfiguration(IOptions<MappingDefinition> mappings)
        {
            // MappingDefinitions hold some information where to search mappings
            MappingDefinition = mappings.Value;
        }

        public void Configure()
        {
            List<Type> mappingDefinitionClasses = new List<Type>();

             // Search Types with special attribute and add it to the typelist

            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfiles(mappingDefinitionClasses.ToArray());
            });
            MapperConfiguration.CompileMappings(); // <-- THIS SHOULD COMPILE THE MAPPING I THNIK?!

        }
</code>```

`

Mapper

```<code> public class MyMapper : IObjectMapper
    {
        public IMapper Mapper { get; }

        public Mapper(MapperConfiguration mappingConfiguration)
        {
            Mapper = mappingConfiguration.MapperConfiguration.CreateMapper();
        }

        public TDestination Map<TSource, TDestination>(TSource source)
        {
            return Mapper.Map<TSource, TDestination>(source);
        }
    }
</code>```

IObjectMapper:

```<code>   public interface IObjectMapper
    {
        TDestination Map<TSource, TDestination>(TSource source);
    }
</code>```

Measure time inside a webApi

```<code>Stopwatch sw = new Stopwatch();
sw.Start();
destObj = _mapper.Map<Source, Destination>(sourceObj);
sw.Stop();
Debug.WriteLine($"Duration of mapping: {sw.ElapsedMilliseconds}");
</code>```

In the Configruate methode of Startup I also get an instance of the mapping configuration and call Configure() that this instance lifes.

答: AM is thread safe. The mapper itself is not expensive, you can share it or not. It does allocate a few things, so it's cheaper to share it if you can. CompileMappings changed a bit, so upgrade to the latest. But other than that, it's probably the JIT compiler you're seeing. Until the mapping is executed, the code doesn't get compiled. CompileMappings just compiles an expression to IL. The JIT compiles IL to machine code. You can profile and verify what happens.</p>

Title: Automapper Compile Mappings

Body:
We use automapper with ASP.NET Core 2.0.

We like to create a mapping configuration once, which will be used from each mapper. We create a mapper per request that we will not have problems because I read once automapper is not thread safe.

We like to precompile the mappingconfiguration at application startup (See in Code MapperConfigruation.CompileMappings();

If I measure the time how long the mapping takes, i see that the first mapping need more time than the other mappings. Is there a reason for that or do I have bug?

Code

In ConfigureService of Startup class:

 services.AddSingleton<MyMapperConfiguration>();
 services.AddScoped<IObjectMapper, MyMapper>();

Mapperconfiguration

public class MyMapperConfiguration
    {
        public MapperConfiguration MapperConfiguration { get; private set; }

        public MappingDefinition MappingDefinition { get; }

        public MapperConfiguration(IOptions<MappingDefinition> mappings)
        {
            // MappingDefinitions hold some information where to search mappings
            MappingDefinition = mappings.Value;
        }

        public void Configure()
        {
            List<Type> mappingDefinitionClasses = new List<Type>();

             // Search Types with special attribute and add it to the typelist

            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfiles(mappingDefinitionClasses.ToArray());
            });
            MapperConfiguration.CompileMappings(); // <-- THIS SHOULD COMPILE THE MAPPING I THNIK?!

        }

`

Mapper

 public class MyMapper : IObjectMapper
    {
        public IMapper Mapper { get; }

        public Mapper(MapperConfiguration mappingConfiguration)
        {
            Mapper = mappingConfiguration.MapperConfiguration.CreateMapper();
        }

        public TDestination Map<TSource, TDestination>(TSource source)
        {
            return Mapper.Map<TSource, TDestination>(source);
        }
    }

IObjectMapper:

   public interface IObjectMapper
    {
        TDestination Map<TSource, TDestination>(TSource source);
    }

Measure time inside a webApi

Stopwatch sw = new Stopwatch();
sw.Start();
destObj = _mapper.Map<Source, Destination>(sourceObj);
sw.Stop();
Debug.WriteLine($"Duration of mapping: {sw.ElapsedMilliseconds}");

In the Configruate methode of Startup I also get an instance of the mapping configuration and call Configure() that this instance lifes.


问:
How to get system date in SQL Server with the format of 'MM dd, yyyy'
How to get the system date in SQL Server with the format of MM dd, yyyy?

I tried everything but I couldn't get the correct format MM dd, yyyy

答:
Use this query,
SELECT FORMAT(Getdate(), 'MM dd, yyyy')


问:
Simple React API requests with Axios
I'm trying to create a wrapper for API calls and I think that i'm missing something. The promise stores the posts in this.post but I cannot figure out the correct way to return the data.

So far I have tried this:

```<code>import axios from 'axios';

const CallumAPI = {
  posts: [

  ],
  all: function() {
    axios.get('http://callum.dev/api/posts')
      .then(res => {
        this.posts = res.data.posts;
      })
    return this.posts;
  }
}

export default CallumAPI
</code>```

In my wrapper I am trying to return the posts so that in my component I can just list them all out. Here's the component code:

```<code><div>
  <ul>
    {
      CallumAPI.all().map(p => (
        <li key={p.id}>
          <Link to={'/post/${p.slug}'}>{p.name}</Link>
        </li>
      ))
    }
  </ul>
</div>
</code>```

答:
You can't directly access the data from axios, as it will always return the promise, so you need either a callback function or need to access it via then once data is available.

Here is what you can do :

Change CallumAPI Like this :

```<code>const CallumAPI = {
  posts: [

  ],
  all: function() {
    return axios.get('https://jsonplaceholder.typicode.com/users') // change your api url
      .then(res => {
        this.posts = res.data;
        return this.posts; // return data so we can use
      })
  }
}
</code>```

And Component like this :

```<code>componentWillMount() {
    CallumAPI.all().then(posts => {
        console.log(posts);
        this.setState({posts}); // set state on data fetch so UI will render
    });
}

render() {
    const { posts } = this.state;
    return (
        <ul>
        { posts.map(p => (
            <li key={p.id}>
                { p.name }
            </li>
            )) }
        </ul>
    );
}
</code>```

Here is WORKING DEMO

Title: Simple React API requests with Axios

Body:
I'm trying to create a wrapper for API calls and I think that i'm missing something. The promise stores the posts in this.post but I cannot figure out the correct way to return the data.

So far I have tried this:

import axios from 'axios';

const CallumAPI = {
  posts: [

  ],
  all: function() {
    axios.get('http://callum.dev/api/posts')
      .then(res => {
        this.posts = res.data.posts;
      })
    return this.posts;
  }
}

export default CallumAPI

In my wrapper I am trying to return the posts so that in my component I can just list them all out. Here's the component code:

    {
      CallumAPI.all().map(p => (

          <Link to={'/post/${p.slug}'}>{p.name}</Link>

      ))
    }

Body:
You can't directly access the data from axios, as it will always return the promise, so you need either a callback function or need to access it via then once data is available.

Here is what you can do :

Change CallumAPI Like this :

const CallumAPI = {
  posts: [

  ],
  all: function() {
    return axios.get('https://jsonplaceholder.typicode.com/users') // change your api url
      .then(res => {
        this.posts = res.data;
        return this.posts; // return data so we can use
      })
  }
}

And Component like this :

componentWillMount() {
    CallumAPI.all().then(posts => {
        console.log(posts);
        this.setState({posts}); // set state on data fetch so UI will render
    });
}

render() {
    const { posts } = this.state;
    return (
        <ul>
        { posts.map(p => (
            <li key={p.id}>
                { p.name }
            </li>
            )) }
        </ul>
    );
}

Here is WORKING DEMO


问:
Pull and rebase from a remote that's been split into submodules
I'm collaborating on a GitHub project (I've forked the repo) that has recently been re-structured into submodules.

Earlier I would git stash my changes, do a git pull --rebase shared_origin master, and then perform git stash pop to continue working. After commiting changes to my local repo, I would push them to my fork of the shared repo using git push my_origin development and then create a PR.

Now that the project has been split into submodules, how do I perform a pull rebase that replicates entire repo (including all submodules), re-apply my (unmerged) changes and continue with my development?

Please do consider the possibility where the file(s) I had changed have been moved to a different directory as a part of submodule-restructuring.

答:
You could consider the option pull --recurse-submodule=yes.

And don't forget you can stash and rebase by default on a git pull.

```<code>git config pull.rebase true
git config rebase.autoStash true
</code>```

Actually, combine that with the config:

```<code>git config fetch.recurseSubmodules true
</code>```

And now, a simple git pull from the parent repo (the one referencing all those submodules) is enough.

Note: submodules are by default in detached HEAD mode, so make sure they have checked out a branch first, and you have done some commits locally in them, if you want the rebase to actually do something in said submodules.

Body:
You could consider the option pull --recurse-submodule=yes.

And don't forget you can stash and rebase by default on a git pull.

git config pull.rebase true
git config rebase.autoStash true

Actually, combine that with the config:

git config fetch.recurseSubmodules true

And now, a simple git pull from the parent repo (the one referencing all those submodules) is enough.

Note: submodules are by default in detached HEAD mode, so make sure they have checked out a branch first, and you have done some commits locally in them, if you want the rebase to actually do something in said submodules.


问:
How to change column names in pandas Dataframe using a list of names?
I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:

```<code>df.rename(columns = list_of_names, inplace=True)
</code>```

However I got a Type Error each time, with an error message that says "list object is not callable".
  I would like to know why does this happen? And What can I do to solve this problem?
Thank you for your help.

答:
you could use</p>

```<code>df.columns = ['Leader', 'Time', 'Score']
</code>```

Body:
I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:

df.rename(columns = list_of_names, inplace=True)

However I got a Type Error each time, with an error message that says "list object is not callable".
  I would like to know why does this happen? And What can I do to solve this problem?
Thank you for your help.

Body:
you could use

df.columns = ['Leader', 'Time', 'Score']


答:
axios request is an async call and you are returning the array even before the promise is resolved. Also you shouldn't have a async request in your render function. You would rather want it to called once and store the result. Have your async request in the componentDidMount function.

You could change your all function to receive a callback function and pass the response to it.

```<code>const CallumAPI = {
  posts: [

  ],
  all: function(cb) {
    axios.get('http://callum.dev/api/posts')
      .then(res => {
        cb(res.data.posts);
      })
  }
}

componentDidMount() {
    CallumAPI.all(this.updateResult);
}

updateResult = (res) => {
    this.setState({res})
}

render() {
<div>
  <ul>
    {
      this.state.res.map(p => (
        <li key={p.id}>
          <Link to={`/post/${p.slug}`}>{p.name}</Link>
        </li>
      ))
    }
  </ul>
</div>
}
</code>```

Title: Simple React API requests with Axios

Body:
axios request is an async call and you are returning the array even before the promise is resolved. Also you shouldn't have a async request in your render function. You would rather want it to called once and store the result. Have your async request in the componentDidMount function.

You could change your all function to receive a callback function and pass the response to it.

const CallumAPI = {
  posts: [

  ],
  all: function(cb) {
    axios.get('http://callum.dev/api/posts')
      .then(res => {
        cb(res.data.posts);
      })
  }
}

componentDidMount() {
    CallumAPI.all(this.updateResult);
}

updateResult = (res) => {
    this.setState({res})
}

render() {
<div>
  <ul>
    {
      this.state.res.map(p => (
        <li key={p.id}>
          <Link to={`/post/${p.slug}`}>{p.name}</Link>
        </li>
      ))
    }
  </ul>
</div>
}


问:
Is it a good practice to wrap all layouts in CoordinatorLayout?
I'm thinking of a way to implement Android Snackbars in my app. Basically, I want to be able to show Snackbar from anywhere in the app.

As I found out, android.support.design.widget.Snackbar performs the best when put in android.support.design.widget.CoordinatorLayout. Otherwise, I cannot swipe it away, it shows over navigation drawer and doesn't interact with Floating Action Button.

So the question is: Is it a good practice to wrap ALL my layouts in CoordinatorLayout, get the reference for it in a BaseActivity, so that it can be passed to Snackbar from almost anywhere?

That seems to be a solid way to ensure the Snackbar and other layout components behave correctly, but... well, means touching all layouts and having one BaseActivity which is extended by all other Activities and which would be accessed from any Fragment wanting to show a Snackbar.

Is there a better way?

答:
I have implemented same like open Snackbar from anywhere in application.

I have created one common method and just pass context and string message i need to display and no need to pass any view. Check out my code snippet.

```<code> public static void showSnackBar(Activity context, String msg) {
   Snackbar.make(context.getWindow().getDecorView().findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG).show();
 }
</code>```

Using this, You will have your Snackbar on bottom every time.

Body:
I have implemented same like open Snackbar from anywhere in application.

I have created one common method and just pass context and string message i need to display and no need to pass any view. Check out my code snippet.

 public static void showSnackBar(Activity context, String msg) {
   Snackbar.make(context.getWindow().getDecorView().findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG).show();
 }

Using this, You will have your Snackbar on bottom every time.


问:
Can I use OpenGL GLES instead of full OpelGL on desktop?
I want to learn OpenGL to program a game in C language but I am a little confused about which library choose, the intention is to generate a C library with the game logic and using Android NDK to interface with the resources in phones.

I found an example that use GLESv2 library and this works well, I think I know that the GLES library was created because mobile devices can't use full OpenGL library.

but the real question is: Is GLES a subset of full OpelGL library in order that I can build and run my game app using GLES library on linux desktop?

Can you give me a clue if I'm going the right way with these library?

答:
This depends on which OpenGL library you linked to your application. For OpenGL, you should link with libGL.so, but for OpenGLESv2, you should link with libGLESv2.so.

To use OpenGL：

```<code> header file directory: /usr/include/GL
 library file: /usr/lib/libGL.so
</code>```

To use OpenGLESv2：

```<code> header file directory: /usr/include/GLES2
 library file: /usr/lib/libGLESvs.so
</code>```

By the way, according to Andriod Dashboards, at present, above 60% android devices have converted to using OpenGLES v3.x. Maybe you'd better give a try to OpenGLES v3.x.

Body:
This depends on which OpenGL library you linked to your application. For OpenGL, you should link with libGL.so, but for OpenGLESv2, you should link with libGLESv2.so.

To use OpenGL：

 header file directory: /usr/include/GL
 library file: /usr/lib/libGL.so

To use OpenGLESv2：

 header file directory: /usr/include/GLES2
 library file: /usr/lib/libGLESvs.so

By the way, according to Andriod Dashboards, at present, above 60% android devices have converted to using OpenGLES v3.x. Maybe you'd better give a try to OpenGLES v3.x.


问:
How avoid adding duplicates to database managed by EntityFramework caused by Seed method?
Every time I run the application same objects are added to the database(duplicates).

My Global.asax:

```<code>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;

namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
            //Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
</code>```

and My Configuration.cs with Seed method:

```<code>namespace WebApplication2.Migrations
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {
            var persons = new List<Person> {
         new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
         new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
        };

        persons.ForEach(person => context.Persons.AddOrUpdate(person));
        context.SaveChanges();

        var meetings = new List<Meeting>{
            new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
        };

        meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
        context.SaveChanges();

        var statuses = new List<Status> {
            new Status{Name = "OK"},
            new Status {Name = "NOT_OK"}
        };

        statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
        context.SaveChanges();

        }
    }
}
</code>```

Every time I run the app Seed adds duplicate records:

I needed to comment contents of Seed method to prevent adding duplicates.

Question: (1) What should I change so Seed method will be run only to recreate database after migration?

EDIT:

In the Seed method there is comment:

```<code>  //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
</code>```

but my method is called ALWAYS, not only after migrations. Why is it so?

答:
```<code>var paidOutType = new List<PaidOutType>
                {
                    new PaidOutType { PaidOutTypeID = 1, Code = "001", Description = "PAID OUT 1", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                    new PaidOutType { PaidOutTypeID = 2, Code = "002", Description = "PAID OUT 2", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                    new PaidOutType { PaidOutTypeID = 3, Code = "002", Description = "PAID OUT 3", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                };
                paidOutType.ForEach(u => smartPOSContext.PaidOutType.AddOrUpdate(u));
                smartPOSContext.SaveChanges();
</code>```

Body:
Every time I run the application same objects are added to the database(duplicates).

My Global.asax:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;

namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
            //Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

and My Configuration.cs with Seed method:

namespace WebApplication2.Migrations
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {
            var persons = new List<Person> {
         new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
         new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
        };

        persons.ForEach(person => context.Persons.AddOrUpdate(person));
        context.SaveChanges();

        var meetings = new List<Meeting>{
            new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
        };

        meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
        context.SaveChanges();

        var statuses = new List<Status> {
            new Status{Name = "OK"},
            new Status {Name = "NOT_OK"}
        };

        statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
        context.SaveChanges();

        }
    }
}

Every time I run the app Seed adds duplicate records:

I needed to comment contents of Seed method to prevent adding duplicates.

Question: (1) What should I change so Seed method will be run only to recreate database after migration?

EDIT:

In the Seed method there is comment:

  //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

but my method is called ALWAYS, not only after migrations. Why is it so?


问:
Map on filter giving compilation issue
What could be the issue here ?

I get the following error on compilation:

```<code>error: cannot find symbol
                                .collect(toList())
                                         ^
  symbol:   method toList()
  location: class stocks
 error: invalid method reference
                                .map(Stock::getSymbol)
                                     ^
  cannot find symbol
    symbol:   method getSymbol()
    location: class Stock
</code>```

Class Stock does have a public method getSymbol

```<code>   static class StockUtil{

            public static Predicate<Stock> isLessThanLimit(Double limit){
                return s -> s.tick < limit;
            }

            public static String toUpperCase(String stock){
                return stock.toUpperCase();
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            List<Stock> stocks = new ArrayList<>(Arrays.asList(new Stock("AMZ",312.0),
                new Stock("Yahoo",212.0),
                new Stock("ORCL",512.0),
                new Stock("SAP",112.0),
                new Stock("Google",412.0),
                new Stock("FB",12.0),
                new Stock("TWT",315.0)));

            //print list of stock names below 400 in uppercase
            System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(toList())
                    );
</code>```

答:
You have not defined the method toList() or you forgot to do static import, try:

```<code>import static java.util.stream.Collectors.toList;
</code>```

no other changes expected in your code.

If you do not want to do static import:

```<code>System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(Collectors.toList())
                    );
</code>```

Refer to java documentation of Collectors for details.

Title: Map on filter giving compilation issue

Body:
What could be the issue here ?

I get the following error on compilation:

error: cannot find symbol
                                .collect(toList())
                                         ^
  symbol:   method toList()
  location: class stocks
 error: invalid method reference
                                .map(Stock::getSymbol)
                                     ^
  cannot find symbol
    symbol:   method getSymbol()
    location: class Stock

Class Stock does have a public method getSymbol

   static class StockUtil{

            public static Predicate<Stock> isLessThanLimit(Double limit){
                return s -> s.tick < limit;
            }

            public static String toUpperCase(String stock){
                return stock.toUpperCase();
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            List<Stock> stocks = new ArrayList<>(Arrays.asList(new Stock("AMZ",312.0),
                new Stock("Yahoo",212.0),
                new Stock("ORCL",512.0),
                new Stock("SAP",112.0),
                new Stock("Google",412.0),
                new Stock("FB",12.0),
                new Stock("TWT",315.0)));

            //print list of stock names below 400 in uppercase
            System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(toList())
                    );

Body:
You have not defined the method toList() or you forgot to do static import, try:

import static java.util.stream.Collectors.toList;

no other changes expected in your code.

If you do not want to do static import:

System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(Collectors.toList())
                    );

Refer to java documentation of Collectors for details.


问:
JSF navigation problem
I am not able to navigate from one page to another after clicking the button on the page. I have defined the navigation rules.

```<code><managed-bean>
 <description>helloWorld</description>
 <managed-bean-name>helloWorld</managed-bean-name>
 <managed-bean-class>com.ritz.web.HelloWorld</managed-bean-class>
 <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
 <from-view-id>/HelloWorldProg.xhtml</from-view-id>
 <navigation-case>
  <from-outcome>success</from-outcome>
  <to-view-id>/welcome.xhtml</to-view-id>
 </navigation-case>
</navigation-rule>
<application>
 <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>
</code>```

web.xml is

```<code><!-- Welcome page -->
<welcome-file-list>
 <welcome-file>faces/HelloWorld.xhtml</welcome-file>
</welcome-file-list>

<!-- JSF mapping -->
<servlet>
 <servlet-name>Faces Servlet</servlet-name>
 <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<!-- Map these files with JSF -->
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</code>```

答:
First of all you you need a method to set action after button click:

```<code>public String nextPage()
{
    if (username.equals("guest") && password.equals("guest"))
    {
        return "loginSuccess";
    }
    return "loginFailure";
}
</code>```

Next thing you need to do is connect your button action attribute with method:

```<code><h:commandButton value="Submit Values" action="#{YourBean.nextPage}"/>
</code>```

Then you need to do is set a navigation rules:

```<code><navigation-rule>
    <description></description>
    <from-view-id>/login.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>loginSuccess</from-outcome>
        <to-view-id>/loginSuccess.xhtml</to-view-id>
    </navigation-case>
<navigation-case>
        <from-outcome>loginFailure</from-outcome>
        <to-view-id>/loginFailure.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>
</faces-config>
</code>```

And one last thing. If you have mapping like this:

```<code><servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
</code>```

You should put everywehere faces/login.xhtml, faces/success.xhtml and so on.

Title: JSF navigation problem

Body:
I am not able to navigate from one page to another after clicking the button on the page. I have defined the navigation rules.

<managed-bean>
 <description>helloWorld</description>
 <managed-bean-name>helloWorld</managed-bean-name>
 <managed-bean-class>com.ritz.web.HelloWorld</managed-bean-class>
 <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
 <from-view-id>/HelloWorldProg.xhtml</from-view-id>
 <navigation-case>
  <from-outcome>success</from-outcome>
  <to-view-id>/welcome.xhtml</to-view-id>
 </navigation-case>
</navigation-rule>
<application>
 <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>

web.xml is

<welcome-file-list>
 <welcome-file>faces/HelloWorld.xhtml</welcome-file>
</welcome-file-list>

<servlet>
 <servlet-name>Faces Servlet</servlet-name>
 <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

Body:
First of all you you need a method to set action after button click:

public String nextPage()
{
    if (username.equals("guest") && password.equals("guest"))
    {
        return "loginSuccess";
    }
    return "loginFailure";
}

Next thing you need to do is connect your button action attribute with method:

<h:commandButton value="Submit Values" action="#{YourBean.nextPage}"/>

Then you need to do is set a navigation rules:

<navigation-rule>
    <description></description>
    <from-view-id>/login.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>loginSuccess</from-outcome>
        <to-view-id>/loginSuccess.xhtml</to-view-id>
    </navigation-case>
<navigation-case>
        <from-outcome>loginFailure</from-outcome>
        <to-view-id>/loginFailure.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>
</faces-config>

And one last thing. If you have mapping like this:

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

You should put everywehere faces/login.xhtml, faces/success.xhtml and so on.


问:
new BufferedReader in class Files cannot be applied to given types

```<code>List< String> list = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch (IOException e) {
     e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}

String json = sb.toString();
JSONParser parser = new JSONParser();
obj = parser.parse(json);
</code>```

I am getting this error please help !!

答:
The Files#newBufferedReader method takes a mandatory second parameter which is a character set.  If you try the following code, the error should go away:

```<code>List< String> list = new ArrayList<>();

Charset charset = Charset.forName("US-ASCII");

try (BufferedReader br = Files.newBufferedReader(Paths.get(path), charset)) {
    list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

This assumes that your file is encoded in US-ASCII, though if you had another encoding, you could specify that as well.  For example, if your file were UTF-8 encoded, you could use:

```<code>Charset charset = StandardCharsets.UTF_8;
</code>```

Edit:

After the seeing the accepted answer, I noticed that Java 8 introduced a one argument version of Files#newBufferedReader which just takes a single path as input.  However, this is really a helper method which just calls the following:

```<code>return newBufferedReader(path, StandardCharsets.UTF_8);
</code>```

In other words, it defaults to using UTF-8 encoding.  If you want to use some other encoding, then my answer is probably the best approach for you.

Body:
List< String> list = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch (IOException e) {
     e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}

String json = sb.toString();
JSONParser parser = new JSONParser();
obj = parser.parse(json);

I am getting this error please help !!

Body:
The Files#newBufferedReader method takes a mandatory second parameter which is a character set.  If you try the following code, the error should go away:

List< String> list = new ArrayList<>();

Charset charset = Charset.forName("US-ASCII");

try (BufferedReader br = Files.newBufferedReader(Paths.get(path), charset)) {
    list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}

This assumes that your file is encoded in US-ASCII, though if you had another encoding, you could specify that as well.  For example, if your file were UTF-8 encoded, you could use:

Charset charset = StandardCharsets.UTF_8;

Edit:

After the seeing the accepted answer, I noticed that Java 8 introduced a one argument version of Files#newBufferedReader which just takes a single path as input.  However, this is really a helper method which just calls the following:

return newBufferedReader(path, StandardCharsets.UTF_8);

In other words, it defaults to using UTF-8 encoding.  If you want to use some other encoding, then my answer is probably the best approach for you.


问:
Ruby on Rails webfont not displaying locally
I'm using Rails 3.2.22 and have installed a new font using .woff and .woff2 files.  But the font seems to fail to display locally only.  The font shows up fine when I deploy to our staging environment after the assets have been precompiled and bundled up.  I can also follow the url that my local compiled CSS is using to try and display the font, and that link downloads the correct files.

The font files are contained in the "app/assets/fonts" folder, I have this in my application.rb

```<code>config.assets.paths << Rails.root.join("app", "assets", "fonts")
</code>```

and I am pulling the fonts into Sass like so:

```<code>// Custom Font Faces
@font-face {
  font-family: 'Museo Sans Rounded';
  src: font-url('MuseoSansRounded-500-webfont.woff2') format('woff2'),
       font-url('MuseoSansRounded-500-webfont.woff') format('woff');
  font-weight: 500;
  font-style: normal;
}

@font-face {
  font-family: 'Museo Sans Rounded';
  src: font-url('MuseoSansRounded-700-webfont.woff2') format('woff2'),
       font-url('MuseoSansRounded-700-webfont.woff') format('woff');
  font-weight: 700;
  font-style: normal;
}
</code>```

Any clue why this doesn't display locally?

答:
Try to compile assets locally. Follow below steps:

config/environments/production.rb

```<code>config.assets.compile = true
</code>```

then run command:

```<code>RAILS_ENV=production rake assets:precompile
</code>```

and test it.

Body:
I'm using Rails 3.2.22 and have installed a new font using .woff and .woff2 files.  But the font seems to fail to display locally only.  The font shows up fine when I deploy to our staging environment after the assets have been precompiled and bundled up.  I can also follow the url that my local compiled CSS is using to try and display the font, and that link downloads the correct files.

The font files are contained in the "app/assets/fonts" folder, I have this in my application.rb

config.assets.paths << Rails.root.join("app", "assets", "fonts")

and I am pulling the fonts into Sass like so:

// Custom Font Faces
@font-face {
  font-family: 'Museo Sans Rounded';
  src: font-url('MuseoSansRounded-500-webfont.woff2') format('woff2'),
       font-url('MuseoSansRounded-500-webfont.woff') format('woff');
  font-weight: 500;
  font-style: normal;
}

@font-face {
  font-family: 'Museo Sans Rounded';
  src: font-url('MuseoSansRounded-700-webfont.woff2') format('woff2'),
       font-url('MuseoSansRounded-700-webfont.woff') format('woff');
  font-weight: 700;
  font-style: normal;
}

Any clue why this doesn't display locally?

Body:
Try to compile assets locally. Follow below steps:

config/environments/production.rb

config.assets.compile = true

then run command:

RAILS_ENV=production rake assets:precompile

and test it.


答:
Just update the columns attribute:</p>

```<code>df.columns = list_of_names
</code>```

Title: How to change column names in pandas Dataframe using a list of names?

Body:
Just update the columns attribute:

df.columns = list_of_names


问:
A simple example of a cache aware algorithm?
Can someone post any simple explanation of cache aware algorithms? There are lot of links available but the reading material in those sites is academic in nature and time consuming to read and comprehend.</p>

答:
A cache-aware algorithm is designed to minimize the movement of memory pages in and out of the processor's on-chip memory cache.  The idea is to avoid what's called "cache misses," which cause the processor to stall while it loads data from RAM into the processor cache.

A cache-aware algorithm that is less than optimum on paper can outperform a traditional algorithm that is in theory "faster," because the cache-aware algorithm uses memory more efficiently.

A cache-aware algorithm is explicitly coded to take advantage of the processor's cache behavior.  Intimate details about the processor's memory page size and "cache lines" are coded into the algorithm.  As such, a cache-aware algorithm will be highly processor specific.

A cache-oblivious algorithm is coded to use memory in a more cache-friendly manner than a traditional algorithm, but it does not depend on intimate details about the underlying hardware.

OwnerDisplayName: Sesh

OwnerDisplayName: Jim Mischel


问:
Unique elements on basis of keys
I want to find unique elements in a which do not exist in b on the basis of name property

```<code>EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];
</code>```

```<code>var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];

var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];

var data = [];
b.map((n)=>{
  for(i=0;i<a.length;i++) {
    if(n.name!= a[i].name){
      data.push(a[i]);
    }
  }
})

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

答:
Use Array#filter to filter the a array and pass a predicate which uses Array#some to try to find an item. When there is no match, get those items

const a =[
   {"name":"sam","color":"red" },
   {"name":"rash","color":"blue" },
   {"name":"rashffffish","color":"blue" }
];

const b = [
   {"name":"sam","color":"red" },
   {"name":"rash","color":"red" }
];

const filtered = a.filter(itemA => !b.some(itemB => itemA.name === itemB.name));

console.log(filtered);```

Title: Unique elements on basis of keys

Body:
I want to find unique elements in a which do not exist in b on the basis of name property

EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];

var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];

var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];

var data = [];
b.map((n)=>{
  for(i=0;i<a.length;i++) {
    if(n.name!= a[i].name){
      data.push(a[i]);
    }
  }
})

console.log(data);


问:
Immediate evaluation of CTE
I am trying to optimize a very long and complex impala query which contains multiple CTE. Each CTE is used multiple times. My expectation is that once a CTE is created, I should be able to direct impala that results of this CTE should be re-used in main query as-is instead of SCAN HDFS operation on tables involved in CTE again with the main query. Is this possible? if yes how ?

I am using impalad version 2.1.1-cdh5 RELEASE (build 7901877736e29716147c4804b0841afc4ebc9037) version

答:
I do not think so. I believe WITH clause does not create any permanent object, it's just for you avoid cluttering the namespace with new tables or views and to make it easier to refactor large, complex queries by reor‐
dering and replacing their individual parts. The queries used in the WITH clause are good candidates to someday become views or to be materialized as summary tables during the ETL process.</p>

Title: Immediate evaluation of CTE