问:
How to set up notifications with sound/vibration and button logo change?
I am trying to set up notification, but I can't add what I want: I would like the notification coming with sound/vibration, changing also the notification button logo.

Can anyone help me to setup notification? I am trying but it's not working.

The code below is working fine: no error. All notifications are shown, but with no sound / vibration.

```<code>package com.example.mfree.Fragment;
    import android.os.Bundle;
    import androidx.annotation.NonNull;
    import androidx.fragment.app.Fragment;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import com.example.mfree.Adapter.NotificationAdapter;
    import com.example.mfree.Model.Notification;
    import com.example.mfree.R;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;
    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 java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    /**
     * A simple {@link Fragment} subclass.
     */
    public class NotificationFragment extends Fragment {

        private RecyclerView recyclerView;
        NotificationAdapter notificationAdapter;
        private List<Notification>notificationList;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view= inflater.inflate(R.layout.fragment_notification, container, false);

            recyclerView=view.findViewById(R.id.recyler_view);
            recyclerView.setHasFixedSize(true);

            LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
            recyclerView.setLayoutManager(layoutManager);
            notificationList=new ArrayList<>();
            notificationAdapter=new NotificationAdapter(getContext(),notificationList);
            recyclerView.setAdapter(notificationAdapter);
            readNotification();

            return view;
        }

        private void readNotification() {

            FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Notifications").child(firebaseUser.getUid());

            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    notificationList.clear();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren())
                    {
                        Notification notification=snapshot.getValue(Notification.class);
                        notificationList.add(notification);

                    }
                    Collections.reverse(notificationList);
                    notificationAdapter.notifyDataSetChanged();
                }

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

                }
            });

        }

    }

**NotificationAdapter**

package com.example.mfree.Adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mfree.Fragment.PostDetailsFragment;
import com.example.mfree.Fragment.ProfileFragment;
import com.example.mfree.Model.Notification;
import com.example.mfree.Model.Post;
import com.example.mfree.Model.User;
import com.example.mfree.R;
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 java.util.List;

public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder>{

    private Context mContext;
    private List<Notification>mNotification;

    public NotificationAdapter(Context mContext, List<Notification> mNotification) {
        this.mContext = mContext;
        this.mNotification = mNotification;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(mContext).inflate(R.layout.notification_item,parent,false);
        return new NotificationAdapter.ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Notification notification=mNotification.get(position);
        holder.text.setText(notification.getText());
        getUserInfo(holder.image_profile,holder.username,notification.getUserid());
        if (notification.isIspost()){
            holder.post_image.setVisibility(View.VISIBLE);
            getPostImage(holder.post_image,notification.getPostid());
        }else {
            holder.post_image.setVisibility(View.GONE);
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(notification.isIspost()){
                    SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                    editor.putString("postid",notification.getPostid());
                    editor.apply();
                    ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
                    ,new PostDetailsFragment()).commit();

                }else {
                    SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                    editor.putString("profileid",notification.getUserid());
                    editor.apply();
                    ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
                            ,new ProfileFragment()).commit();
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return mNotification.size();
    }

    public class  ViewHolder extends RecyclerView.ViewHolder {

        public ImageView image_profile,post_image;

        TextView username,text;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            image_profile=itemView.findViewById(R.id.image_profile);
            post_image=itemView.findViewById(R.id.image_post);
            username=itemView.findViewById(R.id.username);
            text=itemView.findViewById(R.id.comment);
        }
    }
    private  void getUserInfo (final ImageView imageView, final TextView username, String publisherid){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(publisherid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                try{
                    User user=dataSnapshot.getValue(User.class);
                   Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(imageView);
                    username.setText(user.getUsername());
                }catch (Exception e)
                {
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
    private  void getPostImage(final ImageView imageView, String postid){
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference("posts").child(postid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                try {
                    Post post=dataSnapshot.getValue(Post.class);
                    Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(imageView);
                }catch (Exception e){
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

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

答:
If what you are trying to make is an in-app notification system, you can try ringing the sound on your own using RingtoneManager and Ringtone class as :

```<code>        // to play sound for your custom notification on its arrival
        Uri notificationToneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone notificationTone = RingtoneManager.getRingtone(this, notificationToneUri);
        notificationTone.play();

        //to stop
        notificationTone.stop();
</code>```

See this link for vibration

Body:
I am trying to set up notification, but I can't add what I want: I would like the notification coming with sound/vibration, changing also the notification button logo.

Can anyone help me to setup notification? I am trying but it's not working.

The code below is working fine: no error. All notifications are shown, but with no sound / vibration.

package com.example.mfree.Fragment;
    import android.os.Bundle;
    import androidx.annotation.NonNull;
    import androidx.fragment.app.Fragment;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import com.example.mfree.Adapter.NotificationAdapter;
    import com.example.mfree.Model.Notification;
    import com.example.mfree.R;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;
    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 java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    /**
     * A simple {@link Fragment} subclass.
     */
    public class NotificationFragment extends Fragment {

        private RecyclerView recyclerView;
        NotificationAdapter notificationAdapter;
        private List<Notification>notificationList;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view= inflater.inflate(R.layout.fragment_notification, container, false);

            recyclerView=view.findViewById(R.id.recyler_view);
            recyclerView.setHasFixedSize(true);

            LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
            recyclerView.setLayoutManager(layoutManager);
            notificationList=new ArrayList<>();
            notificationAdapter=new NotificationAdapter(getContext(),notificationList);
            recyclerView.setAdapter(notificationAdapter);
            readNotification();

            return view;
        }

        private void readNotification() {

            FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Notifications").child(firebaseUser.getUid());

            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    notificationList.clear();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren())
                    {
                        Notification notification=snapshot.getValue(Notification.class);
                        notificationList.add(notification);

                    }
                    Collections.reverse(notificationList);
                    notificationAdapter.notifyDataSetChanged();
                }

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

                }
            });

        }

    }

**NotificationAdapter**

package com.example.mfree.Adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mfree.Fragment.PostDetailsFragment;
import com.example.mfree.Fragment.ProfileFragment;
import com.example.mfree.Model.Notification;
import com.example.mfree.Model.Post;
import com.example.mfree.Model.User;
import com.example.mfree.R;
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 java.util.List;

public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder>{

    private Context mContext;
    private List<Notification>mNotification;

    public NotificationAdapter(Context mContext, List<Notification> mNotification) {
        this.mContext = mContext;
        this.mNotification = mNotification;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(mContext).inflate(R.layout.notification_item,parent,false);
        return new NotificationAdapter.ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Notification notification=mNotification.get(position);
        holder.text.setText(notification.getText());
        getUserInfo(holder.image_profile,holder.username,notification.getUserid());
        if (notification.isIspost()){
            holder.post_image.setVisibility(View.VISIBLE);
            getPostImage(holder.post_image,notification.getPostid());
        }else {
            holder.post_image.setVisibility(View.GONE);
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(notification.isIspost()){
                    SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                    editor.putString("postid",notification.getPostid());
                    editor.apply();
                    ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
                    ,new PostDetailsFragment()).commit();

                }else {
                    SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                    editor.putString("profileid",notification.getUserid());
                    editor.apply();
                    ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
                            ,new ProfileFragment()).commit();
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return mNotification.size();
    }

    public class  ViewHolder extends RecyclerView.ViewHolder {

        public ImageView image_profile,post_image;

        TextView username,text;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            image_profile=itemView.findViewById(R.id.image_profile);
            post_image=itemView.findViewById(R.id.image_post);
            username=itemView.findViewById(R.id.username);
            text=itemView.findViewById(R.id.comment);
        }
    }
    private  void getUserInfo (final ImageView imageView, final TextView username, String publisherid){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(publisherid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                try{
                    User user=dataSnapshot.getValue(User.class);
                   Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(imageView);
                    username.setText(user.getUsername());
                }catch (Exception e)
                {
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
    private  void getPostImage(final ImageView imageView, String postid){
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference("posts").child(postid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                try {
                    Post post=dataSnapshot.getValue(Post.class);
                    Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(imageView);
                }catch (Exception e){
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

Body:
If what you are trying to make is an in-app notification system, you can try ringing the sound on your own using RingtoneManager and Ringtone class as :

        // to play sound for your custom notification on its arrival
        Uri notificationToneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone notificationTone = RingtoneManager.getRingtone(this, notificationToneUri);
        notificationTone.play();

        //to stop
        notificationTone.stop();

See this link for vibration


来源: stackexchange

问:
How to get pod names from deployment?
We have created deployments which in turns creates pod.
I need to get the Pod names created by my deployment file.

```<code>kubectl get -f deployment.yml
</code>```

The above command list the deployment names. If i type kubectl get pod it displays the pod names which is having some random extra strings added with deployment names.

Even if i use the -o json option still unable to get the pod names.

How to get all the pods created by deployment? Even a shell script way would be fine.

my deployment file looks below

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    ansible: test-2020-05-26-00-04-1590476651
    podRef: pod-ansibles
  name: rd-2020-05-26-00-04-1590476651
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: nginx
        ...
        ....
</code>```

