问:
Initializing Firebase auth object error
I am getting an error whenever I try to run the app:

Here is .java class:

```<code>package com.safariagaming.flix;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
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;

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener{

    //defining view objects
    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignup;
    private ProgressDialog progressDialog;

    //defining firebaseauth object
    private FirebaseAuth firebaseAuth;

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

        //initializing firebase auth object
        firebaseAuth = FirebaseAuth.getInstance();

        //initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonSignup = (Button) findViewById(R.id.buttonSignup);

        progressDialog = new ProgressDialog(this);

        //attaching listener to button
        buttonSignup.setOnClickListener(this);
    }

    private void registerUser(){

        //getting email and password from edit texts
        String email = editTextEmail.getText().toString().trim();
        String password  = editTextPassword.getText().toString().trim();

        //checking if email and passwords are empty
        if(TextUtils.isEmpty(email)){
            Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
            return;
        }

        //if the email and password are not empty
        //displaying a progress dialog

        progressDialog.setMessage("Registering Please Wait...");

        //creating a new user
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        //calling register method on click
        registerUser();
    }
}
</code>```

(I think that the error happens because I am not initializing firebase auth object correctly)

Here is my XML class

```<code>android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<LinearLayout
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="Signup" />

</LinearLayout>
</code>```

Here is my error message that I am encountering

```<code>03-29 18:14:49.700 9230-9230/com.safariagaming.flix E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.safariagaming.flix, PID: 9230
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
                                                                      at com.safariagaming.flix.SignUpScreen.registerUser(SignUpScreen.java:72)
                                                                      at com.safariagaming.flix.SignUpScreen.onClick(SignUpScreen.java:93)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
You should have defined the variables email and password outside the method registerUser(). It seems that your Button is not correctly set as well.

```<code>package com.safariagaming.flix;

/**
 * Imports...
 */

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener {

   private String email = null;
   private String password = null;
   private FirebaseAuth.AuthStateListener mAuthListener;

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

  /**
   * Inits and code...
   */

    // Signup button on listener
    buttonSignup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        email = editTextEmail.getText().toString().trim();
        password = editTextPassword.getText().toString().trim();

        // Verifications
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(LoginActivity.this, R.string.empty_email, Toast.LENGTH_SHORT).show();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(LoginActivity.this, R.string.wrong_email, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, R.string.empty_password, Toast.LENGTH_SHORT).show();
        }

        // Authenticating user
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (!task.isSuccessful()) {
                            Toast.makeText(LoginActivity.this, R.string.wrong_credentials, Toast.LENGTH_SHORT).show();
                        } else {
                            goDashboard();
                            finish();
                        }
                    }
                });
             }
         });
      }
   // onStart() state listener
   @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
             mAuth.removeAuthStateListener(mAuthListener);
        }
    }
 }
</code>```

Title: Initializing Firebase auth object error

Body:
I am getting an error whenever I try to run the app:

Here is .java class:

package com.safariagaming.flix;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
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;

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener{

    //defining view objects
    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignup;
    private ProgressDialog progressDialog;

    //defining firebaseauth object
    private FirebaseAuth firebaseAuth;

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

        //initializing firebase auth object
        firebaseAuth = FirebaseAuth.getInstance();

        //initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonSignup = (Button) findViewById(R.id.buttonSignup);

        progressDialog = new ProgressDialog(this);

        //attaching listener to button
        buttonSignup.setOnClickListener(this);
    }

    private void registerUser(){

        //getting email and password from edit texts
        String email = editTextEmail.getText().toString().trim();
        String password  = editTextPassword.getText().toString().trim();

        //checking if email and passwords are empty
        if(TextUtils.isEmpty(email)){
            Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
            return;
        }

        //if the email and password are not empty
        //displaying a progress dialog

        progressDialog.setMessage("Registering Please Wait...");

        //creating a new user
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        //calling register method on click
        registerUser();
    }
}

(I think that the error happens because I am not initializing firebase auth object correctly)

Here is my XML class

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<LinearLayout
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="Signup" />

</LinearLayout>

Here is my error message that I am encountering

03-29 18:14:49.700 9230-9230/com.safariagaming.flix E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.safariagaming.flix, PID: 9230
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
                                                                      at com.safariagaming.flix.SignUpScreen.registerUser(SignUpScreen.java:72)
                                                                      at com.safariagaming.flix.SignUpScreen.onClick(SignUpScreen.java:93)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
You should have defined the variables email and password outside the method registerUser(). It seems that your Button is not correctly set as well.

package com.safariagaming.flix;

/**
 * Imports...
 */

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener {

   private String email = null;
   private String password = null;
   private FirebaseAuth.AuthStateListener mAuthListener;

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

  /**
   * Inits and code...
   */

    // Signup button on listener
    buttonSignup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        email = editTextEmail.getText().toString().trim();
        password = editTextPassword.getText().toString().trim();

        // Verifications
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(LoginActivity.this, R.string.empty_email, Toast.LENGTH_SHORT).show();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(LoginActivity.this, R.string.wrong_email, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, R.string.empty_password, Toast.LENGTH_SHORT).show();
        }

        // Authenticating user
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (!task.isSuccessful()) {
                            Toast.makeText(LoginActivity.this, R.string.wrong_credentials, Toast.LENGTH_SHORT).show();
                        } else {
                            goDashboard();
                            finish();
                        }
                    }
                });
             }
         });
      }
   // onStart() state listener
   @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
             mAuth.removeAuthStateListener(mAuthListener);
        }
    }
 }


来源: stackexchange

问:
Delete button code sometimes working
How to debug the following code?</p>

```<code>Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
        If vbYes Then
            Try
                con.Open()
                cmd.Connection = con
                cmd.CommandText = "Delete From TB_stinfo where id=?"
                cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
                cmd.ExecuteNonQuery()
                MessageBox.Show("one record is deleted")
            Catch ex As Exception
                MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
            Finally
                dt.Clear()
                Form1_Load(sender, e)
                clear()
                checkcon()
            End Try
        Else
            MsgBox("This record is not deleted")
        End If
</code>```

答:
I reformatted your code so it was more readable:

```<code>Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
    Try
        con.Open()
        cmd.Connection = con cmd.CommandText = "Delete From TB_stinfo where id=?"
        cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
        cmd.ExecuteNonQuery()
        MessageBox.Show("one record is deleted")
    Catch ex As Exception
        MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
    Finally
        dt.Clear()
        Form1_Load(sender, e)
        clear()
        checkcon()
    End Try
Else
    MsgBox("This record is not deleted")
End If
</code>```

The number one issue I see here is that we do not see what the value of the key is you're deleting on , nor the format of the data that's in the table to delete from. It's impossible to determine what exactly is wrong from this code.

My suggestion is to set a breakpoint on this line cmd.ExecuteNonQuery() and see what the value of TextBox1.Text is and make sure it is what you expect it to be, look for leading/trailing spaces or anything else that's unexpected..  Other than that there isn't much else to go on here in terms of context.

ContentLicense: CC BY-SA 3.0

Title: Delete button code sometimes working

Body:
How to debug the following code?

Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
        If vbYes Then
            Try
                con.Open()
                cmd.Connection = con
                cmd.CommandText = "Delete From TB_stinfo where id=?"
                cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
                cmd.ExecuteNonQuery()
                MessageBox.Show("one record is deleted")
            Catch ex As Exception
                MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
            Finally
                dt.Clear()
                Form1_Load(sender, e)
                clear()
                checkcon()
            End Try
        Else
            MsgBox("This record is not deleted")
        End If

Body:
I reformatted your code so it was more readable:

Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
    Try
        con.Open()
        cmd.Connection = con cmd.CommandText = "Delete From TB_stinfo where id=?"
        cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
        cmd.ExecuteNonQuery()
        MessageBox.Show("one record is deleted")
    Catch ex As Exception
        MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
    Finally
        dt.Clear()
        Form1_Load(sender, e)
        clear()
        checkcon()
    End Try
Else
    MsgBox("This record is not deleted")
End If

The number one issue I see here is that we do not see what the value of the key is you're deleting on , nor the format of the data that's in the table to delete from. It's impossible to determine what exactly is wrong from this code.

My suggestion is to set a breakpoint on this line cmd.ExecuteNonQuery() and see what the value of TextBox1.Text is and make sure it is what you expect it to be, look for leading/trailing spaces or anything else that's unexpected..  Other than that there isn't much else to go on here in terms of context.


问:
Further smooth the vertices of THREE.TextGeometry object via threex.dilategeometry.js
This is quite a specific question so I will do my best to articulate and explain the problem. So my goal is to create an effect that makes my TextGeometry look dilated or Bloated Text. I managed to find a Three.js extension called threex.dilategeometry.js will allows me to dilate the geometry of the object.

For example this is how my text normally looks:

With the inclusion of the threex.dilategeometry I apply a dilate factor of %15 so the text now looks like this:

So has you can see the effect works as expected. Please take a look at the code for this below:

```<code>    //Self made function to create text

    var one = new threeLab.asset.CreateMasterText(this.text,'Lambert');
    this.scene.add(one.wireframe);
    this.scene.add(one.mesh);

    //lets clone it
    var geoclone = one.geometry.clone();

    //need these to make it work
    geoclone.mergeVertices();
    //geoclone.computeCentroids();
    geoclone.computeFaceNormals();
    geoclone.computeVertexNormals();

    //the threex dilate effect
    THREEx.dilateGeometry(geoclone, 0.15);

    //create new material and add to a new mesh to create the halo effect
    var testMat     = new THREE.MeshNormalMaterial({color:0x222222});
    var meshHalo    = new THREE.Mesh(geoclone, testMat );

    this.scene.add( meshHalo );
