问:
Android Studio 4 cannot detect java code and Cannot open SDK Manager,Settings
I just updated to latest android studio and had invalidated caches and restart but after that my project files are all red and android studio cannot detect java.
Whenever I hover on red line, It shows a configure JDK option.
I had downloaded latest jdk from oracle website and selected that in java path but that also didn't work. I am not able to open settings, SDK manager, neither can I configure SDK.

Below is the error dialog

I tried all the options below but cannot solve the issue

答:
Finally after hours of debugging , here is how I solved all the issues.

Cause of the problem : Improper Update

Checked IDE log, which was showing an exception thrown by a plugin. So I uninstalled that plugin.

Deleted old folder of android studio .Android-studio-3.6 present inside C\Users\<Username>\

Most of the errors were gone but android studio was shwowing a warning "Two different JDK locations are selected for building gradle....", so I went to control panel and deleted all old versions of java except for the latest JDK 14.0.1 which I downloaded from Oracle website.

Still it was showing the same error so I downloaded Android Studio 4.0 exe file from their website and re-installed Android studio. While Reinstalling, I did not select Android Virtual device as it was already installed.


来源: stackexchange

问:
Why cannot I create generic arraylist member of generic class?
I want to add methods to return the list or particular element and I want it to work with any generic class. Why isnt Java allowing this?</p>

```<code>class ArrayListBuilder<E>{
    private ArrayList<E> a_list=new ArrayList<>();
}
</code>```

答:
I tried to compile your code and got these errors

```<code>ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
            ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
                                    ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
2 errors
</code>```

As you can see there actually are two errors, the first one meaning that you need to import java.util.ArrayList. Once you do that, your code compiles fine. So put in the first line of your code

```<code>import java.util.ArrayList;
</code>```

TL;DR: the solution to your problem is reading all of the error messages. Not just the last one.

ContentLicense: CC BY-SA 4.0

Body:
I want to add methods to return the list or particular element and I want it to work with any generic class. Why isnt Java allowing this?

class ArrayListBuilder<E>{
    private ArrayList<E> a_list=new ArrayList<>();
}

Body:
I tried to compile your code and got these errors

ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
            ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
                                    ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
2 errors

As you can see there actually are two errors, the first one meaning that you need to import java.util.ArrayList. Once you do that, your code compiles fine. So put in the first line of your code

import java.util.ArrayList;

TL;DR: the solution to your problem is reading all of the error messages. Not just the last one.


问:
Multidimensional array flattening technique still leaves empty arrays
There are many references on S/O showing various methods to flatten a multidimensional recursive array (with more than two levels). I have been through dozens (and tried most) but I'm still running into an odd problem with every one I've tried. What I am getting as a result is:

```<code>Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000043
    [1] => 1000045
    [2] => 1000050
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000030
    [1] => 1000032
    [2] => 1000058
    [3] => 1000064
) ...
</code>```

But what I'm expecting is a truly flattened single array:

```<code>Array
    [0] => 1000043
    [1] => 1000045
    [2] => 1000050
    [3] => 1000030
    [4] => 1000032
    [5] => 1000058
    [6] => 1000064
)
</code>```

The method I found on S/O is supposed to handle an "empty array" (which I assume is the problem) but I'm still getting the wrong output. Here is my code:

```<code>function array_flatten5(array $array)
{
    $flat = array(); // initialize return array
    $stack = array_values($array); // initialize stack
    while($stack) // process stack until done
    {
        $value = array_shift($stack);
        if (is_array($value)) // a value to further process
        {
            $stack = array_merge(array_values($value), $stack);
        }
        else // a value to take
        {
           $flat[] = $value;
        }
    }
    return $flat;
}
</code>```

Could someone point out what I missing here because I'm thinking it's something simple but at this point my eyes are crossed with the number of attempts I've made. Thank you for any help you can provide.

Here is the original array. It is 4-deep:

```<code>Array ( [0] => 1000043 [1] => 1000045 [2] => 1000050 ) Array ( [0] => 1000030 [1] => 1000032 [2] => 1000058 [3] => 1000064 ) Array ( [0] => 1000041 [1] => 1000059 [2] => 1000069 ) Array ( [0] => 1000021 [1] => 1000044 [2] => 1000049 [3] => 1000071 ) Array ( [0] => 1000009 [1] => 1000013 [2] => 1000015 [3] => 1000017 [4] => 1000053 ) Array ( [0] => 1000022 [1] => 1000034 [2] => 1000070 ) Array ( [0] => 1000038 [1] => 1000047 [2] => 1000055 [3] => 1000063 ) Array ( [0] => 1000019 [1] => 1000054 [2] => 1000060 [3] => 1000066 [4] => 1000068 ) Array ( [0] => 1000006 [1] => 1000014 [2] => 1000016 [3] => 1000072 ) Array ( [0] => 1000024 [1] => 1000025 [2] => 1000046 [3] => 1000061 [4] => 1000067 ) Array ( [0] => 1000028 [1] => 1000039 [2] => 1000048 ) Array ( [0] => 1000042 [1] => 1000057 ) Array ( [0] => 1000027 [1] => 1000033 [2] => 1000036 [3] => 1000037 ) Array ( [0] => 1000008 [1] => 1000010 [2] => 1000012 [3] => 1000018 ) Array ( [0] => 1000026 [1] => 1000062 [2] => 1000065 ) Array ( [0] => 1000020 [1] => 1000023 [2] => 1000031 [3] => 1000035 [4] => 1000040 ) Array ( [0] => 1000007 [1] => 1000011 [2] => 1000029 ) Array ( [0] => 1000051 [1] => 1000052 [2] => 1000056 ) Array ( [0] => 1000001 [1] => 1000002 [2] => 1000003 [3] => 1000004 [4] => 1000005 ) Array ( [0] => 1000073 )
</code>```

And here is the outcome using the array_walk_recursive suggestion ...

```<code>Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000111
    [1] => 1000113
    [2] => 1000129
    [3] => 1000134
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000012
    [1] => 1000085
)
Array
(
) ...
</code>```

答:
You didn't prepare suitable array, but looking on this code you need probably just array_walk_recursive() function.

```<code>$array = [
    [1, 2, 3, 4],
    [[5, 6], [7, 8]],
    [[[9], [10]], [11]]
];

$result = [];
array_walk_recursive($array, function ($tempV) use (&$result) {
    $result[] = $tempV;
});

print_r($result);
</code>```

Output:

```<code>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
)
</code>```

Body:
There are many references on S/O showing various methods to flatten a multidimensional recursive array (with more than two levels). I have been through dozens (and tried most) but I'm still running into an odd problem with every one I've tried. What I am getting as a result is:

Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000043
    [1] => 1000045
    [2] => 1000050
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000030
    [1] => 1000032
    [2] => 1000058
    [3] => 1000064
) ...

But what I'm expecting is a truly flattened single array:

Array
    [0] => 1000043
    [1] => 1000045
    [2] => 1000050
    [3] => 1000030
    [4] => 1000032
    [5] => 1000058
    [6] => 1000064
)

The method I found on S/O is supposed to handle an "empty array" (which I assume is the problem) but I'm still getting the wrong output. Here is my code:

function array_flatten5(array $array)
{
    $flat = array(); // initialize return array
    $stack = array_values($array); // initialize stack
    while($stack) // process stack until done
    {
        $value = array_shift($stack);
        if (is_array($value)) // a value to further process
        {
            $stack = array_merge(array_values($value), $stack);
        }
        else // a value to take
        {
           $flat[] = $value;
        }
    }
    return $flat;
}

Could someone point out what I missing here because I'm thinking it's something simple but at this point my eyes are crossed with the number of attempts I've made. Thank you for any help you can provide.

Here is the original array. It is 4-deep:

Array ( [0] => 1000043 [1] => 1000045 [2] => 1000050 ) Array ( [0] => 1000030 [1] => 1000032 [2] => 1000058 [3] => 1000064 ) Array ( [0] => 1000041 [1] => 1000059 [2] => 1000069 ) Array ( [0] => 1000021 [1] => 1000044 [2] => 1000049 [3] => 1000071 ) Array ( [0] => 1000009 [1] => 1000013 [2] => 1000015 [3] => 1000017 [4] => 1000053 ) Array ( [0] => 1000022 [1] => 1000034 [2] => 1000070 ) Array ( [0] => 1000038 [1] => 1000047 [2] => 1000055 [3] => 1000063 ) Array ( [0] => 1000019 [1] => 1000054 [2] => 1000060 [3] => 1000066 [4] => 1000068 ) Array ( [0] => 1000006 [1] => 1000014 [2] => 1000016 [3] => 1000072 ) Array ( [0] => 1000024 [1] => 1000025 [2] => 1000046 [3] => 1000061 [4] => 1000067 ) Array ( [0] => 1000028 [1] => 1000039 [2] => 1000048 ) Array ( [0] => 1000042 [1] => 1000057 ) Array ( [0] => 1000027 [1] => 1000033 [2] => 1000036 [3] => 1000037 ) Array ( [0] => 1000008 [1] => 1000010 [2] => 1000012 [3] => 1000018 ) Array ( [0] => 1000026 [1] => 1000062 [2] => 1000065 ) Array ( [0] => 1000020 [1] => 1000023 [2] => 1000031 [3] => 1000035 [4] => 1000040 ) Array ( [0] => 1000007 [1] => 1000011 [2] => 1000029 ) Array ( [0] => 1000051 [1] => 1000052 [2] => 1000056 ) Array ( [0] => 1000001 [1] => 1000002 [2] => 1000003 [3] => 1000004 [4] => 1000005 ) Array ( [0] => 1000073 )

