问:
Replace bokeh object inside div on-click
I'm able to get the bokeh object to render properly inside a div on the webpage. The bokeh object is returned via Flask and is generated based on a user-click. However, my problem is that on every user-click, the new bokeh object that is produced, gets appended to the div.

I've read about the .html() way of replacing content, and I've also read about document.getElementById, but I'm not sure how to replace my div content and avoid the append. Any help is appreciated.

The relevant snippet from my index.html

```<code>rows.forEach(row => {

    row.addEventListener("click", () => {
        var pic = <<my_url>> + ($(row).attr("data-href"));
        $.ajax({
            data : {},
            dataType: "json",
            type : 'GET',
            url : <<my flask app path>>
        })
        .then(function(response) {return response;})
        .then(function(item) {
            Bokeh.embed.embed_item(item);
        })
    });
});
</code>```

答:
emptying the contents of the div on-click is the approach I took to resolve my situation. i.e., </p>

```<code>$(div).empty();
</code>```

Body:
I'm able to get the bokeh object to render properly inside a div on the webpage. The bokeh object is returned via Flask and is generated based on a user-click. However, my problem is that on every user-click, the new bokeh object that is produced, gets appended to the div.

I've read about the .html() way of replacing content, and I've also read about document.getElementById, but I'm not sure how to replace my div content and avoid the append. Any help is appreciated.

The relevant snippet from my index.html

rows.forEach(row => {

    row.addEventListener("click", () => {
        var pic = <<my_url>> + ($(row).attr("data-href"));
        $.ajax({
            data : {},
            dataType: "json",
            type : 'GET',
            url : <<my flask app path>>
        })
        .then(function(response) {return response;})
        .then(function(item) {
            Bokeh.embed.embed_item(item);
        })
    });
});

Body:
emptying the contents of the div on-click is the approach I took to resolve my situation. i.e.,

$(div).empty();


来源: stackexchange

问:
Shortcut Items, Quick Actions 3D Touch swift
I am for some reason having some troubles figuring out the Shortcut Items in my app. I have followed all the tutorials and I believe that I have done everything right; however, it is acting really weird. The problem is that when you completely close out that app and do the 3D Touch Shortcut item on the home screen, it takes you to the correct part of the app as it should; however, when the app is open in the background (like you just click the home button) it doesn't take you to the correct part of the app, it just opens it. This is really odd and I am not sure what to do because I have followed all the instructions. Thank you so much!

Code:

```<code>func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {

    if shortcutItem.type == "com.myapp.newMessage" {

        let sb = UIStoryboard(name: "Main", bundle: nil)

        let vc = sb.instantiateViewController(withIdentifier: "RecentVC") as! UITabBarController
         vc.selectedIndex = 2 //this takes me to the contacts controller

        let root = UIApplication.shared.keyWindow?.rootViewController

        root?.present(vc, animated: false, completion: {
            completionHandler(true)
        })

    } else if shortcutItem.type == "com.myapp.groups" {
        let sb = UIStoryboard(name: "Main", bundle: nil)

        let vc = sb.instantiateViewController(withIdentifier: "RecentVC") as! UITabBarController
        vc.selectedIndex = 1 //this takes me to the groups controller

        let root = UIApplication.shared.keyWindow?.rootViewController

        root?.present(vc, animated: false, completion: {
            completionHandler(true)
        })

    } else {
        //more short cut items I will add later
    }
}
</code>```

NOTE: these are static Shortcut Items, and I configured them in the info.plist file, This function that was presented is the only place in the app besides the info.plist file that have anything about the Shortcut Items.

EDIT: This seems like an issue with the RootViewController, because I have tried multiple different ways of doing this, and it still gives me the same warning message

2017-11-22 22:36:46.473195-0800 QuickChat2.0[3055:1068642] Warning: Attempt to present  on  whose view is not in the window hierarchy!

I just tried to accomplish my goals this way through this post but it gives me the exact same results as before.

