问:
How to show warning message when back button is pressed in fragments
I want application to show warning message when user press back button and if user select Yes it will go back. And i am in navigation graph fragment.

I have searched many time in stack Overflow and tried:

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}
</code>```

But it is showing giver error:
Method does not override method from its superclass

Edit:
I want to set onBackPressedListener(Mobiles back button) in Navigation graphs fragment

答:
When using Fragments 1.1.0 (which is in alpha right now), you can follow the Provide custom back navigation documentation, which shows how to register an OnBackPressedCallback, which allows you to register for onBackPressed() callbacks from within a Fragment:

```<code>public class MyFragment extends Fragment {

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
        @Override
        public void handleOnBackPressed() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setTitle("Save Or Not");
            builder.setMessage("Do you want to save this? ");
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // Save your content
                save();
                // Then pop
                NavHostFragment.findNavController(MyFragment.this).popBackStack();
            }
            builder.setNegativeButton("Discard",null);
            builder.show();
        });
        }
    });
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
  }
}
</code>```

Body:
I want application to show warning message when user press back button and if user select Yes it will go back. And i am in navigation graph fragment.

I have searched many time in stack Overflow and tried:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}

But it is showing giver error:
Method does not override method from its superclass

Edit:
I want to set onBackPressedListener(Mobiles back button) in Navigation graphs fragment

Body:
When using Fragments 1.1.0 (which is in alpha right now), you can follow the Provide custom back navigation documentation, which shows how to register an OnBackPressedCallback, which allows you to register for onBackPressed() callbacks from within a Fragment:

public class MyFragment extends Fragment {

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
        @Override
        public void handleOnBackPressed() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setTitle("Save Or Not");
            builder.setMessage("Do you want to save this? ");
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // Save your content
                save();
                // Then pop
                NavHostFragment.findNavController(MyFragment.this).popBackStack();
            }
            builder.setNegativeButton("Discard",null);
            builder.show();
        });
        }
    });
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
  }
}


来源: stackexchange

问:
How to find the placement of a List within another List?
I am working with two lists. The first contains a large sequence of strings. The second contains a smaller list of strings. I need to find where the second list exists in the first list.

I worked with enumeration, and due to the large size of the data, this is very slow, I was hoping for a faster way.

```<code>    List<string> first = new List<string>() { "AAA","BBB","CCC","DDD","EEE","FFF" };

    List<string> second = new List<string>() { "CCC","DDD","EEE" };

int x = SomeMagic(first,second);
</code>```

And I would need x to = 2.

答:
If you are willing to use MoreLinq then consider using Window:

```<code>var windows = first.Window(second.Count);
var result = windows
                .Select((subset, index) => new { subset, index = (int?)index })
                .Where(z => Enumerable.SequenceEqual(second, z.subset))
                .Select(z => z.index)
                .FirstOrDefault();

Console.WriteLine(result);
Console.ReadLine();
</code>```

Window will allow you to look at 'slices' of the data in chunks (based on the length of your second list). Then SequenceEqual can be used to see if the slice is equal to second. If it is, the index can be returned. If it doesn't find a match, null will be returned.

ContentLicense: CC BY-SA 4.0

Body:
I am working with two lists. The first contains a large sequence of strings. The second contains a smaller list of strings. I need to find where the second list exists in the first list.

I worked with enumeration, and due to the large size of the data, this is very slow, I was hoping for a faster way.

    List<string> first = new List<string>() { "AAA","BBB","CCC","DDD","EEE","FFF" };

    List<string> second = new List<string>() { "CCC","DDD","EEE" };

int x = SomeMagic(first,second);

And I would need x to = 2.

Body:
If you are willing to use MoreLinq then consider using Window:

var windows = first.Window(second.Count);
var result = windows
                .Select((subset, index) => new { subset, index = (int?)index })
                .Where(z => Enumerable.SequenceEqual(second, z.subset))
                .Select(z => z.index)
                .FirstOrDefault();

Console.WriteLine(result);
Console.ReadLine();

Window will allow you to look at 'slices' of the data in chunks (based on the length of your second list). Then SequenceEqual can be used to see if the slice is equal to second. If it is, the index can be returned. If it doesn't find a match, null will be returned.


问:
How to take screenshots fast in Java?
I am implementing a simple eye tracker, which requires fast screenshoting of what is happening on the screen simultaneously with capturing the video from webcam.

The thing is that the way of doing it with Robot, mentioned here: https://stackoverflow.com/questions/2475303/java-library-for-capturing-active-window-screenshot
is extremely slow.

By the way, retrieving the video from a webcam works much faster and returns the byte array, which is very fast to be processed.

Does anybody know a faster solution? C++ libraries, which can be linked to Java for doing this may help as well.

Thank you!

UPDATE:
Decided to switch to OpenCV, now looking for the way to make screenshot with it :)

答:
To capture full screen.

```<code>Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(destination));
</code>```

To capture partial screen.

```<code>Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle(0, 0, screenSize.width / 2, screenSize.height / 2);
Robot robot = new Robot();
BufferedImage screenFullImage = robot.createScreenCapture(rect);
ImageIO.write(screenFullImage, format, new File(destination));
</code>```

Reference : link

ContentLicense: CC BY-SA 3.0

Title: How to take screenshots fast in Java?

Body:
To capture full screen.

Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(destination));

To capture partial screen.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle(0, 0, screenSize.width / 2, screenSize.height / 2);
Robot robot = new Robot();
BufferedImage screenFullImage = robot.createScreenCapture(rect);
ImageIO.write(screenFullImage, format, new File(destination));

Reference : link


问:
Getting letters in a string. Why my code didn't work well?
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

```<code>Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }
</code>```

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

答:
this code will help you to extarct the exact substring from your main string

public static void main (String [] args) {

```<code>Scanner input = new Scanner (System.in);
System.out.println("Enter a String");
String name = input.next();
/*from this line it will extract the charcter from the string
 * according to tour indexes given
 */
