问:
Using a ArrayAdapter won't work with fragment
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

```<code>public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}
</code>```

The fragment class:

```<code>public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}
</code>```

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

```<code>public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}
</code>```

}

The way I created the Parceable:

```<code>Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);
</code>```

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

答:
You are using Creare_istoricAdapter in your Fragment_alerte_trimise so it needs context. therefor we can give activity context or application context(beyond the activity level)

Moreover...

getContext() - Returns the context view only current running activity.

getActivity()- Return the Activity this fragment is currently associated with.

getActivity() can be used in a Fragment for getting the parent Activity of the Fragment.

Add this code changes to your code.

```<code>getActivity().getApplicationContext()
</code>```

Body:
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}

The fragment class:

public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}

}

The way I created the Parceable:

Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

Body:
You are using Creare_istoricAdapter in your Fragment_alerte_trimise so it needs context. therefor we can give activity context or application context(beyond the activity level)

Moreover...

getContext() - Returns the context view only current running activity.

getActivity()- Return the Activity this fragment is currently associated with.

getActivity() can be used in a Fragment for getting the parent Activity of the Fragment.

Add this code changes to your code.

getActivity().getApplicationContext()


来源: stackexchange

问:
Would this be an acceptable solution for a Polyfill for JavaScript bind method?
First I copy the current passed context into dummy.
Then I add a method fn as the currently passed Function.
The dummy object exists in the closure.
Finally I'll return a function which executes the dummy.fn with the initially passed arguments.

```<code>Function.prototype.bind2 = function(context, ...args){
    var dummy = {...context}
    dummy.fn = this
    return function(){
        return dummy.fn(...args)
    }
}
</code>```

Edit 1: After first suggestion for the new dummy object, I changed it to the following

```<code>Function.prototype.bind2 = function(context, ...args){
    var dummy = Object.create(context)
    dummy.fn = this
    return function(){
        return dummy.fn(...args)
    }
}
</code>```

Edit 2: for the spread operator fix, I've used eval:

```<code>Function.prototype.bind2 = function(){
    var args = arguments;
    var dummy = Object.create(args[0]);
    dummy.fn = this;
    return function(){
                return eval('dummy.fn('+Object.values(args).slice(1,).join(',')+')')
           }
}
</code>```

答:
No, from first glance, there's several problems:

bind will invoke the method on the passed context, not a copy of it — your version makes it impossible for the bound function to affect the context directly

The method of copying an object that you employ will cut an object from its prototype, and also any magic it might have

bind will also allow the function to accept additional parameters that are not bound

Any environment that would require bind to be polyfilled would not be able to handle the ... spread syntax.

Function.prototype.bind2 = function(context, ...args){
    var dummy = {...context}
    dummy.fn = this
    return function(){
        return dummy.fn(...args)
    }
}

let obj = Object.create({
  name: "an obj",
  getName: function() { return this.name; },
  setFoo: function() { this.foo = 42; },
  showBarBaz: function(bar, baz) { console.log(bar, baz) }
});
obj.setFoo.bind2(obj)();                 // does not set `obj.foo`
console.log(obj);
console.log(obj.getName.bind2(obj)());   // no access to prototype
obj.showBarBaz.bind2(obj, "bar")("baz"); // does not pass "baz"

obj.setFoo.bind(obj)();                  // sets `obj.foo`
console.log(obj);
console.log(obj.getName.bind(obj)());    // full access to prototype
obj.showBarBaz.bind(obj, "bar")("baz");  // passes "baz"```

ContentLicense: CC BY-SA 4.0

Body:
First I copy the current passed context into dummy.
Then I add a method fn as the currently passed Function.
The dummy object exists in the closure.
Finally I'll return a function which executes the dummy.fn with the initially passed arguments.

Function.prototype.bind2 = function(context, ...args){
    var dummy = {...context}
    dummy.fn = this
    return function(){
        return dummy.fn(...args)
    }
}

Edit 1: After first suggestion for the new dummy object, I changed it to the following

Function.prototype.bind2 = function(context, ...args){
    var dummy = Object.create(context)
    dummy.fn = this
    return function(){
        return dummy.fn(...args)
    }
}

Edit 2: for the spread operator fix, I've used eval:

Function.prototype.bind2 = function(){
    var args = arguments;
    var dummy = Object.create(args[0]);
    dummy.fn = this;
    return function(){
                return eval('dummy.fn('+Object.values(args).slice(1,).join(',')+')')
           }
}


问:
SQL Server: How do I work out what is changing my data?
Here's a simplified version of my problem:

I have lots of articles in a table. Say, 10,000 rows. About once a week 5-10 of the values of the ArticleAuthor column [Nvarchar(255)] get overwritten with the same data - all from another article.

The code is actaully really huge and old and it's proved tough to find the offending process.

I'm thinking I might put a temporary trigger on the table to log when it gets updated etc and work from there.

Anyone got any better ideas?

Thanks in advance!

I'm using SQL Server 2005 by the way!

答: You could also use SQL Profiler and leave it running for a week and then parse the result log to find the offending process.  Make sure you use filters though to trim down the logging.</p>

ContentLicense: CC BY-SA 3.0


问:
Blank Screen - Matter.js
matter.js -

This is one of the demo from matter.js. It returns a blank screen. I have tried several approaches and spent hours and hours on this, still can't figure out what is wrong here.

I've checked brackets, syntax and typo but it still returns a blank screen.

I've checked matter.js is loading correctly in the background.

Can someone kindly point out the mistakes here?

```<code><script>
window.addEventListener('load', function() {

//Fetch our canvas
var canvas = document.getElementById('world22');

    var Engine = Matter.Engine,
        Render = Matter.Render,
        Runner = Matter.Runner,
        Composites = Matter.Composites,
        Events = Matter.Events,
        Constraint = Matter.Constraint,
        MouseConstraint = Matter.MouseConstraint,
        Mouse = Matter.Mouse,
        World = Matter.World,
        Bodies = Matter.Bodies;

    // create engine
    var engine = Engine.create(),
        world = engine.world;

    // create renderer
    var render = Render.create({
        // element: document.body,
        canvas: canvas,
        engine: engine,
        options: {
            width: 800,
            height: 600,
            showAngleIndicator: true,
        }
    });

    Render.run(render);

    // create runner
    var runner = Runner.create();
    Runner.run(runner, engine);

    // add bodies
    var ground = Bodies.rectangle(395, 600, 815, 50, { isStatic: true }),
        rockOptions = { density: 0.004 },
        rock = Bodies.polygon(170, 450, 8, 20, rockOptions),
        anchor = { x: 170, y: 450 },
        elastic = Constraint.create({
            pointA: anchor,
            bodyB: rock,
            stiffness: 0.05
        });

    var pyramid = Composites.pyramid(500, 300, 9, 10, 0, 0, function(x, y) {
        return Bodies.rectangle(x, y, 25, 40);
    });

    var ground2 = Bodies.rectangle(610, 250, 200, 20, { isStatic: true });

    var pyramid2 = Composites.pyramid(550, 0, 5, 10, 0, 0, function(x, y) {
        return Bodies.rectangle(x, y, 25, 40);
    });

    World.add(engine.world, [ground, pyramid, ground2, pyramid2, rock, elastic]);

    Events.on(engine, 'afterUpdate', function() {
        if (mouseConstraint.mouse.button === -1 && (rock.position.x > 190
 rock.position.y < 430)) {
            rock = Bodies.polygon(170, 450, 7, 20, rockOptions);
            World.add(engine.world, rock);
            elastic.bodyB = rock;
        }
    });

    // add mouse control
    var mouse = Mouse.create(render.canvas),
        mouseConstraint = MouseConstraint.create(engine, {
            mouse: mouse,
            constraint: {
                stiffness: 0.2,
                render: {
                    visible: false
                }
            }
        });

    World.add(world, mouseConstraint);

    // keep the mouse in sync with rendering
    render.mouse = mouse;

    // fit the render viewport to the scene
    Render.lookAt(render, {
        min: { x: 0, y: 0 },
        max: { x: 800, y: 600 }
    });

        });
  </script>

<canvas id="world22"></canvas>
</code>```