答:
I think a cleaner method is to set your flags in the performActionFor method, then check for them once your VC loads. Using this notification will handle the shortcut every time the app becomes active, including launch.</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Sends notification if active app is reentered to handle quick actions
    NotificationCenter.default.addObserver(self, selector: #selector(handleQuickActions), name: UIApplication.didBecomeActiveNotification, object: nil)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am for some reason having some troubles figuring out the Shortcut Items in my app. I have followed all the tutorials and I believe that I have done everything right; however, it is acting really weird. The problem is that when you completely close out that app and do the 3D Touch Shortcut item on the home screen, it takes you to the correct part of the app as it should; however, when the app is open in the background (like you just click the home button) it doesn't take you to the correct part of the app, it just opens it. This is really odd and I am not sure what to do because I have followed all the instructions. Thank you so much!

Code:

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {

    if shortcutItem.type == "com.myapp.newMessage" {

        let sb = UIStoryboard(name: "Main", bundle: nil)

        let vc = sb.instantiateViewController(withIdentifier: "RecentVC") as! UITabBarController
         vc.selectedIndex = 2 //this takes me to the contacts controller

        let root = UIApplication.shared.keyWindow?.rootViewController

        root?.present(vc, animated: false, completion: {
            completionHandler(true)
        })

    } else if shortcutItem.type == "com.myapp.groups" {
        let sb = UIStoryboard(name: "Main", bundle: nil)

        let vc = sb.instantiateViewController(withIdentifier: "RecentVC") as! UITabBarController
        vc.selectedIndex = 1 //this takes me to the groups controller

        let root = UIApplication.shared.keyWindow?.rootViewController

        root?.present(vc, animated: false, completion: {
            completionHandler(true)
        })

    } else {
        //more short cut items I will add later
    }
}

NOTE: these are static Shortcut Items, and I configured them in the info.plist file, This function that was presented is the only place in the app besides the info.plist file that have anything about the Shortcut Items.

EDIT: This seems like an issue with the RootViewController, because I have tried multiple different ways of doing this, and it still gives me the same warning message

2017-11-22 22:36:46.473195-0800 QuickChat2.0[3055:1068642] Warning: Attempt to present  on  whose view is not in the window hierarchy!

I just tried to accomplish my goals this way through this post but it gives me the exact same results as before.

Body:
I think a cleaner method is to set your flags in the performActionFor method, then check for them once your VC loads. Using this notification will handle the shortcut every time the app becomes active, including launch.

override func viewDidLoad() {
    super.viewDidLoad()
    // Sends notification if active app is reentered to handle quick actions
    NotificationCenter.default.addObserver(self, selector: #selector(handleQuickActions), name: UIApplication.didBecomeActiveNotification, object: nil)

ContentLicense: CC BY-SA 4.0


问:
Not getting Image URL String to FirebaseDatabase
I want my firebase database to initialize with the user profile pic image URL I try to add this but i thing profileImageUrl variable not initialize with ImageUri variable? pls help to get this thing done...

i just want 5th variable profile image link initialize with image url string that is come from URI variable but it's not initialize

this is my project logcat

```<code>2020-05-31 11:23:23.475 23993-23993/com.ramzan.snnstocks D/WindowClient: Add to mViews: DecorView@3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal@878094
2020-05-31 11:23:23.479 23993-23993/com.ramzan.snnstocks D/ViewRootImpl[UserRegistration]: hardware acceleration is enabled, this = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}
2020-05-31 11:23:23.482 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:23.688 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:23:26.588 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:32.551 23993-23993/com.ramzan.snnstocks I/UserRegistration: OnActivityResult: RESULT OK
2020-05-31 11:23:32.566 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:32.596 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:24:12.578 23993-23993/com.ramzan.snnstocks D/WindowClient: Remove from mViews: DecorView@3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal@878094
2020-05-31 11:24:16.941 23993-23993/com.ramzan.snnstocks D/UserRegistration: onSuccess : https://firebasestorage.googleapis.com/v0/b/snn-stocks-c12fc.appspot.com/o/Profile_Image%2F9352682709.jpeg?alt=media&token=801f8e9d-cf5f-4d0a-890a-57823d50973a
</code>```

here is my UserRegistration Activity...

```<code>import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.ramzan.snnstocks.Model.Users;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;

import de.hdodenhof.circleimageview.CircleImageView;

public class UserRegistration extends AppCompatActivity {

    private Spinner spinner;
    private CircleImageView mImageView;
    private static final int PICK_IMAGE = 101;
    private EditText et_name, et_mobile, et_pass;
    private Button btn_user;
    private static String name, mobile, pass, spinner_port_place,profile_image_url;

    private ProgressDialog loadingBar;
    private DatabaseReference mDatabase;
    private Bitmap bitmap;
    private static final String TAG = "UserRegistration";

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

        mImageView = findViewById(R.id.profile_image);
        loadingBar = new ProgressDialog(this);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        spinner = findViewById(R.id.spinner_port_place);

        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(UserRegistration.this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Port_Name));
        myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(myAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner_port_place = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // initializing UI components
        et_name = findViewById(R.id.textInputEditTextLayout_name);
        et_mobile = findViewById(R.id.textInputEditTextLayout_mobile);
        et_pass = findViewById(R.id.textInputEditTextLayout_pass);
        btn_user = findViewById(R.id.btn_user_registration);

        //onClick listner to Button

        btn_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name = et_name.getText().toString();
                mobile = et_mobile.getText().toString();
                pass = et_pass.getText().toString();

                if (name.isEmpty()) {
                    et_name.setError("Full Name Required");
                    et_name.requestFocus();

                } else if (mobile.isEmpty()) {
                    et_mobile.setError("Mobile Number is Required");
                    et_mobile.requestFocus();

                } else if (pass.isEmpty()) {
                    et_pass.setError("Choose Your Password");
                    et_pass.requestFocus();
                } else {

                    uploadData();

                }

            }
        });

        //OnClick Listner on Image View

        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager())
                        != null) {
                    startActivityForResult(intent, PICK_IMAGE);
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE) {
            switch (resultCode) {
                case RESULT_OK:

                    Log.i(TAG, "OnActivityResult: RESULT OK");
                    bitmap = (Bitmap) data.getExtras().get("data");
                    mImageView.setImageBitmap(bitmap);
                    break;

                case RESULT_CANCELED:
                    Log.i(TAG, "OnActivityResult: RESULT CANCELLED");
                    break;

                default:
                    break;

            }
        }
    }

    // upload data from here...

    private void uploadData() {

        loadingBar.setTitle("Registering Retailer....");
        loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
        loadingBar.setCanceledOnTouchOutside(false);

        loadingBar.show();

        handleUpload(bitmap);
        //Initialize Firebase Database;

        mDatabase = FirebaseDatabase.getInstance().getReference();

        createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
    }

    // profile image upload

    private void handleUpload(Bitmap bitmap) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        final StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile_Image").child(mobile + ".jpeg");

        reference.putBytes(baos.toByteArray())
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Toast.makeText(UserRegistration.this, "Upload Successfull...", Toast.LENGTH_SHORT).show();
                        getDownloadUrl(reference);
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "onFailure : ", e.getCause());
            }
        });

    }

    private void getDownloadUrl(StorageReference reference) {
        reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                profile_image_url = uri.toString();
                Log.d(TAG, "onSuccess : " + uri);
                initializeUrl(uri);
            }
        });
    }

    private void initializeUrl(Uri uri) {

        profile_image_url = uri.toString();
    }

    private void createUserDatabase(final String name, final String mobile, final String pass, final String spinner_port_place, final String profile_image_url) {

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (!(dataSnapshot.child("Users").child(mobile).exists() && !(dataSnapshot.child("Admin").child(mobile).exists()))) {

                    Users new_user = new Users(name, mobile, pass, spinner_port_place, profile_image_url);

                    mDatabase.child("Users").child(mobile).setValue(new_user).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            loadingBar.dismiss();
                            Toast.makeText(UserRegistration.this, "Your Account Has Been Created Successfully !", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(UserRegistration.this, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            loadingBar.dismiss();
                            String msg;
                            msg = e.toString();
                            Toast.makeText(UserRegistration.this, "Error : " + msg, Toast.LENGTH_LONG).show();

                        }
                    });

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

}
</code>```

答:
You can try this:

```<code>private void uploadData() {

    loadingBar.setTitle("Registering Retailer....");
    loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
    loadingBar.setCanceledOnTouchOutside(false);

    loadingBar.show();

    handleUpload(bitmap);
}

private void initializeUrl(Uri uri) {

    profile_image_url = uri.toString();

    //Initialize Firebase Database;

    mDatabase = FirebaseDatabase.getInstance().getReference();

    createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
}
</code>```

And use addListenerForSingleValueEvent instead of addValueEventListener. More useful.

Upload the profile picture first, then save the user to the database.

This is not the case with your code. You save the user to the database and pass to the other screen until the profile picture is uploaded.

Body:
I want my firebase database to initialize with the user profile pic image URL I try to add this but i thing profileImageUrl variable not initialize with ImageUri variable? pls help to get this thing done...

i just want 5th variable profile image link initialize with image url string that is come from URI variable but it's not initialize

this is my project logcat

2020-05-31 11:23:23.475 23993-23993/com.ramzan.snnstocks D/WindowClient: Add to mViews: DecorView@3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal@878094
2020-05-31 11:23:23.479 23993-23993/com.ramzan.snnstocks D/ViewRootImpl[UserRegistration]: hardware acceleration is enabled, this = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}
2020-05-31 11:23:23.482 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:23.688 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:23:26.588 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:32.551 23993-23993/com.ramzan.snnstocks I/UserRegistration: OnActivityResult: RESULT OK
2020-05-31 11:23:32.566 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView@3fca5d8[UserRegistration]
2020-05-31 11:23:32.596 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:24:12.578 23993-23993/com.ramzan.snnstocks D/WindowClient: Remove from mViews: DecorView@3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal@878094
2020-05-31 11:24:16.941 23993-23993/com.ramzan.snnstocks D/UserRegistration: onSuccess : https://firebasestorage.googleapis.com/v0/b/snn-stocks-c12fc.appspot.com/o/Profile_Image%2F9352682709.jpeg?alt=media&token=801f8e9d-cf5f-4d0a-890a-57823d50973a

here is my UserRegistration Activity...

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.ramzan.snnstocks.Model.Users;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;

import de.hdodenhof.circleimageview.CircleImageView;

public class UserRegistration extends AppCompatActivity {

    private Spinner spinner;
    private CircleImageView mImageView;
    private static final int PICK_IMAGE = 101;
    private EditText et_name, et_mobile, et_pass;
    private Button btn_user;
    private static String name, mobile, pass, spinner_port_place,profile_image_url;

    private ProgressDialog loadingBar;
    private DatabaseReference mDatabase;
    private Bitmap bitmap;
    private static final String TAG = "UserRegistration";

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

        mImageView = findViewById(R.id.profile_image);
        loadingBar = new ProgressDialog(this);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        spinner = findViewById(R.id.spinner_port_place);

        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(UserRegistration.this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Port_Name));
        myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(myAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner_port_place = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // initializing UI components
        et_name = findViewById(R.id.textInputEditTextLayout_name);
        et_mobile = findViewById(R.id.textInputEditTextLayout_mobile);
        et_pass = findViewById(R.id.textInputEditTextLayout_pass);
        btn_user = findViewById(R.id.btn_user_registration);

        //onClick listner to Button

        btn_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name = et_name.getText().toString();
                mobile = et_mobile.getText().toString();
                pass = et_pass.getText().toString();

                if (name.isEmpty()) {
                    et_name.setError("Full Name Required");
                    et_name.requestFocus();

                } else if (mobile.isEmpty()) {
                    et_mobile.setError("Mobile Number is Required");
                    et_mobile.requestFocus();

                } else if (pass.isEmpty()) {
                    et_pass.setError("Choose Your Password");
                    et_pass.requestFocus();
                } else {

                    uploadData();

                }

            }
        });

        //OnClick Listner on Image View

        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager())
                        != null) {
                    startActivityForResult(intent, PICK_IMAGE);
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE) {
            switch (resultCode) {
                case RESULT_OK:

                    Log.i(TAG, "OnActivityResult: RESULT OK");
                    bitmap = (Bitmap) data.getExtras().get("data");
                    mImageView.setImageBitmap(bitmap);
                    break;

                case RESULT_CANCELED:
                    Log.i(TAG, "OnActivityResult: RESULT CANCELLED");
                    break;

                default:
                    break;

            }
        }
    }

    // upload data from here...

    private void uploadData() {

        loadingBar.setTitle("Registering Retailer....");
        loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
        loadingBar.setCanceledOnTouchOutside(false);

        loadingBar.show();

        handleUpload(bitmap);
        //Initialize Firebase Database;

        mDatabase = FirebaseDatabase.getInstance().getReference();

        createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
    }

    // profile image upload

    private void handleUpload(Bitmap bitmap) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        final StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile_Image").child(mobile + ".jpeg");

        reference.putBytes(baos.toByteArray())
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Toast.makeText(UserRegistration.this, "Upload Successfull...", Toast.LENGTH_SHORT).show();
                        getDownloadUrl(reference);
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "onFailure : ", e.getCause());
            }
        });

    }

    private void getDownloadUrl(StorageReference reference) {
        reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                profile_image_url = uri.toString();
                Log.d(TAG, "onSuccess : " + uri);
                initializeUrl(uri);
            }
        });
    }

    private void initializeUrl(Uri uri) {

        profile_image_url = uri.toString();
    }

    private void createUserDatabase(final String name, final String mobile, final String pass, final String spinner_port_place, final String profile_image_url) {

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (!(dataSnapshot.child("Users").child(mobile).exists() && !(dataSnapshot.child("Admin").child(mobile).exists()))) {

                    Users new_user = new Users(name, mobile, pass, spinner_port_place, profile_image_url);

                    mDatabase.child("Users").child(mobile).setValue(new_user).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            loadingBar.dismiss();
                            Toast.makeText(UserRegistration.this, "Your Account Has Been Created Successfully !", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(UserRegistration.this, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            loadingBar.dismiss();
                            String msg;
                            msg = e.toString();
                            Toast.makeText(UserRegistration.this, "Error : " + msg, Toast.LENGTH_LONG).show();

                        }
                    });

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

}