</code>```

In order for the extension to work it is reliant on:

```<code>    geoclone.mergeVertices();
    geoclone.computeFaceNormals();
    geoclone.computeVertexNormals();
</code>```

Which I assume does all the vertices/face calculations to translate them with the dilate effect. One thing that I have noticed as a result of the effect with TextGeometry is that there are parts of the letters which have not translated well and you will see jagged edges on some of the letters:

So my question being, is it possible to somehow smooth further the vertices of the Text geometry to give a more smooth and less jagged appearance?

UPDATE 30/03/17

So I increased the bevel-segments of my extruded text geometry which helped to round it off better before I applied the threex effect

答:
So I increased the 'Bevelsegments' of the TextGeometry object to create a more rounder text. The whole purpose of the exercise is that I wanted to encase text with the object like below:

Many thanks @2pha :)

Body:
This is quite a specific question so I will do my best to articulate and explain the problem. So my goal is to create an effect that makes my TextGeometry look dilated or Bloated Text. I managed to find a Three.js extension called threex.dilategeometry.js will allows me to dilate the geometry of the object.

For example this is how my text normally looks:

With the inclusion of the threex.dilategeometry I apply a dilate factor of %15 so the text now looks like this:

So has you can see the effect works as expected. Please take a look at the code for this below:

    //Self made function to create text

    var one = new threeLab.asset.CreateMasterText(this.text,'Lambert');
    this.scene.add(one.wireframe);
    this.scene.add(one.mesh);

    //lets clone it
    var geoclone = one.geometry.clone();

    //need these to make it work
    geoclone.mergeVertices();
    //geoclone.computeCentroids();
    geoclone.computeFaceNormals();
    geoclone.computeVertexNormals();

    //the threex dilate effect
    THREEx.dilateGeometry(geoclone, 0.15);

    //create new material and add to a new mesh to create the halo effect
    var testMat     = new THREE.MeshNormalMaterial({color:0x222222});
    var meshHalo    = new THREE.Mesh(geoclone, testMat );

    this.scene.add( meshHalo );

In order for the extension to work it is reliant on:

    geoclone.mergeVertices();
    geoclone.computeFaceNormals();
    geoclone.computeVertexNormals();

Which I assume does all the vertices/face calculations to translate them with the dilate effect. One thing that I have noticed as a result of the effect with TextGeometry is that there are parts of the letters which have not translated well and you will see jagged edges on some of the letters:

So my question being, is it possible to somehow smooth further the vertices of the Text geometry to give a more smooth and less jagged appearance?

UPDATE 30/03/17

So I increased the bevel-segments of my extruded text geometry which helped to round it off better before I applied the threex effect


问:
After updating Android Studio 2.3, it does not debug completely
I have just updated my AS 2.2 to 2.3.

The problem is that now AS does not show me the error lines, if the app has an error, it shows:

```<code>Connected to the target VM, address: 'localhost:8600', transport: 'socket'
</code>```

I googled, the most thing that an other program uses this port, but I do not think so:

Can anyone help me?

if I try to change my Gradle version from 3.3 to 2.3, I get this error:

答:
I have fixes this Problem with new Insall  of Android Studio 2.2.3 (before SDK deinstalled too)
which has Gadle verion 2.1.14 and Plugin 2.2.3

I have opend my project again and ofcourse i must change the gradle version and plugin like from 3.3 to 2.1.14

I hope that will help other when they can  not find other way.

Body:
I have just updated my AS 2.2 to 2.3.

The problem is that now AS does not show me the error lines, if the app has an error, it shows:

Connected to the target VM, address: 'localhost:8600', transport: 'socket'

I googled, the most thing that an other program uses this port, but I do not think so:

Can anyone help me?

if I try to change my Gradle version from 3.3 to 2.3, I get this error:


问:
.htaccess file causing too many redirects error
I have the following redirect rules in my .htaccess file:

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule !^(.*)$ /index.php/$1 [L]
</code>```

This is causing a too many redirects error on my site. Moreover, this problem is occurring only on my local machine and the site is working just fine on the remote server.

Please help!

答:
```<code>RewriteRule !^(.*)$ index.php?/$1 [L]
</code>```

Try adding the question mark after index.php and check Michael Berkowski's answer.

Body:
I have the following redirect rules in my .htaccess file:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule !^(.*)$ /index.php/$1 [L]

This is causing a too many redirects error on my site. Moreover, this problem is occurring only on my local machine and the site is working just fine on the remote server.

Please help!

Body:
RewriteRule !^(.*)$ index.php?/$1 [L]

Try adding the question mark after index.php and check Michael Berkowski's answer.


问:
The right way to compare a System.Double to '0' (a number, int?)
I have this if expression,

```<code>void Foo()
{
    System.Double something = GetSomething();
    if (something == 0) //Comparison of floating point numbers with equality
                     // operator. Possible loss of precision while rounding value
        {}
}
</code>```

Is that expression equal with

```<code>void Foo()
{
    System.Double something = GetSomething();
    if (something < 1)
        {}
}
</code>```

? Because then I might have a problem, entering the if with e.g. a value of 0.9.

答:
If you simply want to suppress the warning, do this:

```<code>if (something.Equals(0.0))
</code>```

Of course, this is only a valid solution if you know that drift isn't a concern. I often do this to check if I'm about to divide by zero.

ContentLicense: CC BY-SA 4.0

Body:
I have this if expression,

void Foo()
{
    System.Double something = GetSomething();
    if (something == 0) //Comparison of floating point numbers with equality
                     // operator. Possible loss of precision while rounding value
        {}
}

Is that expression equal with

void Foo()
{
    System.Double something = GetSomething();
    if (something < 1)
        {}
}

? Because then I might have a problem, entering the if with e.g. a value of 0.9.

Body:
If you simply want to suppress the warning, do this:

if (something.Equals(0.0))

Of course, this is only a valid solution if you know that drift isn't a concern. I often do this to check if I'm about to divide by zero.


问:
How to use Visual Studio Team Services as a NuGet feed in LINQPad
I am using LINQPad 5 and VSTS (visual studio team services)
I have a NuGet feed (v3) in VSTS and I would like to use packages from there(private) in LINQPad

I have tried using the personal access token from VSTS as the NuGet password in LINQPad
I have tried putting the VSTS credential provider for nuget in AppData\Local\NuGet\CredentialProviders

I have tried putting the VSTS credential provider for nuget in AppData\Local\LINQPad\NuGet\CredentialProviders

I have tried using my VSTS username and password as the nuget credentials

How is this done? Is there a bug in LINQPad? Is this not supported yet?

答:
We managed to get it to work by using the v2 nuget API:

```<code>/nuget/v2
</code>```

instead of:

```<code>/nuget/v3/index.json
</code>```

Just put the personal access token in the password text box on LINQPad Package Sources dialog box.

Body:
We managed to get it to work by using the v2 nuget API:

/nuget/v2

instead of:

/nuget/v3/index.json

Just put the personal access token in the password text box on LINQPad Package Sources dialog box.


问:
Update facebook page status from that page itself
I'm trying to update the status of my page (from my page). I have been successful in posting to the wall of the page with the following code:

```<code>require_once 'facebook-php-sdk/src/facebook.php';

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => '...',
  'secret' => '...'
));

$attachment = array(
'access_token' => "...",
'message'=> "Hello World"
);

$facebook->api('/pageId/feed','POST', $attachment);
</code>```

But the post shows that I posted to the page from my account(ie: Joe Blogs) where I want it to show that it was posted by the page itself (ie: Page Name).