String subString = name.substring(0, 3);
System.out.println("Substring is :"+subString);

}
</code>```

Body:
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

Body:
this code will help you to extarct the exact substring from your main string

public static void main (String [] args) {

Scanner input = new Scanner (System.in);
System.out.println("Enter a String");
String name = input.next();
/*from this line it will extract the charcter from the string
 * according to tour indexes given
 */
String subString = name.substring(0, 3);
System.out.println("Substring is :"+subString);

}


问:
Jekyll post not generated
I am trying to add a new post to my Jekyll site, but I cannot see it on the generated pages when I run jekyll serve.

What are some common reasons for a Jekyll post to not be generated?

答:
Just to add one more reason, when you move an article from _drafts to _post, you sometimes need to delete the _site for the article to be regenerated.

In my case it often happens that _site will not be entirely deleted before re-generation so the new article won't appear.

Anyway rm -rf _site and bundle exec jekyll serve works :)

Title: Jekyll post not generated


问:
Displaying graphs/charts in Django
I'm making a report app in Django that involves plenty of graphs and charts.

Is there an easy graphing library/module that allows me to achieve this workflow:

Execute my SQL queries

Parse the returned data to the graphing library/module

Graphing library/module manipulates the data into a chart/graph which I can output to a Django template easily.

I've spent the last couple of days playing around with Matplotlib and Django. There are seemingly only a few ways to get the graphs to render in Django.

Use 2 views, one to render the PNG and the other one to output the HTML with the img src pointing to the first view. Link

Data URI's

Write the image to file and then call it with the view

Is there anyway I can do this more easily?

Thanks

答:
One lighter alternative is pycha

See this blogpost to get an idea: A quick post on using Python Charts to generate nice SVG charts for your django website

Another option is to include google charts
in your templates.

If rendering the graph via js in your templates is an option, these
are two popular libraries:

http://www.highcharts.com

http://www.jqplot.com

Title: Displaying graphs/charts in Django


问:
NLTK and cx_Freeze issues
I'm deploying a simple Tkinter application that takes care of processing a word file and returning a txt file with tokenized words. The main ingredients are Tkinter and NLTK.

After creating the building folder with cx_Freeze, I found several problems.
When I try to launch the resulting exe file on another pc with Windows installed, the console lists that 'punkt' is not available.

I tried to insert the following code block immediately after the import of nltk:

```<code>from tkinter import *
from tkinter.filedialog import askopenfilename
import os
import nltk
nltk.download('punkt')     #HERE
nltk.download('stopwords') #ALSO HERE
import string
from collections import Counter
import win32com.client
from pywintypes import com_error
</code>```

This is the piece of code of imports and here is where it later goes into error, during execution:

```<code>pathToProc = self.originalFile.get()
sent_tokenizer = nltk.data.load('tokenizers/punkt/italian.pickle')
snt = nltk.stem.SnowballStemmer('italian')
it_stop_words = nltk.corpus.stopwords.words('italian') + ['\n', '\t', '']
trashes = it_stop_words + list(string.punctuation)
tokensTOT = []
try:
    myDoc = word.Documents.Open(pathToProc, False, False, True)
    sentences = sent_tokenizer.tokenize(word.ActiveDocument.Range().Text)
    myDoc.Close()
    del myDoc
    for sentence in sentences:
        tokensTOT = tokensTOT + nltk.word_tokenize(sentence)
except com_error:
    print('IMPOSSIBILE DECIFRARE IL FILE')
</code>```

The following is the code I used to create the build folder, aimed to being copied and pasted on all windows computers.

```<code>from cx_Freeze import setup, Executable
import os, sys

os.environ['TCL_LIBRARY'] = r'C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\tcl\tk8.6'

include_files = [r"C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\DLLs\tcl86t.dll",
                 r"C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\DLLs\tk86t.dll",
                 r"C:"]
packages = ["os",
            "tkinter",
            "nltk",
            "string",
            "collections",
            "win32com.client",
            "pywintypes",
            "socket"]
setup(
    name = 'Bea Tokenizer',
    version = "2.5",
    description = "Simple Tkinker tokenizer window",
    options = {"build_exe": {
               'packages': packages,
               'include_files': include_files,
               'include_msvcr': True,
               }},
    executables = [Executable("beaTokenizer.py", base = None)]
)
</code>```

Despite having entered nltk.download('punkt') and
nltk.download('stopwords') the error this time is different:

```<code>[nltk_data] Error loading punkt: <urlopen error unknown url type:
[nltk_data] https>
[nltk_data] Error loading stopwords: <urlopen error unknown url type:
[nltk_data] https>
</code>```

I wonder why nltk lends itself so badly to deploying, despite being a widely used and continuously developing framework.

I hope I've been clear and correctly explained the answer.

答:
Try to download the nltk packages you need in the setup script into a specific destination folder, let cx_Freeze include this folder into the frozen application, and use the same folder for the nltk packages in your main application, which should then find the packages already downloaded.

Add the following lines to your setup script (used to create the build folder according to your description):

import nltk
nltk.download('punkt', download_dir='nltk_packages')
nltk.download('stopwords', download_dir='nltk_packages')
include_files = ['nltk_packages',
                 # add here further include_files items you need
                ]
```

<p>and modify the download calls in your main script:</p>

<pre class="lang-py prettyprint-override"><code>nltk.download('punkt', download_dir='nltk_packages')
nltk.download('stopwords', download_dir='nltk_packages')
</code>```

I'm not able to test this answer (probably because of proxy limitations), but as far as I can judge from the source code of nltk, this or a similar solution should solve your problem. You might need to tweak the destination folder paths passed to download_dir and include_files according to the behavior of nltk.

Title: NLTK and cx_Freeze issues

Body:
I'm deploying a simple Tkinter application that takes care of processing a word file and returning a txt file with tokenized words. The main ingredients are Tkinter and NLTK.

After creating the building folder with cx_Freeze, I found several problems.
When I try to launch the resulting exe file on another pc with Windows installed, the console lists that 'punkt' is not available.

I tried to insert the following code block immediately after the import of nltk:

from tkinter import *
from tkinter.filedialog import askopenfilename
import os
import nltk
nltk.download('punkt')     #HERE
nltk.download('stopwords') #ALSO HERE
import string
from collections import Counter
import win32com.client
from pywintypes import com_error

This is the piece of code of imports and here is where it later goes into error, during execution:

pathToProc = self.originalFile.get()
sent_tokenizer = nltk.data.load('tokenizers/punkt/italian.pickle')
snt = nltk.stem.SnowballStemmer('italian')
it_stop_words = nltk.corpus.stopwords.words('italian') + ['\n', '\t', '']
trashes = it_stop_words + list(string.punctuation)
tokensTOT = []
try:
    myDoc = word.Documents.Open(pathToProc, False, False, True)
    sentences = sent_tokenizer.tokenize(word.ActiveDocument.Range().Text)
    myDoc.Close()
    del myDoc
    for sentence in sentences:
        tokensTOT = tokensTOT + nltk.word_tokenize(sentence)
except com_error:
    print('IMPOSSIBILE DECIFRARE IL FILE')

The following is the code I used to create the build folder, aimed to being copied and pasted on all windows computers.

from cx_Freeze import setup, Executable
import os, sys

os.environ['TCL_LIBRARY'] = r'C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\tcl\tk8.6'

include_files = [r"C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\DLLs\tcl86t.dll",
                 r"C:\Users\AOUP\AppData\Local\Programs\Python\Python37-32\DLLs\tk86t.dll",
                 r"C:"]
packages = ["os",
            "tkinter",
            "nltk",
            "string",
            "collections",
            "win32com.client",
            "pywintypes",
            "socket"]
setup(
    name = 'Bea Tokenizer',
    version = "2.5",
    description = "Simple Tkinker tokenizer window",
    options = {"build_exe": {
               'packages': packages,
               'include_files': include_files,
               'include_msvcr': True,
               }},
    executables = [Executable("beaTokenizer.py", base = None)]
)

Despite having entered nltk.download('punkt') and
nltk.download('stopwords') the error this time is different:

[nltk_data] Error loading punkt: <urlopen error unknown url type:
[nltk_data] https>
[nltk_data] Error loading stopwords: <urlopen error unknown url type:
[nltk_data] https>

I wonder why nltk lends itself so badly to deploying, despite being a widely used and continuously developing framework.

I hope I've been clear and correctly explained the answer.

Body:
Try to download the nltk packages you need in the setup script into a specific destination folder, let cx_Freeze include this folder into the frozen application, and use the same folder for the nltk packages in your main application, which should then find the packages already downloaded.

Add the following lines to your setup script (used to create the build folder according to your description):

import nltk
nltk.download('punkt', download_dir='nltk_packages')
nltk.download('stopwords', download_dir='nltk_packages')
include_files = ['nltk_packages',
                 # add here further include_files items you need
                ]

and modify the download calls in your main script:

nltk.download('punkt', download_dir='nltk_packages')
nltk.download('stopwords', download_dir='nltk_packages')

I'm not able to test this answer (probably because of proxy limitations), but as far as I can judge from the source code of nltk, this or a similar solution should solve your problem. You might need to tweak the destination folder paths passed to download_dir and include_files according to the behavior of nltk.


问:
Is there a different way to convert to hexadecimal?
I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "

The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.

```<code>string TextToConvert = "Test Andrei";
            TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);

            List<char> Chars = TextToConvert.ToCharArray().ToList();
            string CharValue = "";
            string secondHexConvert = "";
            foreach(char c in Chars)
            {
                CharValue+=Convert.ToInt32(c);
                secondHexConvert+=Convert.ToString(c, 16)+" ";
            }
            string hexValue = String.Format("{0:X}", CharValue)+" ";