so is there any way that i can get all pods which has deployment label 'test-2020-05-26-00-04-1590476651' ?

when i tried 'kubectl get pod -l ansible=test-2020-05-26-00-04-1590476651' . it shows

'No resources found in default namespace.' seems it can only display deploy name 'kubectl get deploy -l ansible=test-2020-05-26-00-04-1590476651'

But i need all pod names which is under a deployment..

答:
Usually, we label deployment's pods.

```<code>  template:
    metadata:
      labels:
        app: my-app
</code>```

So, we can get all pod filter by label

```<code>kubectl get pod -l app=my-app
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get pod names from deployment?

Body:
We have created deployments which in turns creates pod.
I need to get the Pod names created by my deployment file.

kubectl get -f deployment.yml

The above command list the deployment names. If i type kubectl get pod it displays the pod names which is having some random extra strings added with deployment names.

Even if i use the -o json option still unable to get the pod names.

How to get all the pods created by deployment? Even a shell script way would be fine.

my deployment file looks below

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    ansible: test-2020-05-26-00-04-1590476651
    podRef: pod-ansibles
  name: rd-2020-05-26-00-04-1590476651
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: nginx
        ...
        ....

so is there any way that i can get all pods which has deployment label 'test-2020-05-26-00-04-1590476651' ?

when i tried 'kubectl get pod -l ansible=test-2020-05-26-00-04-1590476651' . it shows

'No resources found in default namespace.' seems it can only display deploy name 'kubectl get deploy -l ansible=test-2020-05-26-00-04-1590476651'

But i need all pod names which is under a deployment..

Body:
Usually, we label deployment's pods.

  template:
    metadata:
      labels:
        app: my-app

So, we can get all pod filter by label

kubectl get pod -l app=my-app


问:
Problem with AJAX chat
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

```<code>function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}
</code>```

Then the text field :

```<code>  <div id="sender">
     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>
  </div>
</code>```

And finally the php file:

```<code>$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);
</code>```

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

答:
doWork(document.getElementById('msg'));

this there is a button element. It has no msg property i.e. undefined, within string conversion.

ContentLicense: CC BY-SA 3.0

Title: Problem with AJAX chat

Body:
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}

Then the text field :

     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>

And finally the php file:

$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron


问:
Using Selenium to enter text into Rich Text editor
Here is a screen shot

RichTextEditor

What is the best way to use Selenium C# to enter text into this text box?

答: Target your SendKeys to the div element of that richtext that has attribute contenteditable='true'</p>


问:
How to remove and add css styles using javascript - added style not reflected in UI
I have created a stackblitz for my code.
https://stackblitz.com/edit/ngxdatatable-sort-test-qfeux3?file=src/app/app.component.ts

Basically i am trying to add a custom icon if sorting is not performed on the columns.
If any sorting is performed, I am retaining the existing icon.

While trying to add the custom icon, I am removing the existing classnames and adding the new icon.
When i debug, i can see the new custom icon getting added, but after execution , the added custom icon is getting removed.

答:
I checked your code and after the following changes, I am able to see the icon change. Try to check if this is the problem.</p>

```<code>onSort(event){
    const name: string = event.column.name;
    name = name.toLowerCase();
    console.log(event);
    if(name=="company") {
      event.sorts.push({"id":0});
    }
     if(name =="name") {
      event.sorts.push({"id":1});
    }

     if(name=="age") {
      event.sorts.push({"id":3});
    }
     for (let i = 0; i < this.columns.length; i++) {
       console.log("id value",event.sorts[1].id);
        console.log("i value",i);
       if(event.sorts[1].id == i){
         console.log("inside id value",event.sorts[1].id);
         console.log("inside i value",i);
         console.log("do nothing");
       } else {
         console.log('change icon');
         // here i am removing the existing icon and adding the custom icon
             document.getElementsByClassName("sort-btn")[i].classList.remove(
           "datatable-icon-down");
           document.getElementsByClassName("sort-btn")[i].classList.remove("sort-desc");
            document.getElementsByClassName("sort-btn")[i].classList.remove(
           "datatable-icon-up");
           document.getElementsByClassName("sort-btn")[i].classList.remove("sort-asc");
  // running in debug mode, during execution i can see custom icon getting added, but after execution i am not able to see the added icon,
    if (i == 2) {
      document.getElementsByClassName("sort-btn")[i].classList.remove("datatable-iconCustom");
       } else {
           setTimeout(()=>{

           document.getElementsByClassName("sort-btn")[i].classList.add("datatable-iconCustom");
         },10);

       }
       }
        }
  }
</code>```

Body:
I checked your code and after the following changes, I am able to see the icon change. Try to check if this is the problem.

onSort(event){
    const name: string = event.column.name;
    name = name.toLowerCase();
    console.log(event);
    if(name=="company") {
      event.sorts.push({"id":0});
    }
     if(name =="name") {
      event.sorts.push({"id":1});
    }

     if(name=="age") {
      event.sorts.push({"id":3});
    }
     for (let i = 0; i < this.columns.length; i++) {
       console.log("id value",event.sorts[1].id);
        console.log("i value",i);
       if(event.sorts[1].id == i){
         console.log("inside id value",event.sorts[1].id);
         console.log("inside i value",i);
         console.log("do nothing");
       } else {
         console.log('change icon');
         // here i am removing the existing icon and adding the custom icon
             document.getElementsByClassName("sort-btn")[i].classList.remove(
           "datatable-icon-down");
           document.getElementsByClassName("sort-btn")[i].classList.remove("sort-desc");
            document.getElementsByClassName("sort-btn")[i].classList.remove(
           "datatable-icon-up");
           document.getElementsByClassName("sort-btn")[i].classList.remove("sort-asc");
  // running in debug mode, during execution i can see custom icon getting added, but after execution i am not able to see the added icon,
    if (i == 2) {
      document.getElementsByClassName("sort-btn")[i].classList.remove("datatable-iconCustom");
       } else {
           setTimeout(()=>{

           document.getElementsByClassName("sort-btn")[i].classList.add("datatable-iconCustom");
         },10);

       }
       }
        }
  }


问:
Counting words using c
I would like to know why my code isn't compiling properly. What I'm trying to accomplish is counting words. I already have where it asks for spaces but that doesn't work if it's multiple sentences in one string. Because it will count the space after a punctuation mark as a word when the punctuation mark is doing the same.

```<code> while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            count++;
        }
        if (isspace(s[n])) //count words
        {
            word++;
        }
        if (s[n] == '.' || s[n] == '?' || s[n] == '!')
        {
            else if (s[n + 1] isspace) //This is the problem
            {
                word--;
            }
            sent++;
            word++;
        }
        n++;
    }
</code>```

I'm pretty sure that this would be correct, but it's not compiling properly so im kinda just stuck here. from my understanding saying (s[n + 1]) is saying if the letter after the one it is currently checking is a space then see if it is a space, if true then word-- else word++. If this is wrong can you please tell me why.

答:
This code can compile without error:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main()

{

 char s[10] = "";
 int n = 0;
 int count =  0;
 int word = 0;
 int sent = 0;

 while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            count++;
        }
        if (isspace(s[n])) //count words
        {
            word++;
        }
        if (s[n] == '.' || s[n] == '?' || s[n] == '!')
        {
          // What to do here ?
        }
        else if (isspace(s[n + 1]))
        {
                word--;
        }
           sent++;
           word++;
     }
        n++;
}
</code>```

Title: Counting words using c

Body:
I would like to know why my code isn't compiling properly. What I'm trying to accomplish is counting words. I already have where it asks for spaces but that doesn't work if it's multiple sentences in one string. Because it will count the space after a punctuation mark as a word when the punctuation mark is doing the same.

 while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            count++;
        }
        if (isspace(s[n])) //count words
        {
            word++;
        }
        if (s[n] == '.' || s[n] == '?' || s[n] == '!')
        {
            else if (s[n + 1] isspace) //This is the problem
            {
                word--;
            }
            sent++;
            word++;
        }
        n++;
    }

I'm pretty sure that this would be correct, but it's not compiling properly so im kinda just stuck here. from my understanding saying (s[n + 1]) is saying if the letter after the one it is currently checking is a space then see if it is a space, if true then word-- else word++. If this is wrong can you please tell me why.

Body:
This code can compile without error:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main()

{

 char s[10] = "";
 int n = 0;
 int count =  0;
 int word = 0;
 int sent = 0;

 while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            count++;
        }
        if (isspace(s[n])) //count words
        {
            word++;
        }
        if (s[n] == '.' || s[n] == '?' || s[n] == '!')
        {
          // What to do here ?
        }
        else if (isspace(s[n + 1]))
        {
                word--;
        }
           sent++;
           word++;
     }
        n++;
}