Or am I going about it the wrong way? Should I be trying to change the Status of the page (if possible)?

Any help would be greatly appreciated.

答:
pageID should be defined as the page your trying to post to:</p>

```<code>$pageID = "872348971237345"; //obtained from page's url

$status = $facebook->api($pageID.'/feed', 'post', $attachment);
</code>```

Body:
I'm trying to update the status of my page (from my page). I have been successful in posting to the wall of the page with the following code:

require_once 'facebook-php-sdk/src/facebook.php';

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => '...',
  'secret' => '...'
));

$attachment = array(
'access_token' => "...",
'message'=> "Hello World"
);

$facebook->api('/pageId/feed','POST', $attachment);

But the post shows that I posted to the page from my account(ie: Joe Blogs) where I want it to show that it was posted by the page itself (ie: Page Name).

Or am I going about it the wrong way? Should I be trying to change the Status of the page (if possible)?

Any help would be greatly appreciated.

Body:
pageID should be defined as the page your trying to post to:

$pageID = "872348971237345"; //obtained from page's url

$status = $facebook->api($pageID.'/feed', 'post', $attachment);

ContentLicense: CC BY-SA 2.5


问:
How to declare a C# Record Type?
I read on a blog that C# 7 will feature record types

```<code>class studentInfo(string StudentFName, string StudentMName, string StudentLName);
</code>```

However when I tried it, I get these errors

CS0116    A namespace cannot directly contain members such as fields or
  methods

  CS1022    Type or namespace definition, or end-of-file expected

  CS1514    { expected

How is this supposed to work?

Update: it's a feature of C# 9
 https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/

答:
Update:

C# 9 now contains record types.

```<code>public record Person
{
    public string LastName { get; }
    public string FirstName { get; }

    public Person(string first, string last) => (FirstName, LastName) = (first, last);
}
</code>```

Old answer:

Record types are not (yet) implemented in C#. See the proposal in the official GitHub repository:

https://github.com/dotnet/csharplang/blob/master/proposals/records.md

Discuss or vote at https://github.com/dotnet/csharplang/issues/39

Title: How to declare a C# Record Type?

Body:
I read on a blog that C# 7 will feature record types

class studentInfo(string StudentFName, string StudentMName, string StudentLName);

However when I tried it, I get these errors

CS0116    A namespace cannot directly contain members such as fields or
  methods

  CS1022    Type or namespace definition, or end-of-file expected

  CS1514    { expected

How is this supposed to work?

Update: it's a feature of C# 9
 https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/

Body:
Update:

C# 9 now contains record types.

public record Person
{
    public string LastName { get; }
    public string FirstName { get; }

    public Person(string first, string last) => (FirstName, LastName) = (first, last);
}

Old answer:

Record types are not (yet) implemented in C#. See the proposal in the official GitHub repository:

https://github.com/dotnet/csharplang/blob/master/proposals/records.md

Discuss or vote at https://github.com/dotnet/csharplang/issues/39


问:
Where relationship column equals?
I am trying to grab all records where Player's relationship called stats() has a column value of something. I would usually do ::where('column_name' 'column_value') for the players table, but how can I get ::where the relationship table's column equals to something?

```<code>Player::where('column_name', 'column_value')->get();
</code>```

But I want to check a column in the relationships table?

```<code>public function roleplay()
{
    return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id', 'id');
}
</code>```

答:
This will filter Player based on a related table</p>

```<code>Player::whereHas('roleplay', function($q){
   $q->where('column_name', 'value');
})->get();
</code>```

Title: Where relationship column equals?

Body:
I am trying to grab all records where Player's relationship called stats() has a column value of something. I would usually do ::where('column_name' 'column_value') for the players table, but how can I get ::where the relationship table's column equals to something?

Player::where('column_name', 'column_value')->get();

But I want to check a column in the relationships table?

public function roleplay()
{
    return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id', 'id');
}

Body:
This will filter Player based on a related table

Player::whereHas('roleplay', function($q){
   $q->where('column_name', 'value');
})->get();


问:
Questions of 'Designing for Performance' document at Android Developer site
In the Avoid Creating Objects section of the page Designing for Performance in the Android Developer documentation I read some paragraphs for which I am not able to visualize a code representation:

An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.

How would these 'parallel arrays of ints' look like? Would it be something like instead of having a method with a signature such as getData():int[][] returning
```
   [a][b]
   [c][d]
   [e][f]
```

... it would be better to have two methods, each returning one of the 'columns' of data? as in:
getFirstDimensionData():int[]
```
   [a]
   [c]
   [e]
```
and a second one getSecondDimensionData():int[]
```
   [b]
   [d]
   [f]
```

What is an 'array of (int,int) objects? ... something like an array of objects of a-type-not-yet-defined that has two int member instances defining its state?

The immediate next paragraph:

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.

... makes me think that the author is making up some sort of notation. I guess my key question is: is the author of the page using this (somethingX, somethingY) notation to refer to an arbitrary class that 'wraps' the elements inside the parentheses?

Finally, is this a standard notation or just something the author of the page created by himself and omitted to explain?

Can anyone, please, shed some light? :)

Thanks in advance,

Y

答:
What they're saying is that

```<code>class foo {
    int a;
    int b;
}

foo[] bar;
</code>```

Is slower than

```<code>int[] foo;
</code>```

With foo[row*2] being a and foo[row*2+1] being b.

The notation (foo, bar) is trying to symbolize a class that contains foo and bar (like (a,b) in my above example).

I don't believe it's a standard notation, but it wouldn't be the first time I've been proven wrong.

Body:
In the Avoid Creating Objects section of the page Designing for Performance in the Android Developer documentation I read some paragraphs for which I am not able to visualize a code representation:

An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.

How would these 'parallel arrays of ints' look like? Would it be something like instead of having a method with a signature such as getData():int[][] returning

   [a][b]
   [c][d]
   [e][f]

... it would be better to have two methods, each returning one of the 'columns' of data? as in:
getFirstDimensionData():int[]

   [a]
   [c]
   [e]

and a second one getSecondDimensionData():int[]

   [b]
   [d]
   [f]

What is an 'array of (int,int) objects? ... something like an array of objects of a-type-not-yet-defined that has two int member instances defining its state?

The immediate next paragraph:

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.

... makes me think that the author is making up some sort of notation. I guess my key question is: is the author of the page using this (somethingX, somethingY) notation to refer to an arbitrary class that 'wraps' the elements inside the parentheses?

Finally, is this a standard notation or just something the author of the page created by himself and omitted to explain?

Can anyone, please, shed some light? :)

Thanks in advance,

Y

Body:
What they're saying is that

class foo {
    int a;
    int b;
}

foo[] bar;

Is slower than

int[] foo;

With foo[row*2] being a and foo[row*2+1] being b.

The notation (foo, bar) is trying to symbolize a class that contains foo and bar (like (a,b) in my above example).

I don't believe it's a standard notation, but it wouldn't be the first time I've been proven wrong.


问:
Applying function to multiple files and saving data to data frame row by row?
I'm using for loop to apply several functions to text files in my work directory then write the new files to the directory using writeLines function. At the end of each iteration I would like to record the file name and number of rows in one data frame called d.f.

I created a data frame using:

```<code>d.f <- (file_name,number_of_rows)
</code>```

The code looks something like:

```<code>my_files <- list.files(path="path to my wd")
for (i in 1:length(my_files) { ..........
.........
.........
a <- readLines(my_files[i], skipNul=TRUE)
.........
.........
# here is the line I tried to add to record the data:
d.f <- rbind(my_files[i], length(a))
}
</code>```

Any suggestions how to make this work?

答:
```<code>my_files <- list.files(path="path to my wd")
a <-  readLines(my_files[1], skipNul=TRUE)
d.f <- data.frame(my_files[1],nrow(a))
for (i in 2:length(my_files) { ..........
.........
.........
a <- readLines(my_files[i], skipNul=TRUE)
.........
.........
dummy <- data.frame(my_files[i],nrow(a))
names(dummy) <- names(d.f)
d.f <- rbind(d.f,dummy)
}
</code>```

Body:
I'm using for loop to apply several functions to text files in my work directory then write the new files to the directory using writeLines function. At the end of each iteration I would like to record the file name and number of rows in one data frame called d.f.

I created a data frame using:

d.f <- (file_name,number_of_rows)

The code looks something like:

my_files <- list.files(path="path to my wd")
for (i in 1:length(my_files) { ..........
.........
.........
a <- readLines(my_files[i], skipNul=TRUE)
.........
.........
# here is the line I tried to add to record the data:
d.f <- rbind(my_files[i], length(a))
}

Any suggestions how to make this work?


问:
Htaccess breaks css and javascripts
```<code>RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]
</code>```

i have an htaccess code like this but it breaks css, javascripts and images. something happens like this

sayfa = css

id = style.css

答:
Use a condition before that rule to confirm the request isn't for js or css files.

```<code>RewriteCond %{THE_REQUEST} !(?:css|js)$
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]
</code>```

Regex demo: https://regex101.com/r/7WPKGh/1/

The ?: is a non-capture group. The | are alternations. The $ is the end of the string.

For jpeg, jpg, gif, and pngs it could be updated to:

```<code>RewriteCond %{THE_REQUEST} !(?:css|js|jpe?g|png|gif)$
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]
</code>```

Title: Htaccess breaks css and javascripts

Body:
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]

i have an htaccess code like this but it breaks css, javascripts and images. something happens like this

sayfa = css

id = style.css

Body:
Use a condition before that rule to confirm the request isn't for js or css files.

RewriteCond %{THE_REQUEST} !(?:css|js)$
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]

Regex demo: https://regex101.com/r/7WPKGh/1/

The ?: is a non-capture group. The | are alternations. The $ is the end of the string.

For jpeg, jpg, gif, and pngs it could be updated to:

RewriteCond %{THE_REQUEST} !(?:css|js|jpe?g|png|gif)$
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]


问:
Is a Ruby global variable different per process?
Is the value of a Ruby global variable different for each process?

For example, if I do $count = 5, will that change the value of $count on another process?

I'm wondering this because Puma clustered mode can fork multiple processes (workers), and I want to make sure $count is unique per worker.

答: Yes, globals should be unique per process.</p>


答:
Record types were on the roadmap for C# 7.0, but were ultimately delayed until a later version of the language.

To quote Mads Torgersen in reply to this blog post,

[Primary constructors] are still on the radar, along with the related concept of record types (which we considered for C# 7.0), and I am hopeful that we can land on a better design – maybe one that encompasses both.

As of C# 7's release, the GitHub proposal for this language feature still indicates that the implementation is "In Progress."

Title: How to declare a C# Record Type?


问:
g++ writing on memory and messing up with SSH process on BBB?
This is a crazy question and maybe it does not make sense at all, but I need some help here. I am developing an application in a BeagleBone Black (BBB) in C++ (compiling with g++). Just as a matter of information, BBB is an open-source hardware board (like Arduino or Raspberry Pi) which can be accessed through SSH (and only via SSH). I use opencv and zxing libraries. Everything was working fine until I started using zxing (Google's open source QR reader library). So when I started compiling my application including this library, it worked fine until I turn the BBB off. Once I turned it back on, I am not able to connect via SSH anymore. This is something really weird and I cannot think why would this happen.

Recently, I had a problem in my application related to the memory area where some variables are and those areas being overwritten (checking with gdb). So I started wondering that maybe the BBB do not handle memory properly and something related to the SSH process is being overwritten. I do not know how SSH processes are handled on a computer, so I do not know if this is some crazy idea. Can anyone think if it is possible that the compilation (or zxing) is related somehow with the SSH not working after that? Is that even possible?

BBB uses Angstrom distribution.

答: Probably the Beaglebone storage got full when you compiled zxing, so in next boots sshd can't be started.</p>


问:
How to get results from Facebook Insights API
I'm trying to get useful data from the Insights section using the the Graph API Explorer.

I've tried different metrics and dates, and the results for data is always empty.

I was able to look at my page dashboard for number of likes and select a range based on that, but I still don't see any data.

If the access_key is an issue, would it return an error saying so, or just return empty results?

Here is the debug output from a popular company that I would imagine has new likes in the past few weeks.

```<code>=== Query
  curl -i -X GET \
   "https://graph.facebook.com/v2.8/14226545351/insights/page_positive_feedback_by_type?since=1487788679&until=1490812690&access_token=<access token sanitized>"
=== Access Token Info
  {
    "perms": [
      "user_likes",
      "manage_pages",
      "pages_show_list",
      "public_profile"
    ],
    "page_id": 167544343274096,
    "user_id": "10152810337959467",
    "app_id": 145634995501895
  }
=== Parameters
- Query Parameters

  {
    "since": "1487788679",
    "until": "1490812690"
  }
- POST Parameters

  {}
=== Response
  {
    "data": [],
    "paging": {
      "previous": "https://graph.facebook.com/v2.8/14226545351/insights?access_token=<access token sanitized>&pretty=0&since=1484764668&until=1487788679&metric=page_positive_feedback_by_type",
      "next": "https://graph.facebook.com/v2.8/14226545351/insights?access_token=<access token sanitized>&pretty=0&since=1490812690&until=1493836701&metric=page_positive_feedback_by_type"
    },
    "__debug__": {}
  }
=== Debug Information from Graph API Explorer
- https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=14226545351%2Finsights%2Fpage_positive_feedback_by_type%3Fsince%3D1487788679%26until%3D1490812690&version=v2.8
</code>```

Is anyone able to give an actual working example? I have not come across any yet.

答:
I discovered in the Graph API explorer, when you generate an access token, you need to give it permission "read_insights".

Also, this will only work on a page which your account has access to that given object.

Unfortunately the documentation is pretty vague in this area and there was no permissions error message give.

Body:
I'm trying to get useful data from the Insights section using the the Graph API Explorer.

I've tried different metrics and dates, and the results for data is always empty.

I was able to look at my page dashboard for number of likes and select a range based on that, but I still don't see any data.

If the access_key is an issue, would it return an error saying so, or just return empty results?

Here is the debug output from a popular company that I would imagine has new likes in the past few weeks.

=== Query
  curl -i -X GET \
   "https://graph.facebook.com/v2.8/14226545351/insights/page_positive_feedback_by_type?since=1487788679&until=1490812690&access_token=<access token sanitized>"
=== Access Token Info
  {
    "perms": [
      "user_likes",
      "manage_pages",
      "pages_show_list",
      "public_profile"
    ],
    "page_id": 167544343274096,
    "user_id": "10152810337959467",
    "app_id": 145634995501895
  }
=== Parameters
- Query Parameters

  {
    "since": "1487788679",
    "until": "1490812690"
  }
- POST Parameters

  {}
=== Response
  {
    "data": [],
    "paging": {
      "previous": "https://graph.facebook.com/v2.8/14226545351/insights?access_token=<access token sanitized>&pretty=0&since=1484764668&until=1487788679&metric=page_positive_feedback_by_type",
      "next": "https://graph.facebook.com/v2.8/14226545351/insights?access_token=<access token sanitized>&pretty=0&since=1490812690&until=1493836701&metric=page_positive_feedback_by_type"
    },
    "__debug__": {}
  }
=== Debug Information from Graph API Explorer
- https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=14226545351%2Finsights%2Fpage_positive_feedback_by_type%3Fsince%3D1487788679%26until%3D1490812690&version=v2.8

Is anyone able to give an actual working example? I have not come across any yet.


问:
Customised Outlook 2010 Navigation pane
I want to create a custom navigation pane for Outlook.
My current setup (see image) works OK for dragging and dropping individual emails to the appropriate folder. NB I'm using Outlook 2010

Currently I have a button in the Quick Access Toolbar which runs the OpenFolders vba sub, and tiles them all out (or closes them)

However ideally I want them all in a single window.

Also I'm not sure how to open with all folders visible - in my case this means approx. 3 columns of folder names (this doesn't change much so could be hardcoded).
Names would ideally be clipped to decrease screen width.

Ultimately this single 'navigation pane' would also have a little button at the RHS of each folder name, which would automatically move the email in the reading pane and select the next email (rather than dragging and dropping).

This is my current simple code (NB GetFolderPath returns a reference to the relevant folder from the path below the inbox)

```<code>Global myEmailRoot
Global lastOFTime

Sub OpenFolders()
    myEmailRoot = "me@email.com\Inbox\"

    'Single Clicking the OpenFolders button will open the windows, or if already open then retile them in order
    'Double Clicking the OpenFolders button in the Quick Access Toolbar will close the windows

    If sortIfFolderWindowsExist Then
        If Timer() - lastOFTime < 5 Then
            closeFolderWindows
        End If
        Exit Sub
    End If

    lastOFTime = Timer()

    Dim oFolder As Outlook.Folder

    Set oFolder = GetFolderPath("CCG")
    oFolder.Display
    resizeWin (0)

    Set oFolder = GetFolderPath("Mental Health")
    oFolder.Display
    resizeWin (1)

    Set oFolder = GetFolderPath("Personal")
    oFolder.Display
    resizeWin (2)

    Set oFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
    oFolder.Display
    resizeWin (3)

End Sub

Sub resizeWin(col)
    Outlook.Application.ActiveExplorer.Left = col * 150
    Outlook.Application.ActiveExplorer.Top = 0
    Outlook.Application.ActiveExplorer.Width = 1920 - (col * 150)
    Outlook.Application.ActiveExplorer.Height = 1024
End Sub

Function sortIfFolderWindowsExist()
    ' resort windows (if they exist) so layering is correct
    i = 1
    curColPix = 0
    While i > 0
        For i = Explorers.Count To 0 Step -1
            If Explorers(i).Left = curColPix Then
                Explorers(i).Activate
                Exit For
            End If
        Next
        curColPix = curColPix + 150
        If curColPix > 450 Then
            sortIfFolderWindowsExist = True
            Exit Function
        End If
    Wend
End Function

Function closeFolderWindows()
    ' resort windows (if they exist) so layering is correct
    i = 1
    curColPix = 450
    maxWin = 0
    minWin = 9999
    While i > 0
        For i = Explorers.Count To 1 Step -1
            If Explorers(i).Left = curColPix Then
                If i > maxWin Then maxWin = i
                If i < minWin Then minWin = i
                correctWins = correctWins + 1
                Explorers(i).Activate
                If maxWin - minWin = 3 Then
                    For j = 1 To 4
                        Explorers(minWin).Close
                    Next
                    Exit Function
                End If
                Exit For
            End If
        Next
        curColPix = curColPix - 150
    Wend
End Function

Function GetFolderPath(ByVal folderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer

    On Error GoTo GetFolderPath_Error
    If Left(folderPath, 2) = "\\" Then
        folderPath = Right(folderPath, Len(folderPath) - 2)
    Else
        folderPath = myEmailRoot & folderPath
    End If

    'Convert folderpath to array
    FoldersArray = Split(folderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.Item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPath = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPath = oFolder
    Exit Function

GetFolderPath_Error:
    Set GetFolderPath = Nothing
    Exit Function
End Function
</code>```

答: No, there's no method to expand/collapse folder hierarchies in the Navigation Pane.  Your only relevant options are to set Explorer.CurrentFolder or Folder.Display</p>

Title: Customised Outlook 2010 Navigation pane

Body:
I want to create a custom navigation pane for Outlook.
My current setup (see image) works OK for dragging and dropping individual emails to the appropriate folder. NB I'm using Outlook 2010

Currently I have a button in the Quick Access Toolbar which runs the OpenFolders vba sub, and tiles them all out (or closes them)

However ideally I want them all in a single window.

Also I'm not sure how to open with all folders visible - in my case this means approx. 3 columns of folder names (this doesn't change much so could be hardcoded).
Names would ideally be clipped to decrease screen width.