答:
Fixes:

(1) Change your world22 element from canvas to a div, or to any other suitable element. Apparently matter.js will create it's own canvas in the container and thus can't do anything with canvas inside a canvas.

(2) There is a missing || in your condition here causing a syntax error, between rock.position.x > 190 rock.position.y < 430. Don't know if this became a typo when pasting to SO.

(3) Use the property element when specifying the container element when creating the render. Don't use canvas: canvas. Use element: canvas. Regarding here Render.create({ ... });

Here is the modified source. I suppose you can safely ignore how I included the matter.js script. I don't know if the version matters and assume you have the latest.

<!doctype html>

```

I based my debugging by referring to a minimal example provided here https://github.com/liabru/matter-js/wiki/Getting-started ....

At first I didn't catch on to the canvas problem, but then I used the browser dev tools and inspected the world22 element. Another canvas was nested so that's how I knew.

Title: Blank Screen - Matter.js

Body:
matter.js -

This is one of the demo from matter.js. It returns a blank screen. I have tried several approaches and spent hours and hours on this, still can't figure out what is wrong here.

I've checked brackets, syntax and typo but it still returns a blank screen.

I've checked matter.js is loading correctly in the background.

Can someone kindly point out the mistakes here?

<canvas id="world22"></canvas>

Body:
Fixes:

(1) Change your world22 element from canvas to a div, or to any other suitable element. Apparently matter.js will create it's own canvas in the container and thus can't do anything with canvas inside a canvas.

(2) There is a missing || in your condition here causing a syntax error, between rock.position.x > 190 rock.position.y < 430. Don't know if this became a typo when pasting to SO.

(3) Use the property element when specifying the container element when creating the render. Don't use canvas: canvas. Use element: canvas. Regarding here Render.create({ ... });

Here is the modified source. I suppose you can safely ignore how I included the matter.js script. I don't know if the version matters and assume you have the latest.

<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.js"></script>
<script>
window.addEventListener('load', function() {

 //Fetch our canvas
 var canvas = document.getElementById('world22');

    var Engine = Matter.Engine,
        Render = Matter.Render,
        Runner = Matter.Runner,
        Composites = Matter.Composites,
        Events = Matter.Events,
        Constraint = Matter.Constraint,
        MouseConstraint = Matter.MouseConstraint,
        Mouse = Matter.Mouse,
        World = Matter.World,
        Bodies = Matter.Bodies;

    // create engine
    var engine = Engine.create(),
        world = engine.world;

    // create renderer
    var render = Render.create({
        element: canvas,
        engine: engine,
        options: {
            width: 800,
            height: 600,
            showAngleIndicator: true,
        }
    });

    Render.run(render);

    // create runner
    var runner = Runner.create();
    Runner.run(runner, engine);

    // add bodies
    var ground = Bodies.rectangle(395, 600, 815, 50, { isStatic: true }),
        rockOptions = { density: 0.004 },
        rock = Bodies.polygon(170, 450, 8, 20, rockOptions),
        anchor = { x: 170, y: 450 },
        elastic = Constraint.create({
            pointA: anchor,
            bodyB: rock,
            stiffness: 0.05
        });

    var pyramid = Composites.pyramid(500, 300, 9, 10, 0, 0, function(x, y) {
        return Bodies.rectangle(x, y, 25, 40);
    });

    var ground2 = Bodies.rectangle(610, 250, 200, 20, { isStatic: true });

    var pyramid2 = Composites.pyramid(550, 0, 5, 10, 0, 0, function(x, y) {
        return Bodies.rectangle(x, y, 25, 40);
    });

    World.add(engine.world, [ground, pyramid, ground2, pyramid2, rock, elastic]);

    Events.on(engine, 'afterUpdate', function() {
        if (mouseConstraint.mouse.button === -1 && (rock.position.x > 190 ||
 rock.position.y < 430)) {
            rock = Bodies.polygon(170, 450, 7, 20, rockOptions);
            World.add(engine.world, rock);
            elastic.bodyB = rock;
        }
    });

    // add mouse control
    var mouse = Mouse.create(render.canvas),
        mouseConstraint = MouseConstraint.create(engine, {
            mouse: mouse,
            constraint: {
                stiffness: 0.2,
                render: {
                    visible: false
                }
            }
        });

    World.add(world, mouseConstraint);

    // keep the mouse in sync with rendering
    render.mouse = mouse;

    // fit the render viewport to the scene
    Render.lookAt(render, {
        min: { x: 0, y: 0 },
        max: { x: 800, y: 600 }
    });

});
</script>

</head>
<body>
<div id="world22"></div>
</body>
<html>

I based my debugging by referring to a minimal example provided here https://github.com/liabru/matter-js/wiki/Getting-started ....

At first I didn't catch on to the canvas problem, but then I used the browser dev tools and inspected the world22 element. Another canvas was nested so that's how I knew.


问:
Best way to pass some variable/id through google cloud functions child?
How to get this running ? Need to pass the itens id in the path to have access to product node, how can I do this ? </p>

```<code>const itens = db.ref();
const eanRef = itens.child('cart').child('itens/{id}').child('product');
</code>```

答:
To replace the value of an integer variable id to a string itens/{id} you can do the following:

var id = 15;

const itens = db.ref();
const eanRef = itens.child('cart').child('itens/'+id.toString()).child('product');
```

Body:
How to get this running ? Need to pass the itens id in the path to have access to product node, how can I do this ?

const itens = db.ref();
const eanRef = itens.child('cart').child('itens/{id}').child('product');


问:
How to get filepath from inside text file and perform operation in bash
I have list of folders path like

```<code>/home/user/wwww
/home/www/www/temp
</code>```

They are stored in a text file . Now i want get those path for dir names and make them all 777 permission

答:
You can do like this:

```<code>cat file.txt | while read line; do chmod 777 "$line"; done
</code>```

This will change mode to 77 for each "$line" in input file file.txt.

Body:
I have list of folders path like

/home/user/wwww
/home/www/www/temp

They are stored in a text file . Now i want get those path for dir names and make them all 777 permission

Body:
You can do like this:

cat file.txt | while read line; do chmod 777 "$line"; done

This will change mode to 77 for each "$line" in input file file.txt.


问:
Issue with script to delete the files with particular extension
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

```<code>import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path
</code>```

答:
We could use Regular expressions to determine if the file is a log file.

Rather than using time module you could use datetime module if your sole intention is to delete the log files that are older than 7 days.

Have a look at code below:

```<code>import re
import datetime
import os

folder_path = "C:\SampleFolder"
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path, file)
    if os.path.isfile(file_full_path) and re.search(r".*\.log.*", file_full_path):
        # Delete files older than x days
        last_mod_time = datetime.datetime.fromtimestamp(os.stat(file_full_path).st_mtime)
        limt_mod_time = datetime.datetime.today() - datetime.timedelta(days=7)

        if last_mod_time < limt_mod_time:
            os.remove(file_full_path)
            print("\n File Removed : ", file_full_path)
</code>```

Body:
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path

Body:
We could use Regular expressions to determine if the file is a log file.

Rather than using time module you could use datetime module if your sole intention is to delete the log files that are older than 7 days.

Have a look at code below:

import re
import datetime
import os

folder_path = "C:\SampleFolder"
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path, file)
    if os.path.isfile(file_full_path) and re.search(r".*\.log.*", file_full_path):
        # Delete files older than x days
        last_mod_time = datetime.datetime.fromtimestamp(os.stat(file_full_path).st_mtime)
        limt_mod_time = datetime.datetime.today() - datetime.timedelta(days=7)

        if last_mod_time < limt_mod_time:
            os.remove(file_full_path)
            print("\n File Removed : ", file_full_path)


问:
Cordova Emulate Android finds no Gradle or installed Android Studio, even though its there
Error Message