And here is the outcome using the array_walk_recursive suggestion ...

Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000111
    [1] => 1000113
    [2] => 1000129
    [3] => 1000134
)
Array
(
)
Array
(
)
Array
(
    [0] => 1000012
    [1] => 1000085
)
Array
(
) ...

Body:
You didn't prepare suitable array, but looking on this code you need probably just array_walk_recursive() function.

$array = [
    [1, 2, 3, 4],
    [[5, 6], [7, 8]],
    [[[9], [10]], [11]]
];

$result = [];
array_walk_recursive($array, function ($tempV) use (&$result) {
    $result[] = $tempV;
});

print_r($result);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
)


问:
Can I make online multiplayer games using flash?
I want to make a simple game so that I can play against my friends at school. The school uses macs. Also if you can't  make online games with flash what can I use. Also can they be 3-d if I eventually get good at making games?</p>

答:
there are several good multiplayer game toolkits for flash. here are a couple to look into:

union
http://www.unionplatform.com/

electroserver
http://www.electrotank.com/

colin

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How can I get selected value in select dom element [Laravel]
Can someone tell me how can I get selected value when I try to edit post in Laravel project.
So here are parts of code

Post.php:

```<code>public function category(){
    return $this->belongsTo('App\Category');
}
</code>```

Category.php:

```<code>public function posts(){
    return $this->hasMany('App\Post');
}
</code>```

PostController.php:

```<code> $post = Post::findOrFail($id);
 $categories = Category::all();
 $tags = Tag::all();
 return view('admin.posts.edit', ['post' => $post, 'categories' => $categories, 'tags' => $tags]);
</code>```

posts/edit.blade.php:

```<code><div class="form-group">
        <label for="category_id">Selecet category</label>
        <select name="category_id" id="category_id" class="form-control">
            <option disabled>List of available post categories</option>
            @foreach($categories as $category)

                <option value="{{ $category->id }}" {{$category->id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>

            @endforeach
        </select>
    </div>
</code>```

答:
Like @Hardood mentioned. $category->id == $category->id will always return true. In fact, if you just want to get the value from form submission. You can just remove that. HTML will handle selected value itself.

You can simply use $request->category_name in your backend.

Body:
Can someone tell me how can I get selected value when I try to edit post in Laravel project.
So here are parts of code

Post.php:

public function category(){
    return $this->belongsTo('App\Category');
}

Category.php:

public function posts(){
    return $this->hasMany('App\Post');
}

PostController.php:

 $post = Post::findOrFail($id);
 $categories = Category::all();
 $tags = Tag::all();
 return view('admin.posts.edit', ['post' => $post, 'categories' => $categories, 'tags' => $tags]);

posts/edit.blade.php:

        Selecet category
        <select name="category_id" id="category_id" class="form-control">
            <option disabled>List of available post categories</option>
            @foreach($categories as $category)

                <option value="{{ $category->id }}" {{$category->id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>

            @endforeach
        </select>


问:
How to resolve this error "Try replacing 'com.example' with your signing id in Xcode: open ios/Runner.xcworkspace"
I have created a flutter project which is linked with firebase.
It works fine with android devices but getting an error when trying to run it at ios device for the first time.

below the output of flutter run command:

答: Replace the info in the box "Bundle Identifier" (in the image), just replace it as "com.example.youremailID.com"</p>


问:
Getting "No file" or empty file when trying to download PDF file with Node.js
The issue:

I need to download a PDF file from my server but getting either "No file" or empty file

Details:

Here is my server-side code:

```<code>let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        })
    const file = fileBuffered;

    res.setHeader("Content-Type", "application/octet-stream");
    res.send(file);
</code>```

The PDF file's that I'm trying to download size is 139,694 bytes. The length of the fileBuffered variable is 132,597. Here is the content of the variable as it is shown in the debugger:

Seems like a legit PDF file

Here is the client-side

```<code>function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,

        headers: {
            "Accept": "application/octet-stream"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    console.log(request);

    return request;
}
</code>```

Problem:
Then I get the response on a client-side it looks like this:

Note the size of the responseText: 254Kb.
What I actually get in the browser is a "Failed - No file" message

What else I tried:

I tried to play with different Content-Types (application/pdf, text/pdf) on a server-side and tried to convert the variable to base64 buffer

```<code>const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
</code>```

and added res.setHeader("Accept-Encoding", "base64");
but still getting the same result.

Any ideas?

答:
I found a solution. I missed a .on("end", ) event while reading data from Dropbox stream. Here is a working solution:

Here is the server-side:

let chunk = [];
let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        }).on('end', () => {
                // console.log("finish");\
                // generate buffer
                fileBuffered = Buffer.concat(chunk);
            });

    const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
    res.setHeader("Content-Type", "application/pdf");
    res.send(file);
```

<p>Client-side:</p>

<pre class="lang-js prettyprint-override"><code>function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,
        responseType: "arraybuffer",
        headers: {
            "Accept": "application/pdf"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    // console.log(request);
    return request;
}
</code>```

Body:
The issue:

I need to download a PDF file from my server but getting either "No file" or empty file

Details:

Here is my server-side code:

let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        })
    const file = fileBuffered;

    res.setHeader("Content-Type", "application/octet-stream");
    res.send(file);

The PDF file's that I'm trying to download size is 139,694 bytes. The length of the fileBuffered variable is 132,597. Here is the content of the variable as it is shown in the debugger:

Seems like a legit PDF file

Here is the client-side

function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,

        headers: {
            "Accept": "application/octet-stream"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    console.log(request);

    return request;
}

Problem:
Then I get the response on a client-side it looks like this:

Note the size of the responseText: 254Kb.
What I actually get in the browser is a "Failed - No file" message

What else I tried:

I tried to play with different Content-Types (application/pdf, text/pdf) on a server-side and tried to convert the variable to base64 buffer

const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;

and added res.setHeader("Accept-Encoding", "base64");
but still getting the same result.

Any ideas?

Body:
I found a solution. I missed a .on("end", ) event while reading data from Dropbox stream. Here is a working solution:

Here is the server-side:

let chunk = [];
let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        }).on('end', () => {
                // console.log("finish");\
                // generate buffer
                fileBuffered = Buffer.concat(chunk);
            });

    const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
    res.setHeader("Content-Type", "application/pdf");
    res.send(file);

Client-side:

function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,
        responseType: "arraybuffer",
        headers: {
            "Accept": "application/pdf"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    // console.log(request);
    return request;
}


问:
How to speed up Spacy's nlp call?
I have to process hundreds of thousands of texts. I have found that the thing that is taking the longest in the following:

```<code>nlp = English()
ruler = EntityRuler(nlp)
patterns = [...]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
...
#This line takes longer than I would like
doc = nlp(whole_chat)
</code>```

Granted, I have many patterns. But is there a way to speed this up? I only have the entity ruler pipe, no others.

答:
By default, Spacy applies lots of models to your document: POS tagger, a syntactic parser, NER, a document categorizer, and maybe something else.

Maybe you do not need some of these models. If it is the case, you can disable them, which will speed up your pipeline. You do it when creating the pipeline, like this:

```<code>nlp = spacy.load('en_core_web_sm', disable=['ner', 'parser'])
</code>```

Or, following the @oleg-ivanytskiy's answer, you can disable these models in the nlp.pipe() call:

```<code>nlp = spacy.load("en_core_web_sm")
for doc in nlp.pipe(texts, disable=["tagger", "parser"]):
    # Do something with the doc here
    print([(ent.text, ent.label_) for ent in doc.ents])
</code>```

Title: How to speed up Spacy's nlp call?

Body:
I have to process hundreds of thousands of texts. I have found that the thing that is taking the longest in the following:

nlp = English()
ruler = EntityRuler(nlp)
patterns = [...]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
...
#This line takes longer than I would like
doc = nlp(whole_chat)

Granted, I have many patterns. But is there a way to speed this up? I only have the entity ruler pipe, no others.

Body:
By default, Spacy applies lots of models to your document: POS tagger, a syntactic parser, NER, a document categorizer, and maybe something else.