Body:
You can try this:

private void uploadData() {

    loadingBar.setTitle("Registering Retailer....");
    loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
    loadingBar.setCanceledOnTouchOutside(false);

    loadingBar.show();

    handleUpload(bitmap);
}

private void initializeUrl(Uri uri) {

    profile_image_url = uri.toString();

    //Initialize Firebase Database;

    mDatabase = FirebaseDatabase.getInstance().getReference();

    createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
}

And use addListenerForSingleValueEvent instead of addValueEventListener. More useful.

Upload the profile picture first, then save the user to the database.

This is not the case with your code. You save the user to the database and pass to the other screen until the profile picture is uploaded.


问:
Images does not download Properly
I've downlaod the images from particular URL using for loop in case some products having more than 5 images .. when i click the product button some of the images only download not all images..but when i debugg the coressponding code it will download all the images.. how is possible ...

This is My Code

```<code>    for (int i = 0; i < obj.Count; i++)
            {
                PartNAme = (obj[i].ToString().Split('='))[1];
                _prtnm = PartNAme.ToString().Split(';')[0];

                _final_URI = _URI + _Prod_name + '/' + _prtnm + ".GIF";

                WebClient client = new WebClient();

                string strtempname = DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");

                rnd = new Random(100);

                string _strfile = "PNImage" + strtempname + rnd.Next().ToString() + ".gif";

                string _path = "../Images/PNImage/" + _strfile;

                string _PPath = Server.MapPath(_path);

                  client.DownloadFile(_final_URI, _PPath);
}
</code>```

答:
I think it's the Random variable causes this issue. Try to put
rnd = new Random(100) out of the loop and see how it works. Usually, the random is the same value if it runs fast.</p>

Title: Images does not download Properly

Body:
I've downlaod the images from particular URL using for loop in case some products having more than 5 images .. when i click the product button some of the images only download not all images..but when i debugg the coressponding code it will download all the images.. how is possible ...

This is My Code

    for (int i = 0; i < obj.Count; i++)
            {
                PartNAme = (obj[i].ToString().Split('='))[1];
                _prtnm = PartNAme.ToString().Split(';')[0];

                _final_URI = _URI + _Prod_name + '/' + _prtnm + ".GIF";

                WebClient client = new WebClient();

                string strtempname = DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");

                rnd = new Random(100);

                string _strfile = "PNImage" + strtempname + rnd.Next().ToString() + ".gif";

                string _path = "../Images/PNImage/" + _strfile;

                string _PPath = Server.MapPath(_path);

                  client.DownloadFile(_final_URI, _PPath);
}


问:
XAMPP phpmyadmin always showing error in processing request
I've just installed the latest version of XAMPP version 7.4.1.
Everytime i go to localhost/phpmyadmin it always shows me this message below. It keeps showing the message every time i try to create a table in the test database so i can't even create a table. I tried creating a new database, but it just shows as processing request and it takes forever but nothing changes.

PS, i redownloaded XAMPP because previously there was a problem with the mysql keep shutting down unexpectedly which i am unable to fix.

答:
Had same essue and fixed it using steps i tried and worked for me...

change main port in xampp -> config-> Services and Port Setting -> main
port to other than 80. eg.:- 81 then follow steps below:
1. in httpd.conf file
 -> change Listen 80 to Listen 81
 -> change ServerName localhost:80 to localhost only without port number
2. In httpd-vhost.conf file: add code below

```<code>NameVirtualHost *:81
<VirtualHost *:81>
   DocumentRoot "C:\XAMPP\htdocs"
   ServerName localhost
</VirtualHost>
</code>```

Stop and start xampp

Test phpmyadmin using url
localhost:81/phpmyadmin
Then good to go...
Steps above is shown in the image links below

Body:
Had same essue and fixed it using steps i tried and worked for me...

change main port in xampp -> config-> Services and Port Setting -> main
port to other than 80. eg.:- 81 then follow steps below:
1. in httpd.conf file
 -> change Listen 80 to Listen 81
 -> change ServerName localhost:80 to localhost only without port number
2. In httpd-vhost.conf file: add code below

NameVirtualHost *:81
<VirtualHost *:81>
   DocumentRoot "C:\XAMPP\htdocs"
   ServerName localhost
</VirtualHost>

Stop and start xampp

Test phpmyadmin using url
localhost:81/phpmyadmin
Then good to go...
Steps above is shown in the image links below


问:
Multiple people using a VBA userform on a common Database
So, my requirements need me to distribute a VBA userform excel file to different people in my organization, and a single database file which will be kept in a network drive (or any other shared location).
I have tested it and it works fine. To save the entry, it downloads the database from network location, saves the inputs from userform and then closes back the file.
My only concern is that what if multiple people are filling the userform at the same time and pressing the submit button. Will all the information get recorded on database or some entries might get lost?

Please guide me on this, and suggest me any thing that needs to be done.

答:
It depends on a few things but you could lose data. One mechanism I've used in the past where people wanted to download files is implement a checkout system - this pseudo-code which you could have in the distributed UserForm file:

```<code>Sub DownloadAndSave()
' In the location in the network folder:
' If a file exists called "MyData_CHECKOUT.xlsm" then
      'deny a save
' Else
      ' RENAME the target file to "MyData_CHECKOUT.xlsm"
' Download "MyData_CHEKOUT.xlsm", make changes, save file to network as "MyData.xlsm"
' Delete the MyData_CHECKOUT.xlsm" file
End Sub
</code>```

Although if people have access to the network drive, can they not just OPEN the file directly to make changes (instead of downloading, changing and resaving) - you can then use this code to check if the book is already open, to deny changes being made at the same time:

```<code>Function IsWorkBookOpen(FileName As String) as Boolean
Dim ff As Long, ErrNo As Long

On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0

Select Case ErrNo
Case 0:    IsWorkBookOpen = False
Case 70:   IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
</code>```

Body:
It depends on a few things but you could lose data. One mechanism I've used in the past where people wanted to download files is implement a checkout system - this pseudo-code which you could have in the distributed UserForm file:

Sub DownloadAndSave()
' In the location in the network folder:
' If a file exists called "MyData_CHECKOUT.xlsm" then
      'deny a save
' Else
      ' RENAME the target file to "MyData_CHECKOUT.xlsm"
' Download "MyData_CHEKOUT.xlsm", make changes, save file to network as "MyData.xlsm"
' Delete the MyData_CHECKOUT.xlsm" file
End Sub

Although if people have access to the network drive, can they not just OPEN the file directly to make changes (instead of downloading, changing and resaving) - you can then use this code to check if the book is already open, to deny changes being made at the same time:

Function IsWorkBookOpen(FileName As String) as Boolean
Dim ff As Long, ErrNo As Long

On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0

Select Case ErrNo
Case 0:    IsWorkBookOpen = False
Case 70:   IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function


问:
Three.js webgl video texture CORS issue on safari
In my vuejs nuxt static site hosted on netlify, I'm trying to use a mp4 video hosted on Vimeo Pro as a video texture in three.js with the following (simplified version)

```<code>// create video dom element
let video_ele = document.createElement('video')
video_ele.className = 'video_texture'
video_ele.setAttribute('playsinline', true)
video_ele.muted = true
video_ele.loop = true
video_ele.autoplay = true
video_ele.crossOrigin = 'anonymous'
video_ele.src = "https://vimeo-video-url-here.....mp4"
document.body.appendChild(video_ele)

// create video texture from video
let video_texture = new THREE.VideoTexture(video_ele)
video_texture.minFilter = THREE.LinearFilter
video_texture.magFilter = THREE.LinearFilter
video_texture.format = THREE.RGBFormat

// map video texture to material
material = new THREE.MeshStandardMaterial({
    color: 0xa8a8a8,
    map: video_texture
})
</code>```