I know that the app itself should work, I just had to work on a different part of the project and when I came back to it, this error message suddenly popped up. No solution worked for me, so I am asking here.

If the picture above cant be seen, here is the message again:

Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=C:\Users\Ibs\AppData\Local\Android\sdk (DEPRECATED)
Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio

答: There was a problem with the environmental variable. Deleting it and creating it anew, like in the Gradle documentation solved it for me.</p>


问:
qsort() works in one direction, but not other
This is how I made my comparison function to pass to qsort():

```<code>int charCompare(const void* ptr1, const void* ptr2)
{
   char c1 = *(char*)ptr1;
   char c2 = *(char*)ptr2;
   return c1 - c2;
}
</code>```

And this is the implementation:

```<code>char buffer[SIZE];
/*
 * buffer filled here
 */
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);
</code>```

Nothing gets printed. I'm pretty sure it's because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?

答: You are exactly right that the null(s) are getting included.  You are sorting the entire buffer, not just the part that contains your (null terminated) string.  You need to use strlen(buffer) rather than sizeof(buffer) (and include string.h of course).  You also don't need to divide by sizeof(char) since the sizeof function is defined in terms of char-sized units.

Body:
This is how I made my comparison function to pass to qsort():

int charCompare(const void* ptr1, const void* ptr2)
{
   char c1 = *(char*)ptr1;
   char c2 = *(char*)ptr2;
   return c1 - c2;
}

And this is the implementation:

char buffer[SIZE];
/*
 * buffer filled here
 */
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);

Nothing gets printed. I'm pretty sure it's because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?


问:
curl / soap request with .p12 SSL certificate
I need to SOAP request https://address?wsdl which require .p12 certificate using PHP7.2.

After hours of reasearch only thing I was able to do is making this request from bash:

$ curl -k -E cert.crt.pem --key cert.key.pem https://address?wsdl

which retured WSDL. But I had to split .p12 to separate files and use -k option which makes all this stuff not secure.
Split done by this commands:

```<code>openssl pkcs12 -in mycert.p12 -out cert.key.pem -nocerts -nodes
openssl pkcs12 -in mycert.p12 -out cert.crt.pem -clcerts -nokeys
</code>```

The question is:
How to request this WSDL using cURL from PHP or how to configure new \SoapClient() so it will work?

Is this possible having only .p12 file & password? Or I have to convert it?

Hope this describe what I already was able to do:

```<code><?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_VERBOSE, true);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * This works. But:
 * - I don't have peer verification
 * - Is such file safe? It has encrypted pkey & certificate (I think not encrypted).
 *   I don't know much about that topic. Maybe someone with more experience will be able to tell more.
 *   Maybe some better solution to output this. Maybe as 2 separate files?
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); // DO NOT VERIFY!
curl_setopt($ch,CURLOPT_SSLCERT,__DIR__ . '/cert.pem');
//curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pass); // This is not required :/
curl_setopt($ch,CURLOPT_SSLKEY,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEYPASSWD, $pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * SSL certificate problem: self signed certificate in certificate chain
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch,CURLOPT_SSLCERT,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEY,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEYPASSWD, $pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * ignoring certificate verify locations due to disabled peer verification
 * error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_CAINFO,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_CAPATH,__DIR__);
curl_setopt($ch,CURLOPT_KEYPASSWD,$pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * successfully set certificate verify locations:
 *   CAfile: /www/soap/cert.pem
 *   CApath: /www/soap
 * SSL certificate problem: self signed certificate in certificate chain
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_CAINFO,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_CAPATH,__DIR__);
curl_setopt($ch,CURLOPT_KEYPASSWD,$pass);

$data = curl_exec($ch);

$error = curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

var_dump($data, $httpcode, $error);
?>
</code>```

答:
I was not able to use .p12, .pfx, pkcs12 directly is SOAP.
First we need to read p12 file and convert it to .pem. Later you can cache result ($pemCertContent) to avoid conversion each request or store it as file to use as filepaths.

```<code>    $readSuccessful = openssl_pkcs12_read($content, $certData, $password);
    if (!$readSuccessful) {
        $msg = sprintf('Could not read pkcs12 file `%s`: `%s`.', $filePath, openssl_error_string());
        throw new \Exception($msg);
    }

    $pemCertContent = '';

    if (isset($certData['pkey'])) {
        openssl_pkey_export($certData['pkey'], $pem, $pemPassword);
        $pemCertContent .= $pem;
    }
    if (isset($certData['cert'])) {
        openssl_x509_export($certData['cert'], $cert);
        $pemCertContent .= $cert;
    }

    $pemCertContent; // This is your .pem certificate content. I store it as a file.
</code>```

Depending on need you can use it like this when creating SOAP client:

```<code>    $soapOptions = [
        /* In some cases, when you have 2 certificates you may need to use stream context instead of 'local_cert'
        'stream_context' => stream_context_create([
            'ssl' => [
                'cafile' => $caCert->getFilePath(), // CA Certificate
                'local_cert' => $tlsCertificate->getFilePath(), // PEM certificate
                'passphrase' => $tlsCertificatePass, // Pass for PEM certificate
            ],
        ]),
         */
        'local_cert' => $tlsCertificate->getFilePath(),
        'passphrase' => $tlsCertificatePass,

        'trace' => true,
        'exceptions' => true,
    ];
</code>```

This allows to connect to SoapServer to get wsdl and do request. In my case I also have to sign whole request body with WSSE. To do it I use this with .p12 cert opened by openssl_pkcs12_read function:

```<code>RobRichards\WsePhp\WSSESoap;
RobRichards\XMLSecLibs\XMLSecurityKey;
</code>```

But this is another story.

Body:
I need to SOAP request https://address?wsdl which require .p12 certificate using PHP7.2.

After hours of reasearch only thing I was able to do is making this request from bash:

$ curl -k -E cert.crt.pem --key cert.key.pem https://address?wsdl

which retured WSDL. But I had to split .p12 to separate files and use -k option which makes all this stuff not secure.
Split done by this commands:

openssl pkcs12 -in mycert.p12 -out cert.key.pem -nocerts -nodes
openssl pkcs12 -in mycert.p12 -out cert.crt.pem -clcerts -nokeys

The question is:
How to request this WSDL using cURL from PHP or how to configure new \SoapClient() so it will work?

Is this possible having only .p12 file & password? Or I have to convert it?

Hope this describe what I already was able to do:

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_VERBOSE, true);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * This works. But:
 * - I don't have peer verification
 * - Is such file safe? It has encrypted pkey & certificate (I think not encrypted).
 *   I don't know much about that topic. Maybe someone with more experience will be able to tell more.
 *   Maybe some better solution to output this. Maybe as 2 separate files?
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); // DO NOT VERIFY!
curl_setopt($ch,CURLOPT_SSLCERT,__DIR__ . '/cert.pem');
//curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pass); // This is not required :/
curl_setopt($ch,CURLOPT_SSLKEY,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEYPASSWD, $pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * SSL certificate problem: self signed certificate in certificate chain
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch,CURLOPT_SSLCERT,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEY,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_SSLKEYPASSWD, $pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * ignoring certificate verify locations due to disabled peer verification
 * error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_CAINFO,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_CAPATH,__DIR__);
curl_setopt($ch,CURLOPT_KEYPASSWD,$pass);

/**
 * cert.p12 (with password) -> cert.pem (contains encrypted PKey & client ?unencrypted? cert)
 * $ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
 *
 * Result:
 *
 * TCP_NODELAY set
 * Connected to XXX
 * ALPN, offering http/1.1
 * successfully set certificate verify locations:
 *   CAfile: /www/soap/cert.pem
 *   CApath: /www/soap
 * SSL certificate problem: self signed certificate in certificate chain
 * stopped the pause stream!
 * Closing connection 0
 */
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_CAINFO,__DIR__ . '/cert.pem');
curl_setopt($ch,CURLOPT_CAPATH,__DIR__);
curl_setopt($ch,CURLOPT_KEYPASSWD,$pass);