Maybe you do not need some of these models. If it is the case, you can disable them, which will speed up your pipeline. You do it when creating the pipeline, like this:

nlp = spacy.load('en_core_web_sm', disable=['ner', 'parser'])

Or, following the @oleg-ivanytskiy's answer, you can disable these models in the nlp.pipe() call:

nlp = spacy.load("en_core_web_sm")
for doc in nlp.pipe(texts, disable=["tagger", "parser"]):
    # Do something with the doc here
    print([(ent.text, ent.label_) for ent in doc.ents])


问:
How to add login credential via python script?
I am sure this is an answered question somewhere, but I could not find a solution for me (if you know a duplicate feel free to mark it).

My goal is to query a RESTful API. To do that I need to authenticate. The only way available for me for this API is via web-browser.

Basically, I am loading URL which redirects to another URL. In the second URL, there is a form where I need to input username and password to authenticate. Currently, I input the credentials manually via a web browser.

My question is: Can I do this programmatically such that I don't have to manually input the credentials via a web browser?

Note: the webpage is not verified.

Attempt 1

I tried the following commands, but none worked:

```<code>curl -k -u username:password https://myurl:port
</code>```

It did not return anything.

Attempt 2

```<code>BASE_URL = 'https://myurl:port'
username = 'username'
password = 'password'
r = requests.get(BASE_URL, auth=(username, password), verify=False)
print(r.status_code, r.reason)
</code>```

it prints <Response [200]> but it does not authenticate. This is because when I try to query an API endpoint - it says I am unauthorized. When I input the credentials manually in the browser - then the endpoint query works.

Attempt 3

Finally, I thought (but did not do) I need some way to read the login page and input credentials by getting the html elements and then clicking log in (with selenium for example), but this seems too rough and error-prone. Maybe there is a more elegant way.

Any ideas of how I can do this?

答:
Thanks for showing us your attempts.

If the attempt 2 returns 200 status code. It means it does work which means that basic auth works. Simple solution is to just pass auth=(username, password) to all of your api calls.

Or you can use requests.Session() to authenticate once and keep the session provided that server supports session authentication.

Hope this helps.

Body:
I am sure this is an answered question somewhere, but I could not find a solution for me (if you know a duplicate feel free to mark it).

My goal is to query a RESTful API. To do that I need to authenticate. The only way available for me for this API is via web-browser.

Basically, I am loading URL which redirects to another URL. In the second URL, there is a form where I need to input username and password to authenticate. Currently, I input the credentials manually via a web browser.

My question is: Can I do this programmatically such that I don't have to manually input the credentials via a web browser?

Note: the webpage is not verified.

Attempt 1

I tried the following commands, but none worked:

curl -k -u username:password https://myurl:port

It did not return anything.

Attempt 2

BASE_URL = 'https://myurl:port'
username = 'username'
password = 'password'
r = requests.get(BASE_URL, auth=(username, password), verify=False)
print(r.status_code, r.reason)

it prints <Response [200]> but it does not authenticate. This is because when I try to query an API endpoint - it says I am unauthorized. When I input the credentials manually in the browser - then the endpoint query works.

Attempt 3

Finally, I thought (but did not do) I need some way to read the login page and input credentials by getting the html elements and then clicking log in (with selenium for example), but this seems too rough and error-prone. Maybe there is a more elegant way.

Any ideas of how I can do this?


问:
Laravel Passport: Extending the Token's life time
Question:
I would like to ask how I can extend token's lifetime. As long as the user uses the application and when the user does not perform any activity on the application for one hour, for example, the token is terminated?

Example:

The user login, then a token with lifetime for one hour is generated here

A:

As long as the user responds with the app, the lifespan of this token is extended. (So tokenLieftime = now + 1hour).

B:

The user has no reaction with the app for an hour, then the token is deactivated.

答: You can simply add a middleware to refresh the token and return it to user in every request. Also make sure that you set the lifespan of your refresh token to 1 hour too. Cheers ;)</p>


问:
AJAX DataTable Server Side encountered Error when changing serverSide from true to false
Both these work well IF I set serverSide equal to false and using ajax to post my data as you can see below. Basically I have few dataTable which I would like to reuse the server_side.php in order to fetch data from particular tables (so i need to pass value accordingly in order for the server side). I not sure why it showing error when serverSide is set to be true while posting data to my server_side.php. While setting the serverSide = true, all I see is the client side showing processing in my DataTable. Nothing more nothing less.But if I set serverSide = false, data can be generated flawlessly, everything works fine. In my case I need to use serverSide which is true.

This is my php page which i used to display data passed from server side. The table

```<code><script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.21/r-2.2.4/datatables.min.js"></script>
<script type="text/javascript">
        $(document).ready(function() {

            var example = $('#example').DataTable({
                "processing": true,
                "serverSide": true,
                "responsive": true,
                ajax: {
                    url: "server_side.php",
                    type: "post",
                    data: {
                        view: 'product_upload'
                    }
                },
                "order": [],
                "columnDefs": [{
                    targets: [0],
                    className: "dt-body-center",
                    "orderable": false,
                }, {
                    targets: [1],
                    className: "dt-body-center"
                }]
            });
</script>
</code>```

This is my server_side.php.

```<code><?php
session_start();
$whereAll        = isset($_SESSION["agent_code"]) ? ($_SESSION["agent_code"]) : '';
$view_type       = isset($_POST['view']) ? $_POST['view'] : '';
/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simple to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = $view_type;

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array(
        'db'        => 'product_name',
        'dt'        => 0,
        'formatter' => function ($d, $row) {
            return '<input type="checkbox" id="' . $d . '" class="check_boxes">';
        }
    ),
    array(
        'db'        => 'image_path',
        'dt'        => 1,
        'formatter' => function ($d, $row) {
            return "<img src='" . $d . "' style='width:100px' class='text-center' />";
        }
    ),
    array(
        'db' => 'product_name', 'dt' => 2,
        'formatter' => function ($d, $row) {
            return 'Category :' . $row['category'] . '<br/>Name :' . $row['product_name'] . '<br/>Description :' . $row['product_description'];
        }
    ),
    array('db' => 'quantity', 'dt' => 3),
    array('db' => 'weight', 'dt' => 4),
    array('db' => 'uom', 'dt' => 5),
    array('db' => 'price', 'dt' => 6),
    array(
        'db' => 'product_name', 'dt' => 7,
        'formatter' => function ($d, $row) {
            return '<a href="#">Edit</a><br/><a href="#">Update</a><br/><a href="#">Delete</a>';
        }
    ),
    array('db' => 'category', 'dt' => 8),
    array('db' => 'product_description', 'dt' => 9)
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'ecom',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require('ssp.class.php');

echo json_encode(
    //SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns)
    SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, null, "added_by = '" . $whereAll . "' and is_show = '1'")

);
</code>```

Thank you in advance!

答:
Downgrading DataTable version from 1.10.21 to 1.10.20 fixed my problem.

https://cdn.datatables.net/v/bs4/dt-1.10.21/r-2.2.4/datatables.min.js

https://cdn.datatables.net/v/bs4/dt-1.10.20/r-2.2.4/datatables.min.js

Not sure it is internal error or what.

Body:
Both these work well IF I set serverSide equal to false and using ajax to post my data as you can see below. Basically I have few dataTable which I would like to reuse the server_side.php in order to fetch data from particular tables (so i need to pass value accordingly in order for the server side). I not sure why it showing error when serverSide is set to be true while posting data to my server_side.php. While setting the serverSide = true, all I see is the client side showing processing in my DataTable. Nothing more nothing less.But if I set serverSide = false, data can be generated flawlessly, everything works fine. In my case I need to use serverSide which is true.

This is my php page which i used to display data passed from server side. The table

This is my server_side.php.

<?php
session_start();
$whereAll        = isset($_SESSION["agent_code"]) ? ($_SESSION["agent_code"]) : '';
$view_type       = isset($_POST['view']) ? $_POST['view'] : '';
/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simple to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = $view_type;

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array(
        'db'        => 'product_name',
        'dt'        => 0,
        'formatter' => function ($d, $row) {
            return '<input type="checkbox" id="' . $d . '" class="check_boxes">';
        }
    ),
    array(
        'db'        => 'image_path',
        'dt'        => 1,
        'formatter' => function ($d, $row) {
            return "";
        }
    ),
    array(
        'db' => 'product_name', 'dt' => 2,
        'formatter' => function ($d, $row) {
            return 'Category :' . $row['category'] . '
Name :' . $row['product_name'] . '
Description :' . $row['product_description'];
        }
    ),
    array('db' => 'quantity', 'dt' => 3),
    array('db' => 'weight', 'dt' => 4),
    array('db' => 'uom', 'dt' => 5),
    array('db' => 'price', 'dt' => 6),
    array(
        'db' => 'product_name', 'dt' => 7,
        'formatter' => function ($d, $row) {
            return 'Edit
Update
Delete';
        }
    ),
    array('db' => 'category', 'dt' => 8),
    array('db' => 'product_description', 'dt' => 9)
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'ecom',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require('ssp.class.php');