Everything else works fine on chrome, firefox and also chrome mobile browser.
but in Safari 13 on mac os and ios 13, i get this error thrown in the console

```<code>THREE.WebGLState:
SecurityError: The operation is insecure.
</code>```

I tried replacing the vimeo video with urls of other videos hosted elsewhere and i get same error in safari only.

I'm pretty sure its a CORS issue because when i replace the vimeo or external url with a static video hosted within same host (netlify), it works fine.

I also tried appending a timestamp to the video url just to be sure its not a cache issue, but still no luck

Wondering how can i make this work with an externally hosted video like vimeo?

答:
Upon further testing, it seems to me that the issue was caused by the 302 redirect to their CDN that happens when you use a vimeo file url.

As @gman pointed out, there's a similar issue on Soundclound and i found that the solution provided there worked for my case too.
How to get Safari 12 to process audio from soundcloud?

I solved it by making an async fetch request to get the CDN url and then passing it to the video.src. Works in safari mac and ios (13) now  now!

```<code>  async function getMediaURLForTrack(texture_to_update, passed_url) {
    await fetch(passed_url, {
      method: 'HEAD'
    })
    .then((response) => {
      texture_to_update.src = response.url
    });
  }
</code>```

Body:
In my vuejs nuxt static site hosted on netlify, I'm trying to use a mp4 video hosted on Vimeo Pro as a video texture in three.js with the following (simplified version)

// create video dom element
let video_ele = document.createElement('video')
video_ele.className = 'video_texture'
video_ele.setAttribute('playsinline', true)
video_ele.muted = true
video_ele.loop = true
video_ele.autoplay = true
video_ele.crossOrigin = 'anonymous'
video_ele.src = "https://vimeo-video-url-here.....mp4"
document.body.appendChild(video_ele)

// create video texture from video
let video_texture = new THREE.VideoTexture(video_ele)
video_texture.minFilter = THREE.LinearFilter
video_texture.magFilter = THREE.LinearFilter
video_texture.format = THREE.RGBFormat

// map video texture to material
material = new THREE.MeshStandardMaterial({
    color: 0xa8a8a8,
    map: video_texture
})

Everything else works fine on chrome, firefox and also chrome mobile browser.
but in Safari 13 on mac os and ios 13, i get this error thrown in the console

THREE.WebGLState:
SecurityError: The operation is insecure.

I tried replacing the vimeo video with urls of other videos hosted elsewhere and i get same error in safari only.

I'm pretty sure its a CORS issue because when i replace the vimeo or external url with a static video hosted within same host (netlify), it works fine.

I also tried appending a timestamp to the video url just to be sure its not a cache issue, but still no luck

Wondering how can i make this work with an externally hosted video like vimeo?

Body:
Upon further testing, it seems to me that the issue was caused by the 302 redirect to their CDN that happens when you use a vimeo file url.

As @gman pointed out, there's a similar issue on Soundclound and i found that the solution provided there worked for my case too.
How to get Safari 12 to process audio from soundcloud?

I solved it by making an async fetch request to get the CDN url and then passing it to the video.src. Works in safari mac and ios (13) now  now!

  async function getMediaURLForTrack(texture_to_update, passed_url) {
    await fetch(passed_url, {
      method: 'HEAD'
    })
    .then((response) => {
      texture_to_update.src = response.url
    });
  }


问:
I am trying to implement a onTap() fucntion in PopUpMenu but I am unable to do so

When one of the item from the PopMenuItem I want it to perform some particular task.

I tried implement but it is not doing anything I tried implementing the onTap() function but it was giving me error as constant required.

This is the code

```<code>import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable':
        onEnable();
        break;
      case 'Disable':
        onDisable();
        break;
      case 'Delete':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}
</code>```

Can I call the function that is defined in other program when one of the menu is selected from the PopMenuItem.

The screenshot is shown below.

答:
the value strings you send in popup menu item is not match with your switch cases</p>

```<code>import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable User':
        onEnable();
        break;
      case 'Disable User':
        onDisable();
        break;
      case 'Delete User':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}
</code>```

Body:
When one of the item from the PopMenuItem I want it to perform some particular task.

I tried implement but it is not doing anything I tried implementing the onTap() function but it was giving me error as constant required.

This is the code

import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable':
        onEnable();
        break;
      case 'Disable':
        onDisable();
        break;
      case 'Delete':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}

Can I call the function that is defined in other program when one of the menu is selected from the PopMenuItem.

The screenshot is shown below.

Body:
the value strings you send in popup menu item is not match with your switch cases

import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable User':
        onEnable();
        break;
      case 'Disable User':
        onDisable();
        break;
      case 'Delete User':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}


问:
How can I get all unique tags from an array with lodash?
Im using Vuejs and lodash and particular lodash to try and get all uniqe tags for question in my very simple questions "app". But for some reason lodash returs all of the tags, not the uniqe ones. This is how I have design the array of questions and tags (might be a better way but dunno).

```<code>created() {
  this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
    return {
        tags:[],
        fragor:[
        {
            'fraga': "Question 1",
            'svar' : "This is this explanation",
            'tags' : ['knowledge'],
        },
        {
            'fraga': "Question 2",
            'svar' : "This is this explanation for question 2",
            'tags' : ['knowledge', 'code'],
        },
        {
            'fraga': "Question 3",
            'svar' : "This is this explanation for question 3",
            'tags' : ['code'],
        }
        ]
    }
}
</code>```

tags is return [ "knowledge" ] [ "knowledge", "code" ] [ "code" ] when the expected result should be ['knowledge', 'code']. How can i achive this with lodash and vue?

I made a jsfiddle for you guys.

答:
Optional without lodash:

const fragor = [{ fraga: 'Question 1', svar: 'This is this explanation', tags: ['knowledge'] }, { fraga: 'Question 2', svar: 'This is this explanation for question 2', tags: ['knowledge', 'code'] }, { fraga: 'Question 3', svar: 'This is this explanation for question 3', tags: ['code'] }];

const tags = Array.from(new Set(fragor.map(f => f.tags).flat()));

console.log(tags);```

Body:
Im using Vuejs and lodash and particular lodash to try and get all uniqe tags for question in my very simple questions "app". But for some reason lodash returs all of the tags, not the uniqe ones. This is how I have design the array of questions and tags (might be a better way but dunno).

created() {
  this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
    return {
        tags:[],
        fragor:[
        {
            'fraga': "Question 1",
            'svar' : "This is this explanation",
            'tags' : ['knowledge'],
        },
        {
            'fraga': "Question 2",
            'svar' : "This is this explanation for question 2",
            'tags' : ['knowledge', 'code'],
        },
        {
            'fraga': "Question 3",
            'svar' : "This is this explanation for question 3",
            'tags' : ['code'],
        }
        ]
    }
}

tags is return [ "knowledge" ] [ "knowledge", "code" ] [ "code" ] when the expected result should be ['knowledge', 'code']. How can i achive this with lodash and vue?

I made a jsfiddle for you guys.


问:
Is it possible for a computer to "learn" a regular expression by user-provided examples?
Is it possible for a computer to "learn" a regular expression by user-provided examples?

To clarify:

I do not want to learn regular expressions.

I want to create a program which "learns" a regular expression from examples which are interactively provided by a user, perhaps by selecting parts from a text or selecting begin or end markers.

Is it possible? Are there algorithms, keywords, etc. which I can Google for?

EDIT: Thank you for the answers, but I'm not interested in tools which provide this feature. I'm looking for theoretical information, like papers, tutorials, source code, names of algorithms, so I can create something for myself.

答:
No computer program will ever be able to generate a meaningful regular expression based solely on a list of valid matches.  Let me show you why.

Suppose you provide the examples 111111 and 999999, should the computer generate:

A regex matching exactly those two examples: (111111|999999)

A regex matching 6 identical digits (\d)\1{5}

A regex matching 6 ones and nines [19]{6}

A regex matching any 6 digits \d{6}

Any of the above three, with word boundaries, e.g. \b\d{6}\b

Any of the first three, not preceded or followed by a digit, e.g.
(?<!\d)\d{6}(?!\d)

As you can see, there are many ways in which examples can be generalized into a regular expression.  The only way for the computer to build a predictable regular expression is to require you to list all possible matches.  Then it could generate a search pattern that matches exactly those matches.

If you don't want to list all possible matches, you need a higher-level description.  That's exactly what regular expressions are designed to provide.  Instead of providing a long list of 6-digit numbers, you simply tell the program to match "any six digits".  In regular expression syntax, this becomes \d{6}.

Any method of providing a higher-level description that is as flexible as regular expressions will also be as complex as regular expressions.  All tools like RegexBuddy can do is to make it easier to create and test the high-level description.  Instead of using the terse regular expression syntax directly, RegexBuddy enables you to use plain English building blocks.  But it can't create the high-level description for you, since it can't magically know when it should generalize your examples and when it should not.

It is certainly possible to create a tool that uses sample text along with guidelines provided by the user to generate a regular expression.  The hard part in designing such a tool is how does it ask the user for the guiding information that it needs, without making the tool harder to learn than regular expressions themselves, and without restricting the tool to common regex jobs or to simple regular expressions.

OwnerDisplayName: DR

LastEditorDisplayName: DR

OwnerDisplayName: Jan Goyvaerts

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Hosam Aly


问:
How to make a Web Audio element sound instantly when pressed on mobile?
I am finishing up a beat/sample pad project using web audio and JavaScript. When I click on a sample pad, I want it to sound instantly, and this works fine on the desktop version, however, on mobile, the sample will only sound once I have lifted my finger away from the screen. This then creates a lag of sorts, and you definitely wouldn't be able to play along in time with any music for example. Is there a way to get the sample to sound instantly as soon as it's pressed on a mobile device? I've found that the "mousedown" event seems to work best for desktop, but I can't get the same result with anything that I have tried for mobile.

Please feel free to take a look at the Beat pad project here: http://beatpad.dwcreate.co.uk/

I'll post code later if needed.

Many thanks to anyone who can help me with this problem!

答:
Audio element seems to have latency issues on Apple touch devices...not sure about the others. AudioBuffer will provide more reliable playback immediacy across browsers.  After some fiddling, it seems the "touchstart" event must be bound on the document and wasn't working when bound on the element.

// samples identified by keyboard key code
const samples = [49,50,51,52,53,54,55,56,57,48,45,61,113,119,101,114,116,121,117,105,111,112,91,93,97,115,100,102,103,104,106,107,108,59,39,122,120,99,118,98,110,109,44,46,47]

// audio contect for decoding and playback
const ctx =  new (window.AudioContext || window.webkitAudioContext)({ latencyHint: 'playback' })

// decoded AudioBuffers we'll create for each sample
audioBuffers = {}

// keyboard keys to render
keys = {}

// track download/decode progress
let totalLoaded = 0

init()

function init() {
  samples.forEach(async keyCode => {
    const url = `https://cøder.com/static/61881209/${keyCode}.mp3`
    const buffer = await (await fetch(url)).arrayBuffer()
    ctx.decodeAudioData(buffer, decoded => {
      audioBuffers[keyCode] = decoded
      fileLoaded()
    })
  })
}