</code>```

I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"

答:
You can use the following code to convert a string to hexadecimal:

```<code>     public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
    {
         Byte[] stringBytes = encoding.GetBytes(input);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
         {
             sbBytes.AppendFormat("{0:X2}", b);
        }
        return sbBytes.ToString();
    }
</code>```

And you just call it using:

```<code>string testString = "11111111";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
</code>```

Body:
I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "

The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.

string TextToConvert = "Test Andrei";
            TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);

            List<char> Chars = TextToConvert.ToCharArray().ToList();
            string CharValue = "";
            string secondHexConvert = "";
            foreach(char c in Chars)
            {
                CharValue+=Convert.ToInt32(c);
                secondHexConvert+=Convert.ToString(c, 16)+" ";
            }
            string hexValue = String.Format("{0:X}", CharValue)+" ";

I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"

Body:
You can use the following code to convert a string to hexadecimal:

     public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
    {
         Byte[] stringBytes = encoding.GetBytes(input);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
         {
             sbBytes.AppendFormat("{0:X2}", b);
        }
        return sbBytes.ToString();
    }

And you just call it using:

string testString = "11111111";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);


问:
How to use AWS X-Ray in NodeJs?
I'm trying to use aws-xray-sdk to get the traces of my App,

I have written three APIs,

1. Making a call to an AWS S3 service (/traceS3)

2. Making a HTTP call to external endpoint ie. google.com (/traceHttp)

3. Making a DB call to a locally installed MySql DB (/traceMysql)

Also installed the AWS X-Ray Daemon locally

And made AWS configurations using the aws-cli and then ran the daemon using the following command (I'm using Ubuntu) -

```<code>/usr/bin/xray -o -n ap-southeast-2
</code>```

I am referring the following resources -

1. aws x-ray tracing breaks on outgoing requests in Node.js

2. https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html

The Daemon runs successfully but, doesn't send data for all the APIs,

It only sends the data for the /traceS3 and /traceMysql APIs.

Following is the running code -

```<code>var AWSXRay = require('aws-xray-sdk');
var AWS = AWSXRay.captureAWS(require('aws-sdk'));
var mysql = AWSXRay.captureMySQL(require('mysql'));

var express = require('express');
var app = express();

var http = AWSXRay.captureHTTPs(require('http'));
app.use(AWSXRay.express.openSegment('X-Ray-Node-Example'));

AWS.config.update({region: 'ap-southeast-2'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "nodejs",
    port: 3306
});

con.connect(function (err) {
    if (err) throw err

});

app.get('/traceS3', function(req,res){

    // Call S3 to list current buckets
    s3.listBuckets(function(err, data) {
        if (err) {
            console.log("Error", err);
            res.send(err);
        } else {
            res.send(data.Buckets);
        }
    });
});

app.get('/traceHttp', function (req, res) {
    console.log("traceHttp called!\n"+req);

    http.get("http://jsonplaceholder.typicode.com/todos/1", (resp) => {
        console.log(resp);
        res.send("googlefetched")
    });
});

app.get('/traceMysql', function (req, res) {
    console.log("traceMysql called!\n"+req);

    var start = Date.now();

    var query = con.query('SELECT * FROM customer', function (err, rows, fields) {
        if (err) {
            console.log("Error Selecting : %s ", err);
        }
        else {
            var resp = [];
            function Person(id, name) {
                this.id = id;
                this.name = name;
            }

            for (var i = 0; i < rows.length; i++) {
                var id = rows[i].id;
                var name = rows[i].name;
                resp.push(new Person(id, name));
            }
            var end = Date.now();
            res.send(JSON.stringify({ "status": 200, "error": null, "response": resp, "requestTime": end - start }));
        }
    });
});