Ultimately this single 'navigation pane' would also have a little button at the RHS of each folder name, which would automatically move the email in the reading pane and select the next email (rather than dragging and dropping).

This is my current simple code (NB GetFolderPath returns a reference to the relevant folder from the path below the inbox)

Global myEmailRoot
Global lastOFTime

Sub OpenFolders()
    myEmailRoot = "me@email.com\Inbox\"

    'Single Clicking the OpenFolders button will open the windows, or if already open then retile them in order
    'Double Clicking the OpenFolders button in the Quick Access Toolbar will close the windows

    If sortIfFolderWindowsExist Then
        If Timer() - lastOFTime < 5 Then
            closeFolderWindows
        End If
        Exit Sub
    End If

    lastOFTime = Timer()

    Dim oFolder As Outlook.Folder

    Set oFolder = GetFolderPath("CCG")
    oFolder.Display
    resizeWin (0)

    Set oFolder = GetFolderPath("Mental Health")
    oFolder.Display
    resizeWin (1)

    Set oFolder = GetFolderPath("Personal")
    oFolder.Display
    resizeWin (2)

    Set oFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
    oFolder.Display
    resizeWin (3)

End Sub

Sub resizeWin(col)
    Outlook.Application.ActiveExplorer.Left = col * 150
    Outlook.Application.ActiveExplorer.Top = 0
    Outlook.Application.ActiveExplorer.Width = 1920 - (col * 150)
    Outlook.Application.ActiveExplorer.Height = 1024
End Sub

Function sortIfFolderWindowsExist()
    ' resort windows (if they exist) so layering is correct
    i = 1
    curColPix = 0
    While i > 0
        For i = Explorers.Count To 0 Step -1
            If Explorers(i).Left = curColPix Then
                Explorers(i).Activate
                Exit For
            End If
        Next
        curColPix = curColPix + 150
        If curColPix > 450 Then
            sortIfFolderWindowsExist = True
            Exit Function
        End If
    Wend
End Function

Function closeFolderWindows()
    ' resort windows (if they exist) so layering is correct
    i = 1
    curColPix = 450
    maxWin = 0
    minWin = 9999
    While i > 0
        For i = Explorers.Count To 1 Step -1
            If Explorers(i).Left = curColPix Then
                If i > maxWin Then maxWin = i
                If i < minWin Then minWin = i
                correctWins = correctWins + 1
                Explorers(i).Activate
                If maxWin - minWin = 3 Then
                    For j = 1 To 4
                        Explorers(minWin).Close
                    Next
                    Exit Function
                End If
                Exit For
            End If
        Next
        curColPix = curColPix - 150
    Wend
End Function

Function GetFolderPath(ByVal folderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer

    On Error GoTo GetFolderPath_Error
    If Left(folderPath, 2) = "\\" Then
        folderPath = Right(folderPath, Len(folderPath) - 2)
    Else
        folderPath = myEmailRoot & folderPath
    End If

    'Convert folderpath to array
    FoldersArray = Split(folderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.Item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPath = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPath = oFolder
    Exit Function

GetFolderPath_Error:
    Set GetFolderPath = Nothing
    Exit Function
End Function


问:
Would tf.upgrade.py work to update tensorflow files 0.x to 1.0.1 or does it only upgrade to 1.0 version
https://www.tensorflow.org/install/migration

Please help! I need to migrate to the latest version

答:
Keep in mind that the migrate script will not migrate everything, i.e. there will likely be some manual changes required!

When I upgraded last month, some API changes like tf.unpack become tf.unstack but more subtle changes like the position of the axis= argument in tf.split required more careful work. Good luck!


问:
Counting Chars in EditText Changed Listener
In my project I have an EditText. I want to count the characters in the EditText, and show that number it in a TextView. I have written the following code and it works fine. However, my problem is when I click Backspace it counts up, but I need to decrement the number. How can I consider Backspace?

```<code>tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        i++;
        tv.setText(String.valueOf(i) + " / " + String.valueOf(charCounts));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});
</code>```

答:
Use

```<code>s.length()
</code>```

The following was once suggested in one of the answers, but its very inefficient

```<code>textMessage.getText().toString().length()
</code>```

Body:
In my project I have an EditText. I want to count the characters in the EditText, and show that number it in a TextView. I have written the following code and it works fine. However, my problem is when I click Backspace it counts up, but I need to decrement the number. How can I consider Backspace?

tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        i++;
        tv.setText(String.valueOf(i) + " / " + String.valueOf(charCounts));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});

Body:
Use

s.length()

The following was once suggested in one of the answers, but its very inefficient

textMessage.getText().toString().length()


问:
Ordinal scale does not color in properly despite unknown being implied?
I am attempting to make a monitoring interface that checks Windows services and determines its state and start_type using var colorScale = d3.scale.ordinal().

If the state is "RUNNING", I want to color in the cell green. If the state is "STOPPED", I want to color in the cell red. Any other values, to color in white.

Here is my full code:

```<code><html>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
    <script type="text/javascript">
        var parsedCSV = d3.csv("servicecheckupreport.csv", function(parsedCSV){

    var colorScale = d3.scale.ordinal()
        .domain([" ","RUNNING","STOPPED"])
        .range(["White","MediumSpringGreen","OrangeRed"]);

    var body = d3.select("body");
    var headers = Object.keys(parsedCSV[0]);

    var table = body.append('table')
    var thead = table.append('thead')
    var tbody = table.append('tbody');

    var head = thead.selectAll('th')
        .data(headers)
        .enter()
        .append('th')
        .text(function(d) {
            return d;
        });

    var rows = tbody.selectAll('tr')
        .data(parsedCSV)
        .enter()
        .append('tr');

    var cells = rows.selectAll('td')
        .data(function(d) {
            return Object.values(d);
        })
        .enter()
        .append('td')
        .style("background-color", function(d) {
          if(d){
            return colorScale(d);
            }else{
              return "White";
              }
        })
        .text(function(d) {
            return d;
        });
        });
</script>
</code>```

