问:
Android SurfaceView not showing onDraw
For simpleness of the question, I'm drawing an integer on a SurfaceView which increases by 1 every draw.
The increasing actually happens, as I can see on the System.out.
The text on the screen stays on '0'.
Who can tell me what I'm doing wrong?

SurfaceViewTest.java

```<code>package com.niek.surfaceviewtest;

import android.app.Activity;
import android.os.Bundle;

public class SurfaceViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
</code>```

StatusView.java

```<code>package com.niek.surfaceviewtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StatusView extends SurfaceView implements SurfaceHolder.Callback {

    private int tmp;
    private DrawThread drawThread;

    public StatusView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        setFocusable(true);
        drawThread = new DrawThread(getHolder());
    }

    @Override
    public void onDraw(Canvas c) {
            c.drawColor(Color.BLACK);
        Paint p = new Paint();
        p.setColor(Color.RED);
        c.drawText(tmp + "", 10, 10, p);
        tmp++;

        System.out.println(tmp);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawThread.setRunning(true);
        drawThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        drawThread.setRunning(false);
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }

    protected class DrawThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private boolean isRunning;

        public DrawThread(SurfaceHolder surfaceHolder) {
            this.surfaceHolder = surfaceHolder;
            isRunning = false;
        }

        public void setRunning(boolean run) {
            isRunning = run;
        }

        public void run() {
            Canvas c;
            while (isRunning) {
                c = null;
                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                        onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <com.niek.surfaceviewtest.StatusView
        android:id="@+id/statusview1"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:background="#000000"
 />
</LinearLayout>
</code>```

答: Looks like you are showing your main.xml with setContentView(R.layout.main); instead of creating the surface and displaying that.  unless i am missing code somewhere I don't see that as being the case.  </p>

Title: Android SurfaceView not showing onDraw

Body:
For simpleness of the question, I'm drawing an integer on a SurfaceView which increases by 1 every draw.
The increasing actually happens, as I can see on the System.out.
The text on the screen stays on '0'.
Who can tell me what I'm doing wrong?

SurfaceViewTest.java

package com.niek.surfaceviewtest;

import android.app.Activity;
import android.os.Bundle;

public class SurfaceViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

StatusView.java