app.use(AWSXRay.express.closeSegment());
var server = app.listen(8085, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
});
</code>```

Can someone help fix the code?

答:
The symptoms seem similar to those of a bug that was reportedly fixed in v1.2.0

HTTP Patcher leaks response & stalls segments if no other response listener is supplied

Title: How to use AWS X-Ray in NodeJs?

Body:
I'm trying to use aws-xray-sdk to get the traces of my App,

I have written three APIs,

1. Making a call to an AWS S3 service (/traceS3)

2. Making a HTTP call to external endpoint ie. google.com (/traceHttp)

3. Making a DB call to a locally installed MySql DB (/traceMysql)

Also installed the AWS X-Ray Daemon locally

And made AWS configurations using the aws-cli and then ran the daemon using the following command (I'm using Ubuntu) -

/usr/bin/xray -o -n ap-southeast-2

I am referring the following resources -

1. aws x-ray tracing breaks on outgoing requests in Node.js

2. https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html

The Daemon runs successfully but, doesn't send data for all the APIs,

It only sends the data for the /traceS3 and /traceMysql APIs.

Following is the running code -

var AWSXRay = require('aws-xray-sdk');
var AWS = AWSXRay.captureAWS(require('aws-sdk'));
var mysql = AWSXRay.captureMySQL(require('mysql'));

var express = require('express');
var app = express();

var http = AWSXRay.captureHTTPs(require('http'));
app.use(AWSXRay.express.openSegment('X-Ray-Node-Example'));

AWS.config.update({region: 'ap-southeast-2'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "nodejs",
    port: 3306
});

con.connect(function (err) {
    if (err) throw err

});

app.get('/traceS3', function(req,res){

    // Call S3 to list current buckets
    s3.listBuckets(function(err, data) {
        if (err) {
            console.log("Error", err);
            res.send(err);
        } else {
            res.send(data.Buckets);
        }
    });
});

app.get('/traceHttp', function (req, res) {
    console.log("traceHttp called!\n"+req);

    http.get("http://jsonplaceholder.typicode.com/todos/1", (resp) => {
        console.log(resp);
        res.send("googlefetched")
    });
});

app.get('/traceMysql', function (req, res) {
    console.log("traceMysql called!\n"+req);

    var start = Date.now();

    var query = con.query('SELECT * FROM customer', function (err, rows, fields) {
        if (err) {
            console.log("Error Selecting : %s ", err);
        }
        else {
            var resp = [];
            function Person(id, name) {
                this.id = id;
                this.name = name;
            }

            for (var i = 0; i < rows.length; i++) {
                var id = rows[i].id;
                var name = rows[i].name;
                resp.push(new Person(id, name));
            }
            var end = Date.now();
            res.send(JSON.stringify({ "status": 200, "error": null, "response": resp, "requestTime": end - start }));
        }
    });
});

app.use(AWSXRay.express.closeSegment());
var server = app.listen(8085, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
});

Can someone help fix the code?


问:
How to make search based on pickup date and return date?
In the car page,i already input all the data into mysql database(car table).So i want to ease the user to find the car that available on pickup date and return date.So,I made search pickup date and return date in search page.But the error is "could not be execute".

This is using mysql and php.

car.php

```<code></body>
        <table align='center' width='40%' border='0' cellpadding='0' cellspacing='0'>
            <tr>
                <form action="search.php" method="post" enctype="multipart/form-data">
                <td><input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required /></td>
                <td><input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    /></td>
                <td><input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/></td>
    </div>
                </form>
            </table>

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 // Check connection
 if($link === false){
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

 // Attempt select query execution
 $sql = "SELECT * FROM car";
 if($result = mysqli_query($link, $sql)){
 if(mysqli_num_rows($result) > 0){
 echo "<table>";
echo "<tr>";
    echo "<th>Id</th>";
    echo "<th>Name</th>";
    echo "<th>Price(RM)</th>";
    echo "<th>Colour</th>";
    echo "<th>Mode</th>";
    echo "<th>Image</th>";
    echo "<th>Status</th>";
    echo "<th>Add to Booking</th>";
    echo "</tr>";

 while($row = mysqli_fetch_array($result)){
 echo "<tr>";
    echo "<td>" . $row['car_id'] . "</td>";
    echo "<td>" . $row['car_name'] . "</td>";
    echo "<td>" . $row['car_price'] . "</td>";
    echo "<td>" . $row['car_colour'] . "</td>";
    echo "<td>" . $row['car_mode'] . "</td>";
    echo "<td><img src='" . $row['car_image'] . "' height='100'
    width='100'></td>";
    echo "<td>" . $row['car_status'] . "</td>";
    echo '<input type="hidden" name="pickup_date"
  value="'.$pickup_date.'">';
    echo '<input type="hidden" name="return_date"
  value="'.$return_date.'">';
    echo "<td><button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>
    </td>";

  echo "</tr>";
}
    echo "</table>";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
 }

 mysqli_close($link);
?>

 </html>
</code>```

search.php

```<code> <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$search=$_GET['s'];
$query="SELECT * FROM car WHERE date BETWEEN 'pickup_date' AND
 'return_date'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "<table>";
        echo "<tr>";
            echo "<th>Id</th>";
            echo "<th>Name</th>";
            echo "<th>Price(RM)</th>";
            echo "<th>Colour</th>";
            echo "<th>Mode</th>";
            echo "<th>Image</th>";
            echo "<th>Status</th>";
            echo "<th>Add to Booking</th>";

        echo "</tr>";
    while($row = mysqli_fetch_array($result)){
        echo "<tr>";
            echo "<td>" . $row['car_id'] . "</td>";
            echo "<td>" . $row['car_name'] . "</td>";
            echo "<td>" . $row['car_price'] . "</td>";
            echo "<td>" . $row['car_colour'] . "</td>";
            echo "<td>" . $row['car_mode'] . "</td>";
            echo "<td><img src='" . $row['car_image'] . "' height='100' width='100'></td>";
            echo "<td>" . $row['car_status'] . "</td>";
            echo "<td>" . $row['pickup_date'] . "</td>";
            echo "<td>" . $row['return_date'] . "</td>";
            echo "<td><button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>

    </td>";

        echo "</tr>";
    }
    echo "</table>";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

</html>
</code>```

i expect the output is based on pickup_date and return_date.But the output is "ERROR:Could not able to execute".

答:
You Can check with this , When you have two tables you can use inner join query to fetch the data</p>

```<code>SELECT columns
FROM table WHERE pickup_date < 'your_pickup_date' AND return_date >= 'your_pickup_date' ORDER
BY  car or date;
</code>```

Body:
In the car page,i already input all the data into mysql database(car table).So i want to ease the user to find the car that available on pickup date and return date.So,I made search pickup date and return date in search page.But the error is "could not be execute".

This is using mysql and php.

car.php

                <form action="search.php" method="post" enctype="multipart/form-data">
                <input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required />
                <input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    />
                <input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/>

                </form>

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 // Check connection
 if($link === false){
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

 // Attempt select query execution
 $sql = "SELECT * FROM car";
 if($result = mysqli_query($link, $sql)){
 if(mysqli_num_rows($result) > 0){
 echo "
";
echo "
";
    echo "Id	";
    echo "Name	";
    echo "Price(RM)	";
    echo "Colour	";
    echo "Mode	";
    echo "Image	";
    echo "Status	";
    echo "Add to Booking	";
    echo "
";

 while($row = mysqli_fetch_array($result)){
 echo "
";
    echo "" . $row['car_id'] . "	";
    echo "" . $row['car_name'] . "	";
    echo "" . $row['car_price'] . "	";
    echo "" . $row['car_colour'] . "	";
    echo "" . $row['car_mode'] . "	";
    echo "	";
    echo "" . $row['car_status'] . "	";
    echo '<input type="hidden" name="pickup_date"
  value="'.$pickup_date.'">';
    echo '<input type="hidden" name="return_date"
  value="'.$return_date.'">';
    echo "<button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>
    	";

  echo "
";
}
    echo "
";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
 }

 mysqli_close($link);
?>

search.php

 <?php

 $link = mysqli_connect("localhost", "root", "", "online_car_rental");

 if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$search=$_GET['s'];
$query="SELECT * FROM car WHERE date BETWEEN 'pickup_date' AND
 'return_date'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "
";
        echo "
";
            echo "Id	";
            echo "Name	";
            echo "Price(RM)	";
            echo "Colour	";
            echo "Mode	";
            echo "Image	";
            echo "Status	";
            echo "Add to Booking	";

        echo "
";
    while($row = mysqli_fetch_array($result)){
        echo "
";
            echo "" . $row['car_id'] . "	";
            echo "" . $row['car_name'] . "	";
            echo "" . $row['car_price'] . "	";
            echo "" . $row['car_colour'] . "	";
            echo "" . $row['car_mode'] . "	";
            echo "	";
            echo "" . $row['car_status'] . "	";
            echo "" . $row['pickup_date'] . "	";
            echo "" . $row['return_date'] . "	";
            echo "<button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>

    	";

        echo "
";
    }
    echo "
";
    // Free result set
    mysqli_free_result($result);
} else{
    echo "No records matching your query were found.";
}
 } else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

i expect the output is based on pickup_date and return_date.But the output is "ERROR:Could not able to execute".

Body:
You Can check with this , When you have two tables you can use inner join query to fetch the data

SELECT columns
FROM table WHERE pickup_date < 'your_pickup_date' AND return_date >= 'your_pickup_date' ORDER
BY  car or date;


问:
Does using typescript basically give up the prototype-based programming paradigm?
I'm trying to prototype-based programming with typescirpt and found that typescript has limited support for this. So I want to know if using typescript basically gives up the prototype-based programming paradigm?

Here is my demo code:

const Foo = {
  init (name: string) {
    this.name = name
    return this
  },
  getName(): string {
    return this.name
  }
}

const Bar = {
  init (name: string, label: string) {
    Foo.init.call(this, name)
    this.label = label
    return this
  },
  getLabel() {
    return this.label
  }
}
Object.setPrototypeOf(Bar, Foo)

const bar = <typeof Bar> Object.create(Bar)
bar.init('lisiur', 'javascript')
bar.getName()
```

And in the last line typescript complain that Property 'getName' does not exist on type '{ init(name: string, label: string): any; getLabel(): any; }'.ts(2339). Is there a way to fix it?

update:

In lib.d.ts, Object.create and Object.setPrototypeOf all miss necessary type declaration(they all return any). So is there a way to declare my own create and setPrototypeOf to achieve that?

答:
It is possible to create objects with the prototype paradigm, but TypeScript won't be able to infer their types. It is still possible to use typing but they have to be provided manually. An example:

```<code>interface FooBaseType {
  getName(): string
}

interface FooType extends FooBaseType {
  init(name: string): void
}

interface BarType extends FooBaseType {
  init(name: string, label: string): void
  getLabel(): string
}

const Foo = { /* … */ }
const Bar = { /* … */ }
Object.setPrototypeOf(Bar, Foo)

const bar = Object.create(Bar) as BarType // manually affects 'BarType'
bar.init('lisiur', 'javascript')
bar.getName()
</code>```

… Or the same example, using inference from Foo and Bar:

```<code>const Foo = { /* … */ }
const Bar = { /* … */ }
Object.setPrototypeOf(Bar, Foo)

// Remove the following line with TypeScript 3.5
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

type FooBaseType = Omit<typeof Foo, "init">
type FooType = FooBaseType & Pick<typeof Foo, "init">
type BarType = FooBaseType & typeof Bar

const bar = Object.create(Bar) as BarType // manually affects 'BarType'
bar.init('lisiur', 'javascript')
bar.getName()
</code>```

Body:
I'm trying to prototype-based programming with typescirpt and found that typescript has limited support for this. So I want to know if using typescript basically gives up the prototype-based programming paradigm?

Here is my demo code:

const Foo = {
  init (name: string) {
    this.name = name
    return this
  },
  getName(): string {
    return this.name
  }
}

const Bar = {
  init (name: string, label: string) {
    Foo.init.call(this, name)
    this.label = label
    return this
  },
  getLabel() {
    return this.label
  }
}
Object.setPrototypeOf(Bar, Foo)

const bar = <typeof Bar> Object.create(Bar)
bar.init('lisiur', 'javascript')
bar.getName()

And in the last line typescript complain that Property 'getName' does not exist on type '{ init(name: string, label: string): any; getLabel(): any; }'.ts(2339). Is there a way to fix it?

update:

In lib.d.ts, Object.create and Object.setPrototypeOf all miss necessary type declaration(they all return any). So is there a way to declare my own create and setPrototypeOf to achieve that?

Body:
It is possible to create objects with the prototype paradigm, but TypeScript won't be able to infer their types. It is still possible to use typing but they have to be provided manually. An example:

interface FooBaseType {
  getName(): string
}

interface FooType extends FooBaseType {
  init(name: string): void
}

interface BarType extends FooBaseType {
  init(name: string, label: string): void
  getLabel(): string
}

const Foo = { /* … */ }
const Bar = { /* … */ }
Object.setPrototypeOf(Bar, Foo)

const bar = Object.create(Bar) as BarType // manually affects 'BarType'
bar.init('lisiur', 'javascript')
bar.getName()

… Or the same example, using inference from Foo and Bar:

const Foo = { /* … */ }
const Bar = { /* … */ }
Object.setPrototypeOf(Bar, Foo)

// Remove the following line with TypeScript 3.5
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

type FooBaseType = Omit<typeof Foo, "init">
type FooType = FooBaseType & Pick<typeof Foo, "init">
type BarType = FooBaseType & typeof Bar

const bar = Object.create(Bar) as BarType // manually affects 'BarType'
bar.init('lisiur', 'javascript')
bar.getName()


问:
look for the image by caputura of screen, even if it is not in that moment
What code could I use if I want to look for the image, even if it is not at that moment, but when it is found? My code would be:

```<code>import pyautogui as auto
import time
import pyautogui

def Saludar (seconds,schedule) :

    while (1>0) and (schedule == True) :
        time.sleep(seconds)

        x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
        auto.moveTo(x,y)
        pyautogui.click()
        print("YA")

if __name__== "__main__":
    Saludar(2,True)
</code>```

Error:

```<code>Traceback (most recent call last):
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 19, in <module>
    Saludar(2,True)
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 11, in Saludar
    x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
TypeError: 'NoneType' object is not iterable
</code>```

答:
When the image is not found it would raise a TypeError Exception. You can simply handle that with a try/except:

```<code>import pyautogui as auto
import time
import pyautogui

def Saludar(seconds, schedule):
    while (1 > 0) and (schedule == True):
        time.sleep(seconds)
        try:
            x, y = auto.locateCenterOnScreen(
                'Desktop/linea.png', grayscale=True)
            print('Found it!')
            auto.moveTo(x, y)
            pyautogui.click()
        except TypeError:
            """
            Image is not found
            """
            print("Image is Not found on the screen!")

if __name__ == "__main__":
    Saludar(2, True)
</code>```

Body:
What code could I use if I want to look for the image, even if it is not at that moment, but when it is found? My code would be:

import pyautogui as auto
import time
import pyautogui

def Saludar (seconds,schedule) :

    while (1>0) and (schedule == True) :
        time.sleep(seconds)

        x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
        auto.moveTo(x,y)
        pyautogui.click()
        print("YA")

if __name__== "__main__":
    Saludar(2,True)

Error:

Traceback (most recent call last):
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 19, in <module>
    Saludar(2,True)
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 11, in Saludar
    x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
TypeError: 'NoneType' object is not iterable

Body:
When the image is not found it would raise a TypeError Exception. You can simply handle that with a try/except:

import pyautogui as auto
import time
import pyautogui

def Saludar(seconds, schedule):
    while (1 > 0) and (schedule == True):
        time.sleep(seconds)
        try:
            x, y = auto.locateCenterOnScreen(
                'Desktop/linea.png', grayscale=True)
            print('Found it!')
            auto.moveTo(x, y)
            pyautogui.click()
        except TypeError:
            """
            Image is not found
            """
            print("Image is Not found on the screen!")

if __name__ == "__main__":
    Saludar(2, True)


问:
KeyEvent handling in android?
I want to programattically handle the ENTER key in android.
Is there any way to achieve this?
Please Help!!

Thanks in advance

答: Use onKey() to capture the key. KEYCODE_NUMPAD_ENTER is used for the numeric ENTER key, and KEYCODE_DPAD_CENTER is the Directional Pad Center key.

Title: KeyEvent handling in android?


问:
ElasticSearch, appending value to field, but check if field exists first, if not create field then append
I'm trying to dynamically add a new array type field to documents as they need it, If the field exists already (ie, someone else already added an item to the array) then append my item. If it doesn't exist, I need it to create the field then append my item.

Currently I can only append if I first create the field but the way I've written it overwrites existing field values if present.

```<code># Create the field, not ideal as it wipes the field if it existed already

        es.update(
            index='index_name',
            id='doc_id_987324bhashjgbasf',
            body={"doc": {
                'notes': []}})

# Append my value
    es.update(index='index_name', id='doc_id_987324bhashjgbasf',
              body={
                  "script": {
                      "source": "ctx._source.notes.addAll(params.new_note)",
                      "lang": "painless",
                      "params": {
                          "new_note": [{'note': 'Hello I am a note', 'user':'Ari'}]
                      }
                  }
              })
</code>```

Ideally the process I'd like is

Check if field 'notes' exists

If it exists, append new value with existing values

If it doesn't exist, create field then append my value

答:
logstash:

```<code>if [notes] {
    notes.add("NewItem");
} else {
   notes = new ArrayList();
   notes.add("NewItem");
}
</code>```

elasticsearch:

```<code>"script": "if (ctx._source.containsKey(\"notes\")) {ctx._source.notes += value;} else {ctx._source.notes = [value]}"
</code>```

Body:
I'm trying to dynamically add a new array type field to documents as they need it, If the field exists already (ie, someone else already added an item to the array) then append my item. If it doesn't exist, I need it to create the field then append my item.

Currently I can only append if I first create the field but the way I've written it overwrites existing field values if present.

# Create the field, not ideal as it wipes the field if it existed already

        es.update(
            index='index_name',
            id='doc_id_987324bhashjgbasf',
            body={"doc": {
                'notes': []}})

# Append my value
    es.update(index='index_name', id='doc_id_987324bhashjgbasf',
              body={
                  "script": {
                      "source": "ctx._source.notes.addAll(params.new_note)",
                      "lang": "painless",
                      "params": {
                          "new_note": [{'note': 'Hello I am a note', 'user':'Ari'}]
                      }
                  }
              })

Ideally the process I'd like is

Check if field 'notes' exists

If it exists, append new value with existing values

If it doesn't exist, create field then append my value

Body:
logstash:

if [notes] {
    notes.add("NewItem");
} else {
   notes = new ArrayList();
   notes.add("NewItem");
}

elasticsearch:

"script": "if (ctx._source.containsKey(\"notes\")) {ctx._source.notes += value;} else {ctx._source.notes = [value]}"


问:
How to run an Asyncio task without awaiting?
I need to call a task periodically but (a)waiting times are almost more than the period.

In the following code, How can I run do_something() task without need to await for the result?

```<code> import asyncio
 import time
 from random import randint

 period = 1  # Second

 def get_epoch_ms():
     return int(time.time() * 1000.0)

 async def do_something(name):
     print("Start  :", name, get_epoch_ms())
     try:
         # Do something which may takes more than 1 secs.
         slp = randint(1, 5)
         print("Sleep  :", name, get_epoch_ms(), slp)
         await asyncio.sleep(slp)
     except Exception as e:
         print("Error  :", e)

     print("Finish :", name, get_epoch_ms())

 async def main():
     i = 0
     while True:
         i += 1
         # Todo : this line should be change
         await do_something('T' + str(i))
         await asyncio.sleep(period)

 asyncio.get_event_loop().run_until_complete(main())
</code>```

答: Instead of awaiting the coroutine, call asyncio.create_task to spawn a task object that runs in the background. At your next iteration you can check if the task is done and await/cancel it accordingly. (Otherwise asyncio will complain of un-awaited tasks being garbage collected.)

Body:
I need to call a task periodically but (a)waiting times are almost more than the period.

In the following code, How can I run do_something() task without need to await for the result?

 import asyncio
 import time
 from random import randint

 period = 1  # Second

 def get_epoch_ms():
     return int(time.time() * 1000.0)

 async def do_something(name):
     print("Start  :", name, get_epoch_ms())
     try:
         # Do something which may takes more than 1 secs.
         slp = randint(1, 5)
         print("Sleep  :", name, get_epoch_ms(), slp)
         await asyncio.sleep(slp)
     except Exception as e:
         print("Error  :", e)

     print("Finish :", name, get_epoch_ms())

 async def main():
     i = 0
     while True:
         i += 1
         # Todo : this line should be change
         await do_something('T' + str(i))
         await asyncio.sleep(period)

 asyncio.get_event_loop().run_until_complete(main())


问:
Case classes - Copy multiple fields with transforms
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

```<code>import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.
</code>```

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

```<code>val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)
</code>```

See below comment for various reasons why this is inappropriate.

答: The simplest solution is to construct an instance of the new case class using the values from the old one, applying functions to the values as necessary. The code will be very efficient, the purpose of the code will be very clear, it will take less time to write than any other solution, it will be more robust and maintainable than a solution that depends on third-party libraries, and it avoids a hidden dependency between the two classes.

Body:
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)

See below comment for various reasons why this is inappropriate.


问:
What is the javascript MIME type for the type attribute of a script tag?
What is the MIME type of javascript?

More specifically, what is the right thing to put in the "type" attribute of a script tag? application/x-javascript and text/javascript seem to be the main contenders.

答:
The official RFC that defines the Javascript MIME Type is RFC4329.</p>

```
7.  JavaScript Media Types

7.1.  text/javascript (obsolete)

   Type name:               text
   Subtype name:            javascript
   Required parameters:     none
   Optional parameters:     charset, see section 4.1.
   Encoding considerations:
      The same as the considerations in section 3.1 of [RFC3023].

   Security considerations: See section 5.
   Interoperability considerations:
      None, except as noted in other sections of this document.

   Published specification: [JS15]
   Applications which use this media type:
      Script interpreters as discussed in this document.

   Additional information:

      Magic number(s):             n/a
      File extension(s):           .js
      Macintosh File Type Code(s): TEXT

   Person & email address to contact for further information:
      See Author's Address section.

   Intended usage:          OBSOLETE
   Restrictions on usage:   n/a
   Author:                  See Author's Address section.
   Change controller:       The IESG.

7.2.  application/javascript

   Type name:               application
   Subtype name:            javascript
   Required parameters:     none
   Optional parameters:     charset, see section 4.1.
   Encoding considerations:
      The same as the considerations in section 3.2 of [RFC3023].

   Security considerations: See section 5.
   Interoperability considerations:
      None, except as noted in other sections of this document.

   Published specification: [JS15]
   Applications which use this media type:
      Script interpreters as discussed in this document.

   Additional information:

      Magic number(s):             n/a
      File extension(s):           .js
      Macintosh File Type Code(s): TEXT

   Person & email address to contact for further information:
      See Author's Address section.

   Intended usage:          COMMON
   Restrictions on usage:   n/a
   Author:                  See Author's Address section.
   Change controller:       The IESG.
```

OwnerDisplayName: defrex

LastEditorDisplayName: keparo

Body:
The official RFC that defines the Javascript MIME Type is RFC4329.

7.  JavaScript Media Types

7.1.  text/javascript (obsolete)

   Type name:               text
   Subtype name:            javascript
   Required parameters:     none
   Optional parameters:     charset, see section 4.1.
   Encoding considerations:
      The same as the considerations in section 3.1 of [RFC3023].

   Security considerations: See section 5.
   Interoperability considerations:
      None, except as noted in other sections of this document.

   Published specification: [JS15]
   Applications which use this media type:
      Script interpreters as discussed in this document.

   Additional information:

      Magic number(s):             n/a
      File extension(s):           .js
      Macintosh File Type Code(s): TEXT

   Person & email address to contact for further information:
      See Author's Address section.

   Intended usage:          OBSOLETE
   Restrictions on usage:   n/a
   Author:                  See Author's Address section.
   Change controller:       The IESG.

7.2.  application/javascript

   Type name:               application
   Subtype name:            javascript
   Required parameters:     none
   Optional parameters:     charset, see section 4.1.
   Encoding considerations:
      The same as the considerations in section 3.2 of [RFC3023].

   Security considerations: See section 5.
   Interoperability considerations:
      None, except as noted in other sections of this document.

   Published specification: [JS15]
   Applications which use this media type:
      Script interpreters as discussed in this document.

   Additional information:

      Magic number(s):             n/a
      File extension(s):           .js
      Macintosh File Type Code(s): TEXT

   Person & email address to contact for further information:
      See Author's Address section.

   Intended usage:          COMMON
   Restrictions on usage:   n/a
   Author:                  See Author's Address section.
   Change controller:       The IESG.


问:
Cannot mock final Kotlin class using Mockito 2
I am unable to mock a Kotlin final class using Mockito 2. I am using Robolectric in addition.

This is my test code:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class Test {

    // more mocks

    @Mock
    MyKotlinLoader kotlinLoader;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
}
</code>```

The test fails when we try to initialise the mocks in the setUp() method.

In addition, I am using the following gradle dependencies in my code:

```<code>testCompile 'org.robolectric:robolectric:3.3.2'
testCompile 'org.robolectric:shadows-multidex:3.3.2'
testCompile 'org.robolectric:shadows-support-v4:3.3.2'
testCompile("org.powermock:powermock-api-mockito2:1.7.0") {
    exclude module: 'hamcrest-core'
    exclude module: 'objenesis'
}
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-inline:2.8.9'
</code>```

All other unit tests pass using this configuration but as soon as I try to mock the Kotlin class it throws the following error:

Mockito cannot mock/spy because :
 - final class

Please note I am using Mockito version 2 and I am using the inline dependency which automatically enables the ability to mock final classes.

答:
Try adding this below dependency to your build.gradle.

```<code>testImplementation 'org.mockito:mockito-inline:2.8.47'
</code>```

Replace with your mockito version instead of 2.8.47. This will help you to avoid using powermock for the issue.

please look into the below link to know how this thing works.

How to mock a final class with mockito

Body:
I am unable to mock a Kotlin final class using Mockito 2. I am using Robolectric in addition.

This is my test code:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class Test {

    // more mocks

    @Mock
    MyKotlinLoader kotlinLoader;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
}

The test fails when we try to initialise the mocks in the setUp() method.

In addition, I am using the following gradle dependencies in my code:

testCompile 'org.robolectric:robolectric:3.3.2'
testCompile 'org.robolectric:shadows-multidex:3.3.2'
testCompile 'org.robolectric:shadows-support-v4:3.3.2'
testCompile("org.powermock:powermock-api-mockito2:1.7.0") {
    exclude module: 'hamcrest-core'
    exclude module: 'objenesis'
}
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-inline:2.8.9'

All other unit tests pass using this configuration but as soon as I try to mock the Kotlin class it throws the following error:

Mockito cannot mock/spy because :
 - final class

Please note I am using Mockito version 2 and I am using the inline dependency which automatically enables the ability to mock final classes.

Body:
Try adding this below dependency to your build.gradle.

testImplementation 'org.mockito:mockito-inline:2.8.47'

Replace with your mockito version instead of 2.8.47. This will help you to avoid using powermock for the issue.

please look into the below link to know how this thing works.

How to mock a final class with mockito


问:
Rotate and save a photo in laravel
I want to upload photos in server. But before that I want to rotate that image.
My code is like below,

```<code>    $photo = $request->file($field);
    $temp = imagecreatefromjpeg($photo);
    $rotated = imagerotate($temp, 270, 0);
    $extension = $photo->getClientOriginalExtension();
    $flieNametoStore = time()."___".explode('.',$photo->getClientOriginalName())[0].'.'.$extension;
    Storage::disk('public')->put($flieNametoStore,  $rotated);
</code>```

It is not working. It shows error like supplied resource is not a valid stream resource.
I also tried Storage::disk('public')->put($flieNametoStore,  File::get($rotated)); but still it doesn't work.

So, I have two questions.
What can I do to achieve my objective? (rotate and save in server.)
Also, I have used imagecreatefromjpeg function. However, I want to execute same code for other file type.(All types supported by laravel validation of image.)

I searched in SO and found some similar questions. However, those solutions are not giving me my desired output.

答:
use imagejpeg function for save photo

imagerotate return a gd resource type not resource...

```<code>$photo           = request()->file($field);
$temp            = imagecreatefromjpeg($photo);
$rotated         = imagerotate($temp, 270, 0);
$extension       = $photo->getClientOriginalExtension();
$flieNametoStore = time() . "___" . explode('.', $photo->getClientOriginalName())[0] . '.' . $extension;
imagejpeg($rotated,  $flieNametoStore);
</code>```

or

```<code>ob_start();
imagejpeg($rotated);
$rotated = ob_get_contents();
ob_clean();
Storage::disk('public')->put($flieNametoStore, $rotated);
</code>```

Title: Rotate and save a photo in laravel

Body:
I want to upload photos in server. But before that I want to rotate that image.
My code is like below,

    $photo = $request->file($field);
    $temp = imagecreatefromjpeg($photo);
    $rotated = imagerotate($temp, 270, 0);
    $extension = $photo->getClientOriginalExtension();
    $flieNametoStore = time()."___".explode('.',$photo->getClientOriginalName())[0].'.'.$extension;
    Storage::disk('public')->put($flieNametoStore,  $rotated);

It is not working. It shows error like supplied resource is not a valid stream resource.
I also tried Storage::disk('public')->put($flieNametoStore,  File::get($rotated)); but still it doesn't work.

So, I have two questions.
What can I do to achieve my objective? (rotate and save in server.)
Also, I have used imagecreatefromjpeg function. However, I want to execute same code for other file type.(All types supported by laravel validation of image.)

I searched in SO and found some similar questions. However, those solutions are not giving me my desired output.

Body:
use imagejpeg function for save photo

imagerotate return a gd resource type not resource...

$photo           = request()->file($field);
$temp            = imagecreatefromjpeg($photo);
$rotated         = imagerotate($temp, 270, 0);
$extension       = $photo->getClientOriginalExtension();
$flieNametoStore = time() . "___" . explode('.', $photo->getClientOriginalName())[0] . '.' . $extension;
imagejpeg($rotated,  $flieNametoStore);

or

ob_start();
imagejpeg($rotated);
$rotated = ob_get_contents();
ob_clean();
Storage::disk('public')->put($flieNametoStore, $rotated);


问:
How to stop default link click behavior with jQuery
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

```<code><a href="store/cart/" class="update-cart">Update Cart</a>
</code>```

This is what the jQuery looks like:

```<code>$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});
</code>```

What is the problem?

答:
```<code>e.preventDefault();
</code>```

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable,
  without stopping further propagation
  of the event.

Body:
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

Update Cart

This is what the jQuery looks like:

$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});

What is the problem?

Body:
e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable,
  without stopping further propagation
  of the event.


问:
How do I read a large csv file with pandas?
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting a memory error:

```<code>MemoryError                               Traceback (most recent call last)
<ipython-input-58-67a72687871b> in <module>()
----> 1 data=pd.read_csv('aphro.csv',sep=';')