echo json_encode(
    //SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns)
    SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, null, "added_by = '" . $whereAll . "' and is_show = '1'")

);

Thank you in advance!


问:
MySQL median with Join between 3 tables
I have three tables (teacher, course_work and submission) and I want to calculate de median for each teacher. I saw a query for the median calculation and I tried to adapt it without success.

My query right now is like this:

```<code>SELECT
    dd.id,
    AVG(dd.score) as median_val
FROM (
SELECT d.id, d.score, @rownum := @rownum + 1 as row_number, @total_rows := @rownum
FROM (
        SELECT
            teacher.id,
            submission.id AS submission_id,
            submission.score
        FROM teacher
        LEFT JOIN course_work ON teacher.id = course_work.teacher_id
        LEFT JOIN submission ON course_work.id = submission.course_work_id
        ORDER BY teacher.id
) d, (SELECT @rownum := 0) r
WHERE d.score is NOT NULL
ORDER BY d.score
) as dd
WHERE dd.row_number IN (FLOOR((@total_rows + 1) / 2), FLOOR((@total_rows + 2) / 2))
GROUP BY dd.id;
</code>```

Thank you very much.

The SQL Schema is the following:

https://pastebin.com/RT9iWJPH

答:
This might give the result that you are looking. Could you test it on your data.</p>

```<code>SELECT
    t.id as teacherid,
    t.full_name teacherfullname,
    COUNT(*) AS total_rows,
IF
    (
        count(*)% 2 = 1,
        CAST(
            SUBSTRING_INDEX(
                SUBSTRING_INDEX(
                    GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ),
                    ',',
                50 / 100 * COUNT(*)),
                ',',
                - 1
            ) AS DECIMAL
        ),
        ROUND((
                CAST(
                    SUBSTRING_INDEX(
                        SUBSTRING_INDEX( GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ), ',', 50 / 100 * COUNT(*) + 1 ),
                        ',',
                        - 1
                    ) AS DECIMAL
                    ) + CAST(
                    SUBSTRING_INDEX(
                        SUBSTRING_INDEX(
                            GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ),
                            ',',
                        50 / 100 * COUNT(*)),
                        ',',
                        - 1
                    ) AS DECIMAL
                )) / 2
        )) AS median
FROM
    teacher t
    JOIN course_work cw ON cw.teacher_id = t.id
    JOIN submission s ON cw.id = s.course_work_id
WHERE
    s.score IS NOT NULL
GROUP BY
    teacherid
ORDER BY
    s.score
</code>```

Title: MySQL median with Join between 3 tables

Body:
I have three tables (teacher, course_work and submission) and I want to calculate de median for each teacher. I saw a query for the median calculation and I tried to adapt it without success.

My query right now is like this:

SELECT
    dd.id,
    AVG(dd.score) as median_val
FROM (
SELECT d.id, d.score, @rownum := @rownum + 1 as row_number, @total_rows := @rownum
FROM (
        SELECT
            teacher.id,
            submission.id AS submission_id,
            submission.score
        FROM teacher
        LEFT JOIN course_work ON teacher.id = course_work.teacher_id
        LEFT JOIN submission ON course_work.id = submission.course_work_id
        ORDER BY teacher.id
) d, (SELECT @rownum := 0) r
WHERE d.score is NOT NULL
ORDER BY d.score
) as dd
WHERE dd.row_number IN (FLOOR((@total_rows + 1) / 2), FLOOR((@total_rows + 2) / 2))
GROUP BY dd.id;

Thank you very much.

The SQL Schema is the following:

https://pastebin.com/RT9iWJPH

Body:
This might give the result that you are looking. Could you test it on your data.

SELECT
    t.id as teacherid,
    t.full_name teacherfullname,
    COUNT(*) AS total_rows,
IF
    (
        count(*)% 2 = 1,
        CAST(
            SUBSTRING_INDEX(
                SUBSTRING_INDEX(
                    GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ),
                    ',',
                50 / 100 * COUNT(*)),
                ',',
                - 1
            ) AS DECIMAL
        ),
        ROUND((
                CAST(
                    SUBSTRING_INDEX(
                        SUBSTRING_INDEX( GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ), ',', 50 / 100 * COUNT(*) + 1 ),
                        ',',
                        - 1
                    ) AS DECIMAL
                    ) + CAST(
                    SUBSTRING_INDEX(
                        SUBSTRING_INDEX(
                            GROUP_CONCAT( s.score ORDER BY s.score SEPARATOR ',' ),
                            ',',
                        50 / 100 * COUNT(*)),
                        ',',
                        - 1
                    ) AS DECIMAL
                )) / 2
        )) AS median
FROM
    teacher t
    JOIN course_work cw ON cw.teacher_id = t.id
    JOIN submission s ON cw.id = s.course_work_id
WHERE
    s.score IS NOT NULL
GROUP BY
    teacherid
ORDER BY
    s.score


问:
Switching to First tab using Selenium Web Driver with Java
Using selenium web driver with java, i am trying to automate a functionality where i click on a link and it opens a new tab. I want to write a global method for first tab which when called in main test class switches to second tab. I have a separate method to do the assertions on second tab, after the assertions are complete. I want to write another global method which when called closed the second tab and switches back to the first one and resumes the tests on first window.

I have written the below methods and tests:

Main test:

```<code>@Test(enabled = true, dataProvider = "TestThis", description = "ClickThere", groups = {"hello" })

public void AttributeValidationOnHelpPage(TestData testData, String Id, String TableName) {

        menu.switch(Id);
        data = menu.clickData();
        data.selectNoneDateRange();
        TablePage = data.openTable(TableName);
        TablePage.clickAttTab();
        menuPage.clickOnHelpPage();

        // This method, when called will switch to second tab.
         helpPage = menu.switcToHelpPage();

        // After swicthing below is the assertions i want to do on the second tab.

        Assert.assertTrue(driver.getCurrentUrl().contains("Second page Url."));
        String actualValue = helpOnThisPage.getRefTableAttributes();
        Assert.assertEquals(actualValue, "Reference Table Attributes", "Reference Table Attributes Missing");

        // This method, will close the second tab and switches back to first tab and resumes the test.
        helpPage.switchBackTOMainApplication();

    }

    Global Method for Swicthing to second tab:

    public HelpPage switchToHelpPage() {
        String originalHandle = driver.getWindowHandle();
        try {
            TimeUnit.SECONDS.sleep(8);
        } catch (InterruptedException ignore) {
        }
        wait.until(ExpectedConditions.documentReady());
        wait.until(ExpectedConditions.isNotLoading());
        for (String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalHandle)) {
                driver.switchTo().window(handle);
            }
        }
        return new HelpPage(driver);
    }

    Global Method for closing the second tab and swicthing back to first tab.

    public boolean switchBackTOMainApplication() {
        boolean isValid = false;
        String originalHandle = driver.getWindowHandle();
        for (String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalHandle)) {
                driver.switchTo().window(handle);
            }
        }
        driver.close();
        driver.switchTo().window(originalHandle);
        return isValid;
    }
</code>```

Here is the problem i am facing. When "helpPage.switchBackTOMainApplication()" method is called its closing the first tab instead of switching to it. Is there any modification i need to do, which will close the second tab and continue the tests on first tab.

答:
When you click to link you should switch to opened tab and do your validation

```<code>public void switchToNextTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
    }
</code>```

After that, you should return to your main tab

```<code>public void switchTomainTab() {
    ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(tab.get(0));
}
</code>```

If you need to close opened tab and then return to the main tab use this

```<code>public void closeTabAndReturn() {
        driver.close();
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(0));
    }
</code>```

Body:
Using selenium web driver with java, i am trying to automate a functionality where i click on a link and it opens a new tab. I want to write a global method for first tab which when called in main test class switches to second tab. I have a separate method to do the assertions on second tab, after the assertions are complete. I want to write another global method which when called closed the second tab and switches back to the first one and resumes the tests on first window.

I have written the below methods and tests:

Main test:

@Test(enabled = true, dataProvider = "TestThis", description = "ClickThere", groups = {"hello" })