问:
Stuck in "Syncing files to device Chrome"
I use VS as my IDE.

I set all up for web development and the command flutter doctor doesn't state any errors.

When I run my project with Chrome as device, VS gets stuck in "Syncing files to device Chrome".

I also tried running my project through terminal with flutter run -d chrome --verbose, the strange thing that happens when I run that command is that it Syncs successfully all the files (at least that's what the – verbose states) but the browser doesn't show any content.

There aren't errors in the browser console and I have the latest version installed.

答:
I had similar issue and the problem was my index.html file was not pointing to my home page because I've changed the file name. Go to your index.html file under the web folder and check whether the script src is pointing to the correct path of your main function.</p>

```<code> <script src="main.dart.js" type="application/javascript"></script>
</code>```

Body:
I had similar issue and the problem was my index.html file was not pointing to my home page because I've changed the file name. Go to your index.html file under the web folder and check whether the script src is pointing to the correct path of your main function.

 <script src="main.dart.js" type="application/javascript"></script>


问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答:
For [1], you can't: these operators are made to return a value, not perform operations.

The expression

```<code>a ? b : c
</code>```

evaluates to b if a is true and evaluates to c if a is false.

The expression

```<code>b ?? c
</code>```

evaluates to b if b is not null and evaluates to c if b is null.

If you write

```<code>return a ? b : c;
</code>```

or

```<code>return b ?? c;
</code>```

they will always return something.

For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

Body:
For [1], you can't: these operators are made to return a value, not perform operations.

The expression

a ? b : c

evaluates to b if a is true and evaluates to c if a is false.

The expression

b ?? c

evaluates to b if b is not null and evaluates to c if b is null.

If you write

return a ? b : c;

or

return b ?? c;

they will always return something.

For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.


问:
Syntax Error- in Sqlite3 code when inserting data in table
I am writing a code to make a basic table and insert data into it using Sqlite3 in Python 3. The CMD is showing syntax error by putting a pointer at a data set.

```<code>import sqlite3
conn=squlite3.connect('name.sqlite')
cur=conn.cursor()
cur.execute('CREATE TABLE Ages (name TEXT, age INTEGER)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Abiha', 33)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Catrin', 29)')
conn.commit()
cur.execute('SELECT name,age FROM Ages')
for row in cur:
    print(row)
conn.close()
</code>```

This is what the CMD shows:

```<code>cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
                                                   ^
SyntaxError: invalid syntax
</code>```

If you know what is wrong with it please let me know!

答:
You are using single quotes for your execute statements, this is causing Python to see Cael, Abiha and Catrin as an expected variable or keyword.

Change your execute statements to use double quotes like so:

```<code>cur.execute("CREATE TABLE Ages (name TEXT, age INTEGER)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Cael', 16)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Abiha', 33)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Catrin', 29)")
</code>```

You could also escape them like so \' but the above is better.

Body:
I am writing a code to make a basic table and insert data into it using Sqlite3 in Python 3. The CMD is showing syntax error by putting a pointer at a data set.

import sqlite3
conn=squlite3.connect('name.sqlite')
cur=conn.cursor()
cur.execute('CREATE TABLE Ages (name TEXT, age INTEGER)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Abiha', 33)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Catrin', 29)')
conn.commit()
cur.execute('SELECT name,age FROM Ages')
for row in cur:
    print(row)
conn.close()

This is what the CMD shows:

cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
                                                   ^
SyntaxError: invalid syntax

If you know what is wrong with it please let me know!

Body:
You are using single quotes for your execute statements, this is causing Python to see Cael, Abiha and Catrin as an expected variable or keyword.

Change your execute statements to use double quotes like so:

cur.execute("CREATE TABLE Ages (name TEXT, age INTEGER)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Cael', 16)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Abiha', 33)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Catrin', 29)")

You could also escape them like so \' but the above is better.


问:
Mask certain string attributes in Java during logging?
Is there a way I can mask certain string variables of a class like password, etc which will prevent during logging? Like overriding toString() method in such way it does not print in logs.

For instance, we have a class Employee with following fields:

```<code>public class Employee {
    private String username;
    **private String password; //mask this field**
    private String city;
}
</code>```

During logging like

LOGGER.INFO("printing object:"+employee);

Here in logging, I'm trying to print the whole object, Employee here and my requirement is it does not print out masked field, password at all and whereas logging of rest of the fields are fine.

答:
If you are using lombok,  try the exclude option for ToString.

```<code>@Data
@ToString(exclude = {"password"})
public class Employee {
    private String username;
    private String password;
    private String city;
}
</code>```

Body:
Is there a way I can mask certain string variables of a class like password, etc which will prevent during logging? Like overriding toString() method in such way it does not print in logs.

For instance, we have a class Employee with following fields:

public class Employee {
    private String username;
    **private String password; //mask this field**
    private String city;
}

During logging like

LOGGER.INFO("printing object:"+employee);

Here in logging, I'm trying to print the whole object, Employee here and my requirement is it does not print out masked field, password at all and whereas logging of rest of the fields are fine.

Body:
If you are using lombok,  try the exclude option for ToString.

@Data
@ToString(exclude = {"password"})
public class Employee {
    private String username;
    private String password;
    private String city;
}


问:
Subquery within scalar subquery fails with error ORA-00936 Missing Expression

This is the query that does not work:

```<code>SELECT distinct ord.DateOrdered
   , (SELECT docno
      FROM th_mm_c_orderline_history
      WHERE th_mm_c_orderline_history_id
            in (SELECT max(th_mm_c_orderline_history_id)
                FROM th_mm_c_orderline_history
                GROUP BY c_orderline_id )
      order by docno,c_orderline_id) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history
      on th_mm_c_orderline_history.c_order_id=ord.c_order_id
</code>```

It is throwing me ORA-00936 Missing expression error

This query works fine:

```<code>SELECT docno
FROM th_mm_c_orderline_history
WHERE th_mm_c_orderline_history_id
      in (SELECT max(th_mm_c_orderline_history_id)
          FROM th_mm_c_orderline_history
          GROUP BY c_orderline_id )
order by docno,c_orderline_id as docno
</code>```

答:
You can use "order by statement" end of the whole select statement. Because of not use the column C_ORDERLINE_ID in select statement, it can be error in order by statement. Try this version in below.</p>

```<code> SELECT DISTINCT
       C_ORDER.DATEORDER,
       (SELECT DOCNO
          FROM TH_MM_C_ORDERLINE_HISTORY
         WHERE     C_ORDER_ID = C_ORDER_ID
               AND TH_MM_C_ORDERLINE_HISTORY_ID IN (  SELECT MAX (TH_MM_C_ORDERLINE_HISTORY_ID)
                                                        FROM TH_MM_C_ORDERLINE_HISTORY
                                                    GROUP BY C_ORDERLINE_ID)) AS DOCNO,
       C_ORDER.DOCUMENTNO
  FROM C_ORDER
  INNER JOIN C_ORDERLINE ON C_ORDERLINE.C_ORDER_ID = C_ORDER_ID
  ORDER BY DOCNO, C_ORDERLINE_ID;
</code>```

Body:
This is the query that does not work:

SELECT distinct ord.DateOrdered
   , (SELECT docno
      FROM th_mm_c_orderline_history
      WHERE th_mm_c_orderline_history_id
            in (SELECT max(th_mm_c_orderline_history_id)
                FROM th_mm_c_orderline_history
                GROUP BY c_orderline_id )
      order by docno,c_orderline_id) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history
      on th_mm_c_orderline_history.c_order_id=ord.c_order_id

It is throwing me ORA-00936 Missing expression error

This query works fine:

SELECT docno
FROM th_mm_c_orderline_history
WHERE th_mm_c_orderline_history_id
      in (SELECT max(th_mm_c_orderline_history_id)
          FROM th_mm_c_orderline_history
          GROUP BY c_orderline_id )
order by docno,c_orderline_id as docno

Body:
You can use "order by statement" end of the whole select statement. Because of not use the column C_ORDERLINE_ID in select statement, it can be error in order by statement. Try this version in below.

 SELECT DISTINCT
       C_ORDER.DATEORDER,
       (SELECT DOCNO
          FROM TH_MM_C_ORDERLINE_HISTORY
         WHERE     C_ORDER_ID = C_ORDER_ID
               AND TH_MM_C_ORDERLINE_HISTORY_ID IN (  SELECT MAX (TH_MM_C_ORDERLINE_HISTORY_ID)
                                                        FROM TH_MM_C_ORDERLINE_HISTORY
                                                    GROUP BY C_ORDERLINE_ID)) AS DOCNO,
       C_ORDER.DOCUMENTNO
  FROM C_ORDER
  INNER JOIN C_ORDERLINE ON C_ORDERLINE.C_ORDER_ID = C_ORDER_ID
  ORDER BY DOCNO, C_ORDERLINE_ID;