...

MemoryError:
</code>```

Any help on this?

答:
Here follows an example:</p>

```<code>chunkTemp = []
queryTemp = []
query = pd.DataFrame()

for chunk in pd.read_csv(file, header=0, chunksize=<your_chunksize>, iterator=True, low_memory=False):

    #REPLACING BLANK SPACES AT COLUMNS' NAMES FOR SQL OPTIMIZATION
    chunk = chunk.rename(columns = {c: c.replace(' ', '') for c in chunk.columns})

    #YOU CAN EITHER:
    #1)BUFFER THE CHUNKS IN ORDER TO LOAD YOUR WHOLE DATASET
    chunkTemp.append(chunk)

    #2)DO YOUR PROCESSING OVER A CHUNK AND STORE THE RESULT OF IT
    query = chunk[chunk[<column_name>].str.startswith(<some_pattern>)]
    #BUFFERING PROCESSED DATA
    queryTemp.append(query)

#!  NEVER DO pd.concat OR pd.DataFrame() INSIDE A LOOP
print("Database: CONCATENATING CHUNKS INTO A SINGLE DATAFRAME")
chunk = pd.concat(chunkTemp)
print("Database: LOADED")

#CONCATENATING PROCESSED DATA
query = pd.concat(queryTemp)
print(query)
</code>```

Body:
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting a memory error:

MemoryError                               Traceback (most recent call last)
<ipython-input-58-67a72687871b> in <module>()
----> 1 data=pd.read_csv('aphro.csv',sep=';')

...

MemoryError:

Any help on this?

Body:
Here follows an example:

chunkTemp = []
queryTemp = []
query = pd.DataFrame()

for chunk in pd.read_csv(file, header=0, chunksize=<your_chunksize>, iterator=True, low_memory=False):

    #REPLACING BLANK SPACES AT COLUMNS' NAMES FOR SQL OPTIMIZATION
    chunk = chunk.rename(columns = {c: c.replace(' ', '') for c in chunk.columns})

    #YOU CAN EITHER:
    #1)BUFFER THE CHUNKS IN ORDER TO LOAD YOUR WHOLE DATASET
    chunkTemp.append(chunk)

    #2)DO YOUR PROCESSING OVER A CHUNK AND STORE THE RESULT OF IT
    query = chunk[chunk[<column_name>].str.startswith(<some_pattern>)]
    #BUFFERING PROCESSED DATA
    queryTemp.append(query)

#!  NEVER DO pd.concat OR pd.DataFrame() INSIDE A LOOP
print("Database: CONCATENATING CHUNKS INTO A SINGLE DATAFRAME")
chunk = pd.concat(chunkTemp)
print("Database: LOADED")

#CONCATENATING PROCESSED DATA
query = pd.concat(queryTemp)
print(query)


问:
Minimum supported Gradle version is 4.1. Current version is 3.3
I am trying to make android build using command
   ionic cordova build android
  but I am facing error like

Minimum supported Gradle version is 4.1. Current version is 3.3. If using t
          he gradle wrapper, try editing the distributionUrl in D:\BAXA_POS\Development\tr
          unk\Mobile\baxa_pos\gradle\wrapper\gradle-wrapper.properties to gradle-4.1-all.zip

code in build.gradle is

```<code>    /*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

//task wrapper(type: Wrapper) {
 //   gradleVersion = '2.14.1'
//}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: 'CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }

    defaultConfig {
        versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))
        applicationId privateHelpers.extractStringFromManifest("package")

        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
    }

    lintOptions {
      abortOnError false;
    }

    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion

    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        productFlavors {
            armv7 {
                versionCode defaultConfig.versionCode*10 + 2
                ndk {
                    abiFilters "armeabi-v7a", ""
                }
            }
            x86 {
                versionCode defaultConfig.versionCode*10 + 4
                ndk {
                    abiFilters "x86", ""
                }
            }
            all {
                ndk {
                    abiFilters "all", ""
                }
            }
        }
    }
    /*

    ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!

    else if (!cdvVersionCode) {
      def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
      // Vary versionCode by the two most common API levels:
      // 14 is ICS, which is the lowest API level for many apps.
      // 20 is Lollipop, which is the lowest API level for the updatable system webview.
      if (minSdkVersion >= 20) {
        defaultConfig.versionCode += 9
      } else if (minSdkVersion >= 14) {
        defaultConfig.versionCode += 8
      }
    }
    */

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }

    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile(project(path: "CordovaLib", configuration: "debug"))
    releaseCompile(project(path: "CordovaLib", configuration: "release"))
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
        if (task.name == 'validateReleaseSigning' || task.name == 'validateSigningRelease') {
            promptForReleaseKeyPassword()
        }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}