package com.niek.surfaceviewtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StatusView extends SurfaceView implements SurfaceHolder.Callback {

    private int tmp;
    private DrawThread drawThread;

    public StatusView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        setFocusable(true);
        drawThread = new DrawThread(getHolder());
    }

    @Override
    public void onDraw(Canvas c) {
            c.drawColor(Color.BLACK);
        Paint p = new Paint();
        p.setColor(Color.RED);
        c.drawText(tmp + "", 10, 10, p);
        tmp++;

        System.out.println(tmp);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawThread.setRunning(true);
        drawThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        drawThread.setRunning(false);
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }

    protected class DrawThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private boolean isRunning;

        public DrawThread(SurfaceHolder surfaceHolder) {
            this.surfaceHolder = surfaceHolder;
            isRunning = false;
        }

        public void setRunning(boolean run) {
            isRunning = run;
        }

        public void run() {
            Canvas c;
            while (isRunning) {
                c = null;
                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                        onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <com.niek.surfaceviewtest.StatusView
        android:id="@+id/statusview1"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:background="#000000"
 />
</LinearLayout>


来源: stackexchange

问:
how to use vlookup for multiple conditions
i am looking for a multiple vlookup funciton.
for examle . problem statement:
I have 3 columns:a,b,c.
how can i get result c based on a and b match together?
Is there any function to solve this?</p>

答:
Have you considered using the IF function?

=IF (logical_test, [value_if_true], [value_if_false]).

What the logical test is is really up to your creativity.

Detailed explanation here.

ContentLicense: CC BY-SA 4.0


问:
math.sin incorrect result
```<code>>>> import math
>>> math.sin(68)
-0.897927680689
</code>```

But

```<code>sin(68) = 0.927 (3 decimal places)
</code>```

Any ideas about why I am getting this result?

Thanks.

答:
by default angle in Python is calculated in radians. So, you can try to multiply the angle ( degrees ) by 0.01745 - to convert it to degrees and input the values.
print(math.sin(60*0.01745))
0.8659266112878228</p>

ContentLicense: CC BY-SA 3.0

Title: math.sin incorrect result

Body:
>>> import math
>>> math.sin(68)
-0.897927680689

But

sin(68) = 0.927 (3 decimal places)

Any ideas about why I am getting this result?

Thanks.


问:
How to stop overwrite txt file and let it write in new line
The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.</p>

```<code>public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    try{
    File folder = new File("folderName");
    folder.mkdir();
    File f = new File(folder, "file1.txt"); //file to folder
    f.createNewFile(); //skapar fil
    //Scanner fileIn = new Scanner(f);
    System.out.println("File path" +f.getPath());

   //.----------------------------------
while(anw.equals("j")){

        Scanner in = new Scanner(System.in);
        FileWriter fWriter ;// removed null
        BufferedWriter writr;// removed null

        System.out.println("Ange utgiftspost:"); //post
        String post = in.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=in.nextInt();
        in.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = in.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;

        fWriter = new FileWriter(f);
        writr = new BufferedWriter(fWriter);
        writr.write(fileContent);
        writr.newLine();

        if (anw.equals("n")) {
            writr.close();
            //writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut
    }//try

    //Scanner fileIn = new Scanner(f);

      catch(Exception e){
  System.err.println(e.getMessage());
}

    }
</code>```

答:
In my previous question, I had @ASKW answer working for this problem.
He commented that BufferedWriter for my particular case wouldn't work. But to use FilterWriter alone with append would solve it.

Body:
The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.

public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    try{
    File folder = new File("folderName");
    folder.mkdir();
    File f = new File(folder, "file1.txt"); //file to folder
    f.createNewFile(); //skapar fil
    //Scanner fileIn = new Scanner(f);
    System.out.println("File path" +f.getPath());

   //.----------------------------------
while(anw.equals("j")){

        Scanner in = new Scanner(System.in);
        FileWriter fWriter ;// removed null
        BufferedWriter writr;// removed null

        System.out.println("Ange utgiftspost:"); //post
        String post = in.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=in.nextInt();
        in.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = in.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;

        fWriter = new FileWriter(f);
        writr = new BufferedWriter(fWriter);
        writr.write(fileContent);
        writr.newLine();

        if (anw.equals("n")) {
            writr.close();
            //writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut
    }//try

    //Scanner fileIn = new Scanner(f);

      catch(Exception e){
  System.err.println(e.getMessage());
}

    }


问:
C# Function Chaining
Why do i receive error in the following declaration ?

```<code>List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});
</code>```

Error :Can not convert type void to List ?

答:
There is yet another way.</p>

```<code>List<int> intrs =  new List<int>
                        {
                            1,
                            2,
                            3,
                            45
                        };
</code>```

ContentLicense: CC BY-SA 2.5

Title: C# Function Chaining

Body:
Why do i receive error in the following declaration ?

List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});

Error :Can not convert type void to List ?

Body:
There is yet another way.

List<int> intrs =  new List<int>
                        {
                            1,
                            2,
                            3,
                            45
                        };


问:
Real-World Performance of Red-Black vs. 2-3-4 trees, especially considering cache performance?
A single node of a 2-3-4 tree could be constructed with 8 pointers: pointers to up to four child nodes, pointers to up to 3 actual records containing keys that will either match a search key or will determine which of 4 child nodes to recurse to, and a parent node pointer.

Common hardware today has 8-byte pointers, giving a 64-byte node.  Further, modern CPUs have 64-byte cache lines.  Should the nodes be aligned with the cache lines, then each node requires only one cache line hit: after referring to the first of seven pointers, all the rest will be in your L1 cache.

While a red-black tree is far simpler to implement, and small code should be fast code, each level of descent in the tree risks an L1 cache miss.  For 1023 objects, a 2-3-4 tree needs a a worst-case of 5 nodes to be loaded into cache.  A perfectly-balanced binary tree would need 10, but due to imbalance a Red-Black may need more (not sure the worst case: 20?)

Small test harnesses that simply hammer at one data structure will probably keep it all in cache, and so may report the Red-Black tree as being similar performance to the 2-3-4.  But I have a feeling that a complicated real-world application may see much less wall-clock time and lower latency with 2-3-4 trees.

Is there any consensus or research on this?

答:
Your reasoning is certainly correct -- for cold lookups the 2-3-4 tree will perform better just because it hits fewer cache lines.

If the performance of the tree is important, though, that generally means that you're using it often.

If the tree is being using often and it's not pretty much all in the cache, then it must be big.  When a big tree is used often, the higher-level nodes will generally be cached, because each level up is hit twice as often as the level below on average.

So the real performance improvement when it matters is limited to the deepest few levels in the tree.  You can still see a performance with with a 2-3-4 tree, but it's not a runaway, and I think you'd need a special reason to judge it worth the extra code complexity (especially in search and iteration).


问:
How will I set if account_status = 1 then I can able to login otherwise not able to login?
How will I set if account_status = 1 then I can able to login otherwise not able to login? email, phone and password must be there. This is the following code </p>

```<code>public function login(Request $request){

        if(Auth::attempt(['email' => request('email'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }
</code>```

答:
Your mistake is that you try to match account_status to a value which you have got from the request, but you are actually in need to check whether it's 1, so change

```<code>'account_status'=> request('account_status')
</code>```

to

```<code>'account_status'=> 1
</code>```

both in your if and your else if.

Body:
How will I set if account_status = 1 then I can able to login otherwise not able to login? email, phone and password must be there. This is the following code

public function login(Request $request){

        if(Auth::attempt(['email' => request('email'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }

Body:
Your mistake is that you try to match account_status to a value which you have got from the request, but you are actually in need to check whether it's 1, so change

'account_status'=> request('account_status')

to

'account_status'=> 1

both in your if and your else if.


问:
How to parse JSON array to a spinner
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.

JSON format:

```<code>[
  {
    "nsrId": "1018038",
    "koordinatLatLng": [
      59.6908,
      9.04228
    ],
    "navn": "Gransherad barnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Kommunal",
    "antallBarn": 26
  },
  {
    "nsrId": "1012983",
    "koordinatLatLng": [
      59.5763,
      9.19806
    ],
    "navn": "Trolldalen Gårdsbarnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Privat",
    "antallBarn": 24
  },
</code>```

etc...

My code:

```<code>    spinner = findViewById(R.id.barneHage_Spinner);

    hentJSON();
}

private void hentJSON() {
    showSimplProgressDialog(this, "loading...", "Henter Json", false);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("strrrrr", ">>" + response);

                    try {
                        JSONObject obj = new JSONObject(response);

                        barnehageArrayList = new ArrayList<>();
                        JSONArray dataArray = obj.getJSONArray("navn");

                        for (int i = 0; i < dataArray.length(); i++) {
                            Barnehage model = new Barnehage();
                            JSONObject dataobj = dataArray.getJSONObject(i);

                            model.setNavn(dataobj.getString("navn"));
                           // model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));

                            barnehageArrayList.add(model);
                        }

                        for (int i = 0; i < barnehageArrayList.size(); i++) {
                            names.add(barnehageArrayList.get(i).getNavn());
                        }
                        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
                        spinner.setAdapter(spinnerArrayAdapter);
                        removeSimpleProgressDialog();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
</code>```

I expect the output to be a spinner with the only values showing

```<code>1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..
</code>```

etc

答:
I think you were wrong when getting JSON array by JSONArray dataArray = obj.getJSONArray("navn").

Let try using this code:

```<code>    @Override
    public void onResponse (String response) {
        try {
            JSONArray dataArray = new JSONArray(response);
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject dataobj = dataArray.getJSONObject(i);
</code>```

Title: How to parse JSON array to a spinner

Body:
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.

JSON format:

[
  {
    "nsrId": "1018038",
    "koordinatLatLng": [
      59.6908,
      9.04228
    ],
    "navn": "Gransherad barnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Kommunal",
    "antallBarn": 26
  },
  {
    "nsrId": "1012983",
    "koordinatLatLng": [
      59.5763,
      9.19806
    ],
    "navn": "Trolldalen Gårdsbarnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Privat",
    "antallBarn": 24
  },

etc...

My code:

    spinner = findViewById(R.id.barneHage_Spinner);

    hentJSON();
}

private void hentJSON() {
    showSimplProgressDialog(this, "loading...", "Henter Json", false);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("strrrrr", ">>" + response);

                    try {
                        JSONObject obj = new JSONObject(response);

                        barnehageArrayList = new ArrayList<>();
                        JSONArray dataArray = obj.getJSONArray("navn");

                        for (int i = 0; i < dataArray.length(); i++) {
                            Barnehage model = new Barnehage();
                            JSONObject dataobj = dataArray.getJSONObject(i);

                            model.setNavn(dataobj.getString("navn"));
                           // model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));

                            barnehageArrayList.add(model);
                        }

                        for (int i = 0; i < barnehageArrayList.size(); i++) {
                            names.add(barnehageArrayList.get(i).getNavn());
                        }
                        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
                        spinner.setAdapter(spinnerArrayAdapter);
                        removeSimpleProgressDialog();

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

I expect the output to be a spinner with the only values showing

1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..

etc

Body:
I think you were wrong when getting JSON array by JSONArray dataArray = obj.getJSONArray("navn").

Let try using this code:

    @Override
    public void onResponse (String response) {
        try {
            JSONArray dataArray = new JSONArray(response);
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject dataobj = dataArray.getJSONObject(i);


问:
How to nest variables with LESS
I'm used to working with sass when working with projects. However I need to use less for a specific project. Is there a way to nest variables with less like the following example?

```<code>$palettes: (
    brand: (
        base: #ffffff,
        dark: #a31f02,
        green: #61a143
    )
);
</code>```

Then can be used like:

$color-link: palette(brand);

答: The best way to solve the situations is a map. It is a new feature in Less lang that allows you to get values using keys</p>

Title: How to nest variables with LESS

Body:
I'm used to working with sass when working with projects. However I need to use less for a specific project. Is there a way to nest variables with less like the following example?

$palettes: (
    brand: (
        base: #ffffff,
        dark: #a31f02,
        green: #61a143
    )
);

Then can be used like:

$color-link: palette(brand);


问:
VS2017 Break build using tslint on .js files
I found the Typescript Analyzer extension via Set up TSLint for VS2017

However it only works on .ts files. I want to be able to run tslint on .js files and have it break the build on errors. I wasn't able to get my builds to break using eslint either.

Running tslint via command line works as expected.

答:
The TypeScript Analyzer extension does now support linting JavaScript files, including breaking the build on errors.  There's a 'Lint .js and .jsx files' option on Tools/Options/TypeScript Analyzer.

For this to work you need to enable the option in Tools/Options and to create a 'jsRules' section in your tslint.json at the same level as the existing 'rules' section (Tools/TypeScript Analyzer/Edit TSLint settings). Rules that apply to .ts and .tsx files then appear in the existing 'rules' section, and rules that apply to .js and .jsx files need to be added to the new 'jsRules' section.

This means if you want a rule to apply to .ts and .js files it needs to appear twice in tslint.json, once in each section. Some rules will only work with TypeScript (.ts and .tsx) files. See the TSLint documentation for more details.

For example, a tslint.json that (only) applies the no-console rule to both TypeScript and JavaScript files would look as below:

```<code>{
  "rules": {
    "no-console": true
  },
   "jsRules": {
    "no-console": true
  }
}
</code>```

To break the build on errors as usual set 'Show errors' and 'Run on build' to True in Tools/Options/TypeScript Analyzer.

Body:
The TypeScript Analyzer extension does now support linting JavaScript files, including breaking the build on errors.  There's a 'Lint .js and .jsx files' option on Tools/Options/TypeScript Analyzer.

For this to work you need to enable the option in Tools/Options and to create a 'jsRules' section in your tslint.json at the same level as the existing 'rules' section (Tools/TypeScript Analyzer/Edit TSLint settings). Rules that apply to .ts and .tsx files then appear in the existing 'rules' section, and rules that apply to .js and .jsx files need to be added to the new 'jsRules' section.

This means if you want a rule to apply to .ts and .js files it needs to appear twice in tslint.json, once in each section. Some rules will only work with TypeScript (.ts and .tsx) files. See the TSLint documentation for more details.

For example, a tslint.json that (only) applies the no-console rule to both TypeScript and JavaScript files would look as below:

{
  "rules": {
    "no-console": true
  },
   "jsRules": {
    "no-console": true
  }
}

To break the build on errors as usual set 'Show errors' and 'Run on build' to True in Tools/Options/TypeScript Analyzer.


问:
Replacing kivy Listview with RecycleView
I am currently trying to replace some features in an app using the ListView with the RecycleView.

From the documentation I can't figure out how to that though.

The current code looks similar to this:

```<code>ListView:
    id: x
    adapter:
        sla.SimpleListAdapter(data=[], cls=label.Label)

x.adapter.data.append(‘frank’)
</code>```

Are there any resources or tips on how to achieve this?
I am trying to use the recycleview because the ListView seems to be deprecated now.

答:
ListView is removed in Kivy version 1.11.0. Below snippets show the equivalent in RecycleView. There are two examples in  Kivy documentation for RecycleView.

The snippets below show the equivalent using RecycleView.

Snippets: kv file

```<code>RecycleView:
    id: x

    viewclass: 'Label'

    RecycleBoxLayout:
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
</code>```

Snippets: py file

```<code>x.data.append({'text‘: 'frank’)
</code>```

Examples

The following three examples illustrate Kivy RecycleView.

How to fetch data from database and show in table

How to add vertical scroll in RecycleView

main.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior

Builder.load_string('''
<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    id: rv

    # Optional: ScrollView attributes
    bar_width: 5
    bar_color: 1, 0, 0, 1   # red
    bar_inactive_color: 0, 0, 1, 1   # blue
    effect_cls: "ScrollEffect"
    scroll_type: ['bars', 'content']

    viewclass: 'SelectableLabel'

    SelectableRecycleBoxLayout:
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True
''')

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableLabel(RecycleDataViewBehavior, Label):
    ''' Add selection support to the Label '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableLabel, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableLabel, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(x)} for x in range(100)]
        self.data.insert(0, {'text': 'frank'})
        self.data.append({'text': 'liam'})

class TestApp(App):
    title = 'Kivy RecycleView Demo'

    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()
</code>```

Output

Body:
I am currently trying to replace some features in an app using the ListView with the RecycleView.

From the documentation I can't figure out how to that though.

The current code looks similar to this:

ListView:
    id: x
    adapter:
        sla.SimpleListAdapter(data=[], cls=label.Label)

x.adapter.data.append(‘frank’)

Are there any resources or tips on how to achieve this?
I am trying to use the recycleview because the ListView seems to be deprecated now.

Body:
ListView is removed in Kivy version 1.11.0. Below snippets show the equivalent in RecycleView. There are two examples in  Kivy documentation for RecycleView.

The snippets below show the equivalent using RecycleView.

Snippets: kv file

RecycleView:
    id: x

    viewclass: 'Label'

    RecycleBoxLayout:
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

Snippets: py file

x.data.append({'text‘: 'frank’)

Examples

The following three examples illustrate Kivy RecycleView.

How to fetch data from database and show in table

How to add vertical scroll in RecycleView

main.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior

Builder.load_string('''
<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    id: rv

    # Optional: ScrollView attributes
    bar_width: 5
    bar_color: 1, 0, 0, 1   # red
    bar_inactive_color: 0, 0, 1, 1   # blue
    effect_cls: "ScrollEffect"
    scroll_type: ['bars', 'content']

    viewclass: 'SelectableLabel'

    SelectableRecycleBoxLayout:
        default_size: None, dp(26)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True
''')

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableLabel(RecycleDataViewBehavior, Label):
    ''' Add selection support to the Label '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableLabel, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableLabel, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(x)} for x in range(100)]
        self.data.insert(0, {'text': 'frank'})
        self.data.append({'text': 'liam'})

class TestApp(App):
    title = 'Kivy RecycleView Demo'

    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()

Output


问:
How to Modify Bootstrap 4 Mixins without Editing Core Files
So basically, I'm trying to modify the button-variant mixin in bootstrap 4. The core file where the code for this resides is bootstrap\scss\mixins, and the filename is _buttons.scss. In my custom.scss, I have the following code:

```<code>@import "../../node_modules/bootstrap/scss/bootstrap";
</code>```

I would want to keep the mixin name the same and not override it using a different name because it's being used in the file node_modules\bootstrap\scss_buttons.scss in the following code that generates all buttons based on the colors available:

```<code>@each $color, $value in $theme-colors {
.btn-#{$color} {
@include button-variant($value, $value);
}
}
</code>```

What happens is that when the new modified mixin code is added below importing bootstrap in custom.scss, it does not have any effect as the imported bootstrap gets compiled after that code and the default button css gets compiled. Whereas, when the modified mixin code is added after importing bootstrap in custom.scss, there is duplication of buttons in the compiled .css file.

How would one go about modifying the code in a mixin without editing the core bootstrap files?

答:
You should import Bootstrap's SCSS files separately instead of the whole pack, and you should import your own mixins after Bootstrap's _mixins.scss. This way you can override them before Bootstrap's _buttons.scss would use them:

```<code>@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";

@import "my-custom-mixins";

// rest of Bootstrap imports (see bootstrap.scss):
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";
@import "bootstrap/scss/code";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/tables";
@import "bootstrap/scss/forms";
@import "bootstrap/scss/buttons";
@import "my-custom-buttons";
@import "bootstrap/scss/transitions";
@import "bootstrap/scss/dropdown";
@import "bootstrap/scss/button-group";
@import "bootstrap/scss/input-group";
@import "bootstrap/scss/custom-forms";
@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";
@import "bootstrap/scss/card";
@import "bootstrap/scss/breadcrumb";
@import "bootstrap/scss/pagination";
@import "bootstrap/scss/badge";
@import "bootstrap/scss/jumbotron";
@import "bootstrap/scss/alert";
@import "bootstrap/scss/progress";
@import "bootstrap/scss/media";
@import "bootstrap/scss/list-group";
@import "bootstrap/scss/close";
@import "bootstrap/scss/toasts";
@import "bootstrap/scss/modal";
@import "bootstrap/scss/tooltip";
@import "bootstrap/scss/popover";
@import "bootstrap/scss/carousel";
@import "bootstrap/scss/spinners";
@import "bootstrap/scss/utilities";
@import "bootstrap/scss/print";
</code>```

Body:
So basically, I'm trying to modify the button-variant mixin in bootstrap 4. The core file where the code for this resides is bootstrap\scss\mixins, and the filename is _buttons.scss. In my custom.scss, I have the following code:

@import "../../node_modules/bootstrap/scss/bootstrap";

I would want to keep the mixin name the same and not override it using a different name because it's being used in the file node_modules\bootstrap\scss_buttons.scss in the following code that generates all buttons based on the colors available:

@each $color, $value in $theme-colors {
.btn-#{$color} {
@include button-variant($value, $value);
}
}

What happens is that when the new modified mixin code is added below importing bootstrap in custom.scss, it does not have any effect as the imported bootstrap gets compiled after that code and the default button css gets compiled. Whereas, when the modified mixin code is added after importing bootstrap in custom.scss, there is duplication of buttons in the compiled .css file.

How would one go about modifying the code in a mixin without editing the core bootstrap files?

Body:
You should import Bootstrap's SCSS files separately instead of the whole pack, and you should import your own mixins after Bootstrap's _mixins.scss. This way you can override them before Bootstrap's _buttons.scss would use them:

@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";

@import "my-custom-mixins";

// rest of Bootstrap imports (see bootstrap.scss):
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";
@import "bootstrap/scss/code";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/tables";
@import "bootstrap/scss/forms";
@import "bootstrap/scss/buttons";
@import "my-custom-buttons";
@import "bootstrap/scss/transitions";
@import "bootstrap/scss/dropdown";
@import "bootstrap/scss/button-group";
@import "bootstrap/scss/input-group";
@import "bootstrap/scss/custom-forms";
@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";
@import "bootstrap/scss/card";
@import "bootstrap/scss/breadcrumb";
@import "bootstrap/scss/pagination";
@import "bootstrap/scss/badge";
@import "bootstrap/scss/jumbotron";
@import "bootstrap/scss/alert";
@import "bootstrap/scss/progress";
@import "bootstrap/scss/media";
@import "bootstrap/scss/list-group";
@import "bootstrap/scss/close";
@import "bootstrap/scss/toasts";
@import "bootstrap/scss/modal";
@import "bootstrap/scss/tooltip";
@import "bootstrap/scss/popover";
@import "bootstrap/scss/carousel";
@import "bootstrap/scss/spinners";
@import "bootstrap/scss/utilities";
@import "bootstrap/scss/print";


问:
Generate unique json object name gson in Kotlin
How would I be able to generate a new object based on the object names below. What I am trying to do here is that when there is no Object1, gson will generate Object1 with the values below and when there is Object1, gson will generate Object2 and so on.</p>

```<code>{
    "Object1": {
        "Name": "Object1",
        "Color": "Orange",
        "Food": "Pizza"
    },
    "Object2": {
        "Name": "Object2",
        "Color": "Blue",
        "Food": "Pineapple"
    }
}
</code>```

答:
Generating an unique property in your class object means you could dynamically have a class lets say Example.

```<code>FoodData {
 var object1 : Food?
 var object2 : Food?
 // And so on...
}
</code>```

For me this seems like a structural problem. Your response should be specific to the data structure you have and need. A more acceptable approach would be:

```<code>[
     {
        "Name": "Object1",
        "Color": "Orange",
        "Food": "Pizza",
        "someAttr" : "Object1"
    },
    {
        "Name": "Object2",
        "Color": "Blue",
        "Food": "Pineapple",
        "someAttr" : "Object2"
    }
]
</code>```

And then it would make more sense to have a list of food like :

```<code>FoodData {
 var listFood: List<Food>?

}
</code>```

Body:
How would I be able to generate a new object based on the object names below. What I am trying to do here is that when there is no Object1, gson will generate Object1 with the values below and when there is Object1, gson will generate Object2 and so on.

{
    "Object1": {
        "Name": "Object1",
        "Color": "Orange",
        "Food": "Pizza"
    },
    "Object2": {
        "Name": "Object2",
        "Color": "Blue",
        "Food": "Pineapple"
    }
}

Body:
Generating an unique property in your class object means you could dynamically have a class lets say Example.

FoodData {
 var object1 : Food?
 var object2 : Food?
 // And so on...
}

For me this seems like a structural problem. Your response should be specific to the data structure you have and need. A more acceptable approach would be:

[
     {
        "Name": "Object1",
        "Color": "Orange",
        "Food": "Pizza",
        "someAttr" : "Object1"
    },
    {
        "Name": "Object2",
        "Color": "Blue",
        "Food": "Pineapple",
        "someAttr" : "Object2"
    }
]

And then it would make more sense to have a list of food like :

FoodData {
 var listFood: List<Food>?

}


问:
using distinct command
using distinct command in SQL is good practice or not? is there any drawback of distinct command?</p>

答:
It depends entirely on what your use case is.  DISTINCT is useful in certain circumstances, but it can be overused.

The drawbacks are mainly increased load on the query engine to perform the sort (since it needs to compare the resultset to itself to remove duplicates), and it can be used to mask an issue in your data - if you are getting duplicates there may be a problem with your source data.

The command itself isn't inherently good or bad.  You can use a screwdriver to hammer a nail, but that doesn't mean it's a good idea, or that screwdrivers are bad in all cases.

Title: using distinct command


问:
Why does using pipes and map fail on a list of data frames?
I have tibbles nested in a list with an identifier column as well. I would like to run anonymous functions on each nested tibble. However, when I use a pipe to refer to my main df and then to the list that contains my data map does not work.

```<code># Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>%
# map(data, nrow)

# Works
map(df_nested$data, nrow)
</code>```

I would like to understand why doesn't the code work with using a pipe.

答:
It's always better to use mutate when using nested data:

```<code>df_nested %>%
   mutate(Nrow=map(data,nrow)) %>%
   unnest(Nrow)
# A tibble: 3 x 3
  Species    data               Nrow
  <fct>      <list>            <int>
1 setosa     <tibble [50 x 4]>    50
2 versicolor <tibble [50 x 4]>    50
3 virginica  <tibble [50 x 4]>    50
</code>```

Body:
I have tibbles nested in a list with an identifier column as well. I would like to run anonymous functions on each nested tibble. However, when I use a pipe to refer to my main df and then to the list that contains my data map does not work.

# Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>%
# map(data, nrow)

# Works
map(df_nested$data, nrow)

I would like to understand why doesn't the code work with using a pipe.

Body:
It's always better to use mutate when using nested data:

df_nested %>%
   mutate(Nrow=map(data,nrow)) %>%
   unnest(Nrow)
# A tibble: 3 x 3
  Species    data               Nrow
  <fct>      <list>            <int>
1 setosa     <tibble [50 x 4]>    50
2 versicolor <tibble [50 x 4]>    50
3 virginica  <tibble [50 x 4]>    50


问:
IBM Watson Assistant: user input time frame validation
I am using IBM Watson Assistant and try to validate user input against time frames / spans. What function should I use?

I was using  @sys-date.before(now()) method to validate the time frame between past and present of a user input, but it does now work for me. If I input now or today Watson Assistant still thinks it is a past...

@sys-date.before(now()):

Looks "like you're trying to make a reservation in the past. Try again."
  true $day it is

I expect if user inputs now or today to make reservations work, and if user inputs time in the past to response as

"like you're trying to make a reservation in the past. Try again."

The code snippet in question looks like this:

```<code>{ "context":
    { "day": "@sys-date" } }
{ "context":
    { "time": "<? @sys-time.reformatDateTime('h:mm a') ?>" } }
</code>```

答: I solved it! What I did is I put (today) for here @sys-date.before(today())   and now for here @sys-time.before(now())

Body:
I am using IBM Watson Assistant and try to validate user input against time frames / spans. What function should I use?

I was using  @sys-date.before(now()) method to validate the time frame between past and present of a user input, but it does now work for me. If I input now or today Watson Assistant still thinks it is a past...

@sys-date.before(now()):

Looks "like you're trying to make a reservation in the past. Try again."
  true $day it is

I expect if user inputs now or today to make reservations work, and if user inputs time in the past to response as

"like you're trying to make a reservation in the past. Try again."

The code snippet in question looks like this:

{ "context":
    { "day": "@sys-date" } }
{ "context":
    { "time": "<? @sys-time.reformatDateTime('h:mm a') ?>" } }


问:
Failed to download data from Yahoo finance using Quantmod
I was trying to download data from Yahoo finance using Quantmod package as below, but failed to get any data.

```<code>library(quantmod)
> get(getSymbols("^FTSE"))
Error in get(getSymbols("^FTSE")) : object '^FTSE' not found
In addition: Warning message:
^FTSE contains missing values. Some functions will not work if objects contain missing values in the middle of the series. Consider using na.omit(), na.approx(), na.fill(), etc to remove or replace them.
</code>```

Any idea why it is failing would be highly appreciated.

Below is my session information

```<code>> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] quantmod_0.4-14 TTR_0.23-4      xts_0.11-2      zoo_1.8-5

loaded via a namespace (and not attached):
[1] compiler_3.6.0  tools_3.6.0     curl_3.3        grid_3.6.0
[5] lattice_0.20-38
</code>```

Body:
I was trying to download data from Yahoo finance using Quantmod package as below, but failed to get any data.

library(quantmod)
> get(getSymbols("^FTSE"))
Error in get(getSymbols("^FTSE")) : object '^FTSE' not found
In addition: Warning message:
^FTSE contains missing values. Some functions will not work if objects contain missing values in the middle of the series. Consider using na.omit(), na.approx(), na.fill(), etc to remove or replace them.

Any idea why it is failing would be highly appreciated.

Below is my session information

> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] quantmod_0.4-14 TTR_0.23-4      xts_0.11-2      zoo_1.8-5

loaded via a namespace (and not attached):
[1] compiler_3.6.0  tools_3.6.0     curl_3.3        grid_3.6.0
[5] lattice_0.20-38

Body:
I recommend setting the auto.assign argument to FALSE. Then you can assign the output of getSymbols() to whatever object you want.  For example:

ftse <- getSymbols("^FTSE", auto.assign = FALSE)
head(ftse)
#            FTSE.Open FTSE.High FTSE.Low FTSE.Close FTSE.Volume FTSE.Adjusted
# 2007-01-02    6220.8    6312.5   6220.8     6310.9  1074946500        6310.9
# 2007-01-03    6310.9    6322.0   6296.0     6319.0  1606892700        6319.0
# 2007-01-04    6319.0    6319.0   6261.0     6287.0  1902875500        6287.0
# 2007-01-05    6287.0    6287.0   6220.1     6220.1  1622439300        6220.1
# 2007-01-08    6220.1    6246.0   6187.0     6194.2  1326700900        6194.2
# 2007-01-09    6194.2    6218.5   6190.4     6196.1  2143699600        6196.1


问:
Ajax Request to included JSON - readystate 4, status 0
I am performing an Ajax GET request on a JSON file included in my website. So the JSON file is included in a separate sheet. The readystate of the request is "4" while the status is "0". So the request has been sent, but the responsetext is empty.

I have validated the JSON data.
The javascript file returns data where it should on HTML5 page.
Error handling gives readystate "4" and status "0".

This is the code of the javascript file, JSON data is correct and tested.. HTML5 connection also functions as it should, tested.. The javascript file inserts data on the correct element in HTML..

Can anyone spot the error? Thanks everyone!

```<code>var xhr = new XMLHttpRequest();                 //create Request Object

xhr.onload = function(){                        //when the Request is loaded, parse it in a responsetext

if(xhr.status === 200){

    var responseObject = JSON.parse(xhr.responseText);

    var newContent ='';

    for (var i=0; i<responseObject.events.length; i++){

        newContent += responseObject.events[i].color;

        newContent += responseObject.events[i].value;

    }

    document.getElementById("jsonreturn_option").innerHTML = newContent;
}

else{

    document.getElementById("jsonreturn_option").innerHTML = xhr.readyState + "    " + xhr.status  ;

    //readystate is 4, which means that the request has been sent..
    //request status is 0, which means that the responsetext is empty..
}
};

xhr.open('GET','json/options_form.json',true);
xhr.send(null);                                         //no additional data to be sent
</code>```

The JSON Data File

```<code>{
"events":[

{  "color": "red", "value": "#f00"},
{  "color": "green", "value": "#0f0"},
{  "color": "blue", "value": "#00f"},
{  "color": "cyan", "value": "#0ff"}
]
}
</code>```

答: Try xhr.onreadystatechange instead of xhr.onloadand also move xhr.open and xhr.send to top of xhr.onload. Let me know if it works.

Body:
I am performing an Ajax GET request on a JSON file included in my website. So the JSON file is included in a separate sheet. The readystate of the request is "4" while the status is "0". So the request has been sent, but the responsetext is empty.

I have validated the JSON data.
The javascript file returns data where it should on HTML5 page.
Error handling gives readystate "4" and status "0".

This is the code of the javascript file, JSON data is correct and tested.. HTML5 connection also functions as it should, tested.. The javascript file inserts data on the correct element in HTML..

Can anyone spot the error? Thanks everyone!

var xhr = new XMLHttpRequest();                 //create Request Object

xhr.onload = function(){                        //when the Request is loaded, parse it in a responsetext

if(xhr.status === 200){

    var responseObject = JSON.parse(xhr.responseText);

    var newContent ='';

    for (var i=0; i<responseObject.events.length; i++){

        newContent += responseObject.events[i].color;

        newContent += responseObject.events[i].value;

    }

    document.getElementById("jsonreturn_option").innerHTML = newContent;
}

else{

    document.getElementById("jsonreturn_option").innerHTML = xhr.readyState + "    " + xhr.status  ;

    //readystate is 4, which means that the request has been sent..
    //request status is 0, which means that the responsetext is empty..
}
};

xhr.open('GET','json/options_form.json',true);
xhr.send(null);                                         //no additional data to be sent

The JSON Data File

{
"events":[

{  "color": "red", "value": "#f00"},
{  "color": "green", "value": "#0f0"},
{  "color": "blue", "value": "#00f"},
{  "color": "cyan", "value": "#0ff"}
]
}


问:
Integration Of Razorpayx using curl php
Razorpayx curl code :

```<code>curl -u <YOUR_KEY>:<YOUR_SECRET> \-X POST https://api.razorpay.com/v1/contacts \-H "Content-Type: application/json" \-d '{  "name": "Gaurav Kumar",  "email": "gaurav.kumar@example.com",  "contact": "9123456789",  "type": "employee",  "reference_id": "Acme Contact ID 12345",  "notes": {    "note_key": "Beam me up Scotty"  }}'
</code>```

Trying to implement the same from curl-php:

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

$curlConfig = array(
    CURLOPT_URL            => "https://api.razorpay.com/v1/contacts/",
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => array(
        'api-key' => '<KEY>:<SECRET-KEY>'

        ),
    CURLOPT_POSTFIELDS     => array(
        'name' => 'ABCD',
        'email' => "abcd@gmail.com",
        'type' => 'customer'
    )
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
</code>```

Now it is given the error that "Please provide your api key for authentication purposes."
I have already passed the keys via curl header; but it throws error. Please guide how to solve this issue.

答:
I had same problem. Basicaly your api-key wont go in header instead you have to send it as user password .The code below is working perfectly. </p>

```<code>    $ch = curl_init();
    $fields = array();
    $fields["name"] = $name;
    $fields["email"] = $email;
    $fields["contact"] = $phone;
    $fields["reference_id"] = "customer".$phone;
    $fields["type"] = "customer";
    curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/contacts');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "api-key: key-secret");
    $headers = array();
    $headers[] = 'Accept: application/json';
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch);

    if (empty($data) OR (curl_getinfo($ch, CURLINFO_HTTP_CODE != 200))) {
       $data = FALSE;
    } else {
        return json_decode($data, TRUE);
    }
    curl_close($ch);
</code>```

Title: Integration Of Razorpayx using curl php

Body:
Razorpayx curl code :

curl -u <YOUR_KEY>:<YOUR_SECRET> \-X POST https://api.razorpay.com/v1/contacts \-H "Content-Type: application/json" \-d '{  "name": "Gaurav Kumar",  "email": "gaurav.kumar@example.com",  "contact": "9123456789",  "type": "employee",  "reference_id": "Acme Contact ID 12345",  "notes": {    "note_key": "Beam me up Scotty"  }}'

Trying to implement the same from curl-php:

$ch = curl_init();

$curlConfig = array(
    CURLOPT_URL            => "https://api.razorpay.com/v1/contacts/",
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => array(
        'api-key' => '<KEY>:<SECRET-KEY>'

        ),
    CURLOPT_POSTFIELDS     => array(
        'name' => 'ABCD',
        'email' => "abcd@gmail.com",
        'type' => 'customer'
    )
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);

Now it is given the error that "Please provide your api key for authentication purposes."
I have already passed the keys via curl header; but it throws error. Please guide how to solve this issue.

Body:
I had same problem. Basicaly your api-key wont go in header instead you have to send it as user password .The code below is working perfectly.

    $ch = curl_init();
    $fields = array();
    $fields["name"] = $name;
    $fields["email"] = $email;
    $fields["contact"] = $phone;
    $fields["reference_id"] = "customer".$phone;
    $fields["type"] = "customer";
    curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/contacts');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "api-key: key-secret");
    $headers = array();
    $headers[] = 'Accept: application/json';
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch);

    if (empty($data) OR (curl_getinfo($ch, CURLINFO_HTTP_CODE != 200))) {
       $data = FALSE;
    } else {
        return json_decode($data, TRUE);
    }
    curl_close($ch);


问:
Having directory issues with pygame.font.Font() on Mac
I am using a Mac, and am having issues calling the directory of a font file. Here is the code:

```<code>import pygame as pg
ARCADE_FONT = pg.font.Font("~/PycharmProjects/PyGame/Pacman/PAC-FONT.TTF", 15)
</code>```

The directory path I have typed in is exactly what I use in Finder to get to the file, if I press 'Go' and 'Go to Folder', which can also be achieved through pressing the command, shift, and 'G' buttons at once.

Here is the error message:

OSError: unable to read font file '~/PycharmProjects/PyGame/Pacman/PAC-FONT.TTF'

I think it's the right type of file, but not sure if it's an issue with the directory or the file itself.

答:
I think it is because the directory problem. Simply you cannot use symbol '~' to represent your home directory, in your python code.
Try absolute path?
Or a path relative to another path, like using '.' instead.</p>

Body:
I am using a Mac, and am having issues calling the directory of a font file. Here is the code:

import pygame as pg
ARCADE_FONT = pg.font.Font("~/PycharmProjects/PyGame/Pacman/PAC-FONT.TTF", 15)

The directory path I have typed in is exactly what I use in Finder to get to the file, if I press 'Go' and 'Go to Folder', which can also be achieved through pressing the command, shift, and 'G' buttons at once.

Here is the error message:

OSError: unable to read font file '~/PycharmProjects/PyGame/Pacman/PAC-FONT.TTF'

I think it's the right type of file, but not sure if it's an issue with the directory or the file itself.


问:
removeEventListeners doesn't seem to work
I'm trying to make a simple script to handle rating using the star system.
I stopped at the moment of pressing on the star, because all stars should stay in position after clicking on one while event listener is being removed only for this one.

Can you tell what am I doing wrong? I doubt removeEventListener doesn't work properly ;|

const drawStars = (node, starsNumber = 5, cssRef = "_star") => {
  if (starsNumber < 1)
    return false;

  let star;

  // classes to aply when star's filled or not
  const starFilled = `fas fa-star ${cssRef}`;
  const starContour = `far fa-star ${cssRef}`;

  // drawing stars
  for (let i = 1; i <= starsNumber; i++) {
    star = document.createElement('i');
    star.className = `${starContour} ${cssRef}`;
    node.appendChild(star);
  }

  node = [...node.childNodes];

  // putting listeners on every star
  node.forEach((star, index) => {

    // filling stars after hovering
    const mouseOverStar = () => {
      for (let i = 0; i < starsNumber; i++) {
        if (i <= index)
          node[i].className = starFilled;
        else
          node[i].className = starContour;
      }
    }

    // cleaning stars when mouse is out and no star was clicked
    const mouseOutStar = () => {
      node.forEach(star => star.className = starContour);
    }

    // trying to remove event listeners from every star but with no effect
    const clickOnStar = () => {
      node.forEach(star => {
        star.removeEventListener('mouseout', mouseOutStar);
        star.removeEventListener('mouseover', mouseOverStar);
      })
    }

    // applying listeners
    star.addEventListener('mouseover', mouseOverStar);
    star.addEventListener('mouseout', mouseOutStar);
    star.addEventListener('click', clickOnStar);
  });
}

// example of use
const starsContainer = document.querySelector('.stars');
drawStars(starsContainer);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.stars {
  margin: 30px;
  font-size: 30px;
  color: rgb(231, 199, 19);
  cursor: pointer;
}</code>```

  <link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />

```

答:
Try defining your event handlers mouseOverStar, mouseOutStar and clickOnStar outside the drawStars function.

You need to reference the exact same handler both in addEventListener and removeEventListener for it to work.

Check https://www.jonportella.com/you-are-using-browser-events-wrong/

Body:
I'm trying to make a simple script to handle rating using the star system.
I stopped at the moment of pressing on the star, because all stars should stay in position after clicking on one while event listener is being removed only for this one.

Can you tell what am I doing wrong? I doubt removeEventListener doesn't work properly ;|

const drawStars = (node, starsNumber = 5, cssRef = "_star") => {
  if (starsNumber < 1)
    return false;

  let star;

  // classes to aply when star's filled or not
  const starFilled = `fas fa-star ${cssRef}`;
  const starContour = `far fa-star ${cssRef}`;

  // drawing stars
  for (let i = 1; i <= starsNumber; i++) {
    star = document.createElement('i');
    star.className = `${starContour} ${cssRef}`;
    node.appendChild(star);
  }

  node = [...node.childNodes];

  // putting listeners on every star
  node.forEach((star, index) => {

    // filling stars after hovering
    const mouseOverStar = () => {
      for (let i = 0; i < starsNumber; i++) {
        if (i <= index)
          node[i].className = starFilled;
        else
          node[i].className = starContour;
      }
    }

    // cleaning stars when mouse is out and no star was clicked
    const mouseOutStar = () => {
      node.forEach(star => star.className = starContour);
    }

    // trying to remove event listeners from every star but with no effect
    const clickOnStar = () => {
      node.forEach(star => {
        star.removeEventListener('mouseout', mouseOutStar);
        star.removeEventListener('mouseover', mouseOverStar);
      })
    }

    // applying listeners
    star.addEventListener('mouseover', mouseOverStar);
    star.addEventListener('mouseout', mouseOutStar);
    star.addEventListener('click', clickOnStar);
  });
}

// example of use
const starsContainer = document.querySelector('.stars');
drawStars(starsContainer);

.stars {
  margin: 30px;
  font-size: 30px;
  color: rgb(231, 199, 19);
  cursor: pointer;
}

  <link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />


问:
When and why do I need to use cin.ignore() in C++?
I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

```<code>cin.ignore(256, '\n');
</code>```

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

Here is the program I wrote:

```<code>#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}
</code>```

答:
Short answer

Why?  Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.

When?  When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.

Now a detailed answer.

Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n. Now cin picks up 256 and removes it from the stream and \n still remaining in the stream.
Now next when you enter your name, let's say Raddicus, the new contents of the stream is \nRaddicus.

Now here comes the catch.
When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream.
So on calling new line, getline reads and discards \n from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.

Now, how does cin.ignore help here?

According to the ignore documentation extract from cplusplus.com-

istream& ignore (streamsize n = 1, int delim = EOF);

Extracts characters from the input sequence and discards them, until
  either n characters have been extracted, or one compares equal to
  delim.

The function also stops extracting characters if the end-of-file is
  reached. If this is reached prematurely (before either extracting n
  characters or finding delim), the function sets the eofbit flag.

So, cin.ignore(256, '\n');, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).

Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n').

Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.

Body:
I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

cin.ignore(256, '\n');

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

Here is the program I wrote:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}


问:
OAuth2 with Google Cloud Print
I had written a Google Apps Script that connected to Google Cloud Print to automate some printing. The script would auto-run on a time interval, search for relevant files, and if found it would sent them to my printer. My code used OAuthConfig and was working fine, but now that class has been deprecated and after a weekend of trial & error and scouring the interwebs I can't get it to work with OAuth2.

Here's the OAuthConfig code that was working fine:

```<code>function printDoc(docId, docTitle, myPrinterId) {

  var scope = 'https://www.googleapis.com/auth/cloudprint';
  var url = 'https://www.google.com/cloudprint/submit';
  var payloadOfSubmit = {
    "printerid" : myPrinterId,
    "title" : docTitle,
    "content"  : docId,
    "contentType" : "google.kix"
  };

  var fetchArgs = googleOAuth_('google', scope, payloadOfSubmit);
  fetchArgs.method = 'POST';
  var responseOfSubmit = UrlFetchApp.fetch(url, fetchArgs);
  var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());

  return jsonOfSubmit;
}

function googleOAuth_(name, scope, payloadData) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey("anonymous");
  oAuthConfig.setConsumerSecret("anonymous");
  return {
    oAuthServiceName:name,
    oAuthUseToken:"always",
    muteHttpExceptions:true,
    payload:payloadData
  };
}
</code>```

I've successfully connected the github library for OAuth2. However, what's different about the instructions provided there, and on many other sites, is that they assume that the code will be deployed as a web service where a user is prompted to manually click to authorize the request. In my case the code will be saved on a Google Apps Script file, and the Cloud Printer is on the same Google account, so I never needed this manual intervention or back & forth with my original OAuthconfig.

My first attempt by adapting the instructions was:

```<code>function printDoc2(docId, docTitle, myPrinterId) {

  var url = 'https://www.google.com/cloudprint/submit';
  var scope = 'https://www.googleapis.com/auth/cloudprint';
  var payloadOfSubmit = {
    "printerid" : myPrinterId,
    "title" : docTitle,
    "content"  : docId,
    "contentType" : "google.kix",
  };

  var accessToken = googleOAuth_('google', scope).getAccessToken();

  var params = {
    method:"POST",
    headers: {"Authorization": "Bearer " + accessToken},
    muteHttpExceptions:true,
    payload:payloadOfSubmit
  };

  var responseOfSubmit = UrlFetchApp.fetch(url, params);
  //Logger.log(responseOfSubmit);
  var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());

  return jsonOfSubmit;
}

function googleOAuth2_(name, scope) {

  return OAuth2.createService(name)
    .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setClientId("anonymous")
    .setClientSecret("anonymous")
    .setProjectKey(ScriptApp.getProjectKey())
    .setPropertyStore(PropertiesService.getUserProperties())
    .setScope(scope)
    .setCallbackFunction('authCallback');
}

function authCallback(request) {
  var driveService = getDriveService();
  var isAuthorized = driveService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}
</code>```

But this gives me an error "Access not granted or expired" when it tries to run the line:

```<code>var accessToken = googleOAuth_('google', scope).getAccessToken();
</code>```

So I found a apps ScriptApp Method getOAuthToken which seemed like it might give me the token I need. I replaced the above line with:

```<code>var accessToken = ScriptApp.getOAuthToken();
</code>```

And the code executes but my response from the server is "Error 403 User credentials required".

Here's my third attempt based on @Mogsdad's suggestion:

```<code>function sendPrintJob(docId,myPrinterId,docTitle) {

  var payloadOfSubmit = {
            "printerid" : myPrinterId,
            "title" : docTitle,
            "content"  : docId,
            "contentType" : "google.kix" ,
  };

  var request = {
    "method": "POST",
    "headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
    "muteHttpExceptions": true
  };

  var responseOfSubmit = UrlFetchApp.fetch("https://www.google.com/cloudprint/submit", request);
  Logger.log(responseOfSubmit);
}
</code>```

I've tried a number of variations, including creating a Developer Console Project and using the Client ID provided there, but I keep getting stuck at these two issues (access not granted, or credentials required). If anyone can provide any help I'd really appreciate it.

答:
The scope "https://www.googleapis.com/auth/cloudprint" has to be included explicitly in the
manifest file

appscript.json (View > Show manifest file)

```<code>{
  "timeZone": "Europe/Paris",
  "dependencies": {
  },
  "oauthScopes": [
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/cloudprint"
  ],
  "exceptionLogging": "STACKDRIVER"
}
</code>```

Code.gs

```<code>function listPrinters() {
  var options = {
    headers: {
      authorization: 'OAuth ' + ScriptApp.getOAuthToken()
    }
  }
  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', options);
  Logger.log(response);
}
</code>```

Title: OAuth2 with Google Cloud Print

Body:
I had written a Google Apps Script that connected to Google Cloud Print to automate some printing. The script would auto-run on a time interval, search for relevant files, and if found it would sent them to my printer. My code used OAuthConfig and was working fine, but now that class has been deprecated and after a weekend of trial & error and scouring the interwebs I can't get it to work with OAuth2.

Here's the OAuthConfig code that was working fine:

function printDoc(docId, docTitle, myPrinterId) {

  var scope = 'https://www.googleapis.com/auth/cloudprint';
  var url = 'https://www.google.com/cloudprint/submit';
  var payloadOfSubmit = {
    "printerid" : myPrinterId,
    "title" : docTitle,
    "content"  : docId,
    "contentType" : "google.kix"
  };

  var fetchArgs = googleOAuth_('google', scope, payloadOfSubmit);
  fetchArgs.method = 'POST';
  var responseOfSubmit = UrlFetchApp.fetch(url, fetchArgs);
  var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());

  return jsonOfSubmit;
}

function googleOAuth_(name, scope, payloadData) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey("anonymous");
  oAuthConfig.setConsumerSecret("anonymous");
  return {
    oAuthServiceName:name,
    oAuthUseToken:"always",
    muteHttpExceptions:true,
    payload:payloadData
  };
}

I've successfully connected the github library for OAuth2. However, what's different about the instructions provided there, and on many other sites, is that they assume that the code will be deployed as a web service where a user is prompted to manually click to authorize the request. In my case the code will be saved on a Google Apps Script file, and the Cloud Printer is on the same Google account, so I never needed this manual intervention or back & forth with my original OAuthconfig.

My first attempt by adapting the instructions was:

function printDoc2(docId, docTitle, myPrinterId) {

  var url = 'https://www.google.com/cloudprint/submit';
  var scope = 'https://www.googleapis.com/auth/cloudprint';
  var payloadOfSubmit = {
    "printerid" : myPrinterId,
    "title" : docTitle,
    "content"  : docId,
    "contentType" : "google.kix",
  };

  var accessToken = googleOAuth_('google', scope).getAccessToken();

  var params = {
    method:"POST",
    headers: {"Authorization": "Bearer " + accessToken},
    muteHttpExceptions:true,
    payload:payloadOfSubmit
  };

  var responseOfSubmit = UrlFetchApp.fetch(url, params);
  //Logger.log(responseOfSubmit);
  var jsonOfSubmit = JSON.parse(responseOfSubmit.getContentText());

  return jsonOfSubmit;
}

function googleOAuth2_(name, scope) {

  return OAuth2.createService(name)
    .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setClientId("anonymous")
    .setClientSecret("anonymous")
    .setProjectKey(ScriptApp.getProjectKey())
    .setPropertyStore(PropertiesService.getUserProperties())
    .setScope(scope)
    .setCallbackFunction('authCallback');
}

function authCallback(request) {
  var driveService = getDriveService();
  var isAuthorized = driveService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}

But this gives me an error "Access not granted or expired" when it tries to run the line:

var accessToken = googleOAuth_('google', scope).getAccessToken();

So I found a apps ScriptApp Method getOAuthToken which seemed like it might give me the token I need. I replaced the above line with:

var accessToken = ScriptApp.getOAuthToken();

And the code executes but my response from the server is "Error 403 User credentials required".

Here's my third attempt based on @Mogsdad's suggestion:

function sendPrintJob(docId,myPrinterId,docTitle) {

  var payloadOfSubmit = {
            "printerid" : myPrinterId,
            "title" : docTitle,
            "content"  : docId,
            "contentType" : "google.kix" ,
  };

  var request = {
    "method": "POST",
    "headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
    "muteHttpExceptions": true
  };

  var responseOfSubmit = UrlFetchApp.fetch("https://www.google.com/cloudprint/submit", request);
  Logger.log(responseOfSubmit);
}

I've tried a number of variations, including creating a Developer Console Project and using the Client ID provided there, but I keep getting stuck at these two issues (access not granted, or credentials required). If anyone can provide any help I'd really appreciate it.

Body:
The scope "https://www.googleapis.com/auth/cloudprint" has to be included explicitly in the
manifest file

appscript.json (View > Show manifest file)

{
  "timeZone": "Europe/Paris",
  "dependencies": {
  },
  "oauthScopes": [
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/cloudprint"
  ],
  "exceptionLogging": "STACKDRIVER"
}

Code.gs

function listPrinters() {
  var options = {
    headers: {
      authorization: 'OAuth ' + ScriptApp.getOAuthToken()
    }
  }
  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', options);
  Logger.log(response);
}


问:
How to store results of a Dynamic Query in a temp table without creating a table?
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

```<code>  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query
</code>```

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

答:
You can certainly INSERT the results of a stored procedure into a TEMP table:

```<code>CREATE PROCEDURE PurgeMe
AS
SELECT convert(int, 1) AS DaData
UNION
SELECT convert(int, 2)
GO

CREATE TABLE #Doodles  (AnInteger int)

INSERT #Doodles EXECUTE PurgeMe

SELECT * FROM #Doodles
</code>```

Questions arise about the SCOPE of TEMP tables, however.  You might find that in your calling routine you will not be able to see a TEMP table created within your routine.

The solution to the SCOPE problem is to do the following:

Create a minimal TEMP table (say, with one column)

Use ALTER TABLE on the TEMP table within your routine to make its schema match
your needs (this can be tricky, but it can be done)

Put data into the TEMP table

return from your routine - the calling routine will now be able to access the temp
table

If this is of interest I can make a longer post with a stored procedure to do the above.  It was written to facilitate dynamic SQL

Body:
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

Body:
You can certainly INSERT the results of a stored procedure into a TEMP table:

CREATE PROCEDURE PurgeMe
AS
SELECT convert(int, 1) AS DaData
UNION
SELECT convert(int, 2)
GO

CREATE TABLE #Doodles  (AnInteger int)

INSERT #Doodles EXECUTE PurgeMe

SELECT * FROM #Doodles

Questions arise about the SCOPE of TEMP tables, however.  You might find that in your calling routine you will not be able to see a TEMP table created within your routine.

The solution to the SCOPE problem is to do the following:

Create a minimal TEMP table (say, with one column)

Use ALTER TABLE on the TEMP table within your routine to make its schema match
your needs (this can be tricky, but it can be done)

Put data into the TEMP table

return from your routine - the calling routine will now be able to access the temp
table

If this is of interest I can make a longer post with a stored procedure to do the above.  It was written to facilitate dynamic SQL


问:
No line found for nextline/int
I try to let the user input some values in string and int in while loop, however, when I start I get no Line found I tried my best on my own to solve it but nothing worked for me. I wonder how I let the user input the values for the int and string.</p>

```<code>public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    //create file
    File f = new File("C:\\Users\\ae65255\\Desktop\\file.txt");
    try{

        f.createNewFile();
        System.out.println("23");
                        //frågan
    while(anw.equals("j")){

        Scanner fileIn = new Scanner(f);
        System.out.println("Ange utgiftspost:"); //post
        String post = fileIn.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=fileIn.nextInt();
        fileIn.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = fileIn.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;
        PrintWriter writer ;
           writer = new PrintWriter(f);
           writer.println(fileContent);

        if (anw.equals("n")) {
            fileIn.close();
            writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut

    }
      catch(Exception e){
  System.err.println(e.getMessage());
}//frågan
        //System.out.println("---"+post+"---"+cost+"---"+saldo);
    System.out.println("File path" +f.getPath());

    }

}
</code>```

答: @AKSW comment solved my two answers. Using Scanner in = new Scanner(System.in); would let me take the user input from the console. The other was to stop it overwrite the text it which was his latest comment on this post.

Title: No line found for nextline/int

Body:
I try to let the user input some values in string and int in while loop, however, when I start I get no Line found I tried my best on my own to solve it but nothing worked for me. I wonder how I let the user input the values for the int and string.

public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    //create file
    File f = new File("C:\\Users\\ae65255\\Desktop\\file.txt");
    try{

        f.createNewFile();
        System.out.println("23");
                        //frågan
    while(anw.equals("j")){

        Scanner fileIn = new Scanner(f);
        System.out.println("Ange utgiftspost:"); //post
        String post = fileIn.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=fileIn.nextInt();
        fileIn.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = fileIn.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;
        PrintWriter writer ;
           writer = new PrintWriter(f);
           writer.println(fileContent);

        if (anw.equals("n")) {
            fileIn.close();
            writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut

    }
      catch(Exception e){
  System.err.println(e.getMessage());
}//frågan
        //System.out.println("---"+post+"---"+cost+"---"+saldo);
    System.out.println("File path" +f.getPath());

    }

}


答:
Oracle does not support the aggregation of interval datatypes, which is a crying shame because that would be the easiest way to solve problems like this. However, the fiendish mind of Stew Ashton came up with a solution of converting intervals into numbers and back again.

```<code>select numtodsinterval(
  sum(
    (sysdate+(end_date_time - start_date_time) - sysdate) * 24 * 60 * 60
        + extract(second from (end_date_time - start_date_time))
              - trunc(extract(second from (end_date_time - start_date_time))) -- (*)
  )
  , 'second'
)
from table1;
</code>```

Here is a demo on db<>fiddle.

(*) This line makes the answer accurate to microseconds.

Title: Sum of time difference - Oracle SQL

Body:
I have a table:

table1

col1    start_date_time                 end_date_time
Test1   01-06-19 11:43:35.927422000 AM  01-06-19 11:44:20.127907000 AM
Test2   01-06-19 11:44:28.703518000 AM  01-06-19 11:45:06.538883000 AM
Test3   01-06-19 11:42:18.784477000 AM  01-06-19 11:42:27.635102000 AM

I wrote a query which gives me the time difference:

select a.*, end_date_time - start_date_time exec_time from table1 a
order by exec_time desc;

Output Table

col1    start_date_time                 end_date_time                   exec_time
Test1   01-06-19 11:43:35.927422000 AM  01-06-19 11:44:20.127907000 AM  +00 00:00:44.200485
Test2   01-06-19 11:44:28.703518000 AM  01-06-19 11:45:06.538883000 AM  +00 00:00:37.835365
Test3   01-06-19 11:42:18.784477000 AM  01-06-19 11:42:27.635102000 AM  +00 00:00:08.850625

I need the sum like 00:01:29.

How can I sum the exec_time in SQL? I need to find the total time based.

Body:
Oracle does not support the aggregation of interval datatypes, which is a crying shame because that would be the easiest way to solve problems like this. However, the fiendish mind of Stew Ashton came up with a solution of converting intervals into numbers and back again.

select numtodsinterval(
  sum(
    (sysdate+(end_date_time - start_date_time) - sysdate) * 24 * 60 * 60
        + extract(second from (end_date_time - start_date_time))
              - trunc(extract(second from (end_date_time - start_date_time))) -- (*)
  )
  , 'second'
)
from table1;

Here is a demo on db<>fiddle.

(*) This line makes the answer accurate to microseconds.


问:
Automatically checking for a new version of my application
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.

The problem is that I have no idea about what have to be done on the server side.

I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?

Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?

@pilif : thanks for your detailed answer. There is still something which is unclear for me :

like

http://www.example.com/update?version=1.2.4

Then you can return what ever you want, probably also the download-URL of the installer of the new version.

How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the ?version=1.2.4 part in order to return something accordingly ?

答:
I think that simple XML file on the server would be sufficient for version checking only purposes.

You would need then only an ftp account on your server and build system that is able to send a file via ftp after it has built a new version. That build system could even put installation files/zip on your website directly!

OwnerDisplayName: Jérôme

LastEditorDisplayName: Jérôme

OwnerDisplayName: Dentharg


问:
Is Java overkill for news websites?
A client of mine wants a news website designed in Java, and I told him that Java is overkill for that kind of website. I suggested to him that there are dozens of CMS that we can customize for him, as well as other programming languages that are better suited for websites but he insisted.

Is Java overkill for news websites?

答:
I think the language argument is a little irrelevant, you can realistically code anything in anything given enough time and skill. Java is no better/worse than many other tools. However the real answer is already here - using a CMS must make sense. Why write from scratch, sure sounds like a wheel being re-invented.

Why not do a basic list of requirements, cross-match to CMS (Java, Python, Ruby et al), and then price up the same features if you had to code from scratch. That's a pretty good argument.

OwnerDisplayName: Ainab

Title: Is Java overkill for news websites?

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: MrTelly

LastEditorDisplayName: MrTelly