$data = curl_exec($ch);

$error = curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

var_dump($data, $httpcode, $error);
?>

Body:
I was not able to use .p12, .pfx, pkcs12 directly is SOAP.
First we need to read p12 file and convert it to .pem. Later you can cache result ($pemCertContent) to avoid conversion each request or store it as file to use as filepaths.

    $readSuccessful = openssl_pkcs12_read($content, $certData, $password);
    if (!$readSuccessful) {
        $msg = sprintf('Could not read pkcs12 file `%s`: `%s`.', $filePath, openssl_error_string());
        throw new \Exception($msg);
    }

    $pemCertContent = '';

    if (isset($certData['pkey'])) {
        openssl_pkey_export($certData['pkey'], $pem, $pemPassword);
        $pemCertContent .= $pem;
    }
    if (isset($certData['cert'])) {
        openssl_x509_export($certData['cert'], $cert);
        $pemCertContent .= $cert;
    }

    $pemCertContent; // This is your .pem certificate content. I store it as a file.

Depending on need you can use it like this when creating SOAP client:

    $soapOptions = [
        /* In some cases, when you have 2 certificates you may need to use stream context instead of 'local_cert'
        'stream_context' => stream_context_create([
            'ssl' => [
                'cafile' => $caCert->getFilePath(), // CA Certificate
                'local_cert' => $tlsCertificate->getFilePath(), // PEM certificate
                'passphrase' => $tlsCertificatePass, // Pass for PEM certificate
            ],
        ]),
         */
        'local_cert' => $tlsCertificate->getFilePath(),
        'passphrase' => $tlsCertificatePass,

        'trace' => true,
        'exceptions' => true,
    ];

This allows to connect to SoapServer to get wsdl and do request. In my case I also have to sign whole request body with WSSE. To do it I use this with .p12 cert opened by openssl_pkcs12_read function:

RobRichards\WsePhp\WSSESoap;
RobRichards\XMLSecLibs\XMLSecurityKey;

But this is another story.


问:
Trigger parameterized build with curl and crumb
I've seen similar posts to this on SO, but not quite exactly what I am trying to do (or at least no full examples of a command to run).

I am trying to remotely trigger a parameterized build on Jenkins using curl.  I have 'Prevent Cross Site Request Forgery' enabled so I also need to pass a valid crumb.

The script I have is below:

```<code>#!/bin/bash

json="{\"parameter\": [{ \"P1\": \"param1\", \"P2\": \"param2\", \"P3\": \"param3\" }]}"
crumb=`curl "http://SERVER/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)"`

curl -v -H $crumb -X POST http://SERVER/job/JOB_NAME/buildWithParameters -d token=runme --data-urlencode json="$json"
</code>```

I've also tried modifying the URL I'm passing to curl to either:

```<code>USERNAME:APITOKEN@SERVER
</code>```

and

```<code>USERNAME:PASSWORD@SERVER
</code>```

Output from curl is:

```<code>* About to connect() to SERVER port 8080 (#0)
*   Trying SERVER... connected
* Connected to SERVER (SERVER) port 8080 (#0)
* Server auth using Basic with user 'USERNAME'
> POST /job/JOB_NAME/buildWithParameters HTTP/1.1
> Authorization: Basic bjAwNjY5MjI6YWxLaW5kaTg=
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.13.1.0 zlib/1.2.3 libidn/1.18 libssh2/1.2.2
> Host: SERVER:8080
> Accept: */*
> .crumb:776eb589e8b930d9f06cfc2df885314c
> Content-Length: 168
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 403 No valid crumb was included in the request
< Content-Type: text/html;charset=ISO-8859-1
< Cache-Control: must-revalidate,no-cache,no-store
< Content-Length: 1469
< Server: Jetty(8.y.z-SNAPSHOT)
<
</code>```

So it looks like I'm not passing the crumb properly, but I'm not sure what the correct format of the command should be.

答:
This worked for me, I tried to used solutions already mentioned in this page but they had to be adapted a bit due to (a) referer and (b) cookie. Jenkins version 2.204</p>

```<code>sh script:"""

COOKIE_PATH=/tmp/cookie_jenkins_crumb.txt

CRUMB=\$(curl -s -c \$COOKIE_PATH -H '${jenkins_referer}' 'https://useridhere:${jenkins_live_token}@jenkins.example.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' )
# https://support.cloudbees.com/hc/en-us/articles/219257077-CSRF-Protection-Explained
# https://wiki.jenkins.io/display/JENKINS/Remote+access+API#RemoteaccessAPI-CSRFProtection
# but a bit adjusted as it is not exactly usable as it is in the documentation page.
# We discovered that the CRUMB should be identical because it
# is paired with a cookie. Thus save the cookie, it is important.

sed -i 's/ORGANIZATION/${PROJECT_NAME}/g' ${jenkins_credentials_json_template_file_path}
# a json file with labels for quick replacements.

# cat ${jenkins_credentials_json_template_file_path}

# https://support.cloudbees.com/hc/en-us/articles/360030526992-How-to-manage-Credentials-via-the-REST-API
curl -s -b \$COOKIE_PATH -u useridhere:${jenkins_live_token} -H '${jenkins_referer}' -H \"\${CRUMB}\" -X POST --data-urlencode json@${jenkins_credentials_json_template_file_path} 'https://jenkins.example.com/credentials/store/system/domain/_/createCredentials'
"""
</code>```

Body:
I've seen similar posts to this on SO, but not quite exactly what I am trying to do (or at least no full examples of a command to run).

I am trying to remotely trigger a parameterized build on Jenkins using curl.  I have 'Prevent Cross Site Request Forgery' enabled so I also need to pass a valid crumb.

The script I have is below:

#!/bin/bash

json="{\"parameter\": [{ \"P1\": \"param1\", \"P2\": \"param2\", \"P3\": \"param3\" }]}"
crumb=`curl "http://SERVER/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)"`

curl -v -H $crumb -X POST http://SERVER/job/JOB_NAME/buildWithParameters -d token=runme --data-urlencode json="$json"

I've also tried modifying the URL I'm passing to curl to either:

USERNAME:APITOKEN@SERVER

and

USERNAME:PASSWORD@SERVER

Output from curl is:

* About to connect() to SERVER port 8080 (#0)
*   Trying SERVER... connected
* Connected to SERVER (SERVER) port 8080 (#0)
* Server auth using Basic with user 'USERNAME'
> POST /job/JOB_NAME/buildWithParameters HTTP/1.1
> Authorization: Basic bjAwNjY5MjI6YWxLaW5kaTg=
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.13.1.0 zlib/1.2.3 libidn/1.18 libssh2/1.2.2
> Host: SERVER:8080
> Accept: */*
> .crumb:776eb589e8b930d9f06cfc2df885314c
> Content-Length: 168
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 403 No valid crumb was included in the request
< Content-Type: text/html;charset=ISO-8859-1
< Cache-Control: must-revalidate,no-cache,no-store
< Content-Length: 1469
< Server: Jetty(8.y.z-SNAPSHOT)
<

So it looks like I'm not passing the crumb properly, but I'm not sure what the correct format of the command should be.

Body:
This worked for me, I tried to used solutions already mentioned in this page but they had to be adapted a bit due to (a) referer and (b) cookie. Jenkins version 2.204

sh script:"""

COOKIE_PATH=/tmp/cookie_jenkins_crumb.txt

CRUMB=\$(curl -s -c \$COOKIE_PATH -H '${jenkins_referer}' 'https://useridhere:${jenkins_live_token}@jenkins.example.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)' )
# https://support.cloudbees.com/hc/en-us/articles/219257077-CSRF-Protection-Explained
# https://wiki.jenkins.io/display/JENKINS/Remote+access+API#RemoteaccessAPI-CSRFProtection
# but a bit adjusted as it is not exactly usable as it is in the documentation page.
# We discovered that the CRUMB should be identical because it
# is paired with a cookie. Thus save the cookie, it is important.

sed -i 's/ORGANIZATION/${PROJECT_NAME}/g' ${jenkins_credentials_json_template_file_path}
# a json file with labels for quick replacements.

# cat ${jenkins_credentials_json_template_file_path}

# https://support.cloudbees.com/hc/en-us/articles/360030526992-How-to-manage-Credentials-via-the-REST-API
curl -s -b \$COOKIE_PATH -u useridhere:${jenkins_live_token} -H '${jenkins_referer}' -H \"\${CRUMB}\" -X POST --data-urlencode json@${jenkins_credentials_json_template_file_path} 'https://jenkins.example.com/credentials/store/system/domain/_/createCredentials'
"""


问:
How to recover files in git lost and found folder
I used git reset --hard without any commits yet.
I got this link on stackoverflow Undo git reset without any commits yet and I was able to get some files in the .git lost-found folder.

But the file are dangling blob which I cant work on. they are just plain.

How do I get these files back to original form
thanks

答:
I've experienced the lost of files that weren't committed too, and the only solution to retrieve them is not to rely on git, but rather on anything else that can cancel the action of deleting the files.

In my case, cancelling the actions (by that I mean CMD+Z) on my IDE restored the files (I was using RubyMine).

Good luck!


问:
jQuery How to add click to ul
I want to add class checked on li when users click it using jQuery. I have written the below code which works.

HTML

Documents checked

Documents Verified

Forwarded to Logistics

Received by Logistics

```

<pre class="lang-css prettyprint-override"><code>.checked {
  background: green;
}
</code>```

jQuery

$(function() {
    $('li.row').on('click', function() {
      $(this).addClass('checked');
    });
});
```

<p>This is working but I am told this is bad practice and asked to find better way to do this. I do the following but it is not working.</p>

<pre class="lang-js prettyprint-override"><code>$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});
</code>```

答:
```<code>$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});
</code>```

it's wrong because you cant select li by click on you ul
if you want to add class or delete class with click you can use (toggleClass) like this

```<code>$('li').find(.row).on('click', function() {
      $(this).toggleClass('checked');
    });
</code>```

but if you want to just add class write like this

```<code>$('li').find(.row).on('click', function() {
          $(this).addClass('checked');
        });
</code>```

Title: jQuery How to add click to ul

Body:
I want to add class checked on li when users click it using jQuery. I have written the below code which works.

HTML

Documents checked

Documents Verified

Forwarded to Logistics

Received by Logistics

.checked {
  background: green;
}

jQuery

$(function() {
    $('li.row').on('click', function() {
      $(this).addClass('checked');
    });
});

This is working but I am told this is bad practice and asked to find better way to do this. I do the following but it is not working.

$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});

Body:
$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});

it's wrong because you cant select li by click on you ul
if you want to add class or delete class with click you can use (toggleClass) like this

$('li').find(.row).on('click', function() {
      $(this).toggleClass('checked');
    });

but if you want to just add class write like this

$('li').find(.row).on('click', function() {
          $(this).addClass('checked');
        });


问:
How do you disable App Insights remote dependency tracking in a .net core web job
I have a .net core 3.0 web job which is using the Microsoft.Azure.WebJobs.Logging.ApplicationInsights nuget package to log its logs to Application Insights.

This was all great until I saw the azure bill we were generating and the cost of logs was more than anything else! Following a bit of diagnosis I discovered it was due to remote dependency logging.

According to this article logging sql queries and cosmos are enabled automatically:

https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-dependencies

and looking at that logs I can see every sql query being run. Now I'm sure in the right circumstance this is very useful to debug with, but as the nature of the app is it runs a lot of queries which therefore is causing many gigs of logs that I don't really need.

What I can't see though is an easy way to turn it off?

答:
You should set EnableDependencyTracking to false in  builder.ConfigureLogging.

The example:

```<code>    static void Main(string[] args)
    {
        var builder = new HostBuilder();
        builder.ConfigureWebJobs(b =>
        {
            b.AddAzureStorageCoreServices();
            b.AddAzureStorage();
        });
        builder.ConfigureLogging((context, b) =>
        {
            b.AddConsole();
            string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                //set EnableDependencyTracking to false
                b.AddApplicationInsightsWebJobs(o=> { o.InstrumentationKey = instrumentationKey;o.EnableDependencyTracking = false; });
            }
        });

        var host = builder.Build();
        using (host)
        {
            host.Run();
        }
    }
</code>```

Body:
You should set EnableDependencyTracking to false in  builder.ConfigureLogging.

The example:

    static void Main(string[] args)
    {
        var builder = new HostBuilder();
        builder.ConfigureWebJobs(b =>
        {
            b.AddAzureStorageCoreServices();
            b.AddAzureStorage();
        });
        builder.ConfigureLogging((context, b) =>
        {
            b.AddConsole();
            string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                //set EnableDependencyTracking to false
                b.AddApplicationInsightsWebJobs(o=> { o.InstrumentationKey = instrumentationKey;o.EnableDependencyTracking = false; });
            }
        });

        var host = builder.Build();
        using (host)
        {
            host.Run();
        }
    }


问:
Bigquery: Extract data from an array of json
(This is an extension to this question, but my reputation is too low to comment or ask more questions on that topic...)

We work on bigquery, hence limited in importing packages or using other languages. And, as per the link above, js is a solution, but not what I'm looking for here. I implemented it in js, and it was too slow for our needs.

Suppose one of our columns is a string that look like this (array of json):

[{"location":[22.99902,66.000],"t":1},{"location":[55.32168,140.556],"t":2},{"location":[85.0002,20.0055],"t":3}]

I want to extract from the column the json for which "t":2

Where:

some columns don't have elements "t":2

Some columns have several elements "t":2

The number of json elements in each string can change

element "t":2 is not always in second position.

I don't know regexp well enough for this. We tried regexp_extract with  this pattern: r'(\{.*?\"t\":2.*?\})')), but that doesn't work. It extracts everything that precedes "t":2, including the json for "t":2. We only want the json of element "t":2.

Could you advise a regexp pattern that would work?

EDIT:

I have a preference for a solution that gives me 1 match. Suppose I have this string:
[{"location":[22.99902,66.000],"t":1},{"location":[55.32168,140.556],"t":2},{"location":[55.33,141.785],"t":2}],

I would prefer receiving only 1 answer, the first one.

In that case perhaps regexp is less appropriate, but I'm really not sure?

答:
Even though, you have posted a work around your issue. I believe this answer will be informative. You mentioned that one of the answer selected more than what you needed, I wrote the query below to reproduce your case and achieve aimed output.

```<code>  WITH
  data AS (
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":2},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j ),
  refined_data AS (
  SELECT
    REGEXP_EXTRACT(string_j, r"\{\"\w*\"\:\[\d*\.\d*\,\d*\.\d*\]\,\"t\"\:2\}") AS desired_field
  FROM
    data )
  SELECT
  *
  FROM
  refined_data
  WHERE
  desired_field IS NOT NULL
</code>```

Notice that I have used the dummy described in the temp table, populated inside the WITH method. As below:

Afterwords, in the table refined_data, I used the REGEXP_EXTRACT to extract the desired string from the column. Observe that for the rows which there is not a match expression, the output is null. Thus, the table refined_data is as follows :

As you can see, now it is just needed a simple WHERE filter to obtain the desired output, which was done in the last select.

In addition you can see the information about the regex expression I provided here.

Body:
Even though, you have posted a work around your issue. I believe this answer will be informative. You mentioned that one of the answer selected more than what you needed, I wrote the query below to reproduce your case and achieve aimed output.

  WITH
  data AS (
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":2},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j
  UNION ALL
  SELECT
    " [{ \"location\":[22.99902,66.000]\"t\":1},{\"location\":[55.32168,140.556],\"t\":3},{\"location\":[85.0002,20.0055],\"t\":3}] " AS string_j ),
  refined_data AS (
  SELECT
    REGEXP_EXTRACT(string_j, r"\{\"\w*\"\:\[\d*\.\d*\,\d*\.\d*\]\,\"t\"\:2\}") AS desired_field
  FROM
    data )
  SELECT
  *
  FROM
  refined_data
  WHERE
  desired_field IS NOT NULL

Notice that I have used the dummy described in the temp table, populated inside the WITH method. As below:

Afterwords, in the table refined_data, I used the REGEXP_EXTRACT to extract the desired string from the column. Observe that for the rows which there is not a match expression, the output is null. Thus, the table refined_data is as follows :

As you can see, now it is just needed a simple WHERE filter to obtain the desired output, which was done in the last select.

In addition you can see the information about the regex expression I provided here.


问:
Is there anyway to catch javascript 'hover' event with chrome console?
So, I have many lines of Javascript codes which is quite unorganized right now.
One function among many function is doing some action on 'hover' event, however I cannot find it by just looking through the codes.

I am wondering if it is possible to catch which function cause on hover event with google chrome browser's 'Console.log'

答:
Open the developer tools and click on the "Timeline" tab/section. From there hit the record button at the bottom of the page. When it's recording simply hover over the item that you want to investigate, then stop the recording.

In the timeline of events you can look for any mouseover events, and each of them should have an arrow next to them in the timeline. Expanding that arrow will tell you what line of JS was called, how much memory it used and its duration.


问:
Is there any way to pass parameters to a binded variable in Vue.JS with moustache syntax
Let's say i have an HTML of the form:

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>
</code>```

And in my data:

```<code>data() {
  return {
      GREETING_MESSAGE_FROM_TO: 'Hello this message is for {{variable_1}} from {{variable_2}}'
  }
}
</code>```

My question is that is there any way to pass the variables for this template dynamically from within the html. Looking for something similar in Angular.. Something like this format:

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO | [variable_1, variable_2] }}
</div>
</code>```

答:
There are 3 ways:

```<code>data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex',
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
  }
}
</code>```

or better solution:

```<code>data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex'
  }
},
computed() {
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
}
</code>```

and

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>
</code>```

note that when variable_1 or 2 changes, the greeting updates automatically.

but you can use methods too:

```<code>methods: {
      GREETING_MESSAGE_FROM_TO: function (variable_1, variable_2) {
          return `Hello this message is for ${variable_1} from ${variable_2}'
    }
}
</code>```

with this usage

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO('Sam', 'Alex') }}
</div>
</code>```

or reactive data as args.

Body:
Let's say i have an HTML of the form:

  {{ GREETING_MESSAGE_FROM_TO }}

And in my data:

data() {
  return {
      GREETING_MESSAGE_FROM_TO: 'Hello this message is for {{variable_1}} from {{variable_2}}'
  }
}

My question is that is there any way to pass the variables for this template dynamically from within the html. Looking for something similar in Angular.. Something like this format:

  {{ GREETING_MESSAGE_FROM_TO | [variable_1, variable_2] }}

Body:
There are 3 ways:

data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex',
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
  }
}

or better solution:

data() {
  return {
      variable_1: 'Sam',
      variable_2: 'Alex'
  }
},
computed() {
      GREETING_MESSAGE_FROM_TO: `Hello this message is for ${this.variable_1} from ${this.variable_2}'
}

and

<div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>

note that when variable_1 or 2 changes, the greeting updates automatically.

but you can use methods too:

methods: {
      GREETING_MESSAGE_FROM_TO: function (variable_1, variable_2) {
          return `Hello this message is for ${variable_1} from ${variable_2}'
    }
}

with this usage

<div>
  {{ GREETING_MESSAGE_FROM_TO('Sam', 'Alex') }}
</div>

or reactive data as args.


问:
(Resolved)(type 'String' is not a subtype of type 'int') - Flutter
This question has already been answered, continue reading if you think you have the same error, the answer was given by the user: Tariqul Islam

since a few days ago there was a flutter update my code shows the following error:

_TypeError (type 'String' is not a subtype of type 'int')

Obviously the application worked perfectly before this update, even after changing from "int" to "String" the same error I get but the other way around:

_TypeError (type 'int' is not a subtype of type 'String')

As much as I change the values the same error still appears to me, it is also clear that the RestApi that I am using did not have any changes.

I get the error when I get to "Chip", after I change it to String I get the same error in "Number", and after I change both the same error appears but the other way around as I indicated above

Here the Json file model:

```<code>          class EventoModel {
        String id;
        String nombreEvento;
        List<Participantes> participantes;

        EventoModel({
          this.id,
          this.nombreEvento,
          this.participantes
        });

        factory EventoModel.fromJson(Map<String, dynamic> parsedJson){
          var list = parsedJson['participantes'] as List;
          //print(list.runtimeType);
          List<Participantes> participantesList = list.map((i) => Participantes.fromJson(i)).toList();
          return EventoModel(
            id            : parsedJson ['id'],
            nombreEvento  : parsedJson ['nombreEvento'],
            participantes : participantesList
          );
        }
      }

      class Participantes {
      String uniqueId;
      String apellido;
      int chip;
      String nombre;
      int numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });

      factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
        //print(list.runtimeType);
        return Participantes(
          apellido  : parsedJson['Apellido'],
          chip      : parsedJson['Chip'],
          nombre    : parsedJson['Nombre'],
          numero    : parsedJson['Numero'],
          place     : parsedJson['Place'],
          tiempo    : parsedJson['Tiempo'],
        );
      }

      Map<String, dynamic> toJson() {
        return {
          'Apellido'  : apellido,
          'Chip'      : chip,
          'Nombre'    : nombre,
          'Numero'    : numero,
          'Place'     : place,
          'Tiempo'    : tiempo,
        };
      }
    }
</code>```

This is the Json file Example:

```<code>              {
              "nombreEvento" : "Clasico El Colombiano 2020",
              "participantes" : [ {
                "Apellido" : "MARTINEZ GUTIERREZ",
                "Chip" : "739",
                "Nombre" : "JOSE",
                "Numero" : "139",
                "Place" : "1.",
                "Tiempo" : "00:30:12,91"
                }, {
                "Apellido" : "SUAREZ MORERA",
                "Chip" : "707",
                "Nombre" : "DANIEL",
                "Numero" : "107",
                "Place" : "2.",
                "Tiempo" : "02:00:17,54"
                }, {
                "Apellido" : "RODRIGUEZ VARGAS",
                "Chip" : "1686",
                "Nombre" : "JOSE LUIS",
                "Numero" : "274",
                "Place" : "3.",
                "Tiempo" : "02:01:09,09"
                }
              ]
            }
</code>```

Could someone please help me? : c

答:
From the JSON you provided I have made a model class below:
check out and let me know:</p>

```<code>// To parse this JSON data, do
//
//     final eventoModel = eventoModelFromJson(jsonString);

import 'dart:convert';

EventoModel eventoModelFromJson(String str) => EventoModel.fromJson(json.decode(str));

String eventoModelToJson(EventoModel data) => json.encode(data.toJson());

class EventoModel {
    String nombreEvento;
    List<Participante> participantes;

    EventoModel({
        this.nombreEvento,
        this.participantes,
    });

    factory EventoModel.fromJson(Map<String, dynamic> json) => EventoModel(
        nombreEvento: json["nombreEvento"],
        participantes: List<Participante>.from(json["participantes"].map((x) => Participante.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "nombreEvento": nombreEvento,
        "participantes": List<dynamic>.from(participantes.map((x) => x.toJson())),
    };
}

class Participante {
    String apellido;
    String chip;
    String nombre;
    String numero;
    String place;
    String tiempo;

    Participante({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
    });

    factory Participante.fromJson(Map<String, dynamic> json) => Participante(
        apellido: json["Apellido"],
        chip: json["Chip"],
        nombre: json["Nombre"],
        numero: json["Numero"],
        place: json["Place"],
        tiempo: json["Tiempo"],
    );

    Map<String, dynamic> toJson() => {
        "Apellido": apellido,
        "Chip": chip,
        "Nombre": nombre,
        "Numero": numero,
        "Place": place,
        "Tiempo": tiempo,
    };
}

</code>```

Body:
This question has already been answered, continue reading if you think you have the same error, the answer was given by the user: Tariqul Islam

since a few days ago there was a flutter update my code shows the following error:

_TypeError (type 'String' is not a subtype of type 'int')

Obviously the application worked perfectly before this update, even after changing from "int" to "String" the same error I get but the other way around:

_TypeError (type 'int' is not a subtype of type 'String')

As much as I change the values the same error still appears to me, it is also clear that the RestApi that I am using did not have any changes.

I get the error when I get to "Chip", after I change it to String I get the same error in "Number", and after I change both the same error appears but the other way around as I indicated above

Here the Json file model:

          class EventoModel {
        String id;
        String nombreEvento;
        List<Participantes> participantes;

        EventoModel({
          this.id,
          this.nombreEvento,
          this.participantes
        });

        factory EventoModel.fromJson(Map<String, dynamic> parsedJson){
          var list = parsedJson['participantes'] as List;
          //print(list.runtimeType);
          List<Participantes> participantesList = list.map((i) => Participantes.fromJson(i)).toList();
          return EventoModel(
            id            : parsedJson ['id'],
            nombreEvento  : parsedJson ['nombreEvento'],
            participantes : participantesList
          );
        }
      }

      class Participantes {
      String uniqueId;
      String apellido;
      int chip;
      String nombre;
      int numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });

      factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
        //print(list.runtimeType);
        return Participantes(
          apellido  : parsedJson['Apellido'],
          chip      : parsedJson['Chip'],
          nombre    : parsedJson['Nombre'],
          numero    : parsedJson['Numero'],
          place     : parsedJson['Place'],
          tiempo    : parsedJson['Tiempo'],
        );
      }

      Map<String, dynamic> toJson() {
        return {
          'Apellido'  : apellido,
          'Chip'      : chip,
          'Nombre'    : nombre,
          'Numero'    : numero,
          'Place'     : place,
          'Tiempo'    : tiempo,
        };
      }
    }

This is the Json file Example:

              {
              "nombreEvento" : "Clasico El Colombiano 2020",
              "participantes" : [ {
                "Apellido" : "MARTINEZ GUTIERREZ",
                "Chip" : "739",
                "Nombre" : "JOSE",
                "Numero" : "139",
                "Place" : "1.",
                "Tiempo" : "00:30:12,91"
                }, {
                "Apellido" : "SUAREZ MORERA",
                "Chip" : "707",
                "Nombre" : "DANIEL",
                "Numero" : "107",
                "Place" : "2.",
                "Tiempo" : "02:00:17,54"
                }, {
                "Apellido" : "RODRIGUEZ VARGAS",
                "Chip" : "1686",
                "Nombre" : "JOSE LUIS",
                "Numero" : "274",
                "Place" : "3.",
                "Tiempo" : "02:01:09,09"
                }
              ]
            }

Could someone please help me? : c

Body:
From the JSON you provided I have made a model class below:
check out and let me know:

// To parse this JSON data, do
//
//     final eventoModel = eventoModelFromJson(jsonString);

import 'dart:convert';

EventoModel eventoModelFromJson(String str) => EventoModel.fromJson(json.decode(str));

String eventoModelToJson(EventoModel data) => json.encode(data.toJson());

class EventoModel {
    String nombreEvento;
    List<Participante> participantes;

    EventoModel({
        this.nombreEvento,
        this.participantes,
    });

    factory EventoModel.fromJson(Map<String, dynamic> json) => EventoModel(
        nombreEvento: json["nombreEvento"],
        participantes: List<Participante>.from(json["participantes"].map((x) => Participante.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "nombreEvento": nombreEvento,
        "participantes": List<dynamic>.from(participantes.map((x) => x.toJson())),
    };
}

class Participante {
    String apellido;
    String chip;
    String nombre;
    String numero;
    String place;
    String tiempo;

    Participante({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
    });

    factory Participante.fromJson(Map<String, dynamic> json) => Participante(
        apellido: json["Apellido"],
        chip: json["Chip"],
        nombre: json["Nombre"],
        numero: json["Numero"],
        place: json["Place"],
        tiempo: json["Tiempo"],
    );

    Map<String, dynamic> toJson() => {
        "Apellido": apellido,
        "Chip": chip,
        "Nombre": nombre,
        "Numero": numero,
        "Place": place,
        "Tiempo": tiempo,
    };
}


问:
How to print different text on more than one image using jimp in node js?
I want to create a gift card to send many email with different text, I am using the below logic its work to print but overwrite with previous one image gengerated.</p>

```<code>            Jimp.read(fileName)
            .then(function (image) {
                loadedImage1 = image;
                return Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
            })
            .then(font => {

                console.log('[][][', emailData);
                var paths = [];
                for(let i=0; i< Object.keys(emailData['recipient']).length; i++){
                    var receipentName = "Hello "+emailData['recipient'][i].name+', ';
                    loadedImages[i]= Object.assign(loadedImage1);
                    loadedImages[i].print(font, 220, 400, header, 500);
                    loadedImages[i].print(font, 220, 440, venue, 500);

                    loadedImages[i].print(font, 220, 460, location, 500);
                    loadedImages[i].print(font, 220, 520, receipentName, 500);
                    loadedImages[i].print(font, 220, 580, message, 500);
                    //loadedImage.print(font, 10, 30, imageCaption);
                    var path= basePath + '/invitation/' + bookingId + '/' + bookingId+i + '.jpg';
                    //let fullPath = config.BASE_URL + '/uploads/invitation/' + bookingId + '/' + bookingId+i + '.jpg';
                    paths[i] = path;
                    loadedImages[i].write(path);
                }
                res.status(200).json({
                    data: {
                        paths: paths,
                        path: path, //config.BASE_URL + '/uploads/invitation/' + bookingId + '/' + bookingId + '.jpg',
                        bookingData: detail,
                        restaurantDetails: restaurantDetails
                    },
                    status: 1,
                    msg: "Notes data"
                });

            })
            .catch(function (err) {
                console.error(err);
            });
</code>```

答:
Instead of </p>

```<code>loadedImages[i]= Object.assign(loadedImage1);
</code>```

<p>Use </p>

```<code>loadedImages[i]= loadedImage1.clone();
</code>```

Body:
I want to create a gift card to send many email with different text, I am using the below logic its work to print but overwrite with previous one image gengerated.

            Jimp.read(fileName)
            .then(function (image) {
                loadedImage1 = image;
                return Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
            })
            .then(font => {

                console.log('[][][', emailData);
                var paths = [];
                for(let i=0; i< Object.keys(emailData['recipient']).length; i++){
                    var receipentName = "Hello "+emailData['recipient'][i].name+', ';
                    loadedImages[i]= Object.assign(loadedImage1);
                    loadedImages[i].print(font, 220, 400, header, 500);
                    loadedImages[i].print(font, 220, 440, venue, 500);

                    loadedImages[i].print(font, 220, 460, location, 500);
                    loadedImages[i].print(font, 220, 520, receipentName, 500);
                    loadedImages[i].print(font, 220, 580, message, 500);
                    //loadedImage.print(font, 10, 30, imageCaption);
                    var path= basePath + '/invitation/' + bookingId + '/' + bookingId+i + '.jpg';
                    //let fullPath = config.BASE_URL + '/uploads/invitation/' + bookingId + '/' + bookingId+i + '.jpg';
                    paths[i] = path;
                    loadedImages[i].write(path);
                }
                res.status(200).json({
                    data: {
                        paths: paths,
                        path: path, //config.BASE_URL + '/uploads/invitation/' + bookingId + '/' + bookingId + '.jpg',
                        bookingData: detail,
                        restaurantDetails: restaurantDetails
                    },
                    status: 1,
                    msg: "Notes data"
                });

            })
            .catch(function (err) {
                console.error(err);
            });

Body:
Instead of

loadedImages[i]= Object.assign(loadedImage1);

Use

loadedImages[i]= loadedImage1.clone();


问:
Javascript: Adding a page-breaker before an image
I'm kinda new in javaScript, I have a documentation in HTML and I want to have a break-page before every image.

This is the code I've been trying:

```<code><script>
@media print {
    .pagebreak { page-break-before: always; }
}

if (document.querySelectorAll)
    var clsElements = document.querySelectorAll(".image");

for (var i=0, max=clsElements.length; i < max; i++) {
     <div class="pagebreak"> </div>
}
</script>
</code>```

(Defining page break, taking all images, looping through them and using the pagebreak)

Anyone has any idea about how to make it detect the images and put the page-breakers?

edit: i've tried with ".image" and ".img"

答:
All you need to do is have the CSS rule like so:

```<code>@media print {
  .image {
    page-break-after: always ;
  }
}
</code>```

There is no javascript needed! In this case all you want is have a page brake after every image. Which is a "style-only" task. You do not need to manipulate DOM for that.

Read more about break-after CSS here

Why your code did not work:
You have added Css style inside a script tag. That will never work.

Body:
I'm kinda new in javaScript, I have a documentation in HTML and I want to have a break-page before every image.

This is the code I've been trying:

(Defining page break, taking all images, looping through them and using the pagebreak)

Anyone has any idea about how to make it detect the images and put the page-breakers?

edit: i've tried with ".image" and ".img"

Body:
All you need to do is have the CSS rule like so:

@media print {
  .image {
    page-break-after: always ;
  }
}

There is no javascript needed! In this case all you want is have a page brake after every image. Which is a "style-only" task. You do not need to manipulate DOM for that.

Read more about break-after CSS here

Why your code did not work:
You have added Css style inside a script tag. That will never work.


问:
Scaffold-DbContext does not check-out updated files in TFS
I've done some ALTER changes in the database then I performed the scaffold command to update my model as follows: Scaffold-DbContext "Server=localhost;Database=<DB_NAME>;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models\Domain -Force -Project <PROJECT_NAME>.

When I check the model in my project I can see the change in code but files are marked as unchanged in the source control so I have to check-out all updated classes myself.

Is there a way to make the scaffold action auto check-out changes in file?

答:
Assuming you are using Server workspace, as with a Server workspace, modifying a file outside of Visual Studio, TFS doesn't seem to detect the change to the file.

It's suggested to use Local Workspace, with Local workspace, when you modify files outside Visual Studio, your workspace should be able to detect the changes automatically.

If you still want to use Server workspace, you would need to check out the file manually or do a compare to find the modified files, check following cases:

How to have TFS 2010 detect changes done to files outside of Visual Studio?

Force TFS to detect changes


答:
If you have a buffer that contains '\0' characters and you want them to not end up at the start of the buffer, just make sure '\0' sorts to the end of the array:

```<code>int charCompare(const void* ptr1, const void* ptr2)
{
   int c1 = *(char*)ptr1;
   int c2 = *(char*)ptr2;

   if (c1 == 0) c1 = INT_MAX;
   if (c2 == 0) c2 = INT_MAX;

   return c1 - c2;
}
</code>```

Title: qsort() works in one direction, but not other

Body:
This is how I made my comparison function to pass to qsort():

int charCompare(const void* ptr1, const void* ptr2)
{
   char c1 = *(char*)ptr1;
   char c2 = *(char*)ptr2;
   return c1 - c2;
}

And this is the implementation:

char buffer[SIZE];
/*
 * buffer filled here
 */
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);

Nothing gets printed. I'm pretty sure it's because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?

Body:
If you have a buffer that contains '\0' characters and you want them to not end up at the start of the buffer, just make sure '\0' sorts to the end of the array:

int charCompare(const void* ptr1, const void* ptr2)
{
   int c1 = *(char*)ptr1;
   int c2 = *(char*)ptr2;

   if (c1 == 0) c1 = INT_MAX;
   if (c2 == 0) c2 = INT_MAX;

   return c1 - c2;
}


问:
shell - Yes no prompt not working using case
I am using bash 4.2 to create a prompt

```<code>        read -p "Want to print the output to $newname ? (y/n)" $yesno
        case "$yesno" in
           [Yy])
                   outname=$newname;;
           [Nn])
                   echo "Quitting ...";
                   exit 4;;
           *)
                   echo "Quitting !!";
                   exit 5;;
        esac
</code>```

The problem is that whether I give y or n, the output is "Quitting !!"

But if I comment the case *), the result equates outname to newname