public void AttributeValidationOnHelpPage(TestData testData, String Id, String TableName) {

        menu.switch(Id);
        data = menu.clickData();
        data.selectNoneDateRange();
        TablePage = data.openTable(TableName);
        TablePage.clickAttTab();
        menuPage.clickOnHelpPage();

        // This method, when called will switch to second tab.
         helpPage = menu.switcToHelpPage();

        // After swicthing below is the assertions i want to do on the second tab.

        Assert.assertTrue(driver.getCurrentUrl().contains("Second page Url."));
        String actualValue = helpOnThisPage.getRefTableAttributes();
        Assert.assertEquals(actualValue, "Reference Table Attributes", "Reference Table Attributes Missing");

        // This method, will close the second tab and switches back to first tab and resumes the test.
        helpPage.switchBackTOMainApplication();

    }

    Global Method for Swicthing to second tab:

    public HelpPage switchToHelpPage() {
        String originalHandle = driver.getWindowHandle();
        try {
            TimeUnit.SECONDS.sleep(8);
        } catch (InterruptedException ignore) {
        }
        wait.until(ExpectedConditions.documentReady());
        wait.until(ExpectedConditions.isNotLoading());
        for (String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalHandle)) {
                driver.switchTo().window(handle);
            }
        }
        return new HelpPage(driver);
    }

    Global Method for closing the second tab and swicthing back to first tab.

    public boolean switchBackTOMainApplication() {
        boolean isValid = false;
        String originalHandle = driver.getWindowHandle();
        for (String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalHandle)) {
                driver.switchTo().window(handle);
            }
        }
        driver.close();
        driver.switchTo().window(originalHandle);
        return isValid;
    }

Here is the problem i am facing. When "helpPage.switchBackTOMainApplication()" method is called its closing the first tab instead of switching to it. Is there any modification i need to do, which will close the second tab and continue the tests on first tab.

Body:
When you click to link you should switch to opened tab and do your validation

public void switchToNextTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
    }

After that, you should return to your main tab

public void switchTomainTab() {
    ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(tab.get(0));
}

If you need to close opened tab and then return to the main tab use this

public void closeTabAndReturn() {
        driver.close();
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(0));
    }


问:
How to store result of simple python calculator in variable
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

```<code>num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")
</code>```

答: Whatever you do, this code will keep as result, the value of num3 = num1 * num2. You should put these lines in each if, elif </p>

Body:
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")


答:
Problem solved with this part of code (for future users who will read this :) )</p>

```<code>@foreach($categories as $category)

    <option value="{{ $category->id }}"

        @if($post->category->id == $category->id)

           selected

        @endif

    >{{ $category->name }}</option>

@endforeach
</code>```

Title: How can I get selected value in select dom element [Laravel]

Body:
Problem solved with this part of code (for future users who will read this :) )

@foreach($categories as $category)

    <option value="{{ $category->id }}"

        @if($post->category->id == $category->id)

           selected

        @endif

    >{{ $category->name }}</option>

@endforeach


问:
Main thread blocking on scroll and Kingfisher setting the image
I've been running down slow scroll performance and I've noticed that when I scroll and setImage gets called with non-cached images, the performance lags while the download happens.

```<code>if let imageURL = URL(string: presentable.imageUrl) {
    let resource = ImageResource(downloadURL: imageURL)
    photoView.kf.setImage(with: resource, options: [.transition(.fade(0.2))])
}
</code>```

My understanding is that Kingfisher downloads these on a background thread and then displays them on the main thread but the main thread seems to be temporarily blocked. Removing the .transition doesn't help the situation.

Any ideas on how to improve my scroll performance? Thanks

答:
Updating

```<code>self.imageView.contentMode = .scaleAspectFill
</code>```

to

```<code>self.imageView.contentMode = .scaleAspectFit
</code>```

did the trick for me.

I have embedded UICollectionView inside UITableViewCell. Each UICollectionViewCell has an image view which loads image from URL using Kingfisher. My table view scrolling was a lot jerky and I tried different things including not to bind model and setting data to each cell. But nothing made any difference whatsoever. Once I changed content mode of image view, it is now scrolling very smoothly.

As per Rob's answer, it is also possible that setting mode to .scaleAspectFill might be required to do some processing even-though the image size is smaller (even 480 x 320 in my case). After updating mode to .scaleAspectFit, now its scrolling smoothly even for large-sized images.

Body:
I've been running down slow scroll performance and I've noticed that when I scroll and setImage gets called with non-cached images, the performance lags while the download happens.

if let imageURL = URL(string: presentable.imageUrl) {
    let resource = ImageResource(downloadURL: imageURL)
    photoView.kf.setImage(with: resource, options: [.transition(.fade(0.2))])
}

My understanding is that Kingfisher downloads these on a background thread and then displays them on the main thread but the main thread seems to be temporarily blocked. Removing the .transition doesn't help the situation.

Any ideas on how to improve my scroll performance? Thanks

Body:
Updating

self.imageView.contentMode = .scaleAspectFill

to

self.imageView.contentMode = .scaleAspectFit

did the trick for me.

I have embedded UICollectionView inside UITableViewCell. Each UICollectionViewCell has an image view which loads image from URL using Kingfisher. My table view scrolling was a lot jerky and I tried different things including not to bind model and setting data to each cell. But nothing made any difference whatsoever. Once I changed content mode of image view, it is now scrolling very smoothly.

As per Rob's answer, it is also possible that setting mode to .scaleAspectFill might be required to do some processing even-though the image size is smaller (even 480 x 320 in my case). After updating mode to .scaleAspectFit, now its scrolling smoothly even for large-sized images.


问:
Perl weird behaviour in number with decimal point
So I was writing a perl program to do some calculation and
I had put a floating point number as

$x = 00.05;

if I print

print $x * 100.0;

It returns 500.0

But if I do

$x = 0.05;
 print $x * 100.0;

it prints correctly 5.0;

What is this behaviour?
Is there any convention I have to obey that I am missing?

答:
A leading zero means an octal constant, so when you do

```<code>my $x = 00.05;
</code>```

you actually do string concatenation of two octal numbers:

```<code>my $x = 00 . 05; # The same as "0" . "5"
</code>```

which gives you the string "05" and later you do

```<code>print $x * 100.0;  # prints 500
</code>```

since perl interprets as "05" as the number 5

Body:
A leading zero means an octal constant, so when you do

my $x = 00.05;

you actually do string concatenation of two octal numbers:

my $x = 00 . 05; # The same as "0" . "5"

which gives you the string "05" and later you do

print $x * 100.0;  # prints 500

since perl interprets as "05" as the number 5


问:
Create line chart with column titles on X axis
I want to create a line chart for a df with the following structure:

What I want the line chart to show is each contribution of the Participants per column. Meaning on the X-axis should be the column names of T1a_PlantTree_1 - T1a_PlantTree_6 and on the Y-axis the average contribution of all participants (In the df as PROLIFIC_PID)

The Y-axis can be in 0,20,40,60,80,100 steps but doesn't have to.

Resulting from this should be a diagram with a single line for the average contribution of each column that contains T1a_PlantTree_ in its name.

I'm new to R and still struggle with easy tasks. Thanks a lot for any help I get, it's appreciated!

I have tried the following code, but it resulted in 0 observations...

Further result of:
> dput(head(Treatment1a))

Best,
Luca

答:
Is this what you are looking for?

```<code>library(tidyverse)
df <- tibble::tribble(
        ~Px,~T1a_PlantTree_1,~T1a_PlantTree_2,~T1a_PlantTree_3,~T1a_PlantTree_4,~T1a_PlantTree_5,
                                       "P1" , 15 , 40 , 20 , 60 , 58,
                                       "P2" , 15 , 40 , 20 , 60 , 58,
                                       "P3" , 15 , 40 , 20 , 60 , 58,
                                       "P4" , 15 , 40 , 20 , 60 , 58
  )

df %>%
  pivot_longer(-Px, names_to = "Condition", values_to = "values") %>%
  group_by(Condition) %>%
  dplyr::summarise(mean_contribution = mean(values)) %>%
  ggplot(aes(x = Condition, y = mean_contribution, group = 1)) +
  geom_line()
</code>```

Body:
Is this what you are looking for?

library(tidyverse)
df <- tibble::tribble(
        ~Px,~T1a_PlantTree_1,~T1a_PlantTree_2,~T1a_PlantTree_3,~T1a_PlantTree_4,~T1a_PlantTree_5,
                                       "P1" , 15 , 40 , 20 , 60 , 58,
                                       "P2" , 15 , 40 , 20 , 60 , 58,
                                       "P3" , 15 , 40 , 20 , 60 , 58,
                                       "P4" , 15 , 40 , 20 , 60 , 58
  )

df %>%
  pivot_longer(-Px, names_to = "Condition", values_to = "values") %>%
  group_by(Condition) %>%
  dplyr::summarise(mean_contribution = mean(values)) %>%
  ggplot(aes(x = Condition, y = mean_contribution, group = 1)) +
  geom_line()


问:
Tesseract always missing a text line in picture
I am trying to extract data from a picture with OCR. I use Tesseract API in C++ to achieve this.

The original picture is this:

Now the for me important data is this:

However the marked blue line is never recognized does not matter what I try.

The code to analyze the picture with tesseract looks like this:

```<code>std::string readFromFile(const std::string& filename)
{
    tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
    api->SetPageSegMode(tesseract::PSM_AUTO);
    if (api->Init("folder_to_tessdata", "deu+eng")) {
        fprintf(stderr, "Could not initialize tesseract.\n");
        exit(1);
    }

    // Open input image with leptonica library
    Pix *image = pixRead(filename.c_str());
    api->SetImage(image);
    // Get OCR result

    char *outText = api->GetUTF8Text();

    std::string result{ outText };

    api->End();
    delete[] outText;
    pixDestroy(&image);

    return result;
}
</code>```

I tryed to improve the accuracy by preprocessing the image like it is suggested in this question: image processing to improve tesseract OCR accuracy

The Code for the preprocessing:

```<code>cv::Mat image;
image = cv::imread(filename, cv::IMREAD_COLOR);
cv::resize(image, image, cv::Size{}, 1.2, 1.2, cv::INTER_CUBIC);

cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);

auto kernel = cv::Mat(1, 1, CV_8UC1, cv::Scalar(1));
cv::dilate(image, image, kernel);
cv::erode(image, image, kernel);

cv::Mat filter;
cv::bilateralFilter(image, filter, 5, 75, 75);

cv::threshold(filter, image, 0, 255, cv::THRESH_BINARY + cv::THRESH_OTSU);
</code>```

Am I missing something? Can I tweak Tesseract itself more or should I change the preprocessing of the image?

答:
My reference is here.

Note: You don't need to deal with preprocess steps because it seems you already have a pure image. It doesn't have noises much.

My environment information:

```<code>Operating system: Ubuntu 16.04
</code>```

Tesseract version by the command of tesseract --version:

```<code>tesseract 4.1.1-rc2-21-gf4ef
 leptonica-1.78.0
  libgif 5.1.4 : libjpeg 8d (libjpeg-turbo 1.4.2) : libpng 1.2.54 : libtiff 4.0.6 : zlib 1.2.8 : libwebp 0.4.4 : libopenjp2 2.1.2
 Found AVX
 Found SSE
 Found libarchive 3.1.2
</code>```

OpenCV Version by the command of pkg-config --modversion opencv:

```<code>3.4.3
</code>```

Difference: When I checked your code, I have only seen the clear difference with this one. You are opening the image with leptonica library one more time instead of opencv.

Here is the code and resulted output:

Input:

Output texts:

```<code>Al AQ A3 Ad AS A6 Al A8

| 2 3 4 5 6 7 8

WH GN YE GY PK Bu RD VT
K101 K102 K103 K104 K105 K107 K109 K110
Q30,0 Q30.1 Q30.2 Q30.3 Q30.4 Q30.5 Q30.6 Q30.7
=13/L.2 =13/2.2 =13/4.2 =13/6.2 =13/7.2 =13/10.2 FIBL.2 = 1312.2

AS AlO All Al2 AL3 Al4 ALS AL6

9 10 ll 12 13 14 15 16
GY /PK RD/BU WH/GN BN/GN WH/YE YE/BN WH/GY GY/BN
Kl1l K112 y114 K115 K117 K118 K124
Q31,0 Q31.1 Q31.2 Q31.3 Q31.4 Q31.5 Q31.6 Q31.7
=13/13.2 =13/14.2 =13/15.2 =13/16.2 =1B7.2 PIB. =13/21.2

Beckhoff KL 2809
</code>```

Code:

```<code>#include <string>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
    string outText;

    // Create Tesseract object
    tesseract::TessBaseAPI *ocr = new tesseract::TessBaseAPI();

    ocr->Init(NULL, "eng", tesseract::OEM_LSTM_ONLY);

    // Set Page segmentation mode to PSM_AUTO (3)
    ocr->SetPageSegMode(tesseract::PSM_AUTO);

    // Open input image using OpenCV
    Mat im = cv::imread("/ur/image/directory/tessatest.png", IMREAD_COLOR);

    // Set image data
    ocr->SetImage(im.data, im.cols, im.rows, 3, im.step);

    // Run Tesseract OCR on image
    outText = string(ocr->GetUTF8Text());

    // print recognized text
    cout << outText << endl;

    // Destroy used object and release memory
    ocr->End();

    return EXIT_SUCCESS;
}
</code>```

The compilation of the code:

```<code>g++ -O3 -std=c++11 test.cpp -o output `pkg-config --cflags --libs tesseract opencv`
</code>```

Body:
I am trying to extract data from a picture with OCR. I use Tesseract API in C++ to achieve this.

The original picture is this:

Now the for me important data is this:

However the marked blue line is never recognized does not matter what I try.

The code to analyze the picture with tesseract looks like this:

std::string readFromFile(const std::string& filename)
{
    tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
    api->SetPageSegMode(tesseract::PSM_AUTO);
    if (api->Init("folder_to_tessdata", "deu+eng")) {
        fprintf(stderr, "Could not initialize tesseract.\n");
        exit(1);
    }

    // Open input image with leptonica library
    Pix *image = pixRead(filename.c_str());
    api->SetImage(image);
    // Get OCR result

    char *outText = api->GetUTF8Text();

    std::string result{ outText };

    api->End();
    delete[] outText;
    pixDestroy(&image);

    return result;
}

I tryed to improve the accuracy by preprocessing the image like it is suggested in this question: image processing to improve tesseract OCR accuracy

The Code for the preprocessing:

cv::Mat image;
image = cv::imread(filename, cv::IMREAD_COLOR);
cv::resize(image, image, cv::Size{}, 1.2, 1.2, cv::INTER_CUBIC);

cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);

auto kernel = cv::Mat(1, 1, CV_8UC1, cv::Scalar(1));
cv::dilate(image, image, kernel);
cv::erode(image, image, kernel);

cv::Mat filter;
cv::bilateralFilter(image, filter, 5, 75, 75);

cv::threshold(filter, image, 0, 255, cv::THRESH_BINARY + cv::THRESH_OTSU);

Am I missing something? Can I tweak Tesseract itself more or should I change the preprocessing of the image?

Body:
My reference is here.

Note: You don't need to deal with preprocess steps because it seems you already have a pure image. It doesn't have noises much.

My environment information:

Operating system: Ubuntu 16.04

Tesseract version by the command of tesseract --version:

tesseract 4.1.1-rc2-21-gf4ef
 leptonica-1.78.0
  libgif 5.1.4 : libjpeg 8d (libjpeg-turbo 1.4.2) : libpng 1.2.54 : libtiff 4.0.6 : zlib 1.2.8 : libwebp 0.4.4 : libopenjp2 2.1.2
 Found AVX
 Found SSE
 Found libarchive 3.1.2

OpenCV Version by the command of pkg-config --modversion opencv:

3.4.3

Difference: When I checked your code, I have only seen the clear difference with this one. You are opening the image with leptonica library one more time instead of opencv.

Here is the code and resulted output:

Input:

Output texts:

Al AQ A3 Ad AS A6 Al A8

| 2 3 4 5 6 7 8

WH GN YE GY PK Bu RD VT
K101 K102 K103 K104 K105 K107 K109 K110
Q30,0 Q30.1 Q30.2 Q30.3 Q30.4 Q30.5 Q30.6 Q30.7
=13/L.2 =13/2.2 =13/4.2 =13/6.2 =13/7.2 =13/10.2 FIBL.2 = 1312.2

AS AlO All Al2 AL3 Al4 ALS AL6

9 10 ll 12 13 14 15 16
GY /PK RD/BU WH/GN BN/GN WH/YE YE/BN WH/GY GY/BN
Kl1l K112 y114 K115 K117 K118 K124
Q31,0 Q31.1 Q31.2 Q31.3 Q31.4 Q31.5 Q31.6 Q31.7
=13/13.2 =13/14.2 =13/15.2 =13/16.2 =1B7.2 PIB. =13/21.2

Beckhoff KL 2809

Code:

#include <string>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
    string outText;

    // Create Tesseract object
    tesseract::TessBaseAPI *ocr = new tesseract::TessBaseAPI();

    ocr->Init(NULL, "eng", tesseract::OEM_LSTM_ONLY);

    // Set Page segmentation mode to PSM_AUTO (3)
    ocr->SetPageSegMode(tesseract::PSM_AUTO);

    // Open input image using OpenCV
    Mat im = cv::imread("/ur/image/directory/tessatest.png", IMREAD_COLOR);

    // Set image data
    ocr->SetImage(im.data, im.cols, im.rows, 3, im.step);

    // Run Tesseract OCR on image
    outText = string(ocr->GetUTF8Text());

    // print recognized text
    cout << outText << endl;

    // Destroy used object and release memory
    ocr->End();

    return EXIT_SUCCESS;
}

The compilation of the code:

g++ -O3 -std=c++11 test.cpp -o output `pkg-config --cflags --libs tesseract opencv`


问:
ScrollView stacked with another page
The issue is the background of my scrollview is somewhat have pretty same content as my scroll view. i have try looking but can't found the problem, because every place tell that i just have to place the content into the scrollview. Please Help!

The design of the layout