问:
PHP-FPM core dump not generated
I am trying to generate core dumps when PHP fails with WARNING: [pool www] child 2756 exited on signal 11 (SIGSEGV) after 153.518521 seconds from start.
I am using a custom Docker container based on Alpine hosted on ECS.

I've followed multiple guides but PHP-FPM doesn't generate core dumps (I can generate core dump with php cli or with kill -s SIGSEGV $$). Guides I followed :
- https://ma.ttias.be/generate-php-core-dumps-segfaults-php-fpm/ https://www.bggofurther.com/2015/04/generating-core-dumps-for-php-fpm/
- Core dump file is not generated

My config is the following :

```<code>/ # ulimit -c
unlimited

/ # cat /proc/sys/kernel/core_pattern
/tmp/core-dumps/core-%t-%p

/ # cat /proc/sys/kernel/core_uses_pid
0

/ # php-fpm -tt
[global]
 pid = undefined
 error_log = /proc/self/fd/2
 syslog.ident = php-fpm
 syslog.facility = 24
 log_buffering = yes
 log_level = unknown value
 log_limit = 8192
 emergency_restart_interval = 0s
 emergency_restart_threshold = 0
 process_control_timeout = 0s
 process.max = 0
 process.priority = undefined
 daemonize = no
 rlimit_files = 0
 rlimit_core = 0
 events.mechanism = epoll

[www]
 prefix = undefined
 user = www-data
 group = www-data
 listen = 9000
 listen.backlog = 511
 listen.owner = undefined
 listen.group = undefined
 listen.mode = undefined
 listen.allowed_clients = undefined
 process.priority = undefined
 process.dumpable = no
 pm = dynamic
 pm.max_children = 35
 pm.start_servers = 6
 pm.min_spare_servers = 4
 pm.max_spare_servers = 8
 pm.process_idle_timeout = 10
 pm.max_requests = 500
 pm.status_path = /_/php-fpm/status
 ping.path = undefined
 ping.response = undefined
 access.log = /proc/self/fd/2
 access.format = [%{%Y-%m-%dT%H:%M:%S%z}t] %R "%m %{REQUEST_SCHEME}e://%{HTTP_HOST}e%{REQUEST_URI}e" %s %f %{mili}d %{kilo}M %C%%
 slowlog = undefined
 request_slowlog_timeout = 0s
 request_slowlog_trace_depth = 20
 request_terminate_timeout = 0s
 request_terminate_timeout_track_finished = no
 rlimit_files = 0
 rlimit_core = unlimited
 chroot = undefined
 chdir = undefined
 catch_workers_output = yes
 decorate_workers_output = no
 clear_env = no
 security.limit_extensions = .php .phar

configuration file /usr/local/etc/php-fpm.conf test is successful
</code>```

I tried with /proc/sys/kernel/core_uses_pid to 1 and with process.dumpable = yes but core dumps are still not generated.
I suppose there is an issue with PHP-FPM config because when I execute a script in cli (I mean like php generate_sigsegv.php) the core dump is well generated. However, I have no clues why things are going wrong.

For the CLI I use this script :

```<code><?php

  function segfault ($i = 1) {
    echo "$i\n";
    segfault($i + 1);
  }

  segfault();

?>
</code>```

For PHP-FPM I am investigating a bug in my app so I have an API to call to generate SIGSEGV.

答:
The issue was rights on folder where core dumps are generated. Ensure the user used by PHP-FPM has rights to write on the folder.
Because PHP in CLI is executed with the user in your container (mainly root), you may have rights but not PHP-FPM.</p>

Title: PHP-FPM core dump not generated

Body:
I am trying to generate core dumps when PHP fails with WARNING: [pool www] child 2756 exited on signal 11 (SIGSEGV) after 153.518521 seconds from start.
I am using a custom Docker container based on Alpine hosted on ECS.

I've followed multiple guides but PHP-FPM doesn't generate core dumps (I can generate core dump with php cli or with kill -s SIGSEGV $$). Guides I followed :
- https://ma.ttias.be/generate-php-core-dumps-segfaults-php-fpm/ https://www.bggofurther.com/2015/04/generating-core-dumps-for-php-fpm/
- Core dump file is not generated

My config is the following :

/ # ulimit -c
unlimited

/ # cat /proc/sys/kernel/core_pattern
/tmp/core-dumps/core-%t-%p

/ # cat /proc/sys/kernel/core_uses_pid
0

/ # php-fpm -tt
[global]
 pid = undefined
 error_log = /proc/self/fd/2
 syslog.ident = php-fpm
 syslog.facility = 24
 log_buffering = yes
 log_level = unknown value
 log_limit = 8192
 emergency_restart_interval = 0s
 emergency_restart_threshold = 0
 process_control_timeout = 0s
 process.max = 0
 process.priority = undefined
 daemonize = no
 rlimit_files = 0
 rlimit_core = 0
 events.mechanism = epoll

[www]
 prefix = undefined
 user = www-data
 group = www-data
 listen = 9000
 listen.backlog = 511
 listen.owner = undefined
 listen.group = undefined
 listen.mode = undefined
 listen.allowed_clients = undefined
 process.priority = undefined
 process.dumpable = no
 pm = dynamic
 pm.max_children = 35
 pm.start_servers = 6
 pm.min_spare_servers = 4
 pm.max_spare_servers = 8
 pm.process_idle_timeout = 10
 pm.max_requests = 500
 pm.status_path = /_/php-fpm/status
 ping.path = undefined
 ping.response = undefined
 access.log = /proc/self/fd/2
 access.format = [%{%Y-%m-%dT%H:%M:%S%z}t] %R "%m %{REQUEST_SCHEME}e://%{HTTP_HOST}e%{REQUEST_URI}e" %s %f %{mili}d %{kilo}M %C%%
 slowlog = undefined
 request_slowlog_timeout = 0s
 request_slowlog_trace_depth = 20
 request_terminate_timeout = 0s
 request_terminate_timeout_track_finished = no
 rlimit_files = 0
 rlimit_core = unlimited
 chroot = undefined
 chdir = undefined
 catch_workers_output = yes
 decorate_workers_output = no
 clear_env = no
 security.limit_extensions = .php .phar

configuration file /usr/local/etc/php-fpm.conf test is successful

I tried with /proc/sys/kernel/core_uses_pid to 1 and with process.dumpable = yes but core dumps are still not generated.
I suppose there is an issue with PHP-FPM config because when I execute a script in cli (I mean like php generate_sigsegv.php) the core dump is well generated. However, I have no clues why things are going wrong.

For the CLI I use this script :

<?php

  function segfault ($i = 1) {
    echo "$i\n";
    segfault($i + 1);
  }

  segfault();

?>

For PHP-FPM I am investigating a bug in my app so I have an API to call to generate SIGSEGV.


问:
Copy file from One Zone to Other - Azure Data Lake Gen2
I want to copy a file with given path from One Zone of Azure Data Lake to Other Zone of Data Lake.

Example:

Source: /RawZone/Incremental/2020/05/01/file.parquet

Destination: /StdZone/Incremental/2020/05/01/file.parquet

Should i be using Copy Activity to read source as dataset and write to Destination.  Or is there a way to just copy file from source to destination in Azure Data Factory.

答:
As far as I am aware the Copy Activity is the only way.

You will need a dataset to define where the file is coming from and going (though the path can be parameterised) and its format.

If you want to copy the file as is without alteration, set the dataset format to binary to avoid having to define the file structure and 'waste time' extracting and parsing the data within.


问:
How to edit string in .ini file with user input VBScript
I have .ini file and I need to edit one line of that with user input

```<code>##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%
</code>```

In this .ini file I need to change the

```<code>PlayerName = SoulFlyers
</code>```

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

```<code>    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************
</code>```

but it adds lines to .ini files.

How can I solve it?

Thanks.

答:
thanks from all.
i found the solution for my code.
first ask from user to enter his name then, run the prgrom</p>

```<code>    Dim fso, objOutFile,PlayerName,fileStream,ws,objShell
    Do
     PlayerName = inputbox("Please Enter Your Name")
    Loop Until PlayerName <> ""
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objOutFile = fso.CreateTextFile("D:\Program Files (x86)\Games\game\user.ini",True)

objOutFile.WriteLine "##  General configuration attempt:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[Settings]"
objOutFile.WriteLine "AppId = 1843"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "UnlockAllDLCs = 1"
objOutFile.WriteLine "UbiConnection = 0"
objOutFile.WriteLine "IsUserConnected = 1"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "PlayerName = " & PlayerName
objOutFile.WriteLine "Language = en-US"
objOutFile.WriteLine "SaveLocation = %standard%"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "Email = soul@******m"
objOutFile.WriteLine "Password = so*****rd1234"
objOutFile.WriteLine "CdKey = AAAA-BBB*****D"
objOutFile.WriteLine "AccountId = c******c2c1"
objOutFile.WriteLine "TicketId = SoulFl****vers"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "###"
objOutFile.WriteLine "##    Insert the DLC list that you wish to unlock here:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[DLC]"
objOutFile.WriteLine "; %appid% = %Name%"
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""D:\Program Files (x86)\Games\\game.exe""")
</code>```