This is the output:

The problem is, the code will color in the ip address and hostname when those cells should be white.

I am attempting to invoke ordinal.unknown() by using a third value in my array as listed below:

```<code>var colorScale = d3.scale.ordinal()
    .domain([" ","RUNNING","STOPPED"])
    .range(["White","MediumSpringGreen","OrangeRed"]);
</code>```

The first value of the array " " indicates any values that are outside of the second and third on the array will be colored in white, yet it still doesn't.

答:
unknown is only available in D3 v4.x, and you have to set it explicitly:

var data = ["RUNNING", "foo", "STOPPED", "RUNNING", "bar", "STOPPED"];

var colorScale = d3.scaleOrdinal()
    .domain(["RUNNING","STOPPED"])
    .unknown("White")
    .range(["MediumSpringGreen","OrangeRed"]);

data.forEach(function(d){ console.log(colorScale(d))});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

A v3 alternative is calling colorScale only for the two defined values:

var data = ["RUNNING", "foo", "STOPPED", "RUNNING", "bar", "STOPPED"];

var colorScale = d3.scale.ordinal()
    .domain(["RUNNING","STOPPED"])
    .range(["MediumSpringGreen","OrangeRed"]);

data.forEach(function(d){
    if(d === "RUNNING" || d === "STOPPED"){
        console.log("White");
    } else {
    console.log(colorScale(d));
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script></code>```

Besides that, what you said...

The first value of the array " " indicates any values that are outside of the second and third on the array will be colored in white.

... is not correct. A space is not a wildcard for any other value.

And, to finish, I don't know your data structure, but it seems to me that no value is matching (for instance, "STATE: 4 RUNNING" is different from "RUNNING"), and the scale is just cycling through the range. To read more about this, have a look at my answer here: https://stackoverflow.com/a/40675350/5768908

Body:
I am attempting to make a monitoring interface that checks Windows services and determines its state and start_type using var colorScale = d3.scale.ordinal().

If the state is "RUNNING", I want to color in the cell green. If the state is "STOPPED", I want to color in the cell red. Any other values, to color in white.

Here is my full code:

This is the output:

The problem is, the code will color in the ip address and hostname when those cells should be white.

I am attempting to invoke ordinal.unknown() by using a third value in my array as listed below:

var colorScale = d3.scale.ordinal()
    .domain([" ","RUNNING","STOPPED"])
    .range(["White","MediumSpringGreen","OrangeRed"]);

The first value of the array " " indicates any values that are outside of the second and third on the array will be colored in white, yet it still doesn't.

Body:
unknown is only available in D3 v4.x, and you have to set it explicitly:

var data = ["RUNNING", "foo", "STOPPED", "RUNNING", "bar", "STOPPED"];

var colorScale = d3.scaleOrdinal()
    .domain(["RUNNING","STOPPED"])
    .unknown("White")
    .range(["MediumSpringGreen","OrangeRed"]);

data.forEach(function(d){ console.log(colorScale(d))});

<script src="https://d3js.org/d3.v4.min.js"></script>

A v3 alternative is calling colorScale only for the two defined values:

var data = ["RUNNING", "foo", "STOPPED", "RUNNING", "bar", "STOPPED"];

var colorScale = d3.scale.ordinal()
    .domain(["RUNNING","STOPPED"])
    .range(["MediumSpringGreen","OrangeRed"]);

data.forEach(function(d){
    if(d === "RUNNING" || d === "STOPPED"){
        console.log("White");
    } else {
    console.log(colorScale(d));
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Besides that, what you said...

The first value of the array " " indicates any values that are outside of the second and third on the array will be colored in white.

... is not correct. A space is not a wildcard for any other value.

And, to finish, I don't know your data structure, but it seems to me that no value is matching (for instance, "STATE: 4 RUNNING" is different from "RUNNING"), and the scale is just cycling through the range. To read more about this, have a look at my answer here: https://stackoverflow.com/a/40675350/5768908


问:
How to set TTL in Java based app for DynamoDB
Hi I need to set time to live programmatically for a table in DynamoDB via AWS Java SDK. Is it possible? I know that TTL feature is introduced recently - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html

UPDATE:
There is no special annotaion, but we can do it manually:

```<code>@DynamoDBAttribute
private long ttl;
</code>```

and configure it as ttl in AWS - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html

```<code>long now = Instant.now().getEpochSecond(); // unix time
long ttl = 60 * 60 * 24; // 24 hours in sec
setTtl(ttl + now); // when object will be expired
</code>```

答:
Code Sample here.              </p>

```<code>  //Then set ttl field like below for days in java
    //ttl 60 days
    Calendar cal = Calendar.getInstance(); //current date and time
    cal.add(Calendar.DAY_OF_MONTH, 60); //add days
    double ttl =  (cal.getTimeInMillis() / 1000L);
</code>```

Body:
Hi I need to set time to live programmatically for a table in DynamoDB via AWS Java SDK. Is it possible? I know that TTL feature is introduced recently - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html

UPDATE:
There is no special annotaion, but we can do it manually:

@DynamoDBAttribute
private long ttl;

and configure it as ttl in AWS - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html

long now = Instant.now().getEpochSecond(); // unix time
long ttl = 60 * 60 * 24; // 24 hours in sec
setTtl(ttl + now); // when object will be expired

Body:
Code Sample here.

  //Then set ttl field like below for days in java
    //ttl 60 days
    Calendar cal = Calendar.getInstance(); //current date and time
    cal.add(Calendar.DAY_OF_MONTH, 60); //add days
    double ttl =  (cal.getTimeInMillis() / 1000L);


答:
I would suggest just checking if the file exists using a rewrite condition:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]
</code>```

This essentially says, if the requested filename does not actually exist on disk and is not a directory that exists on disk, then try to apply the rule.

Title: Htaccess breaks css and javascripts

Body:
I would suggest just checking if the file exists using a rewrite condition:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)$ index.php?sayfa=$1&id=$2 [L]

This essentially says, if the requested filename does not actually exist on disk and is not a directory that exists on disk, then try to apply the rule.


问:
Python/Pandas: For loop to sum moving range and append to new column
I am fairly new to Python and Pandas so please forgive the uninformed question I'm posing here.

I have a dataframe (QReport) that looks like so:

```<code>DATE            STATE       SALES
2010-12-01       AL          10
2010-12-02       AL          13
2010-12-03       AL          16
2010-12-04       AL          10
2010-12-05       AL          10
2010-12-06       AL          2
2010-12-07       AL          5
2010-12-08       AL          5
</code>```

I'd like to create a seven day sales total column that sums seven day slices of sales and adds that total to a new '7DTotal' column. I've been trying to get at this through a for loop, setting x and y variables as 0 (zero) and 6 indexes which I try to increment each run through the loop:

```<code>x = 0
y = 6
for i in QReport:
    QReport['7DTotal'] = sum(QReport['SALES'][x:y])
    x = x + 1
    y = y + 1
</code>```

This approach, however, is not working and is returning the same value for every row in the newly-added 7DTotal column.

Expected output would be:

```<code>DATE            STATE       SALES   7DTotal
2010-12-01       AL          10        0
2010-12-02       AL          13        0
2010-12-03       AL          16        0
2010-12-04       AL          10        0
2010-12-05       AL          10        0
2010-12-06       AL          2         0
2010-12-07       AL          5         66
2010-12-08       AL          5         61
</code>```

Thanks in advance for any help!

答:
You should use rolling sum:

```<code>QReport['7DTotal'] = pd.rolling_sum(QReport.SALES, 7).fillna(0)
</code>```

or

```<code># Suggested by a commenter
QReport['7DTotal'] = QReport.rolling(7).sum().fillna(0)
</code>```

(The first six elements of the column will be undefined, and fillna fills them with 0s.)

Body:
I am fairly new to Python and Pandas so please forgive the uninformed question I'm posing here.

I have a dataframe (QReport) that looks like so:

DATE            STATE       SALES
2010-12-01       AL          10
2010-12-02       AL          13
2010-12-03       AL          16
2010-12-04       AL          10
2010-12-05       AL          10
2010-12-06       AL          2
2010-12-07       AL          5
2010-12-08       AL          5

I'd like to create a seven day sales total column that sums seven day slices of sales and adds that total to a new '7DTotal' column. I've been trying to get at this through a for loop, setting x and y variables as 0 (zero) and 6 indexes which I try to increment each run through the loop:

x = 0
y = 6
for i in QReport:
    QReport['7DTotal'] = sum(QReport['SALES'][x:y])
    x = x + 1
    y = y + 1

This approach, however, is not working and is returning the same value for every row in the newly-added 7DTotal column.

Expected output would be:

DATE            STATE       SALES   7DTotal
2010-12-01       AL          10        0
2010-12-02       AL          13        0
2010-12-03       AL          16        0
2010-12-04       AL          10        0
2010-12-05       AL          10        0
2010-12-06       AL          2         0
2010-12-07       AL          5         66
2010-12-08       AL          5         61

Thanks in advance for any help!

Body:
You should use rolling sum:

QReport['7DTotal'] = pd.rolling_sum(QReport.SALES, 7).fillna(0)

or

# Suggested by a commenter
QReport['7DTotal'] = QReport.rolling(7).sum().fillna(0)

(The first six elements of the column will be undefined, and fillna fills them with 0s.)


问:
bcrypt-ruby - You don't have bcrypt-ruby installed in your application
I'm  beginner in Ruby on Rails and trying to learn from http://ruby.railstutorial.org/  I'm creating sample_app and got stuck at chapter 6.

My Ruby version: ruby 2.0.0p195 (2013-05-14) [i386-mingw32]

My Rails version: Rails 4.0.0

I have following line in my GemFile:

```<code>gem 'bcrypt-ruby', '~> 3.0.0'
</code>```

If I type gem list bcrypt-ruby , it shows bcrypt-ruby (3.0.1) . But if I try to create user, I get error saying

You don't have bcrypt-ruby installed in your application. Please add it to your Gemfile and run bundle install

I searched a lot on rails website, bcrypt website & even stackoverflow. But, nothing worked. Please help.

答: I've faced this issue recently (as have many others). As per ladyruby723 posted here, use gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt' in your gemfile file.

Body:
I'm  beginner in Ruby on Rails and trying to learn from http://ruby.railstutorial.org/  I'm creating sample_app and got stuck at chapter 6.

My Ruby version: ruby 2.0.0p195 (2013-05-14) [i386-mingw32]

My Rails version: Rails 4.0.0

I have following line in my GemFile:

gem 'bcrypt-ruby', '~> 3.0.0'

If I type gem list bcrypt-ruby , it shows bcrypt-ruby (3.0.1) . But if I try to create user, I get error saying

You don't have bcrypt-ruby installed in your application. Please add it to your Gemfile and run bundle install

I searched a lot on rails website, bcrypt website & even stackoverflow. But, nothing worked. Please help.


问:
Issues with DB after publishing via Database Publishing Wizard from MSFT
I work on quite a few DotNetNuke sites, and occasionally (I haven't figured out the common factor yet), when I use the Database Publishing Wizard from Microsoft to create scripts for the site I've created on my Dev server, after running the scripts at the host (usually GoDaddy.com), and uploading the site files, I get an error...  I'm 99.9% sure that it's not file related, so not sure where to begin in the DB.  Unfortunately with DotNetNuke you don't get the YSOD, but a generic error, with no real way to find the actual exception that has occured.

I'm just curious if anyone has had similar deployment issues using the Database Publishing Wizard, and if so, how they overcame them?  I own the RedGate toolset, but some hosts like GoDaddy don't allow you to direct connect to their servers...

答:
Test your generated scripts on a new local database (using the free SQL Express product or the full meal deal). If it runs fine locally, then you can be confident that it will run elsewhere, all things being equal.

If it bombs when you run it locally, use the process of elimination and work your way through the script execution to find the offending code.

My hunch is that the order of scripts could be off. I think I've had that happen before with the database publishing wizard.

OwnerDisplayName: Purple Ant

OwnerDisplayName: AndrewDotHay


问:
How to insert statements that contains apostrophes into Sqlite database
In my iPhone app I am using an Sqlite database. I have a requirement to store the text in database. The text contains apostrophes.

For example:

```<code>Insert into tbl_insert values ('It is Steve's Shirt');
</code>```

How to store this kind of statements in Sqlite database?

答:
This is something that I go through in SQL Server and MySQL as well. You should definitely use parameterised SQL queries

See this page for examples in many languages.

I strongly discourage the use of literal strings in the update statement. Use parameterized queries. There's no reason to compromise security

You can write a function which replaces each instance of character ' with ''

http://www.kamath.com/codelibrary/cl003_apostrophe.asp

Body:
In my iPhone app I am using an Sqlite database. I have a requirement to store the text in database. The text contains apostrophes.

For example:

Insert into tbl_insert values ('It is Steve's Shirt');

How to store this kind of statements in Sqlite database?


问:
multiplying 3 arrays in JavaScript and saving the result in 4th array and sort them
how to multiply 2nd and 3rd array and save in 4th array and in the and sort them?

I tried to do it by javascript by couldn't get any useful help anywhere

答:
$(function(){
 var itemsArray = [
  { 'item' : 'Hammer', 'Price' : 15.00, 'qty' : 5},
  { 'item' : 'Drill', 'Price' : 49.99, 'qty' : 3},
  { 'item' : 'Screwdriver', 'Price' : 3.00, 'qty' : 6},
  { 'item' : 'Wrench', 'Price' : 6.25, 'qty' : 4},
  { 'item' : 'Pliers', 'Price' : 4.00, 'qty' : 2},
  { 'item' : 'Ratchet', 'Price' : 12.50, 'qty' : 1},
  { 'item' : 'Chisel', 'Price' : 8.50, 'qty' : 7},
  { 'item' : 'Prybar', 'Price' : 7.25, 'qty' : 4},
  { 'item' : 'Saw', 'Price' : 14.50, 'qty' : 6},
  { 'item' : 'Sander', 'Price' : 27.99, 'qty' : 2}
  ];

  var resultArray = itemsArray.map((item) =>{ return {'item' : item.item, 'price' : item.Price, 'qty' : item.qty, 'extprice' : item.qty * item.Price} })

    resultArray.sort((a, b) => {
    var itemA = a.item.toUpperCase(); // ignore upper and lowercase
  var itemB = b.item.toUpperCase(); // ignore upper and lowercase
  if (itemA < itemB) {
    return -1;
  }
  if (itemA > itemB) {
    return 1;
  }

  // names must be equal
  return 0;

  });
  console.log(JSON.stringify(resultArray))

  resultArray.forEach((item) =>{
   $('table tbody').append(`<tr><td>${item.item}</td><td>${item.price}</td><td>${item.qty}</td><td>${item.extprice}</td></tr>`)
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
   border: 1px solid black;
}</code>```

Item	Price	Qty	Ext Price

```

Body:
$(function(){
 var itemsArray = [
  { 'item' : 'Hammer', 'Price' : 15.00, 'qty' : 5},
  { 'item' : 'Drill', 'Price' : 49.99, 'qty' : 3},
  { 'item' : 'Screwdriver', 'Price' : 3.00, 'qty' : 6},
  { 'item' : 'Wrench', 'Price' : 6.25, 'qty' : 4},
  { 'item' : 'Pliers', 'Price' : 4.00, 'qty' : 2},
  { 'item' : 'Ratchet', 'Price' : 12.50, 'qty' : 1},
  { 'item' : 'Chisel', 'Price' : 8.50, 'qty' : 7},
  { 'item' : 'Prybar', 'Price' : 7.25, 'qty' : 4},
  { 'item' : 'Saw', 'Price' : 14.50, 'qty' : 6},
  { 'item' : 'Sander', 'Price' : 27.99, 'qty' : 2}
  ];

  var resultArray = itemsArray.map((item) =>{ return {'item' : item.item, 'price' : item.Price, 'qty' : item.qty, 'extprice' : item.qty * item.Price} })

    resultArray.sort((a, b) => {
    var itemA = a.item.toUpperCase(); // ignore upper and lowercase
  var itemB = b.item.toUpperCase(); // ignore upper and lowercase
  if (itemA < itemB) {
    return -1;
  }
  if (itemA > itemB) {
    return 1;
  }

  // names must be equal
  return 0;

  });
  console.log(JSON.stringify(resultArray))

  resultArray.forEach((item) =>{
   $('table tbody').append(`<tr><td>${item.item}</td><td>${item.price}</td><td>${item.qty}</td><td>${item.extprice}</td></tr>`)
  })
})

table {
   border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Item</td><td>Price</td><td>Qty</td><td>Ext Price</td>
</tr>
</tbody>
</table>


问:
Unable to open/edit LESS file in Visual Studio 2015
I have a .LESS file but I'm unable to open/edit it in Visual Studio 2015?

I can open the file fine in sublime text, notepad etc?

Is there something I'm missing in Visual Studio 2015?

答: I had the same problem. Disabling Workbench worked for me. I didn't have to disable Web Essentials or anything else.</p>


问:
Display edit picture row per row in table with mouseenter AngularJS
i have a problem with my code , i already make a code with mouseover but it was very slow to display per row my picture edit , so i read that mouseenter is faster ( i hope because i have normaly 2000 row),

but i have a problems , it show me all the pictures when i go to the tr,

this is my full code html

```<code>    <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-mouseenter="mouseIn($event)" ng-mouseleave="mouseOut($event)" ng-repeat="x in records">
<td>{{x}}</td>
<td>
<div class="editNucleo" ng-show="editNucleo">
<input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
</div>
</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
  ]

   $scope.mouseIn = function (event) {
        $scope.editNucleo = true;
    }

    $scope.mouseOut = function (event) {
        $scope.editNucleo = false;
    }
});
</script>

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

i need just display and hide the picture in the right row when i make the mouseenter , mouseleave

答:
Your script dont know which specific index to show when mouse entered try this no function required

```<code> <!DOCTYPE html>
 <html>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

 <body ng-app="myApp" ng-controller="myCtrl">
 <table>
  <tr ng-mouseenter="editNucleo = $index" ng mouseleave="editNucleo = null" ng-repeat="x in records">
  <td>{{x}}</td>
  <td>
  <div class="editNucleo" ng-show="editNucleo == $index">
  <input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
  </div>
  </td>
  </tr>
  </table>
  <script>
  var app = angular.module("myApp", []);
   app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
   ];
   $scope.editNucleo = null;
  });
</script>
</code>```

Body:
i have a problem with my code , i already make a code with mouseover but it was very slow to display per row my picture edit , so i read that mouseenter is faster ( i hope because i have normaly 2000 row),

but i have a problems , it show me all the pictures when i go to the tr,

this is my full code html

    <!DOCTYPE html>

{{x}}

<input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />

i need just display and hide the picture in the right row when i make the mouseenter , mouseleave

Body:
Your script dont know which specific index to show when mouse entered try this no function required

 <!DOCTYPE html>
 <html>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

 <body ng-app="myApp" ng-controller="myCtrl">
 <table>
  <tr ng-mouseenter="editNucleo = $index" ng mouseleave="editNucleo = null" ng-repeat="x in records">
  <td>{{x}}</td>
  <td>
  <div class="editNucleo" ng-show="editNucleo == $index">
  <input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
  </div>
  </td>
  </tr>
  </table>
  <script>
  var app = angular.module("myApp", []);
   app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
   ];
   $scope.editNucleo = null;
  });
</script>


问:
Can't deploy UWP app to xbox one
So I have setup my Xbox One as a dev device and actually was able to run my app on my Xbox, but in order to use some new APIs to turn off scaling and what not I had to change my app target version to Build 14332. Unfortunately, after doing this, I am now not able to publish or debug my app to my Xbox and I am not getting very helpful clues as to why not.

I even reverted the target version back to Build 10240 but I am still getting this error:

Severity  Code    Description Project File    Line    Suppression State
  Error     DEP0700 : Registration of the app failed. Deployment Register
  operation with target volume C: on Package
  MyCompany.MyApp_1.1.19.0_x64__5wbv4ypmprn7c from:
  (AppxManifest.xml)  failed with error 0x80070002. See
  http://go.microsoft.com/fwlink/?LinkId=235160 for help diagnosing app
  deployment issues. (0x80073cf9)   MyCompany.MyApp

EDIT: I found a work around. Restart my Xbox One. Literally, every time I run my app, I have to restart my Xbox One! :(

答: I've ran into the really similar problem, however with running on the remote machine. The solution was the same as Pedro Pombeiro did on his Xbox One. I opened Windows Settings > Update & Security > For developers and Unpair All. Problem was solved and I could deploy and run the app on remote PC.

Title: Can't deploy UWP app to xbox one


问:
Browser identifying automatic anchor click as popup
I have a purchase success page that has an anchor to show the invoice as a PDF such as

```<code><a href="link" id="anchorId" target="targetId" style="display: none;">Click</a>
</code>```

That purchase invoice has to be opened automatically, so I did like below:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $('#anchorId')[0].click();
    });
</script>
</code>```

But browsers are not showing the new tab indicating this as a popup. I haven't used window.open so as not to have this kind of browser behaviour.

Is there anything doable to accomplish my use case?

答: You're described behavior is a popup by the browser's (and most folk's) definition so no, it is not likely you will find a workaround.  If you do it would be considered an "exploit".</p>

Body:
I have a purchase success page that has an anchor to show the invoice as a PDF such as

Click

That purchase invoice has to be opened automatically, so I did like below:

But browsers are not showing the new tab indicating this as a popup. I haven't used window.open so as not to have this kind of browser behaviour.

Is there anything doable to accomplish my use case?


问:
Bigcommerce Stencil - How to find top-level category inside category each
I am new to stencil and I am trying to get the top-level category when on a non-top-level category page. I am looking to loop through the categories but only print the items listed below the top-level. Here is what I am using that works if I am on a top-level page but doesnt if I am on a subcategory page.

```<code>{{#each categories}}
            {{#if name '===' ../category.name}}
              <li class="parent {{#if children}}has-children tier-dropdown{{/if}}">
                <a href="{{url}}">{{name}}</a>
                {{#if children}}
                  <ul class="children">
                    <li class="parent-all"><a href="{{url}}">{{lang 'common.navigation_all'}} {{name}}</a></li>
                    {{#each children}}
                      <li>
                        <a href="{{url}}">{{name}}</a>
                        {{#if children}}
                          <ul class="children2">
                            <li class="parent-all"><a href="{{url}}">{{lang 'common.navigation_all'}} {{name}}</a></li>
                            {{#each children}}
                                <li {{#if children}}class="tier-dropdown"{{/if}}>
                                    <a {{#if children}}class="tier-toggle"{{/if}} href="{{url}}">{{name}}</a>
                                    {{#if children}}
                                        <ul class="tier-panel">
                                            <li class="parent-all"><a href="{{url}}">{{lang 'common.navigation_all'}} {{name}}</a></li>
                                            {{#each children}}
                                                <li {{#if children}}class="tier-dropdown"{{/if}}>
                                                    <a {{#if children}}class="tier-toggle"{{/if}} href="{{url}}">{{name}}</a>
                                                    {{#if children}}
                                                        <ul class="tier-panel">
                                                            <li class="parent-all"><a href="{{url}}">{{lang 'common.navigation_all'}} {{name}}</a></li>
                                                            {{#each children}}
                                                                {{> components/common/site-navigation-submenus}}
                                                            {{/each}}
                                                        </ul>
                                                    {{/if}}
                                                </li>
                                            {{/each}}
                                        </ul>
                                    {{/if}}
                                </li>
                            {{/each}}
                          </ul>
                        {{/if}}
                      </li>
                    {{/each}}
                  </ul>
                {{/if}}
              </li>
             {{/if}}
        {{/each}}
</code>```

The main point of emphasis is line 2 as that if statement needs to always point to the top-level category even when on a subcategory page.

I have though about using breadcrumbs but cant come up with a way to use that inside the categories each loop.

答:
There isn't a pure Stencil/Handlebars.js solution for this. You need to be able to do a recursive upward search of the parent categories which BigCommerce doesn't have a helper for. The best solution is to restyle or add items to the list during page load.

You can either use the page url, depending on the structure of your URLs, or breadcrumbs as you mentioned.

TL;DR you need javascript.

Body:
I am new to stencil and I am trying to get the top-level category when on a non-top-level category page. I am looking to loop through the categories but only print the items listed below the top-level. Here is what I am using that works if I am on a top-level page but doesnt if I am on a subcategory page.

{{#each categories}}
            {{#if name '===' ../category.name}}

                {{name}}
                {{#if children}}

{{lang 'common.navigation_all'}} {{name}}

                    {{#each children}}

                        {{name}}
                        {{#if children}}

{{lang 'common.navigation_all'}} {{name}}

                            {{#each children}}

                                    {{name}}
                                    {{#if children}}

{{lang 'common.navigation_all'}} {{name}}

                                            {{#each children}}

                                                    {{name}}
                                                    {{#if children}}

{{lang 'common.navigation_all'}} {{name}}

                                                            {{#each children}}
                                                                {{> components/common/site-navigation-submenus}}
                                                            {{/each}}

                                                    {{/if}}

                                            {{/each}}

                                    {{/if}}

                            {{/each}}

                        {{/if}}

                    {{/each}}

                {{/if}}

             {{/if}}
        {{/each}}

The main point of emphasis is line 2 as that if statement needs to always point to the top-level category even when on a subcategory page.

I have though about using breadcrumbs but cant come up with a way to use that inside the categories each loop.