This is my layout code

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/category_rv"
        android:layout_width="match_parent"
        android:background="@color/colorAccent"
        android:elevation="3dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
            <LinearLayout
                android:id="@+id/LinearLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/category_rv">

                <include layout="@layout/horizontal_scroll_layout" />
            </LinearLayout>
            <LinearLayout
                android:id="@+id/LinearLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/LinearLayout">

                <include layout="@layout/sliding_ad_layout" />
            </LinearLayout>
            <LinearLayout
                android:id="@+id/LinearLayout2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/LinearLayout1">

                <include layout="@layout/grid_product_layout" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Add constraints to your scroll view, not to LinearLayout  </p>

```<code> <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/category_rv">
</code>```

Title: ScrollView stacked with another page

Body:
The issue is the background of my scrollview is somewhat have pretty same content as my scroll view. i have try looking but can't found the problem, because every place tell that i just have to place the content into the scrollview. Please Help!

The design of the layout

This is my layout code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/category_rv"
        android:layout_width="match_parent"
        android:background="@color/colorAccent"
        android:elevation="3dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
            <LinearLayout
                android:id="@+id/LinearLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/category_rv">

                <include layout="@layout/horizontal_scroll_layout" />
            </LinearLayout>
            <LinearLayout
                android:id="@+id/LinearLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/LinearLayout">

                <include layout="@layout/sliding_ad_layout" />
            </LinearLayout>
            <LinearLayout
                android:id="@+id/LinearLayout2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/LinearLayout1">

                <include layout="@layout/grid_product_layout" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Add constraints to your scroll view, not to LinearLayout

 <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/category_rv">


问:
Seaborn showing x-tick labels overlapping
I am trying to make a box plot that looks like this.

Now, there are a lot of tickmarks that I do not need and truly do not show any additional information.
The code I am using is the following:

```<code>plot=sns.boxplot(y=MSE, x=Sim,
                   width=0.5,
                   palette='colorblind')
plot=sns.stripplot(y=MSE, x=Sim,
                  jitter=True,
                  marker='o',
                  alpha=0.15,
                  color='black')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.gca().invert_xaxis()
</code>```

Where MSE and SIM are two numpy arrays of 400 elements each.

I reviewed some solutions that use locator_params and set_xticklabels. However, I want to know:

why this happen and,

is there a simple transformation in the MSE and SIM arrays to solve this?

I hope my questions are clear enough.

Thanks in advance.

答:
Not very sure what you have as Sim, if it is an array of floats, then they are converted to categorical before plotting. The thing you can do, since the labels are not useful, is to use a range of values thats as long as the y-values.

With that, it still overlaps a lot because you are trying to fit 400 x ticks onto the x-axis, and the font size are set by default to be something readable. For example:

```<code>import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
fig,ax = plt.subplots(figsize=(15,6))

MSE = [np.random.normal(0,1,10) for i in range(100)]
Sim = np.arange(len(MSE))
g = sns.boxplot(y=MSE, x=Sim, width=0.5,palette='colorblind',ax=ax)
</code>```

You can set the font size to be smaller and they don't overlap but I guess its hardly readable:

So like you said in your case, they are not useful, you can do:

```<code>ax.set(xticks=Sim[0::10])
</code>```

Body:
I am trying to make a box plot that looks like this.

Now, there are a lot of tickmarks that I do not need and truly do not show any additional information.
The code I am using is the following:

plot=sns.boxplot(y=MSE, x=Sim,
                   width=0.5,
                   palette='colorblind')
plot=sns.stripplot(y=MSE, x=Sim,
                  jitter=True,
                  marker='o',
                  alpha=0.15,
                  color='black')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.gca().invert_xaxis()

Where MSE and SIM are two numpy arrays of 400 elements each.

I reviewed some solutions that use locator_params and set_xticklabels. However, I want to know:

why this happen and,

is there a simple transformation in the MSE and SIM arrays to solve this?

I hope my questions are clear enough.

Thanks in advance.

Body:
Not very sure what you have as Sim, if it is an array of floats, then they are converted to categorical before plotting. The thing you can do, since the labels are not useful, is to use a range of values thats as long as the y-values.

With that, it still overlaps a lot because you are trying to fit 400 x ticks onto the x-axis, and the font size are set by default to be something readable. For example:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
fig,ax = plt.subplots(figsize=(15,6))

MSE = [np.random.normal(0,1,10) for i in range(100)]
Sim = np.arange(len(MSE))
g = sns.boxplot(y=MSE, x=Sim, width=0.5,palette='colorblind',ax=ax)

You can set the font size to be smaller and they don't overlap but I guess its hardly readable:

So like you said in your case, they are not useful, you can do:

ax.set(xticks=Sim[0::10])


问:
For-Each Loop AS3: Is the direction guaranteed?
I would like to know the iteration order for the Array, Dictionary and Object types in AS3, for both the for-each and the for-in loops. Also what factors can change the iteration order of these loop type combinations?

For example I presume that using a for-each on an Array type always move from the first element to the last. For-each cannot be used on a Dictionary so how is the order determined using a for-in loop?

答:
As stated in Essential Actionscript 3.0 by Colin Moock, the order of a for each in loop is not guaranteed unless enumerating an XML or XMLList object;

Click here for Colin Moock's words from his book.

There are workarounds as discussed here, but honestly if you need to guarantee the order then just use a regular old for loop and have it iterate (length, numChildren, etc.) number of times.

OwnerDisplayName: Brian Heylin

LastEditorDisplayName: Brian Heylin

OwnerDisplayName: Brian Hodge


问:
Check if we can travel from source to destination
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

```<code>N = 3
First boat services : 1 2
Second boat services: 2 3
</code>```

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

```<code>public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }
</code>```

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

```<code>public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}
</code>```

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

答:
The problem you want to solve is a typycal problem on which you could apply dfs algorithm. Here is a first approach:

```<code>public class GrafDirLlistes {
ArrayList<Adj>[] elArray; //This is where we store the adjacent vertex to the current vertex

    boolean[] visitOrder;
    int[] path;

    public GrafDirLlistes(int numVert) {
        elArray = new ArrayList[numVert];
        for (int i = 0; i < elArray.length; i++) {
            elArray[i] = new ArrayList();
        }
    }

public boolean existeixAresta(int v_orig, int v_desti) { //Method to check wheter an edge exists
        if (v_orig < 0 || v_orig >= elArray.length) {
            return false;
        }

        for (int i = v_orig; i < elArray[v_orig].size(); i++) {
            if (elArray[v_orig].get(i).vertDest == v_desti) {
                return true;
            }
        }
        return false;
    }
    public boolean afegirAresta(int v_orig, int v_dest, double pes) { // Method to add a new edge

        if (v_orig < 0 || v_orig >= elArray.length || v_dest < 0 || v_dest >= elArray.length) {
            return false;
        }

        if (existeixAresta(v_orig, v_dest)) {
            return false;
        }

        elArray[v_orig].add(new Adj(v_dest, pes));
        return true;
    }
</code>```

Up there we create a graph, putting them in an array of arraylist. The function of the array is to see which are the adjacent vertex. For example, if we have a graph in which 0 points to 1, elArray[0] will have an ArrayList with only 1 element, the 1, that is the vertex 0 is pointing to.
The Adj class

```<code>public class Adj {

    public int vertDest;
    public double weight;

    public Adj(int v, double p) {
        vertDest = v;
        weight = p;
    }

}

</code>```

Dfs method:

```<code>    public void dfs() {
        visitOrder = new boolean[elArray.length];
        path = new int[elArray.length];
        for (int v = 0; v < elArray.length; v++) {
            path[v] = -1;
        }

        for (int v = 0; v < elArray.length; v++) {
            if (!visitOrder[v]) {
                dfs(v);
            }
        }
    }

    private void dfs(int orig) {
        visitOrder[orig] = true;

        for (int i = 0; i < elArray[i].size(); i++) {
            int v_dest = elArray[orig].get(i).vertDest;
            if (!visitOrder[v_dest]) {
                path[v_dest] = orig;
                dfs(v_dest);
            }
        }
    }
</code>```

Now, when you finish dfs(), you only have to check path array, here will be stored if a path exists from x to y

Body:
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

N = 3
First boat services : 1 2
Second boat services: 2 3

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

Body:
The problem you want to solve is a typycal problem on which you could apply dfs algorithm. Here is a first approach:

public class GrafDirLlistes {
ArrayList<Adj>[] elArray; //This is where we store the adjacent vertex to the current vertex

    boolean[] visitOrder;
    int[] path;