Body:
I have .ini file and I need to edit one line of that with user input

##  General configuration attempt:
###
[Settings]
AppId = 1843
;.................................................
UnlockAllDLCs = 1
UbiConnection = 0
IsUserConnected = 1
;.................................................
PlayerName = SoulFlyers
Language = en-US
SaveLocation = %standard%
;.................................................
Email = *****@flyers.com
Password = so*****1234
CdKey = AAAA-BBBB-CCCC-DDDD
AccountId = ********
TicketId = SoulFlye*****Lovers
;.................................................
###
##  Insert the DLC list that you wish to unlock here:
###
[DLC]
; %appid% = %Name%

In this .ini file I need to change the

PlayerName = SoulFlyers

with user input.

I tried with objOutFile.WriteLine and fileStream.WriteLine like this:

    Option Explicit
Const ForAppending = 8
Dim ws,fso,RootFolder,MyFile,firstNameInput,fileStream
Do
    firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""

Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop")
MyFile = RootFolder & "\Edit.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileStream = fso.OpenTextFile(MyFile,ForAppending,True)
fileStream.WriteLine String(50,"*")
fileStream.WriteLine "First name: " & firstNameInput
fileStream.Close
ws.run DblQuote(MyFile)
'*****************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************

but it adds lines to .ini files.

How can I solve it?

Thanks.

Body:
thanks from all.
i found the solution for my code.
first ask from user to enter his name then, run the prgrom

    Dim fso, objOutFile,PlayerName,fileStream,ws,objShell
    Do
     PlayerName = inputbox("Please Enter Your Name")
    Loop Until PlayerName <> ""
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objOutFile = fso.CreateTextFile("D:\Program Files (x86)\Games\game\user.ini",True)