What am I doing wrong?

答:
Could you please try following. 2 things I have fixed in OP's code.

i- We need NOT to put $ while reading value from user in variable yesno.

ii- I have changed user's entered input to small letters so no need to check both the y|Y or n|N responses here.

```<code>read -p "Want to print the output to $newname ? (y/n)" yesno
case $(tr '[:upper:]' '[:lower:]' <<< "$yesno") in
y)
   outname=$newname
   echo "In y condition here...."
   ;;
n)
   echo "Quitting ..."
   exit 4
;;
*)
   echo "Default Quitting !!";
   exit 5
   ;;
esac
</code>```

When I run above code:

```<code>./script.ksh
Want to print the output to  ? (y/n)y
In y condition here....
</code>```

Body:
I am using bash 4.2 to create a prompt

        read -p "Want to print the output to $newname ? (y/n)" $yesno
        case "$yesno" in
           [Yy])
                   outname=$newname;;
           [Nn])
                   echo "Quitting ...";
                   exit 4;;
           *)
                   echo "Quitting !!";
                   exit 5;;
        esac

The problem is that whether I give y or n, the output is "Quitting !!"

But if I comment the case *), the result equates outname to newname

What am I doing wrong?

Body:
Could you please try following. 2 things I have fixed in OP's code.

i- We need NOT to put $ while reading value from user in variable yesno.