</code>```

Code for gradle-wrapper.properties

```<code>        #DATE
        distributionBase=GRADLE_USER_HOME
        distributionPath=wrapper/dists
        zipStoreBase=GRADLE_USER_HOME
        zipStorePath=wrapper/dists
        distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

I have tried everything like changing distributionUrl and changing default gradle version , but everytime I run android build command distributionUrl change itself to old one.Can anyone suggest me something for this, that can work in my case.

答:
Go to Project->android->Wrapper->Gradle->Wrapper->Open gradle-wrapper.properties
 change your version:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

change this line:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
</code>```

Rebuild your application

Body:
I am trying to make android build using command
   ionic cordova build android
  but I am facing error like

Minimum supported Gradle version is 4.1. Current version is 3.3. If using t
          he gradle wrapper, try editing the distributionUrl in D:\BAXA_POS\Development\tr
          unk\Mobile\baxa_pos\gradle\wrapper\gradle-wrapper.properties to gradle-4.1-all.zip

code in build.gradle is

    /*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

//task wrapper(type: Wrapper) {
 //   gradleVersion = '2.14.1'
//}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: 'CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }

    defaultConfig {
        versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))
        applicationId privateHelpers.extractStringFromManifest("package")

        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
    }

    lintOptions {
      abortOnError false;
    }

    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion

    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        productFlavors {
            armv7 {
                versionCode defaultConfig.versionCode*10 + 2
                ndk {
                    abiFilters "armeabi-v7a", ""
                }
            }
            x86 {
                versionCode defaultConfig.versionCode*10 + 4
                ndk {
                    abiFilters "x86", ""
                }
            }
            all {
                ndk {
                    abiFilters "all", ""
                }
            }
        }
    }
    /*

    ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!

    else if (!cdvVersionCode) {
      def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
      // Vary versionCode by the two most common API levels:
      // 14 is ICS, which is the lowest API level for many apps.
      // 20 is Lollipop, which is the lowest API level for the updatable system webview.
      if (minSdkVersion >= 20) {
        defaultConfig.versionCode += 9
      } else if (minSdkVersion >= 14) {
        defaultConfig.versionCode += 8
      }
    }
    */

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }

    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile(project(path: "CordovaLib", configuration: "debug"))
    releaseCompile(project(path: "CordovaLib", configuration: "release"))
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
        if (task.name == 'validateReleaseSigning' || task.name == 'validateSigningRelease') {
            promptForReleaseKeyPassword()
        }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}

Code for gradle-wrapper.properties

        #DATE
        distributionBase=GRADLE_USER_HOME
        distributionPath=wrapper/dists
        zipStoreBase=GRADLE_USER_HOME
        zipStorePath=wrapper/dists
        distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

I have tried everything like changing distributionUrl and changing default gradle version , but everytime I run android build command distributionUrl change itself to old one.Can anyone suggest me something for this, that can work in my case.

Body:
Go to Project->android->Wrapper->Gradle->Wrapper->Open gradle-wrapper.properties
 change your version:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

change this line:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

Rebuild your application