// keyboard press
document.addEventListener('keypress', playSample)

function fileLoaded() {
  totalLoaded++
  document.querySelector('#progress').innerText = `Samples Loaded: ${totalLoaded} / ${samples.length}`

  if (totalLoaded === samples.length) {
    initKeyboard()
  }
}

function playSample({ keyCode }) {
  // play audio sample from beginning
  const [audioBuffer, key] = [audioBuffers[keyCode], keys[keyCode]]
  if (audioBuffer) {
    const bufferSource = ctx.createBufferSource()
    bufferSource.buffer = audioBuffer;
    bufferSource.connect(ctx.destination);
    bufferSource.start(0);

    requestAnimationFrame(_ => {
      key.classList.remove('pressed')
      requestAnimationFrame(_ => {
        key.classList.add('pressed')
      })
    })
  }
}

// draw keyboard on screen
function initKeyboard() {
  const keyboard = document.createElement('div')
  keyboard.className = 'keyboard'

  let row = 0  // keyboard row
  const breakOn = ['q', 'a', 'z'] // start new row

  // render each keyboard key
  samples.forEach(keyCode => {
    const char = String.fromCharCode(keyCode)
    const key = document.createElement('div')

    key.className = 'key'
    key.innerText = char
    key.dataset.code = keyCode

    // start new row
    if (breakOn.includes(char)) {
      row++
      key.style.clear = 'both'
      key.style.marginLeft = `${20*row}px`
    }

    keys[keyCode] = key
    keyboard.append(key)
  })

  // bind click or touch if it's a tablet
  if ('ontouchstart' in window) {
    document.addEventListener('touchstart', handleClick)
  } else {
    document.addEventListener('mousedown', handleClick)
  }

  function handleClick(e) {
    const {dataset: {code}} = e.target
    if (code) {
      playSample({ keyCode: code })
    }
  }

  document.body.innerHTML = ''
  document.body.append(keyboard)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'open sans light', arial, sans-serif;
  background: #f9f9f9;
}
.keyboard {
  width: 620px;
  overflow: hidden;
  white-space: nowrap;
}
.key {
  background: #fff;
  cursor: pointer;
  height: 40px;
  width: 40px;
  margin: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  float: left;
  border-radius: 6px;
  user-select: none;
}
.key.pressed {
  animation: keyPress .5s ease-out;
}

@keyframes keyPress {
  0% {
    background: lime;
  }
  100% {
    background: #fff;
  }
}</code>```

Loading...
```

Body:
Audio element seems to have latency issues on Apple touch devices...not sure about the others. AudioBuffer will provide more reliable playback immediacy across browsers.  After some fiddling, it seems the "touchstart" event must be bound on the document and wasn't working when bound on the element.

// samples identified by keyboard key code
const samples = [49,50,51,52,53,54,55,56,57,48,45,61,113,119,101,114,116,121,117,105,111,112,91,93,97,115,100,102,103,104,106,107,108,59,39,122,120,99,118,98,110,109,44,46,47]

// audio contect for decoding and playback
const ctx =  new (window.AudioContext || window.webkitAudioContext)({ latencyHint: 'playback' })

// decoded AudioBuffers we'll create for each sample
audioBuffers = {}

// keyboard keys to render
keys = {}

// track download/decode progress
let totalLoaded = 0

init()

function init() {
  samples.forEach(async keyCode => {
    const url = `https://cøder.com/static/61881209/${keyCode}.mp3`
    const buffer = await (await fetch(url)).arrayBuffer()
    ctx.decodeAudioData(buffer, decoded => {
      audioBuffers[keyCode] = decoded
      fileLoaded()
    })
  })
}

// keyboard press
document.addEventListener('keypress', playSample)

function fileLoaded() {
  totalLoaded++
  document.querySelector('#progress').innerText = `Samples Loaded: ${totalLoaded} / ${samples.length}`

  if (totalLoaded === samples.length) {
    initKeyboard()
  }
}

function playSample({ keyCode }) {
  // play audio sample from beginning
  const [audioBuffer, key] = [audioBuffers[keyCode], keys[keyCode]]
  if (audioBuffer) {
    const bufferSource = ctx.createBufferSource()
    bufferSource.buffer = audioBuffer;
    bufferSource.connect(ctx.destination);
    bufferSource.start(0);

    requestAnimationFrame(_ => {
      key.classList.remove('pressed')
      requestAnimationFrame(_ => {
        key.classList.add('pressed')
      })
    })
  }
}

// draw keyboard on screen
function initKeyboard() {
  const keyboard = document.createElement('div')
  keyboard.className = 'keyboard'

  let row = 0  // keyboard row
  const breakOn = ['q', 'a', 'z'] // start new row

  // render each keyboard key
  samples.forEach(keyCode => {
    const char = String.fromCharCode(keyCode)
    const key = document.createElement('div')

    key.className = 'key'
    key.innerText = char
    key.dataset.code = keyCode

    // start new row
    if (breakOn.includes(char)) {
      row++
      key.style.clear = 'both'
      key.style.marginLeft = `${20*row}px`
    }

    keys[keyCode] = key
    keyboard.append(key)
  })

  // bind click or touch if it's a tablet
  if ('ontouchstart' in window) {
    document.addEventListener('touchstart', handleClick)
  } else {
    document.addEventListener('mousedown', handleClick)
  }

  function handleClick(e) {
    const {dataset: {code}} = e.target
    if (code) {
      playSample({ keyCode: code })
    }
  }

  document.body.innerHTML = ''
  document.body.append(keyboard)
}

body {
  font-family: 'open sans light', arial, sans-serif;
  background: #f9f9f9;
}
.keyboard {
  width: 620px;
  overflow: hidden;
  white-space: nowrap;
}
.key {
  background: #fff;
  cursor: pointer;
  height: 40px;
  width: 40px;
  margin: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  float: left;
  border-radius: 6px;
  user-select: none;
}
.key.pressed {
  animation: keyPress .5s ease-out;
}

@keyframes keyPress {
  0% {
    background: lime;
  }
  100% {
    background: #fff;
  }
}

<div id="progress">Loading...</div>


问:
PHP reduced value from another input value
I want make value of input from another input value,
 so if i add number in first input,
 second input is reduced from first input,
 can someone help me...