ii- I have changed user's entered input to small letters so no need to check both the y|Y or n|N responses here.

read -p "Want to print the output to $newname ? (y/n)" yesno
case $(tr '[:upper:]' '[:lower:]' <<< "$yesno") in
y)
   outname=$newname
   echo "In y condition here...."
   ;;
n)
   echo "Quitting ..."
   exit 4
;;
*)
   echo "Default Quitting !!";
   exit 5
   ;;
esac

When I run above code:

./script.ksh
Want to print the output to  ? (y/n)y
In y condition here....


问:
HOw to convert jquery to react js
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

```<code>$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});
</code>```

HTML

```<code><div id="overlay" class="">Focus/Blur</div>
<input type="txt" id="password"/>
</code>```

答:
No need to convert that code into 'React' from jQuery. The simple way is just include '$' the add that code like the following method. It will work.

```<code>    import React from 'react';
    import $ from 'jquery';

    function ExampleFunction(props) {

      $(document).ready(function() {
        $("input#password").focus(function() {
         $("#overlay").addClass("newoverlay");
        }).blur(function() {
          $("#overlay").removeClass("newoverlay");
        });
      });

return (<React.Fragment>
<div> Your code </div>
</React.Fragment>);
}

export default ExampleFunction;
</code>```

You may need to update this code based on the class-based or functional components respectively.

Title: HOw to convert jquery to react js

Body:
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});

HTML

Focus/Blur

<input type="txt" id="password"/>

Body:
No need to convert that code into 'React' from jQuery. The simple way is just include '$' the add that code like the following method. It will work.

    import React from 'react';
    import $ from 'jquery';

    function ExampleFunction(props) {

      $(document).ready(function() {
        $("input#password").focus(function() {
         $("#overlay").addClass("newoverlay");
        }).blur(function() {
          $("#overlay").removeClass("newoverlay");
        });
      });

return (<React.Fragment>
<div> Your code </div>
</React.Fragment>);
}

export default ExampleFunction;

You may need to update this code based on the class-based or functional components respectively.