objOutFile.WriteLine "##  General configuration attempt:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[Settings]"
objOutFile.WriteLine "AppId = 1843"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "UnlockAllDLCs = 1"
objOutFile.WriteLine "UbiConnection = 0"
objOutFile.WriteLine "IsUserConnected = 1"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "PlayerName = " & PlayerName
objOutFile.WriteLine "Language = en-US"
objOutFile.WriteLine "SaveLocation = %standard%"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "Email = soul@******m"
objOutFile.WriteLine "Password = so*****rd1234"
objOutFile.WriteLine "CdKey = AAAA-BBB*****D"
objOutFile.WriteLine "AccountId = c******c2c1"
objOutFile.WriteLine "TicketId = SoulFl****vers"
objOutFile.WriteLine ";................................................."
objOutFile.WriteLine "###"
objOutFile.WriteLine "##    Insert the DLC list that you wish to unlock here:"
objOutFile.WriteLine "###"
objOutFile.WriteLine "[DLC]"
objOutFile.WriteLine "; %appid% = %Name%"
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""D:\Program Files (x86)\Games\\game.exe""")


问:
Difference between "CPU OpenCL Project" and "GPU OpenCL Project"
I installed the Intel OpenCL SDK and I wanted to create a project. Visual Studio 2017 showed me those two options and a third "Empty OpenCL Project". I don't know what the difference between the two is. I tried to look through the template code but since I don't (yet) know anything about OpenCL I couldn't understand their difference.

License header:

```<code>/*****************************************************************************
 * Copyright (c) 2013-2016 Intel Corporation
 * All rights reserved.
 *
 * WARRANTY DISCLAIMER
 *
 * THESE MATERIALS ARE PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THESE
 * MATERIALS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Intel Corporation is the author of the Materials, and requests that all
 * problem reports or change requests be submitted to it directly
 *****************************************************************************/
</code>```

I ran a diff as suggested:

```<code>625,629c625,626
<     // Create new OpenCL buffer objects
<     // As these buffer are used only for read by the kernel, you are recommended to create it with flag CL_MEM_READ_ONLY.
<     // Always set minimal read/write flags for buffers, it may lead to better performance because it allows runtime
<     // to better organize data copying.
<     // You use CL_MEM_COPY_HOST_PTR here, because the buffers should be populated with bytes at inputA and inputB.
---
>     cl_image_format format;
>     cl_image_desc desc;
631c628,650
<     ocl->srcA = clCreateBuffer(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, inputA, &err);
---
>     // Define the image data-type and order -
>     // one channel (R) with unit values
>     format.image_channel_data_type = CL_UNSIGNED_INT32;
>     format.image_channel_order     = CL_R;
>
>     // Define the image properties (descriptor)
>     desc.image_type        = CL_MEM_OBJECT_IMAGE2D;
>     desc.image_width       = arrayWidth;
>     desc.image_height      = arrayHeight;
>     desc.image_depth       = 0;
>     desc.image_array_size  = 1;
>     desc.image_row_pitch   = 0;
>     desc.image_slice_pitch = 0;
>     desc.num_mip_levels    = 0;
>     desc.num_samples       = 0;
> #ifdef CL_VERSION_2_0
>     desc.mem_object        = NULL;
> #else
>     desc.buffer            = NULL;
> #endif
>
>     // Create first image based on host memory inputA
>     ocl->srcA = clCreateImage(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, inputA, &err);
634c653
<         LogError("Error: clCreateBuffer for srcA returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for srcA returned %s\n", TranslateOpenCLError(err));
638c657,658
<     ocl->srcB = clCreateBuffer(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, inputB, &err);
---
>     // Create second image based on host memory inputB
>     ocl->srcB = clCreateImage(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, inputB, &err);
641c661
<         LogError("Error: clCreateBuffer for srcB returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for srcB returned %s\n", TranslateOpenCLError(err));
645,649c665,666
<     // If the output buffer is created directly on top of output buffer using CL_MEM_USE_HOST_PTR,
<     // then, depending on the OpenCL runtime implementation and hardware capabilities,
<     // it may save you not necessary data copying.
<     // As it is known that output buffer will be write only, you explicitly declare it using CL_MEM_WRITE_ONLY.
<     ocl->dstMem = clCreateBuffer(ocl->context, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, outputC, &err);
---
>     // Create third (output) image based on host memory outputC
>     ocl->dstMem = clCreateImage(ocl->context, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, outputC, &err);
652c669
<         LogError("Error: clCreateBuffer for dstMem returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for dstMem returned %s\n", TranslateOpenCLError(err));
734c751,755
<     cl_int *resultPtr = (cl_int *)clEnqueueMapBuffer(ocl->commandQueue, ocl->dstMem, true, CL_MAP_READ, 0, sizeof(cl_uint) * width * height, 0, NULL, NULL, &err);
---
>     size_t origin[] = {0, 0, 0};
>     size_t region[] = {width, height, 1};
>     size_t image_row_pitch;
>     size_t image_slice_pitch;
>     cl_int *resultPtr = (cl_int *)clEnqueueMapImage(ocl->commandQueue, ocl->dstMem, true, CL_MAP_READ, origin, region, &image_row_pitch, &image_slice_pitch, 0, NULL, NULL, &err);
783c804
<     cl_device_type deviceType = CL_DEVICE_TYPE_CPU;
---
>     cl_device_type deviceType = CL_DEVICE_TYPE_GPU;
</code>```

I could also paste int the two complete source files but they are long (900 lines).

答:
You've sort of answered it yourself with the diff.
In the diff output you can see one project uses a clBuffer object while the other uses the clImage.

Image support is optional in the OpenCL standard, so it depends on the device and driver. GPU devices may have better performance with the image type, and most if not all Intel integrated GPUs support the image types (AFAIK).

Both codes use the host pointer, which works well on Intel devices as the iGPU and CPU can address the same memory, or at least behave that way. However, this may not always be optimal for discrete GPUs.

Body:
I installed the Intel OpenCL SDK and I wanted to create a project. Visual Studio 2017 showed me those two options and a third "Empty OpenCL Project". I don't know what the difference between the two is. I tried to look through the template code but since I don't (yet) know anything about OpenCL I couldn't understand their difference.

License header:

/*****************************************************************************
 * Copyright (c) 2013-2016 Intel Corporation
 * All rights reserved.
 *
 * WARRANTY DISCLAIMER
 *
 * THESE MATERIALS ARE PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THESE
 * MATERIALS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Intel Corporation is the author of the Materials, and requests that all
 * problem reports or change requests be submitted to it directly
 *****************************************************************************/

I ran a diff as suggested:

625,629c625,626
<     // Create new OpenCL buffer objects
<     // As these buffer are used only for read by the kernel, you are recommended to create it with flag CL_MEM_READ_ONLY.
<     // Always set minimal read/write flags for buffers, it may lead to better performance because it allows runtime
<     // to better organize data copying.
<     // You use CL_MEM_COPY_HOST_PTR here, because the buffers should be populated with bytes at inputA and inputB.
---
>     cl_image_format format;
>     cl_image_desc desc;
631c628,650
<     ocl->srcA = clCreateBuffer(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, inputA, &err);
---
>     // Define the image data-type and order -
>     // one channel (R) with unit values
>     format.image_channel_data_type = CL_UNSIGNED_INT32;
>     format.image_channel_order     = CL_R;
>
>     // Define the image properties (descriptor)
>     desc.image_type        = CL_MEM_OBJECT_IMAGE2D;
>     desc.image_width       = arrayWidth;
>     desc.image_height      = arrayHeight;
>     desc.image_depth       = 0;
>     desc.image_array_size  = 1;
>     desc.image_row_pitch   = 0;
>     desc.image_slice_pitch = 0;
>     desc.num_mip_levels    = 0;
>     desc.num_samples       = 0;
> #ifdef CL_VERSION_2_0
>     desc.mem_object        = NULL;
> #else
>     desc.buffer            = NULL;
> #endif
>
>     // Create first image based on host memory inputA
>     ocl->srcA = clCreateImage(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, inputA, &err);
634c653
<         LogError("Error: clCreateBuffer for srcA returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for srcA returned %s\n", TranslateOpenCLError(err));
638c657,658
<     ocl->srcB = clCreateBuffer(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, inputB, &err);
---
>     // Create second image based on host memory inputB
>     ocl->srcB = clCreateImage(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, inputB, &err);
641c661
<         LogError("Error: clCreateBuffer for srcB returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for srcB returned %s\n", TranslateOpenCLError(err));
645,649c665,666
<     // If the output buffer is created directly on top of output buffer using CL_MEM_USE_HOST_PTR,
<     // then, depending on the OpenCL runtime implementation and hardware capabilities,
<     // it may save you not necessary data copying.
<     // As it is known that output buffer will be write only, you explicitly declare it using CL_MEM_WRITE_ONLY.
<     ocl->dstMem = clCreateBuffer(ocl->context, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_uint) * arrayWidth * arrayHeight, outputC, &err);
---
>     // Create third (output) image based on host memory outputC
>     ocl->dstMem = clCreateImage(ocl->context, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, &format, &desc, outputC, &err);
652c669
<         LogError("Error: clCreateBuffer for dstMem returned %s\n", TranslateOpenCLError(err));
---
>         LogError("Error: clCreateImage for dstMem returned %s\n", TranslateOpenCLError(err));
734c751,755
<     cl_int *resultPtr = (cl_int *)clEnqueueMapBuffer(ocl->commandQueue, ocl->dstMem, true, CL_MAP_READ, 0, sizeof(cl_uint) * width * height, 0, NULL, NULL, &err);
---
>     size_t origin[] = {0, 0, 0};
>     size_t region[] = {width, height, 1};
>     size_t image_row_pitch;
>     size_t image_slice_pitch;
>     cl_int *resultPtr = (cl_int *)clEnqueueMapImage(ocl->commandQueue, ocl->dstMem, true, CL_MAP_READ, origin, region, &image_row_pitch, &image_slice_pitch, 0, NULL, NULL, &err);
783c804
<     cl_device_type deviceType = CL_DEVICE_TYPE_CPU;
---
>     cl_device_type deviceType = CL_DEVICE_TYPE_GPU;

I could also paste int the two complete source files but they are long (900 lines).


问:
Is there any option to calculate the pricing of certain resource in my GCP project.?
I need to calculate the pricing of selected resources like compute engine,dataproc and cloud sql in my gcp project. Is there any way to manage and calculate the cost programatically?</p>

答: You can use the Billing catalog API for this. You can get the price of the SKU, and then perform by yourselves the calculation that you want.</p>


问:
How to read & write Local MySQL Server 8 from Google Colab with Pyspark?
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

```<code>    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()
</code>```

An here is the connection string:

```<code>MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()
</code>```

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

```<code>Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)
</code>```

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?

答:
Here's how I install and setup MySQL on Colab

# install, set connection
!apt-get install mysql-server > /dev/null
!service mysql start
!mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'"
!pip -q install PyMySQL
%load_ext sql
%config SqlMagic.feedback=False
%config SqlMagic.autopandas=True
%sql mysql+pymysql://root:root@/
# query using %sql or %%sql
df = %sql SELECT Host, User, authentication_string FROM mysql.user
df
```

Body:
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()

An here is the connection string:

MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?


问:
what does first <T> in "<T> Future<T> submit(Callable<T> task)" stands for?
I'm new to Java and is trying to learn the concept of return type. I was reading Java API for the interface ExecutorService:

I know for submit(Callable<T> task), it returns a Future object of T type, however, there is another <T> in front of Future<T>, what does it represent?

答:
This is an example of generic method. Generic methods allow "type parameters"(in this case ) to be used to express "dependencies" among the types of one or more arguments to a method and/or its return type.

In this case,  Future submit(Callable task),  in front of Future indicates the dependency among type specified for Future and Callable.

In another case,  void copy(List dest, List src),  indicates that T and S have a dependency which is S extends T.

If there isn't such a dependency, a generic method should not be used.
Ex: void fn(T t) - since there is only one arg and no return type, no need to specify leading  to indicate a generic method.

More details here.


问:
c# SslStream.Read Loop problem
I've been learning C# by creating an app and i've hit a snag i'm really struggling with.

Basicly i have the code below which is what im using to read from a network stream I have setup. It works but as its only reading 1 packet for each time the sslstream.Read() unblocks. It's causes a big backlog of messages.

What im looking at trying to do is if the part of the stream read contains multiple packets read them all.

I've tried multiple times to work it out but i just ended up in a big mess of code.

If anyone could help out I'd appreciate it!

(the first 4bytes of each packet is the size of the packet.. packets range between 8 bytes and 28,000 bytes)

        SslStream _sslStream = (SslStream)_sslconnection;
        int bytes = -1;
        int nextread = 0;
        int byteslefttoread = -1;
        byte[] tmpMessage;
        byte[] buffer = new byte[3000000];
        do
        {
            bytes = _sslStream.Read(buffer, nextread, 8192);
           int packetSize = BitConverter.ToInt32(buffer, 0);
            nextread += bytes;
            byteslefttoread = packetSize - nextread;

            if (byteslefttoread <= 0)
            {
                int leftover = Math.Abs(byteslefttoread);
                do
                {
                    tmpMessage = new byte[packetSize];
                    Buffer.BlockCopy(buffer, 0, tmpMessage, 0, packetSize);

                    PacketHolder tmpPacketHolder = new PacketHolder(tmpMessage, "in");
                    lock (StaticMessageBuffers.MsglockerIn)
                    {
                        //puts message into the message queue.. not very oop... :S
                        MessageInQueue.Enqueue(tmpPacketHolder);
                    }
                }
                while (leftover > 0);

                Buffer.BlockCopy(buffer, packetSize , buffer, 0, leftover);
                byteslefttoread = 0;
                nextread = leftover;

            }

        } while (bytes != 0);
```

答:
If you are using .Net 3.5 or later I would highly suggest you look into Windows Communication Foundation (wcf). It will simply anything you are trying to do over a network.

On the other hand, if you are doing this purely for educational purposes.
Take a look at this link. Your best bet is to read from the stream in somewhat smaller increments, and feed that data into another stream. Once you can identify the length of data you need for a message, you can cut the second stream off into a message. You can setup an outside loop where available bytes are being checked and wait until its value is > 0 to start the next message. Also should note, that any network code should be running on its own thread, so as to not block the UI thread.

Title: c# SslStream.Read Loop problem


问:
LLVM API: correct way to create/dispose
I'm attempting to implement a simple JIT compiler using the LLVM C API. So far, I have no problems generating IR code and executing it, that is: until I start disposing objects and recreating them.

What I basically would like to do is to clean up the JIT'ted resources the moment they're no longer used by the engine. What I'm basically attempting to do is something like this:

```<code>while (true)
{
    // Initialize module & builder
    InitializeCore(GetGlobalPassRegistry());
    module = ModuleCreateWithName(some_unique_name);
    builder = CreateBuilder();

    // Initialize target & execution engine
    InitializeNativeTarget();
    engine = CreateExecutionEngineForModule(...);
    passmgr = CreateFunctionPassManagerForModule(module);
    AddTargetData(GetExecutionEngineTargetData(engine), passmgr);
    InitializeFunctionPassManager(passmgr);

    // [... my fancy JIT code ...] --** Will give a serious error the second iteration

    // Destroy
    DisposePassManager(passmgr);
    DisposeExecutionEngine(engine);
    DisposeBuilder(builder);
    // DisposeModule(module); //--> Commented out: Deleted by execution engine

    Shutdown();
}
</code>```

However, this doesn't seem to be working correctly: the second iteration of the loop I get a pretty bad error...

So to summarize: what's the correct way to destroy and re-create the LLVM API?

答:
```<code>  /* program init */
LLVMInitializeNativeTarget();
LLVMInitializeNativeAsmPrinter();
LLVMInitializeNativeAsmParser();
LLVMLinkInMCJIT();

    ctx->context = LLVMContextCreate();
    ctx->builder = LLVMCreateBuilderInContext(ctx->context);
    LLVMParseBitcodeInContext2(ctx->context, module_template_buf, &module) // create module

    do IR code creation
    {
        function = LLVMAddFunction(ctx->module, "my_func")
        LLVMAppendBasicBlockInContext(ctx->context, ...
        LLVMBuild...
        ...
    }
    optional optimization
    {
        LLVMPassManagerBuilderRef pass_builder = LLVMPassManagerBuilderCreate();
        LLVMPassManagerBuilderSetOptLevel(pass_builder, 3);
        LLVMPassManagerBuilderSetSizeLevel(pass_builder, 0);
        LLVMPassManagerBuilderUseInlinerWithThreshold(pass_builder, 1000);
        LLVMPassManagerRef function_passes = LLVMCreateFunctionPassManagerForModule(ctx->module);
        LLVMPassManagerRef module_passes = LLVMCreatePassManager();
        LLVMPassManagerBuilderPopulateFunctionPassManager(pass_builder, function_passes);
        LLVMPassManagerBuilderPopulateModulePassManager(pass_builder, module_passes);
        LLVMPassManagerBuilderDispose(pass_builder);
        LLVMInitializeFunctionPassManager(function_passes);
        for (LLVMValueRef value = LLVMGetFirstFunction(ctx->module); value;
             value = LLVMGetNextFunction(value))
        {
            LLVMRunFunctionPassManager(function_passes, value);
        }
        LLVMFinalizeFunctionPassManager(function_passes);
        LLVMRunPassManager(module_passes, ctx->module);
        LLVMDisposePassManager(function_passes);
        LLVMDisposePassManager(module_passes);
    }

    optional for debug
    {
        LLVMVerifyModule(ctx->module, LLVMAbortProcessAction, &error);
        LLVMPrintModule
    }
    if (LLVMCreateJITCompilerForModule(&ctx->engine, ctx->module, 0, &error) != 0)
    my_func = (exec_func_t)(uintptr_t)LLVMGetFunctionAddress(ctx->engine, "my_func");

    LLVMRemoveModule(ctx->engine, ctx->module, &ctx->module, &error);
    LLVMDisposeModule(ctx->module);
    LLVMDisposeBuilder(ctx->builder);

    do
    {
         my_func(...);
    }

    LLVMDisposeExecutionEngine(ctx->engine);
    LLVMContextDispose(ctx->context);

/* program finit */
LLVMShutdown();
</code>```

Title: LLVM API: correct way to create/dispose

Body:
I'm attempting to implement a simple JIT compiler using the LLVM C API. So far, I have no problems generating IR code and executing it, that is: until I start disposing objects and recreating them.

What I basically would like to do is to clean up the JIT'ted resources the moment they're no longer used by the engine. What I'm basically attempting to do is something like this:

while (true)
{
    // Initialize module & builder
    InitializeCore(GetGlobalPassRegistry());
    module = ModuleCreateWithName(some_unique_name);
    builder = CreateBuilder();

    // Initialize target & execution engine
    InitializeNativeTarget();
    engine = CreateExecutionEngineForModule(...);
    passmgr = CreateFunctionPassManagerForModule(module);
    AddTargetData(GetExecutionEngineTargetData(engine), passmgr);
    InitializeFunctionPassManager(passmgr);

    // [... my fancy JIT code ...] --** Will give a serious error the second iteration

    // Destroy
    DisposePassManager(passmgr);
    DisposeExecutionEngine(engine);
    DisposeBuilder(builder);
    // DisposeModule(module); //--> Commented out: Deleted by execution engine

    Shutdown();
}

However, this doesn't seem to be working correctly: the second iteration of the loop I get a pretty bad error...

So to summarize: what's the correct way to destroy and re-create the LLVM API?


问:
How can I extend Array.prototype.push()?
I'm trying to extend the Array.push method so that using push will trigger a callback method and then perform the normal array function.

I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.

```<code>arr = [];
arr.push = function(data){

    //callback method goes here

    this = Array.push(data);
    return this.length;
}

arr.push('test');
</code>```

答:
There's another, more native method to achieve this: Proxy

```<code>const target = [];

const handler = {
  set: function(array, index, value) {
    // Call callback function here

    // The default behavior to store the value
    array[index] = value;

    // Indicate success
    return true;
  }
};

const proxyArray = new Proxy(target, handler);
</code>```

Body:
I'm trying to extend the Array.push method so that using push will trigger a callback method and then perform the normal array function.

I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.

arr = [];
arr.push = function(data){

    //callback method goes here

    this = Array.push(data);
    return this.length;
}

arr.push('test');

Body:
There's another, more native method to achieve this: Proxy

const target = [];

const handler = {
  set: function(array, index, value) {
    // Call callback function here

    // The default behavior to store the value
    array[index] = value;

    // Indicate success
    return true;
  }
};

const proxyArray = new Proxy(target, handler);


问:
PropTypes in functional stateless component
Without using class, how do I use PropTypes in functional stateless component of react?</p>

```<code>export const Header = (props) => (
   <div>hi</div>
)
</code>```

答:
It's done the same way you do with Class Based Components

```<code>import PropTypes from "prop-types";

    const = function_name => {}

    function_name.propTypes = {
       prop_name : PropTypes.number
       . . . . . . . . . . . . . .
    }
</code>```

Hope This Helps !

Body:
Without using class, how do I use PropTypes in functional stateless component of react?

export const Header = (props) => (

hi

)

Body:
It's done the same way you do with Class Based Components

import PropTypes from "prop-types";

    const = function_name => {}

    function_name.propTypes = {
       prop_name : PropTypes.number
       . . . . . . . . . . . . . .
    }

Hope This Helps !


问:
Create Max and Min column values from a single column value pandas
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

```<code>Kg
0.5
0.5
1
1
1
2
2
5
5
5
</code>```

Expected Output

```<code>Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5
</code>```

How can this be done in pandas ?

答:
Use zip and dict for mapping new column created by DataFrame.insert with unique sorted values by np.unique with added first 0 value by np.insert:

```<code>df = df.rename(columns={'Kg':'Kg_To'})
a = np.unique(df["Kg_To"])
df.insert(0, 'Kg_from', df['Kg_To'].map(dict(zip(a, np.insert(a, 0, 0)))))
print (df)
   Kg_from  Kg_To
0      0.0    0.5
1      0.0    0.5
2      0.5    1.0
3      0.5    1.0
4      0.5    1.0
5      1.0    2.0
6      1.0    2.0
7      2.0    5.0
8      2.0    5.0
9      2.0    5.0
</code>```

Body:
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

Kg
0.5
0.5
1
1
1
2
2
5
5
5

Expected Output

Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5

How can this be done in pandas ?

Body:
Use zip and dict for mapping new column created by DataFrame.insert with unique sorted values by np.unique with added first 0 value by np.insert:

df = df.rename(columns={'Kg':'Kg_To'})
a = np.unique(df["Kg_To"])
df.insert(0, 'Kg_from', df['Kg_To'].map(dict(zip(a, np.insert(a, 0, 0)))))
print (df)
   Kg_from  Kg_To
0      0.0    0.5
1      0.0    0.5
2      0.5    1.0
3      0.5    1.0
4      0.5    1.0
5      1.0    2.0
6      1.0    2.0
7      2.0    5.0
8      2.0    5.0
9      2.0    5.0


问:
Transformation of Cartesian coordinates to Cylindrical coordinates
What is wrong with this, please? I would like to define Cartesian coordinate system, and then I would like to compute Cylindrical coordinate with respect to axis x.

I got an error:

```<code>    R = math.sqrt(y[i]**2 + z[i]**2)
TypeError: only size-1 arrays can be converted to Python scalars
</code>```

Code:

```<code>import numpy as np
import math

XMIN =-0.15
XMAX = 0.15
YMIN = -0.1
YMAX = 0.1
ZMIN = -0.1
ZMAX = 0.1
sampling = 100

x_ = np.linspace(XMIN, XMAX, sampling)
y_ = np.linspace(YMIN, YMAX, sampling)
z_ = np.linspace(ZMIN, ZMAX, sampling)

x, y, z = np.meshgrid(x_, y_, z_, indexing='ij')

assert np.all(x[:,0,0] == x_)
assert np.all(y[0,:,0] == y_)
assert np.all(z[0,0,:] == z_)

# cylindric coordinates (R, theta, z)
R_coor = []
THETA_coor = []
Z_coor = []

for i in range(sampling-1):
    R = math.sqrt(y[i]**2 + z[i]**2)
    THETA = math.atan(y[i]/z[i])
    Z = x[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)
</code>```

答:
Close to a typo.

In the offending line, you are using math.sqrt which can only operate on scalars. You must use the numpy version np.sqrt to operate on numpy ndarrays, or use x_, y_, z_ to have scalars.

So you should use either:

```<code>for i in range(sampling-1):
    R = math.sqrt(y_[i]**2 + z_[i]**2)
    THETA = math.atan2(y_[i], z_[i])     # always prefere atan2 to atan...
    Z = x_[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)
</code>```

or:

```<code>for i in range(sampling-1):
    R = np.sqrt(y[i]**2 + z[i]**2)
    THETA = np.arctan2(y[i],z[i])
    Z = x[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)
</code>```

Unrelated, but atan will break at pi/2 because you get an infinite quotient and can only return angle in the ]-pi/2, pi/2[ open segment, while atan2 can process the whole circle...

Body:
What is wrong with this, please? I would like to define Cartesian coordinate system, and then I would like to compute Cylindrical coordinate with respect to axis x.

I got an error:

    R = math.sqrt(y[i]**2 + z[i]**2)
TypeError: only size-1 arrays can be converted to Python scalars

Code:

import numpy as np
import math

XMIN =-0.15
XMAX = 0.15
YMIN = -0.1
YMAX = 0.1
ZMIN = -0.1
ZMAX = 0.1
sampling = 100

x_ = np.linspace(XMIN, XMAX, sampling)
y_ = np.linspace(YMIN, YMAX, sampling)
z_ = np.linspace(ZMIN, ZMAX, sampling)

x, y, z = np.meshgrid(x_, y_, z_, indexing='ij')

assert np.all(x[:,0,0] == x_)
assert np.all(y[0,:,0] == y_)
assert np.all(z[0,0,:] == z_)

# cylindric coordinates (R, theta, z)
R_coor = []
THETA_coor = []
Z_coor = []

for i in range(sampling-1):
    R = math.sqrt(y[i]**2 + z[i]**2)
    THETA = math.atan(y[i]/z[i])
    Z = x[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)

Body:
Close to a typo.

In the offending line, you are using math.sqrt which can only operate on scalars. You must use the numpy version np.sqrt to operate on numpy ndarrays, or use x_, y_, z_ to have scalars.

So you should use either:

for i in range(sampling-1):
    R = math.sqrt(y_[i]**2 + z_[i]**2)
    THETA = math.atan2(y_[i], z_[i])     # always prefere atan2 to atan...
    Z = x_[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)

or:

for i in range(sampling-1):
    R = np.sqrt(y[i]**2 + z[i]**2)
    THETA = np.arctan2(y[i],z[i])
    Z = x[i]
    R_coor.append(R)
    THETA_coor.append(THETA)
    Z_coor.append(Z)

Unrelated, but atan will break at pi/2 because you get an infinite quotient and can only return angle in the ]-pi/2, pi/2[ open segment, while atan2 can process the whole circle...


问:
PHPUnit willReturnMap always returns null
I have a unit test which uses the following mocked class

```<code>$this->stubHandle = $this->getMockBuilder(Handle::class)->disableOriginalConstructor()->getMock();
</code>```

When I run

```<code>$key = new Key($this->stubHandle);
$this->stubHandle->method('__call')->will($this->returnCallback('var_dump'));
$key->nonExistingMethod('element0', 'element1', []);
</code>```

it outputs

```<code>string(17) "nonExistingMethod"
</code>```

and

```<code>array(3) {
  [0] =>
  string(8) "element0"
  [1] =>
  string(8) "element1"
  [2] =>
  array(0) {
  }
}
</code>```

which I think it means the first argument of method __call is a string and the second argument is an array. No more arguments passed.

When I mock the return value of method __call like

```<code>$this->stubHandle->method('__call')->willReturn(1);
</code>```

The return value is always 1 as expected.

When I mock the return value of method __call like

```<code>$this->stubHandle->method('__call')->willReturnMap(
    [
        ['argument1', null, 'returnValue'],
    ]
);
</code>```

I expect the return value to be 'returnValue' when the first argument of method __call is 'argument1' while the seconds argument doesn't care.
If the first argument isn't 'argument1', I expect a return value of null.

Are these expectations correct?

No matter what I try, the return value is always null when I mock this value with method willReturnMap.

If my expectations are wrong, please lead me to a way to accomplish my goals to mock the return value, depending on the first argument (only) and also explain to me how to apply willReturnMap.

答:
It seems my search for method willReturnMap mislead me a bit.

I was under the assumption using null in the map, it would act as a "don't care", but it literally means null.

```<code>$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', null, 'returnValue'],
    ]
);
</code>```

means the arguments of method __call must explicitly be 'nonExistingMethod' & null if you want the return value to be 'returnValue'. Any other argument-values will return null instead.

E.g. $key->nonExistingMethod(null);

For the map to return 'returnValue' in my example, it should have been:

```<code>$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', ['element0', 'element1', []], 'returnValue'],
    ]
);
$key->nonExistingMethod('element0', 'element1', []);
</code>```

In short...
When using argument mapping, the values can't be a "don't Care".

Body:
I have a unit test which uses the following mocked class

$this->stubHandle = $this->getMockBuilder(Handle::class)->disableOriginalConstructor()->getMock();

When I run

$key = new Key($this->stubHandle);
$this->stubHandle->method('__call')->will($this->returnCallback('var_dump'));
$key->nonExistingMethod('element0', 'element1', []);

it outputs

string(17) "nonExistingMethod"

and

array(3) {
  [0] =>
  string(8) "element0"
  [1] =>
  string(8) "element1"
  [2] =>
  array(0) {
  }
}

which I think it means the first argument of method __call is a string and the second argument is an array. No more arguments passed.

When I mock the return value of method __call like

$this->stubHandle->method('__call')->willReturn(1);

The return value is always 1 as expected.

When I mock the return value of method __call like

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['argument1', null, 'returnValue'],
    ]
);

I expect the return value to be 'returnValue' when the first argument of method __call is 'argument1' while the seconds argument doesn't care.
If the first argument isn't 'argument1', I expect a return value of null.

Are these expectations correct?

No matter what I try, the return value is always null when I mock this value with method willReturnMap.

If my expectations are wrong, please lead me to a way to accomplish my goals to mock the return value, depending on the first argument (only) and also explain to me how to apply willReturnMap.

Body:
It seems my search for method willReturnMap mislead me a bit.

I was under the assumption using null in the map, it would act as a "don't care", but it literally means null.

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', null, 'returnValue'],
    ]
);

means the arguments of method __call must explicitly be 'nonExistingMethod' & null if you want the return value to be 'returnValue'. Any other argument-values will return null instead.

E.g. $key->nonExistingMethod(null);

For the map to return 'returnValue' in my example, it should have been:

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', ['element0', 'element1', []], 'returnValue'],
    ]
);
$key->nonExistingMethod('element0', 'element1', []);

In short...
When using argument mapping, the values can't be a "don't Care".


问:
What grants are needed to DESCRIBE a Snowflake-object?
The DESCRIBE function of Snowflake can be applied to many objects, like users, warehouses or databases (https://docs.snowflake.com/en/sql-reference/sql/desc.html).

I cannot find what grants are required to execute DESCRIBE. From experiments, I figured out a few things:
- In most cases, only the OWNER of an object is allowed to DESCRIBE that object
- Exception: DESCRIBE DATABASE is allowed to be executed by non-owners
- (Exception: DESCRIBE SCHEMA fails when the schema holds an external table, but this is probably just not implemented)

I cannot find in the documentation what the general grants are in order to perform DESCRIBE. My test seem to suggest that there is no general rule, but I would be very happy of somebody can prove me wrong :-)

答:
From my experiments, all of the basic objects that lie under a schema, such as Tables, Procedures and Functions, File Formats, Stages, etc. will permit DESCRIBE commands if any of its privilege types is granted to the accessor. This implicit behaviour may be why it is not specially called-out in Snowflake's access control documentation page.

For almost all other types of objects, the MONITOR privilege is necessary to permit DESCRIBE commands. Quoting a relevant part from the documentation:

MONITOR

Resource Monitor , Warehouse , Database , Schema, Task

Grants ability to see details within an object (e.g. queries and usage within a warehouse).