```<code>$value1 = 10;
echo "<input type='text' value='$value2'></input>";
$value3 = $value1 - $value2;
echo "<input type='text' value='$value3'></input>";
</code>```

答:
use javascript for that kind problem it easy to handle</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input type="text" name="val2" id='val2' oninput="loadVal3(this.value)">
<input type="text" name="val3" id='val3'>
<script type="text/javascript">
    function loadVal3(val) {
        let val1=10;
        if(!isNaN(val)&&val!=""){
            document.getElementById('val3').value=val1-val;
        }else{
            document.getElementById('val3').value="";
        }
    }
</script>
</body>
</html>
</code>```

Body:
I want make value of input from another input value,
 so if i add number in first input,
 second input is reduced from first input,
 can someone help me...

$value1 = 10;
echo "<input type='text' value='$value2'></input>";
$value3 = $value1 - $value2;
echo "<input type='text' value='$value3'></input>";

Body:
use javascript for that kind problem it easy to handle

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input type="text" name="val2" id='val2' oninput="loadVal3(this.value)">
<input type="text" name="val3" id='val3'>
<script type="text/javascript">
    function loadVal3(val) {
        let val1=10;
        if(!isNaN(val)&&val!=""){
            document.getElementById('val3').value=val1-val;
        }else{
            document.getElementById('val3').value="";
        }
    }
</script>
</body>
</html>


问:
Generate DateTime Series in Months using C# and Entity Framework
I am a newbie. This is my entity model

```<code>''' public virtual DateTime StartDate { get; set; }

    [Required]
    public virtual string Name { get; set; }
    [Column(TypeName = "money")]
    public virtual decimal SalesAmount { get; set; }
    [Column(TypeName = "money")]
    public virtual decimal CostofSales { get; set; }

    [Column(TypeName = "money")]
    public virtual decimal GrossProfit { get { return SalesAmount - CostofSales; } }

    public virtual int Months { get; set; }

    public virtual DateTime EndDate { get {return StartDate.AddMonths(Months); } } '''
</code>```

Now I want to ensure that when a user enters their start date and the months they want to project for then, my database will be filled with months between start date and end date. This means I need a way to make a monthly date time series which they can then use to generate sales projections on a monthly basis over the period they set. Please help or point me to a similar solution that can help

答:
You shouldn't put the logic in the EF models.  EF models are just used to map objects to the database tables.

I am thinking you want something like this:

```<code>public class SalesProjection
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal SalesAmount { get; set; }

    public decimal CostofSales { get; set; }

    //Mark only the navigation properties with the keyword 'virtual'
    public virtual IEnumerable<ProjectionMonth> ProjectionMonths { get; set; }
}

public class ProjectionMonth
{
     public int Id { get; set; }

     public int SalesProjectionId { get; set; }

     public int Month { get; set; }

     [ForeignKey("SalesProjectionId ")] //EF attribute to denote foreign key.
     public virtual SalesProjection SalesProjection { get; set; }
}
</code>```

The entity models should not contain any business logic such as calculations (e.g GrossProfit).  GrossProfit can be calculated on the fly instead of saving it to the database.  All business logic should be done in Data Transfer Objects (DTO).  Create another set of models (DTO) that will be used to transform the data based on business rules.  These are the models you can return to the client:

```<code>    public class SalesProjectionDTO
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal SalesAmount { get; set; }

        public decimal CostofSales { get; set; }

        public decimal GrossProfit { get; set; }
    }
</code>```

Then, assuming you are using Entity Framework:

```<code>public List<SalesProjectionDTO> GetProjectionsByDateRange(int startMonth, int endMonth)
{
     var projections = _context.SalesProjection
       .Where(sp => sp.SalesProjectionMonths
                      .Any(m => m.Month >= startMonth && m.Month <= endMonth))
       .Select(sp => new SalesProjectionDTO {
               Name = sp.Name,
               SalesAmount = sp.SalesAmount,
               CostOfSales = sp.CostOfSales,
               GrossProfit = sp.SalesAmount - sp.CostOfSales
         }).ToList();

     return projections;
}