    public GrafDirLlistes(int numVert) {
        elArray = new ArrayList[numVert];
        for (int i = 0; i < elArray.length; i++) {
            elArray[i] = new ArrayList();
        }
    }

public boolean existeixAresta(int v_orig, int v_desti) { //Method to check wheter an edge exists
        if (v_orig < 0 || v_orig >= elArray.length) {
            return false;
        }

        for (int i = v_orig; i < elArray[v_orig].size(); i++) {
            if (elArray[v_orig].get(i).vertDest == v_desti) {
                return true;
            }
        }
        return false;
    }
    public boolean afegirAresta(int v_orig, int v_dest, double pes) { // Method to add a new edge

        if (v_orig < 0 || v_orig >= elArray.length || v_dest < 0 || v_dest >= elArray.length) {
            return false;
        }

        if (existeixAresta(v_orig, v_dest)) {
            return false;
        }

        elArray[v_orig].add(new Adj(v_dest, pes));
        return true;
    }

Up there we create a graph, putting them in an array of arraylist. The function of the array is to see which are the adjacent vertex. For example, if we have a graph in which 0 points to 1, elArray[0] will have an ArrayList with only 1 element, the 1, that is the vertex 0 is pointing to.
The Adj class

public class Adj {

    public int vertDest;
    public double weight;

    public Adj(int v, double p) {
        vertDest = v;
        weight = p;
    }

}

Dfs method:

    public void dfs() {
        visitOrder = new boolean[elArray.length];
        path = new int[elArray.length];
        for (int v = 0; v < elArray.length; v++) {
            path[v] = -1;
        }

        for (int v = 0; v < elArray.length; v++) {
            if (!visitOrder[v]) {
                dfs(v);
            }
        }
    }

    private void dfs(int orig) {
        visitOrder[orig] = true;

        for (int i = 0; i < elArray[i].size(); i++) {
            int v_dest = elArray[orig].get(i).vertDest;
            if (!visitOrder[v_dest]) {
                path[v_dest] = orig;
                dfs(v_dest);
            }
        }
    }

Now, when you finish dfs(), you only have to check path array, here will be stored if a path exists from x to y


问:
Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
When I try to start my app on Heroku I got the following stack trace.
It is just a basic ts.app like you see with ts-node and nodemon.

I am really interested in what the answer is going to be.

```<code>2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting process with command `npm start`
2020-05-30T00:03:14.405285+00:00 app[web.1]:
2020-05-30T00:03:14.405303+00:00 app[web.1]: > discordtoornamentmanager@1.0.0 start /app
2020-05-30T00:03:14.405303+00:00 app[web.1]: > ts-node src/App.ts
2020-05-30T00:03:14.405304+00:00 app[web.1]:
2020-05-30T00:03:14.833655+00:00 app[web.1]: (node:23) ExperimentalWarning: The ESM module loader is experimental.
2020-05-30T00:03:14.839311+00:00 app[web.1]: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
2020-05-30T00:03:14.839312+00:00 app[web.1]:     at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
2020-05-30T00:03:14.839314+00:00 app[web.1]:     at Loader.getFormat (internal/modules/esm/loader.js:113:42)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-05-30T00:03:14.839316+00:00 app[web.1]:     at Loader.import (internal/modules/esm/loader.js:178:17)
2020-05-30T00:03:14.847801+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-05-30T00:03:14.847998+00:00 app[web.1]: npm ERR! errno 1
2020-05-30T00:03:14.848957+00:00 app[web.1]: npm ERR! discordtoornamentmanager@1.0.0 start: `ts-node src/App.ts`
2020-05-30T00:03:14.849050+00:00 app[web.1]: npm ERR! Exit status 1
2020-05-30T00:03:14.849172+00:00 app[web.1]: npm ERR!
2020-05-30T00:03:14.849254+00:00 app[web.1]: npm ERR! Failed at the discordtoornamentmanager@1.0.0 start script.
2020-05-30T00:03:14.849337+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-05-30T00:03:14.854859+00:00 app[web.1]:
2020-05-30T00:03:14.854998+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-05-30T00:03:14.855069+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-05-30T00_03_14_850Z-debug.log
2020-05-30T00:03:14.907689+00:00 heroku[web.1]: Process exited with status 1
2020-05-30T00:03:14.943718+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

This is my package.json

```<code>{
   "name": "discordtoornamentmanager",
   "version": "1.0.0",
   "description": "",
   "main": "dist/app.js",
   "type": "module",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "dev": "nodemon -x ts-node src/App.ts",
      "start": "ts-node src/App.ts"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
      "@types/node": "^14.0.5",
      "axios": "^0.19.2",
      "discord.js": "^12.2.0",
      "pg": "^8.2.1",
      "reflect-metadata": "^0.1.10",
      "typeorm": "0.2.25",
      "typescript": "^3.9.3",
      "nodemon": "^2.0.4",
      "ts-node": "8.10.1"

   }
}
</code>```

And this is my tsconfig

```<code>{
   "compilerOptions": {
      "lib": [
         "es6"
      ],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "dist",
      "resolveJsonModule": true,
      "emitDecoratorMetadata": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "include": ["src/**/*.ts"],
   "exclude": ["node_modules", "**/*.spec.ts"]
}
</code>```

答:
Remove "type": "module" from package.json

https://github.com/TypeStrong/ts-node/issues/935

https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-1163471306

If you don't want to remove "type": "module" (for example if you're using import statements in your .ts which allows the inference of types from modules), then you can use the following option in tsconfig.json:

```<code>{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}
</code>```

And then you can start the server with the config using ts-node.

Install:

```<code>npm install -g ts-node
</code>```

Run:

```<code>ts-node-esm my_server.ts
</code>```

Body:
When I try to start my app on Heroku I got the following stack trace.
It is just a basic ts.app like you see with ts-node and nodemon.

I am really interested in what the answer is going to be.

2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting process with command `npm start`
2020-05-30T00:03:14.405285+00:00 app[web.1]:
2020-05-30T00:03:14.405303+00:00 app[web.1]: > discordtoornamentmanager@1.0.0 start /app
2020-05-30T00:03:14.405303+00:00 app[web.1]: > ts-node src/App.ts
2020-05-30T00:03:14.405304+00:00 app[web.1]:
2020-05-30T00:03:14.833655+00:00 app[web.1]: (node:23) ExperimentalWarning: The ESM module loader is experimental.
2020-05-30T00:03:14.839311+00:00 app[web.1]: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
2020-05-30T00:03:14.839312+00:00 app[web.1]:     at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
2020-05-30T00:03:14.839314+00:00 app[web.1]:     at Loader.getFormat (internal/modules/esm/loader.js:113:42)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
2020-05-30T00:03:14.839315+00:00 app[web.1]:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-05-30T00:03:14.839316+00:00 app[web.1]:     at Loader.import (internal/modules/esm/loader.js:178:17)
2020-05-30T00:03:14.847801+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-05-30T00:03:14.847998+00:00 app[web.1]: npm ERR! errno 1
2020-05-30T00:03:14.848957+00:00 app[web.1]: npm ERR! discordtoornamentmanager@1.0.0 start: `ts-node src/App.ts`
2020-05-30T00:03:14.849050+00:00 app[web.1]: npm ERR! Exit status 1
2020-05-30T00:03:14.849172+00:00 app[web.1]: npm ERR!
2020-05-30T00:03:14.849254+00:00 app[web.1]: npm ERR! Failed at the discordtoornamentmanager@1.0.0 start script.
2020-05-30T00:03:14.849337+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-05-30T00:03:14.854859+00:00 app[web.1]:
2020-05-30T00:03:14.854998+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-05-30T00:03:14.855069+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-05-30T00_03_14_850Z-debug.log
2020-05-30T00:03:14.907689+00:00 heroku[web.1]: Process exited with status 1
2020-05-30T00:03:14.943718+00:00 heroku[web.1]: State changed from starting to crashed

This is my package.json

{
   "name": "discordtoornamentmanager",
   "version": "1.0.0",
   "description": "",
   "main": "dist/app.js",
   "type": "module",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "dev": "nodemon -x ts-node src/App.ts",
      "start": "ts-node src/App.ts"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
      "@types/node": "^14.0.5",
      "axios": "^0.19.2",
      "discord.js": "^12.2.0",
      "pg": "^8.2.1",
      "reflect-metadata": "^0.1.10",
      "typeorm": "0.2.25",
      "typescript": "^3.9.3",
      "nodemon": "^2.0.4",
      "ts-node": "8.10.1"

   }
}

And this is my tsconfig

{
   "compilerOptions": {
      "lib": [
         "es6"
      ],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "dist",
      "resolveJsonModule": true,
      "emitDecoratorMetadata": true,
      "esModuleInterop": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "include": ["src/**/*.ts"],
   "exclude": ["node_modules", "**/*.spec.ts"]
}

Body:
Remove "type": "module" from package.json

https://github.com/TypeStrong/ts-node/issues/935

https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-1163471306

If you don't want to remove "type": "module" (for example if you're using import statements in your .ts which allows the inference of types from modules), then you can use the following option in tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}

And then you can start the server with the config using ts-node.

Install:

npm install -g ts-node

Run:

ts-node-esm my_server.ts