public void SaveProjections(SalesProjectionDTO projection, int startMonth, int endMonth)
{
     //check if projection exists
     var entity= _context.SalesProjection.Where(sp => sp.Id == projection.Id)
           .FirstOrDefault() ?? new SalesProjection();

     if (entity== null)
         _context.Add(projection);

     entity.Name = projection.Name;
     entity.SalesAmount = projection.SalesAmount;
     entity.CostOfSales = projection.CostOfSames;

     for (var i = startMonth; i <= endMonth; i++){
          entity.ProjectionMonths.Add(
               new ProjectionMonth {
                    Month = i;
               }
     }

     _context.SaveChanges();
}
</code>```

Body:
I am a newbie. This is my entity model

''' public virtual DateTime StartDate { get; set; }

    [Required]
    public virtual string Name { get; set; }
    [Column(TypeName = "money")]
    public virtual decimal SalesAmount { get; set; }
    [Column(TypeName = "money")]
    public virtual decimal CostofSales { get; set; }

    [Column(TypeName = "money")]
    public virtual decimal GrossProfit { get { return SalesAmount - CostofSales; } }

    public virtual int Months { get; set; }

    public virtual DateTime EndDate { get {return StartDate.AddMonths(Months); } } '''

Now I want to ensure that when a user enters their start date and the months they want to project for then, my database will be filled with months between start date and end date. This means I need a way to make a monthly date time series which they can then use to generate sales projections on a monthly basis over the period they set. Please help or point me to a similar solution that can help

Body:
You shouldn't put the logic in the EF models.  EF models are just used to map objects to the database tables.

I am thinking you want something like this:

public class SalesProjection
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal SalesAmount { get; set; }

    public decimal CostofSales { get; set; }

    //Mark only the navigation properties with the keyword 'virtual'
    public virtual IEnumerable<ProjectionMonth> ProjectionMonths { get; set; }
}

public class ProjectionMonth
{
     public int Id { get; set; }

     public int SalesProjectionId { get; set; }

     public int Month { get; set; }

     [ForeignKey("SalesProjectionId ")] //EF attribute to denote foreign key.
     public virtual SalesProjection SalesProjection { get; set; }
}

The entity models should not contain any business logic such as calculations (e.g GrossProfit).  GrossProfit can be calculated on the fly instead of saving it to the database.  All business logic should be done in Data Transfer Objects (DTO).  Create another set of models (DTO) that will be used to transform the data based on business rules.  These are the models you can return to the client:

    public class SalesProjectionDTO
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal SalesAmount { get; set; }

        public decimal CostofSales { get; set; }

        public decimal GrossProfit { get; set; }
    }

Then, assuming you are using Entity Framework:

public List<SalesProjectionDTO> GetProjectionsByDateRange(int startMonth, int endMonth)
{
     var projections = _context.SalesProjection
       .Where(sp => sp.SalesProjectionMonths
                      .Any(m => m.Month >= startMonth && m.Month <= endMonth))
       .Select(sp => new SalesProjectionDTO {
               Name = sp.Name,
               SalesAmount = sp.SalesAmount,
               CostOfSales = sp.CostOfSales,
               GrossProfit = sp.SalesAmount - sp.CostOfSales
         }).ToList();

     return projections;
}

public void SaveProjections(SalesProjectionDTO projection, int startMonth, int endMonth)
{
     //check if projection exists
     var entity= _context.SalesProjection.Where(sp => sp.Id == projection.Id)
           .FirstOrDefault() ?? new SalesProjection();

     if (entity== null)
         _context.Add(projection);

     entity.Name = projection.Name;
     entity.SalesAmount = projection.SalesAmount;
     entity.CostOfSales = projection.CostOfSames;

     for (var i = startMonth; i <= endMonth; i++){
          entity.ProjectionMonths.Add(
               new ProjectionMonth {
                    Month = i;
               }
     }

     _context.SaveChanges();
}


问:
Where has this class been used?
For example, I create a UserDataModel class like this:

```<code>import 'package:meta/meta.dart';

import '../../../../globals/errors/exceptions.dart';
import '../../domain/entities/user_data.dart';
import '../../../../globals/utils/value_checker.dart';

class UserDataModel extends UserData {
  UserDataModel(
      {@required String fullname,
      @required String username,
      @required String token})
      : super(fullname: fullname, username: username, token: token);

  factory UserDataModel.fromJson(Map<String, dynamic> json) {
    return UserDataModel(
        fullname: json['fullname'],
        username: json['username'],
        token: json['token']);
  }

  factory UserDataModel.fromEntity(UserData userData) {
    return UserDataModel(
        fullname: userData.fullname,
        username: userData.username,
        token: userData.token);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> result = new Map<String, dynamic>();
    result = {
      "fullname": fullname,
      "username": username,
      "token": token,
    };

    return result;
  }
}
</code>```

I want to know, which UserDataModel class is initialized in any file? For example, I initialize the UserDataModel class in the repository.dart file or maybe main.dart or something else. How can I know that in VSCode?

答:
I have been found solution :
1. Right click on class that I want to search for the class use
2. Select "Go to definition"
3. And I found where the class is used

Title: Where has this class been used?

Body:
For example, I create a UserDataModel class like this:

import 'package:meta/meta.dart';

import '../../../../globals/errors/exceptions.dart';
import '../../domain/entities/user_data.dart';
import '../../../../globals/utils/value_checker.dart';

class UserDataModel extends UserData {
  UserDataModel(
      {@required String fullname,
      @required String username,
      @required String token})
      : super(fullname: fullname, username: username, token: token);

  factory UserDataModel.fromJson(Map<String, dynamic> json) {
    return UserDataModel(
        fullname: json['fullname'],
        username: json['username'],
        token: json['token']);
  }

  factory UserDataModel.fromEntity(UserData userData) {
    return UserDataModel(
        fullname: userData.fullname,
        username: userData.username,
        token: userData.token);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> result = new Map<String, dynamic>();
    result = {
      "fullname": fullname,
      "username": username,
      "token": token,
    };

    return result;
  }
}

I want to know, which UserDataModel class is initialized in any file? For example, I initialize the UserDataModel class in the repository.dart file or maybe main.dart or something else. How can I know that in VSCode?


问:
Callback and Testing Highcharts
I am currently using angular 9 with Highcharts.

Link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk

Some instructions for running on application-side / test-side :

Test - side : inside angular.json file on line number 18, change

```<code>    "main": "src/main.ts",
</code>```

to

```<code>    "main": "src/main-testing.ts",
</code>```

and do a refresh of the browser.

Application - side : Change exactly the opposite of previous.

```<code>   "main": "src/main-testing.ts",
</code>```

to

```<code>   "main": "src/main.ts",
</code>```

Here are a few issues i am stuck upon :

I have used chart callback to get the chart instance , but it is not working ( inside hello.component.ts ,
line numbers 38 to 40 ). How should i call it and when does actually the callback happens in Highcharts ?

If suppose somehow i am able to assign the chart instance to chartCreated variable. Can i control the
chart now, like line numbers 60 to 62 ( if i uncomment that ), will it work ? Basically i wanted to
know the usefulness of updateFlag in Highcharts.

Unable to addSeries when ngOnChanges is called inside hello.component.ts

Inside the spec file  hello.component.spec.ts  i wanted to test the chart by putting a numeric data / adding a series
on my own , like i did when onClick() is called. But jasmine shows error

```<code>   TypeError : Cannot read series of undefined
   TypeError : Cannot read property 'addSeries' of undefined
</code>```

How to resolve these ?

EDIT 1 : Implemented ngOnChanges and ngOnInit and removed most of the code from app.component.ts to hello.component.ts

答:
As per @gsa.interactive suggestion , following test cases worked :</p>

```<code>  it('should check for changes in the data of the series in charts ',()=>{
      component.chartCreated.series[0].data[0].update(5);
      //console.log(component.chartCreated);
      expect(component.chartCreated.series[0].yData).toEqual([5,2,3]);
  });

  it('should check for changes in the series in charts ',()=>{
    component.chartCreated.addSeries({
        data: [3,4,2],
        type: 'line'
    });

    //console.log(component.chartCreated);
    expect(component.chartCreated.series.length).toBe(2);
    expect(component.chartCreated.series[1].yData).toEqual([3,4,2]);
  });
</code>```

Title: Callback and Testing Highcharts

Body:
I am currently using angular 9 with Highcharts.

Link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk

Some instructions for running on application-side / test-side :

Test - side : inside angular.json file on line number 18, change

    "main": "src/main.ts",

to

    "main": "src/main-testing.ts",

and do a refresh of the browser.

Application - side : Change exactly the opposite of previous.

   "main": "src/main-testing.ts",

to

   "main": "src/main.ts",

Here are a few issues i am stuck upon :

I have used chart callback to get the chart instance , but it is not working ( inside hello.component.ts ,
line numbers 38 to 40 ). How should i call it and when does actually the callback happens in Highcharts ?

If suppose somehow i am able to assign the chart instance to chartCreated variable. Can i control the
chart now, like line numbers 60 to 62 ( if i uncomment that ), will it work ? Basically i wanted to
know the usefulness of updateFlag in Highcharts.

Unable to addSeries when ngOnChanges is called inside hello.component.ts

Inside the spec file  hello.component.spec.ts  i wanted to test the chart by putting a numeric data / adding a series
on my own , like i did when onClick() is called. But jasmine shows error

   TypeError : Cannot read series of undefined
   TypeError : Cannot read property 'addSeries' of undefined

How to resolve these ?

EDIT 1 : Implemented ngOnChanges and ngOnInit and removed most of the code from app.component.ts to hello.component.ts

Body:
As per @gsa.interactive suggestion , following test cases worked :

  it('should check for changes in the data of the series in charts ',()=>{
      component.chartCreated.series[0].data[0].update(5);
      //console.log(component.chartCreated);
      expect(component.chartCreated.series[0].yData).toEqual([5,2,3]);
  });

  it('should check for changes in the series in charts ',()=>{
    component.chartCreated.addSeries({
        data: [3,4,2],
        type: 'line'
    });

    //console.log(component.chartCreated);
    expect(component.chartCreated.series.length).toBe(2);
    expect(component.chartCreated.series[1].yData).toEqual([3,4,2]);
  });


问:
React-Redux async functions using thunk not working
Types.js File:

```<code>const ADD_TOKENS = "ADD_TOKENS";

export { ADD_TOKENS};
</code>```

Actions.js File:

```<code>import { ADD_TOKENS } from "./types";

function addTokens() {
  return {
    type: ADD_TOKENS,
  };
}

const actionCreators = {
  addTokens,
};

export { actionCreators };
</code>```

Reducers.js File

```<code>import { ADD_TOKENS } from "./types";
import getTokens from "../../api/getTokens";

const initialState = {
  access_token: null,
  refresh_token: null,
  expiration_time: null,
};

function applyAddTokens(state) {
  console.log("Function being hit"); //yes
  return async (dispatch) => {
    console.log("Function being hit"); //no
    const token = await getTokens();
    return {
      ...state,
      access_token: dispath(token.access_token),
      refresh_token: dispath(token.refresh_token),
      expiration_time: dispath(token.expiration_time),
    };
  };
}

function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TOKENS:
      return applyAddTokens(state);
    default:
      return state;
  }
}

export default reducer;
</code>```

index.js File

```<code>import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators as actions } from "./actions";

class Login extends Component {
  render() {
    const { addTokens } = this.props;
    console.log("Props in Login/index.js", this.props);
    return (
      <View>
        <TouchableOpacity onPress={addTokens}>
            <Text>Login</Text>
          </TouchableOpacity>
      </View>
    );
  }
}

function mapStateToProps(state) {
  const { access_token, refresh_token, expiration_time } = state;
  return {
    access_token,
    refresh_token,
    expiration_time,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    addTokens: bindActionCreators(actions.addTokens, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);
</code>```

store.js File

```<code>import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../components/Login/reducers";

const store = createStore(reducer, applyMiddleware(thunk));

export default store;
</code>```

Why is this not working? Why is applyAddTokens function's thunk not producing anything? Let me know if anyone needs any additional details. getTokens() returns an object that contains access_token, refresh_token, and expiration_time. This worked before when I tried it without async (just regular data without any request).

答:
Your code flow is like below:

In your JSX, upon onPress, you trigger the action addTokens.

This action returns an object of type ADD_TOKENS

Redux will directly execute the reducer (the ADD_TOKENS switch case). Here you are calling an async function applyAddTokens.

Redux will execute it IMMEDIATELY (without waiting for promise result) and returns the output of applyAddTokens function which is a pending promise

That's it.

Solution

First, put all async code in your actions. Keep reducers light and use it only to update state.

To use thunk, your action must return a function (not an object).

See this example as well

Body:
Types.js File:

const ADD_TOKENS = "ADD_TOKENS";

export { ADD_TOKENS};

Actions.js File:

import { ADD_TOKENS } from "./types";

function addTokens() {
  return {
    type: ADD_TOKENS,
  };
}

const actionCreators = {
  addTokens,
};

export { actionCreators };

Reducers.js File

import { ADD_TOKENS } from "./types";
import getTokens from "../../api/getTokens";

const initialState = {
  access_token: null,
  refresh_token: null,
  expiration_time: null,
};

function applyAddTokens(state) {
  console.log("Function being hit"); //yes
  return async (dispatch) => {
    console.log("Function being hit"); //no
    const token = await getTokens();
    return {
      ...state,
      access_token: dispath(token.access_token),
      refresh_token: dispath(token.refresh_token),
      expiration_time: dispath(token.expiration_time),
    };
  };
}

function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TOKENS:
      return applyAddTokens(state);
    default:
      return state;
  }
}

export default reducer;

index.js File

import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators as actions } from "./actions";

class Login extends Component {
  render() {
    const { addTokens } = this.props;
    console.log("Props in Login/index.js", this.props);
    return (
      <View>
        <TouchableOpacity onPress={addTokens}>
            <Text>Login</Text>
          </TouchableOpacity>
      </View>
    );
  }
}

function mapStateToProps(state) {
  const { access_token, refresh_token, expiration_time } = state;
  return {
    access_token,
    refresh_token,
    expiration_time,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    addTokens: bindActionCreators(actions.addTokens, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

store.js File

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../components/Login/reducers";

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

Why is this not working? Why is applyAddTokens function's thunk not producing anything? Let me know if anyone needs any additional details. getTokens() returns an object that contains access_token, refresh_token, and expiration_time. This worked before when I tried it without async (just regular data without any request).


问:
Why is the Android emulator so slow? How can we speed up the Android emulator?
I have got a 2.67  GHz Celeron processor, and 1.21  GB of RAM on a x86 Windows XP Professional machine.

My understanding is that the Android Emulator should start fairly quickly on such a machine, but for me, it doesn't. I have followed all the instructions in setting up the IDE, SDKs, JDKs and such and have had some success in starting the emulator quickly, but that is very rare. How can I, if possible, fix this problem?

Even if it starts and loads the home screen, it is very sluggish. I have tried the Eclipse IDE in version 3.5 (Galileo) and 3.4 (Ganymede).

答:
I've similar issues on a Mac. What I did;

1) on the emulator, settings-display ->
disable screen orientation

2) on Eclipse, emulator startup options ->
-cpu-delay 100

Those had some effect in lowering CPU use (not it is around 40-60%), not ultimate solution.
But again, the CPU use is NOT >100% anymore!


问:
Image not showing in Gmail - Using django python-postmark
I've used django python-postmark for mailing. Now my problem is that my static images are not shown on Gmail. Gmail prepends a url proxy to the src of the images. if the prepended url proxy is removed, the image will show perfectly. What am I missing here? or how do I fix this? thanks

These are my code for the image. this supposed to result to src="https://mysite_here.com/static/img/img.png"

```<code>{% load static %}
{% load custom_tag %}
<img src="{% site_url %}{% static 'img/img.png' %}">
</code>```

But upon showing on gmail, the src is now prepended which causes the image to not show. Here's what the gmail generated:

```<code><img src="https://ci3.googleusercontent.com/proxy/rYDcSW7inrn8_vlXhcrSojT1T06pKEKyrzmXgb5cje_JCc9ze25emLbFDuBub3CWP_ASqgUXbqn6RureN5Fy0Nd-eFdllL14aq16UQ_rXrB4-dWp=s0-d-e1-ft#https://mysite_here.com/static/img/img.png" class="m_-186473825407072632logo CToWUd">
</code>```

答:
I was testing when Gmail request the image, using python SimpleHTTPServer, as suggested in this post: https://blog.filippo.io/how-the-new-gmail-image-proxy-works-and-what-this-means-for-you/ and realized that the image was actually been reached.

The problem was that I was serving a .svg image. I realized this was the error by reading this another question: https://webmasters.stackexchange.com/questions/123969/images-from-googleusercontent-com-giving-404.

Once I replaced the image for a .png and .jpg it started to work.

Hope this can give some light. I don't really know why Gmail can't handle .svg

Body:
I've used django python-postmark for mailing. Now my problem is that my static images are not shown on Gmail. Gmail prepends a url proxy to the src of the images. if the prepended url proxy is removed, the image will show perfectly. What am I missing here? or how do I fix this? thanks

These are my code for the image. this supposed to result to src="https://mysite_here.com/static/img/img.png"

{% load static %}
{% load custom_tag %}

But upon showing on gmail, the src is now prepended which causes the image to not show. Here's what the gmail generated:


问:
Why compiler says Works cannot be resolved to a type?
I just want to declare a generic type for simple things but the compiler get errors that type is not resolved!
this is how i did in main:

```<code>//Main and Works are in same file
public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}
</code>```

and this is my class declaration
`

```<code>//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}
</code>```

`

答:
I want to make them separate classes. (Main and Workers each in one class

If you want separate classes for those, you may want to put main method into a class declaration. Something around

Works.java

```<code>public class Works {
    // Works class declarations
}
</code>```

Main.java

```<code>// If it's in the same folder/package you don't need to import Works
public class Main {
    // main method here
    public static void main(String[] args){
        // Do something
    }
}
</code>```

Also, let say you want to put both in a different folder/package, you'll need to add package statement to define which folder the class is in relative to the class that have a main method in it.

For example:

Works location:

1)  PROJECT_FOLDER/workstuff/Works.java

You will need to declare package workstuff;

Class with main method location:

1) PROJECT_FOLDER/Main.java

You won't need to declare package statement since it's in root folder

2) PROJECT_FOLDER/somepackage/Main.java

You'll need to declare package somepackage;

As for both Main class cases, you'll need to import workstuff.Works

Body:
I just want to declare a generic type for simple things but the compiler get errors that type is not resolved!
this is how i did in main:

//Main and Works are in same file
public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}

and this is my class declaration
`

//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}

`

Body:
I want to make them separate classes. (Main and Workers each in one class

If you want separate classes for those, you may want to put main method into a class declaration. Something around

Works.java

public class Works {
    // Works class declarations
}

Main.java

// If it's in the same folder/package you don't need to import Works
public class Main {
    // main method here
    public static void main(String[] args){
        // Do something
    }
}

Also, let say you want to put both in a different folder/package, you'll need to add package statement to define which folder the class is in relative to the class that have a main method in it.

For example:

Works location:

1)  PROJECT_FOLDER/workstuff/Works.java

You will need to declare package workstuff;

Class with main method location:

1) PROJECT_FOLDER/Main.java

You won't need to declare package statement since it's in root folder

2) PROJECT_FOLDER/somepackage/Main.java

You'll need to declare package somepackage;

As for both Main class cases, you'll need to import workstuff.Works


问:
How to get the error code from requests.exceptions.ChunkedEncodingError
I sometimes get this error.

```<code>requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(10054, '현재 연결은 원격 호스트에 의해 강제로 끊겼습니다', None, 10054, None)", ConnectionResetError(10054, '현재 연결은 원격 호스트에 의해 강제로 끊겼습니다', None, 10054, None))
</code>```

Since I see the error code 10054, I want to handle this error with error code like this

```<code>    try:
        result =  requests.get(url=url, **kwargs)
    except requests.exceptions.ChunkedEncodingError as e:
        #get the error code from e and then
        if errorcode==10054:
            #do something
</code>```

I tried this at first but it gave me another error that the ChunkedEncodingError object has no arg.

```<code>    try:
        result =  requests.get(url=url, **kwargs)
    except requests.exceptions.ChunkedEncodingError as e:
        errorcode = e.arg[1]
        if errorcode==10054:
            #do something
</code>```

答:
Can you try the following:</p>

```<code>try:
    result =  requests.get(url=url, **kwargs)
except requests.exceptions.ChunkedEncodingError as e:
    #get the error code from e and then
    if e.errno==10054:
        #do something
</code>```

Body:
I sometimes get this error.

requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(10054, '현재 연결은 원격 호스트에 의해 강제로 끊겼습니다', None, 10054, None)", ConnectionResetError(10054, '현재 연결은 원격 호스트에 의해 강제로 끊겼습니다', None, 10054, None))

Since I see the error code 10054, I want to handle this error with error code like this

    try:
        result =  requests.get(url=url, **kwargs)
    except requests.exceptions.ChunkedEncodingError as e:
        #get the error code from e and then
        if errorcode==10054:
            #do something

I tried this at first but it gave me another error that the ChunkedEncodingError object has no arg.

    try:
        result =  requests.get(url=url, **kwargs)
    except requests.exceptions.ChunkedEncodingError as e:
        errorcode = e.arg[1]
        if errorcode==10054:
            #do something

Body:
Can you try the following:

try:
    result =  requests.get(url=url, **kwargs)
except requests.exceptions.ChunkedEncodingError as e:
    #get the error code from e and then
    if e.errno==10054:
        #do something