问:
Best way to integrate Angular2+ into ASP.Net MVC 4
I'm working with an old Asp.Net Framework 4 legacy system. The employer wants me to integrate Angular inside of it to use components within the currently existing site. I know it is possible, but I've only ever worked on SPAs as their own sites, never as additions.

I would like information on how to integrate Angular into Asp.Net, specifically how to add npm, how to render the components, and how to run it locally.

Any help is always appreciated.

答:
TLDR: Build a ng project within your ASP.Net project directory and then add a webpack config to compile your typescript files into JavaScript. After that just add the webpack build/watch command as part of the visual studio build events.

Long Explanation:

Navigate to your ASP.Net project directory

Add a ng project using the Angular CLI ng create project_name

Create a webpack.config.js file in your Angular project directory and download the appropriate loaders and presets you would like to use. (I.E. typescript-loader, babel-loader, etc.)

Set npm scripts within your packages.json file to run webpack on command

Right click on your ASP.Net project and select properties->build events

Type in your npm script (with the appropriate directories added) into the pre-build event. This will run webpack when you press the visual studio start button.

I think this configuration works really well, but I would like to fine tune it to make it idiot-proof. Right now it would be very easy for a new developer to screw up the webpack commands or forget to add the build event script.


来源: stackexchange

问:
where to run commands on mysql
I work on a java project using mysql as database, at some level I needed to increase  the value of max_allowed_packet variable, I checked in the net but I can't find my.cnf or my.ini.
So I need to run some recommended command such as set global max_allowed_packet=33554432 but I do not know where to find the terminal to do that.
I am using mySql 8.0 on windows 10

答:
The default location for mysql.exe is C:\Program Files\MySQL\MySQL Server 8.0\bin.

In the same directory you will find mysqladmin.exe, which gives a clue about where my.cnf of my.ini is:

mysqladmin | findstr "my.ini"

If the my.cnf or my.ini if not found at above locations, it is probably in the datadir

mysqladmin variables -u root -p | findstr datadir

ContentLicense: CC BY-SA 4.0

Title: where to run commands on mysql


问:
LIMIT Postgres DELETE
Simple DELETE with safety LIMIT throws a syntax error:

```<code>DELETE FROM system."products" LIMIT 1
</code>```

ERROR: Syntax ERROR at "LIMIT"

SQL state: 42601

How do I limit the amount of rows to delete?

(PostgresSQL version 9.6)

答:
You can use LIMIT only in the SELECT statement.

Try this:

```<code>DELETE FROM system."products" WHERE id IN (SELECT id FROM system."products" LIMIT 1)

</code>```

Otherwise you can have something like this

```<code>DELETE FROM system."products" WHERE id bewteen ? and ?
</code>```

Obviously this can work only if there is in your table an unique column (named id in my examples)!

Title: LIMIT Postgres DELETE

Body:
Simple DELETE with safety LIMIT throws a syntax error:

DELETE FROM system."products" LIMIT 1

ERROR: Syntax ERROR at "LIMIT"

SQL state: 42601

How do I limit the amount of rows to delete?

(PostgresSQL version 9.6)

Body:
You can use LIMIT only in the SELECT statement.

Try this:

DELETE FROM system."products" WHERE id IN (SELECT id FROM system."products" LIMIT 1)

Otherwise you can have something like this

DELETE FROM system."products" WHERE id bewteen ? and ?

Obviously this can work only if there is in your table an unique column (named id in my examples)!


问:
File permission displayed a lot question marks in docker container
I wrote a Dockerfile, the last contents are

```<code>RUN echo "root:root" | chpasswd
RUN echo "beakerx:beakerx" | chpasswd
RUN usermod -aG sudo beakerx

RUN echo beakerx | sudo -S chown -R beakerx:beakerx /home/beakerx/.local
RUN echo beakerx | sudo -S find /home/beakerx/.local -type d -exec chmod 755 {} \;
RUN echo beakerx | sudo -S find /home/beakerx/.local -type f -exec chmod 644 {} \;

RUN id
RUN ls -la /home/beakerx/.local
RUN ls -la /home/beakerx/.local/share

USER beakerx

RUN id
RUN ls -la /home/beakerx/.local
RUN ls -la /home/beakerx/.local/share
</code>```

When I build this image, it gave me the following errors.

```<code>Step 17/29 : RUN echo "root:root" | chpasswd
 ---> Running in b07756b764ef
 ---> 11a182191463
Removing intermediate container b07756b764ef
Step 18/29 : RUN echo "beakerx:beakerx" | chpasswd
 ---> Running in 2f2bc836b1af
 ---> dee6ebdf5b9c
Removing intermediate container 2f2bc836b1af
Step 19/29 : RUN usermod -aG sudo beakerx
 ---> Running in 8a1ccfffd565
 ---> d7815406e070
Removing intermediate container 8a1ccfffd565
Step 20/29 : RUN echo beakerx | sudo -S chown -R beakerx:beakerx /home/beakerx/.local
 ---> Running in 19aebc73f517
 ---> a8cb84a563c5
Removing intermediate container 19aebc73f517
Step 21/29 : RUN echo beakerx | sudo -S find /home/beakerx/.local -type d -exec chmod 755 {} \;
 ---> Running in 7c2434fa279a
 ---> 5ce4b0b0e859
Removing intermediate container 7c2434fa279a
Step 22/29 : RUN echo beakerx | sudo -S find /home/beakerx/.local -type f -exec chmod 644 {} \;
 ---> Running in 5f57457f1fe5
 ---> 1bb42b3ef8f3
Removing intermediate container 5f57457f1fe5
Step 23/29 : RUN id
 ---> Running in 101209499f50
uid=0(root) gid=0(root) groups=0(root)
 ---> e45945b090ab
Removing intermediate container 101209499f50
Step 24/29 : RUN ls -la /home/beakerx/.local
 ---> Running in d337b58c1571
total 12
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 25 beakerx beakerx 4096 Sep  7 01:30 ..
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 share
 ---> 7fd474369e15
Removing intermediate container d337b58c1571
Step 25/29 : RUN ls -la /home/beakerx/.local/share
 ---> Running in e05cd55aaae6
total 12
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 ..
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 jupyter
 ---> 03191c2d9fc8
Removing intermediate container e05cd55aaae6
Step 26/29 : USER beakerx
 ---> Running in 40b2d522ea0f
 ---> 604503b2152b
Removing intermediate container 40b2d522ea0f
Step 27/29 : RUN id
 ---> Running in e7b8ed6a1165
uid=1000(beakerx) gid=1000(beakerx) groups=1000(beakerx),27(sudo)
 ---> 5987e9d9f0bb
Removing intermediate container e7b8ed6a1165
Step 28/29 : RUN ls -la /home/beakerx/.local
 ---> Running in 4c65bd4a383e
ls: cannot access '/home/beakerx/.local/share': Permission denied
total 8
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 25 beakerx beakerx 4096 Sep  7 01:30 ..
d?????????  ? ?       ?          ?            ? share
ERROR: Service 'beakerx-cling-prebuild' failed to build: The command '/bin/sh -c ls -la /home/beakerx/.local' returned a non-zero code: 1
</code>```

That's quite strange, I can see the right permission using root, but a lot of question marks using other users. When I removed these debugging code and run this docker image, it gave me PermissionError: [Errno 13] Permission denied: '/home/beakerx/.local/share/jupyter/runtime' errors.

I have searched a lot on the Internet, but couldn't found some helpful info about this.

答:
This is a very weird bug in older docker versions. It happens if the first user that access the directory is non-root. Just change the order of the commands to access the dir as user.

Run something like  ls /home/beakerx/, before issuing USER beakerx.

It worked for me.

Body:
I wrote a Dockerfile, the last contents are

RUN echo "root:root" | chpasswd
RUN echo "beakerx:beakerx" | chpasswd
RUN usermod -aG sudo beakerx

RUN echo beakerx | sudo -S chown -R beakerx:beakerx /home/beakerx/.local
RUN echo beakerx | sudo -S find /home/beakerx/.local -type d -exec chmod 755 {} \;
RUN echo beakerx | sudo -S find /home/beakerx/.local -type f -exec chmod 644 {} \;

RUN id
RUN ls -la /home/beakerx/.local
RUN ls -la /home/beakerx/.local/share

USER beakerx

RUN id
RUN ls -la /home/beakerx/.local
RUN ls -la /home/beakerx/.local/share

When I build this image, it gave me the following errors.

Step 17/29 : RUN echo "root:root" | chpasswd
 ---> Running in b07756b764ef
 ---> 11a182191463
Removing intermediate container b07756b764ef
Step 18/29 : RUN echo "beakerx:beakerx" | chpasswd
 ---> Running in 2f2bc836b1af
 ---> dee6ebdf5b9c
Removing intermediate container 2f2bc836b1af
Step 19/29 : RUN usermod -aG sudo beakerx
 ---> Running in 8a1ccfffd565
 ---> d7815406e070
Removing intermediate container 8a1ccfffd565
Step 20/29 : RUN echo beakerx | sudo -S chown -R beakerx:beakerx /home/beakerx/.local
 ---> Running in 19aebc73f517
 ---> a8cb84a563c5
Removing intermediate container 19aebc73f517
Step 21/29 : RUN echo beakerx | sudo -S find /home/beakerx/.local -type d -exec chmod 755 {} \;
 ---> Running in 7c2434fa279a
 ---> 5ce4b0b0e859
Removing intermediate container 7c2434fa279a
Step 22/29 : RUN echo beakerx | sudo -S find /home/beakerx/.local -type f -exec chmod 644 {} \;
 ---> Running in 5f57457f1fe5
 ---> 1bb42b3ef8f3
Removing intermediate container 5f57457f1fe5
Step 23/29 : RUN id
 ---> Running in 101209499f50
uid=0(root) gid=0(root) groups=0(root)
 ---> e45945b090ab
Removing intermediate container 101209499f50
Step 24/29 : RUN ls -la /home/beakerx/.local
 ---> Running in d337b58c1571
total 12
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 25 beakerx beakerx 4096 Sep  7 01:30 ..
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 share
 ---> 7fd474369e15
Removing intermediate container d337b58c1571
Step 25/29 : RUN ls -la /home/beakerx/.local/share
 ---> Running in e05cd55aaae6
total 12
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 ..
drwxr-xr-x 6 beakerx beakerx 4096 Sep  7 01:30 jupyter
 ---> 03191c2d9fc8
Removing intermediate container e05cd55aaae6
Step 26/29 : USER beakerx
 ---> Running in 40b2d522ea0f
 ---> 604503b2152b
Removing intermediate container 40b2d522ea0f
Step 27/29 : RUN id
 ---> Running in e7b8ed6a1165
uid=1000(beakerx) gid=1000(beakerx) groups=1000(beakerx),27(sudo)
 ---> 5987e9d9f0bb
Removing intermediate container e7b8ed6a1165
Step 28/29 : RUN ls -la /home/beakerx/.local
 ---> Running in 4c65bd4a383e
ls: cannot access '/home/beakerx/.local/share': Permission denied
total 8
drwxr-xr-x  6 beakerx beakerx 4096 Sep  7 01:30 .
drwxr-xr-x 25 beakerx beakerx 4096 Sep  7 01:30 ..
d?????????  ? ?       ?          ?            ? share
ERROR: Service 'beakerx-cling-prebuild' failed to build: The command '/bin/sh -c ls -la /home/beakerx/.local' returned a non-zero code: 1

That's quite strange, I can see the right permission using root, but a lot of question marks using other users. When I removed these debugging code and run this docker image, it gave me PermissionError: [Errno 13] Permission denied: '/home/beakerx/.local/share/jupyter/runtime' errors.

I have searched a lot on the Internet, but couldn't found some helpful info about this.


问:
jira rest-api attach file to issue using powershell
I want to attach a file to an jira issue , i am able to do it with postman, but have tried several ways without break through.
my code looks like this

```<code>function ConvertTo-Base64($string) {
$bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}

function Get-HttpBasicHeader([string]$username, [string]$password, $Headers = @{}) {
    $b64 = ConvertTo-Base64 "$($username):$($Password)"
    $Headers["Authorization"] = "Basic $b64"
    $Headers["X-Atlassian-Token"] = "nocheck"
return $Headers
}

$restapiuri = "https://xxxx.xxxx.com/rest/api//2/issue/test-8442/attachments"
$headers = Get-HttpBasicHeader "xxxxxx" "xxxxxxxx"

$myfile = "C:\TEMP\out.txt"
$fileBytes = [System.IO.File]::ReadAllBytes($myfile);
$fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
$boundary = [guid]::NewGuid().ToString()
$LF = "`r`n";

$body = '(
            "--$boundary",
            "Content-Disposition: form-data; name=`"fil`"; filename=`"out.txt`"",
            "Content-Type: application/octet-stream$LF",
            $fileEnc,
            "--$boundary--$LF"
           ) -join $LF

 '

Invoke-RestMethod -uri $restapiuri  -Headers $headers  -Method POST -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $body
</code>```

In postman i am doing a post request with
Authorization
Basic Auth
headers
header X-Atlassian-Token = o-check
Content-Type = multipart/form-data
Body form-data
key     value
file    filepath

The powershell doesn't return any errors, but it does not attach any file either
I have tried several examples without luck so if any of you have any ideas on have to do this in powershell i would be glad.

I am on powershell version

Major  Minor  Build  Revision

5      1      14409  1018

答:
I found the following that looks to be a good fit for this scenario.

```<code>function Upload-JiraFile($jiraTicket, $filepath, $authorization)
{
    $wc = new-object System.Net.WebClient
    $wc.Headers.Add("Authorization", $authorization)
    $wc.Headers.Add("X-Atlassian-Token", "nocheck")
    $wc.UploadFile("$URIPath/issue/$jiraTicket/attachments", $filepath)
}
</code>```

Here is how you could use it with the bare minimal modification to the code you have today:

```<code>$URIPath = "https://xxxx.xxxx.com/rest/api/2"
Upload-JiraFile -JiraTicket test-8442 -FilePath c:\temp\MyJpg.jpg `
   -Authorization $Headers["Authorization"]
</code>```

Excerpted from this thread.

Body:
I want to attach a file to an jira issue , i am able to do it with postman, but have tried several ways without break through.
my code looks like this

function ConvertTo-Base64($string) {
$bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}

function Get-HttpBasicHeader([string]$username, [string]$password, $Headers = @{}) {
    $b64 = ConvertTo-Base64 "$($username):$($Password)"
    $Headers["Authorization"] = "Basic $b64"
    $Headers["X-Atlassian-Token"] = "nocheck"
return $Headers
}

$restapiuri = "https://xxxx.xxxx.com/rest/api//2/issue/test-8442/attachments"
$headers = Get-HttpBasicHeader "xxxxxx" "xxxxxxxx"

$myfile = "C:\TEMP\out.txt"
$fileBytes = [System.IO.File]::ReadAllBytes($myfile);
$fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
$boundary = [guid]::NewGuid().ToString()
$LF = "`r`n";

$body = '(
            "--$boundary",
            "Content-Disposition: form-data; name=`"fil`"; filename=`"out.txt`"",
            "Content-Type: application/octet-stream$LF",
            $fileEnc,
            "--$boundary--$LF"
           ) -join $LF

 '

Invoke-RestMethod -uri $restapiuri  -Headers $headers  -Method POST -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $body

In postman i am doing a post request with
Authorization
Basic Auth
headers
header X-Atlassian-Token = o-check
Content-Type = multipart/form-data
Body form-data
key     value
file    filepath

The powershell doesn't return any errors, but it does not attach any file either
I have tried several examples without luck so if any of you have any ideas on have to do this in powershell i would be glad.

I am on powershell version

Major  Minor  Build  Revision

5      1      14409  1018

Body:
I found the following that looks to be a good fit for this scenario.

function Upload-JiraFile($jiraTicket, $filepath, $authorization)
{
    $wc = new-object System.Net.WebClient
    $wc.Headers.Add("Authorization", $authorization)
    $wc.Headers.Add("X-Atlassian-Token", "nocheck")
    $wc.UploadFile("$URIPath/issue/$jiraTicket/attachments", $filepath)
}

Here is how you could use it with the bare minimal modification to the code you have today:

$URIPath = "https://xxxx.xxxx.com/rest/api/2"
Upload-JiraFile -JiraTicket test-8442 -FilePath c:\temp\MyJpg.jpg `
   -Authorization $Headers["Authorization"]

Excerpted from this thread.


问:
Resizing images to fit inside a container
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

```

How I would like it to look:

答:
Adding css to the images should do the trick

```<code>max-width: 100%;
</code>```

https://codepen.io/genesy/pen/YzXGXXb it works here.. same code

EDIT: turned it into grid if you want equal image sizes too

```<code><div class="wrapper">
  <div class="panel">
    <img class=" " src="https://docplayer.org/docs-images/22/1321497/images/61-0.png">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
</div>
</code>```

```<code>.wrapper {
  display: grid;
  grid-template-rows: 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  height: 100%;
  width: 100%;
}
.panel {
  width: 100%;
  height: 100%;
}
img {
  max-width: 100%;
  max-height: 100%;
  width:
}
html, body {
  height: 100%;
  width: 100%:
}
</code>```

Body:
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

How I would like it to look:

Body:
Adding css to the images should do the trick

max-width: 100%;

https://codepen.io/genesy/pen/YzXGXXb it works here.. same code

EDIT: turned it into grid if you want equal image sizes too

<div class="wrapper">
  <div class="panel">
    <img class=" " src="https://docplayer.org/docs-images/22/1321497/images/61-0.png">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
  <div class="panel">
    <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1">
  </div>
</div>

.wrapper {
  display: grid;
  grid-template-rows: 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  height: 100%;
  width: 100%;
}
.panel {
  width: 100%;
  height: 100%;
}
img {
  max-width: 100%;
  max-height: 100%;
  width:
}
html, body {
  height: 100%;
  width: 100%:
}


问:
Is there a way to make a "reusable snapshot" of a program?
Here's the situation: I am working on a relatively big C++ program (in Linux). This program can be separated in two parts. Part A is just a bunch of precomputations based in some data that remains the same over time that builds a pretty complex and big data structure. The problem is that part A takes too much time (around a minute), and you can assume that it cannot be significantly optimized further. Part B, which goes right after part A, is basically some queries on the data loaded in part A.

So, here's what I want to do: since the data structure built in part A is always the same, wouldn't it be nice to have a "snapshot" of it, and so, every time you load the program you can just retrieve the data from the snapshot very quickly and just jump right to B?

And here's the question: Is there a way to do that?

答:
If you control all the allocations used in this data-structure, there might be a reasonable way.

You start with the bytes of your "A.saved" file. Rather than having pointers, you instead have offsets from the start of the file.

```<code>unsigned char * start; // !! global pointer

template <typename T>
class offset_ptr {
    std::size_t offset;
public:
    offset_ptr(std::size_t offset) : offset(offset) {}
    offset_ptr(T* ptr) : offset(pointer - start) {}

    T& operator*() const { return *reinterpret_cast<T*>(start + offset); }
    T& operator->() const { return reinterpret_cast<T*>(start + offset); }
};
</code>```

Body:
If you control all the allocations used in this data-structure, there might be a reasonable way.

You start with the bytes of your "A.saved" file. Rather than having pointers, you instead have offsets from the start of the file.

unsigned char * start; // !! global pointer

template <typename T>
class offset_ptr {
    std::size_t offset;
public:
    offset_ptr(std::size_t offset) : offset(offset) {}
    offset_ptr(T* ptr) : offset(pointer - start) {}

    T& operator*() const { return *reinterpret_cast<T*>(start + offset); }
    T& operator->() const { return reinterpret_cast<T*>(start + offset); }
};


答:
You can configure using  MySql Workbench.Navigate  to menu items Server-->Status or System Variables.
Search for max_allowed_packet</p>

Title: where to run commands on mysql

Body:
I work on a java project using mysql as database, at some level I needed to increase  the value of max_allowed_packet variable, I checked in the net but I can't find my.cnf or my.ini.
So I need to run some recommended command such as set global max_allowed_packet=33554432 but I do not know where to find the terminal to do that.
I am using mySql 8.0 on windows 10


问:
"Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED" on a project that should work out of the box
https://github.com/zzh8829/yolov3-tf2 is the project. I've installed all the correct versions ofthings I think.

google is telling me that it is probably a low VRAM issue but I am still looking around for other reasons. please help.
I am using :

Windows 10 (don't say "there's your problem" I need it)

cuDNN 7.4.6

CUDA 10.0

tensorflow 2.0.0

python 3.6

I have a gtx1660 super 6GB VRAM with a ryzen 7 2700x on 16GB of RAM. I'm getting a gt1080 8gig in a few days I'm going to add to the second PCI slot.

the Error is as follows:

```<code>2019-11-30 06:31:26.167368: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2019-11-30 06:31:27.843742: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2019-11-30 06:31:27.853725: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
Traceback (most recent call last):
  File ".\convert.py", line 34, in <module>
    app.run(main)
  File "C:\Program Files\Python36\lib\site-packages\absl\app.py", line 299, in run
    _run_main(main, args)
  File "C:\Program Files\Python36\lib\site-packages\absl\app.py", line 250, in _run_main
    sys.exit(main(argv))
  File ".\convert.py", line 25, in main
    output = yolo(img)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 708, in call
    convert_kwargs_to_constants=base_layer_utils.call_context().saving)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 860, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 708, in call
    convert_kwargs_to_constants=base_layer_utils.call_context().saving)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 860, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\layers\convolutional.py", line 197, in call
    outputs = self._convolution_op(inputs, self.kernel)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 1134, in __call__
    return self.conv_op(inp, filter)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 639, in __call__
    return self.call(inp, filter)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 238, in __call__
    name=self.name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 2010, in conv2d
    name=name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\gen_nn_ops.py", line 1031, in conv2d
    data_format=data_format, dilations=dilations, name=name, ctx=_ctx)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\gen_nn_ops.py", line 1130, in conv2d_eager_fallback
    ctx=_ctx, name=name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a wa
rning log message was printed above. [Op:Conv2D]

</code>```

答:
Simple fix:
insert this line under the imports in "convert.py"

```<code>import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
</code>```

this will ignore your gpu while loading the weights.

Body:
https://github.com/zzh8829/yolov3-tf2 is the project. I've installed all the correct versions ofthings I think.

google is telling me that it is probably a low VRAM issue but I am still looking around for other reasons. please help.
I am using :

Windows 10 (don't say "there's your problem" I need it)

cuDNN 7.4.6

CUDA 10.0

tensorflow 2.0.0

python 3.6

I have a gtx1660 super 6GB VRAM with a ryzen 7 2700x on 16GB of RAM. I'm getting a gt1080 8gig in a few days I'm going to add to the second PCI slot.

the Error is as follows:

2019-11-30 06:31:26.167368: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2019-11-30 06:31:27.843742: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2019-11-30 06:31:27.853725: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
Traceback (most recent call last):
  File ".\convert.py", line 34, in <module>
    app.run(main)
  File "C:\Program Files\Python36\lib\site-packages\absl\app.py", line 299, in run
    _run_main(main, args)
  File "C:\Program Files\Python36\lib\site-packages\absl\app.py", line 250, in _run_main
    sys.exit(main(argv))
  File ".\convert.py", line 25, in main
    output = yolo(img)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 708, in call
    convert_kwargs_to_constants=base_layer_utils.call_context().saving)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 860, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 708, in call
    convert_kwargs_to_constants=base_layer_utils.call_context().saving)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\network.py", line 860, in _run_internal_graph
    output_tensors = layer(computed_tensors, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\keras\layers\convolutional.py", line 197, in call
    outputs = self._convolution_op(inputs, self.kernel)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 1134, in __call__
    return self.conv_op(inp, filter)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 639, in __call__
    return self.call(inp, filter)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 238, in __call__
    name=self.name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\nn_ops.py", line 2010, in conv2d
    name=name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\gen_nn_ops.py", line 1031, in conv2d
    data_format=data_format, dilations=dilations, name=name, ctx=_ctx)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\ops\gen_nn_ops.py", line 1130, in conv2d_eager_fallback
    ctx=_ctx, name=name)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a wa
rning log message was printed above. [Op:Conv2D]

Body:
Simple fix:
insert this line under the imports in "convert.py"

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

this will ignore your gpu while loading the weights.


问:
Job scheduling variation
I am trying to solve a variation of interval scheduling problem : Given a set of n jobs, each of which require 1 unit of processing to finish, and every job has an availability interval(a start time and end time between which it can be executed) for which it is available, find the the maximum number of jobs that can be scheduled.

The solution I tried was sorting the jobs and always picking the ones with the earliest end time of availability, while removing jobs that are not available after every iteration.

```<code>while jobs are not empty:
    remove jobs that are not available
    find the job with earliest end_availability_time
    execute the job
</code>```

I am using a priority queue where I insert all the jobs in the beginning, instead of sorting.
The time complexity of this solution is O(nlogn) ( Every job is inserted once to the priority queue and popped once from the priority queue).

Is there an optimal way to solve this?

答:
You can see this as an instance of the assignment problem. You just have to transform the intervals in slots of one unit, and connect each job to every one-unit time interval it can be executed in.

One possible algorithm to solve this is the Hungarian algorithm, or you can encode it as a maximum flow problem and solve it with the Ford-Fulkerson algorithm.

Edit
Thinking about it more, your solution is also optimal. Here's a sketch of the proof: let A be the optimal solution found by the greedy algorithm, and B a different optimal solution.  Consider a job j that is scheduled in B, but not in A. This means that the greedy algorithm removed j from the list of available jobs, which could happen only if it scheduled another job for every slot of time in j's availablity interval. Then, one of these jobs cannot be in B, because it would be scheduled at the same time of j. Thus means that A and B have the same number of jobs.

In other words, the greedy algorithm schedules a job at every time slot, so it must be optimal.

Title: Job scheduling variation

Body:
I am trying to solve a variation of interval scheduling problem : Given a set of n jobs, each of which require 1 unit of processing to finish, and every job has an availability interval(a start time and end time between which it can be executed) for which it is available, find the the maximum number of jobs that can be scheduled.

The solution I tried was sorting the jobs and always picking the ones with the earliest end time of availability, while removing jobs that are not available after every iteration.

while jobs are not empty:
    remove jobs that are not available
    find the job with earliest end_availability_time
    execute the job

I am using a priority queue where I insert all the jobs in the beginning, instead of sorting.
The time complexity of this solution is O(nlogn) ( Every job is inserted once to the priority queue and popped once from the priority queue).

Is there an optimal way to solve this?


问:
Prevent all clicks on embedded element
I use embedded tweets in my website, however, I would like to prevent any type of user interaction with these embedded tweets other than showing them to my users. Following the advise here, I wrapped the embed code inside a
 element with the CSS property pointer-events:none, as in the example below, nevertheless, the embedded tweet in the  remains clickable. Any ideas how to mask it with an invisible NON-CLICKABLE layer?

Or hey, ya know, just relax and have fun. https://twitter.com/U53iZEL9O9
— Meg Turney (@megturney) February 19, 2020

```

答:
What you wrote actually works well, and Chrome doesn't send click events to it. But we can add an eventListener to override anything that might be attached to it, and prevent the event from propagating with event.stopPropagation(). I added some CSS to disable text highlighting/selection as well.

It's a little hard to demonstrate an event is not firing, but you can see the console won't log the "Uh oh, I got clicked" message even if you click around.

document.querySelectorAll(".unclickable").forEach(
  element => element.addEventListener("click",
    event => {
      event.preventDefault();
      return event.stopPropagation();
    }
  )
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.unclickable * {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Opera and Firefox */
}</code>```

Or hey, ya know, just relax and have fun. https://twitter.com/U53iZEL9O9
— Meg Turney (@megturney) February 19, 2020

```

Title: Prevent all clicks on embedded element

Body:
What you wrote actually works well, and Chrome doesn't send click events to it. But we can add an eventListener to override anything that might be attached to it, and prevent the event from propagating with event.stopPropagation(). I added some CSS to disable text highlighting/selection as well.

It's a little hard to demonstrate an event is not firing, but you can see the console won't log the "Uh oh, I got clicked" message even if you click around.

document.querySelectorAll(".unclickable").forEach(
  element => element.addEventListener("click",
    event => {
      event.preventDefault();
      return event.stopPropagation();
    }
  )
);

.unclickable * {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Opera and Firefox */
}

<div onclick="console.log('Uh oh, I got clicked')" class="unclickable right" style="display:inline-block;float:left;pointer-events:none;z-index:2">
  <blockquote class="twitter-tweet">
    <p lang="en" dir="ltr">Or hey, ya know, just relax and have fun. <a href="https://twitter.com/U53iZEL9O9">https://twitter.com/U53iZEL9O9</a></p>&mdash; Meg Turney (@megturney) <a href="https://twitter.com/megturney/status/1230141853246402560?ref_src=twsrc%5Etfw">February 19, 2020</a></blockquote>
  <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>


问:
Populate select options using jQuery and data attribute values
I'd like to add dates from a HTML list to a form.

To avoid changing the actual forms all the time I'd like to fetch the dates from text. Say I have a list with dates, if the user clicks the button that pops up the form I want to have the <select> in the form with the dates. (I do not intent to make every date clickable and pop up the form with the selected date)

So for example, my client edits the text of the page and adds the dates in the webpage text in a list like this:

```<code><ul id="course1">
 <li>Date 1</li>
 <li>Date 2</li>
 <li>Date 3</li>
</ul>
</code>```

In the text there's a button that opens a modal window with a form, all i want is to populate a <select> in that form with the dates from that list.

I managed to get it to work with just a normal text value like so;

HTML:

```<code><a class="programma-kiezer" data-prog="Forming Fase" href="#" data-toggle="modal" data-target="onderwijs">button</a>
</code>```

And then it just takes the value of "data-prog" and puts it into the form

jQuery:

```<code>jQuery(window).on("load", function () {

   jQuery('.programma-kiezer').on('click', function(e) {
       e.preventDefault();

       jQuery('input[name="programma"]').val( jQuery(this).data('prog'));
   });
});
</code>```

But how can I add option values from a list of dates and add those to the form?

Thanks so much in advance!

答:
You can take the
s' texts and create <option>s for each of them.

Something like:

$('#onderwijs').on('shown.bs.modal', function() {
  const dates = $('#course1 li').map((i, li) => $(li).text()).get();
  // dates = ['2020-12-05', '2019-09-05', '2028-05-04']
  let html = dates.map(date => {
    return `<option>${date}</option>`;
  }).join('');
  // html = <option>2020-12-05</option><option>2019-09-05</option><option>2028-05-04</option>

  $('#dates').html(html);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

button

<ul id="course1">
 <li>2020-12-05</li>
 <li>2019-09-05</li>
 <li>2028-05-04</li>
</ul>

<div class="modal" id="onderwijs" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <select id="dates"></select>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div></code>```

Read more about

jQuery map (get is returning a native javascript array).

javascript map

join

jQuery html

Let me know if something is not clear.

Body:
I'd like to add dates from a HTML list to a form.

To avoid changing the actual forms all the time I'd like to fetch the dates from text. Say I have a list with dates, if the user clicks the button that pops up the form I want to have the <select> in the form with the dates. (I do not intent to make every date clickable and pop up the form with the selected date)

So for example, my client edits the text of the page and adds the dates in the webpage text in a list like this:

Date 1

Date 2

Date 3

In the text there's a button that opens a modal window with a form, all i want is to populate a <select> in that form with the dates from that list.

I managed to get it to work with just a normal text value like so;

HTML:

button

And then it just takes the value of "data-prog" and puts it into the form

jQuery:

jQuery(window).on("load", function () {

   jQuery('.programma-kiezer').on('click', function(e) {
       e.preventDefault();

       jQuery('input[name="programma"]').val( jQuery(this).data('prog'));
   });
});

But how can I add option values from a list of dates and add those to the form?

Thanks so much in advance!

Body:
You can take the <li>s' texts and create <option>s for each of them.

Something like:

$('#onderwijs').on('shown.bs.modal', function() {
  const dates = $('#course1 li').map((i, li) => $(li).text()).get();
  // dates = ['2020-12-05', '2019-09-05', '2028-05-04']
  let html = dates.map(date => {
    return `<option>${date}</option>`;
  }).join('');
  // html = <option>2020-12-05</option><option>2019-09-05</option><option>2028-05-04</option>

  $('#dates').html(html);
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<a class="programma-kiezer" data-prog="Forming Fase" href="#" data-toggle="modal" data-target="#onderwijs">button</a>

<ul id="course1">
 <li>2020-12-05</li>
 <li>2019-09-05</li>
 <li>2028-05-04</li>
</ul>

<div class="modal" id="onderwijs" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <select id="dates"></select>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Read more about

jQuery map (get is returning a native javascript array).

javascript map

join

jQuery html

Let me know if something is not clear.


问:
Find item by key in Javascript
Quick rookie question please.

Suppose I have a javsacript object like so:

```<code>var meh=[["cars",27], ["bikes",85], ["skates",4]];
</code>```

To go through each data object here, I can do this:

```<code>$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });
</code>```

And considering I know the place of, say, cars, I can do this to access it:

```<code>console.log(meh[0][0]) //shows "Cars"
</code>```

and of course, if I want the value of cars, I need to do this:

```<code>console.log(meh[0][1]) //Shows 27
</code>```

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

答:
If you have access to the code and can change the object, change it to something like this:

```<code>meh = {
  'cars': 27,
  'bikes': 85,
  'skates': 4
};
</code>```

and you can access them with keys like

```<code>meh["cars"] //will give you 27
</code>```

If you cannot change the code, then the only way I see is using jQuery.each and comparing each key with your known key and assigning it to a temp variable.

ContentLicense: CC BY-SA 3.0

Title: Find item by key in Javascript

Body:
Quick rookie question please.

Suppose I have a javsacript object like so:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });

And considering I know the place of, say, cars, I can do this to access it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I want the value of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

Body:
If you have access to the code and can change the object, change it to something like this:

meh = {
  'cars': 27,
  'bikes': 85,
  'skates': 4
};

and you can access them with keys like

meh["cars"] //will give you 27

If you cannot change the code, then the only way I see is using jQuery.each and comparing each key with your known key and assigning it to a temp variable.


问:
Remove border when display property is set to none
This seems to be a simple task but for some reason I am having issues removing a border when the display property is set to none.

From what I've always understood is that when the display property is set to none it removes that element from the html flow.  However, in the example I've provided it still shows a border on the last element.

```<code><div class="outer">
  <div class="inner">
    <div class="control">Foo</div>
    <div class="control d-none">Bar</div>
  </div>
</div>
</code>```

https://jsfiddle.net/6hfzpcoL/

答:
The 'd-none' element is still present, it is only not visible to the user. if you inspect the container you will see it is still there, so Foo isn't considered a last child - therefore border is still being applied.

What you are trying to achieve cannot be done with CSS only you would need to use Javascript or JQuery.

Body:
This seems to be a simple task but for some reason I am having issues removing a border when the display property is set to none.

From what I've always understood is that when the display property is set to none it removes that element from the html flow.  However, in the example I've provided it still shows a border on the last element.

Foo

Bar

https://jsfiddle.net/6hfzpcoL/


问:
Remove all cocoapod dependencies from a project
So I have a large Xcode project with Obj-C and Swift code, with many many cocoapods dependencies.

But my developer of choice doesn't work with cocoapod dependencies.
I know this is a bit strange but he just doesn't want to set up his Mac with pods and it's not negotiable with him (also switching devs is not an option).

So...my question.
Is it possible to remove all cocoapod dependencies and still have the project compile and run as it currently does?
I have a feeling people will say - it depends on your project.
But if I could just get a rough "Yes it is possible" or "No it is always impossible" that would be great.
And if it is possible, how does one go about starting such a task?

I don't know if this will help but here's a list of all the current Cocoapod dependencies in the project:

pod 'Countly'

pod 'CocoaLumberjack'

pod 'Fabric'

pod 'Crashlytics'

pod 'AFNetworking', '~> 2.0'

pod 'MBProgressHUD'

pod 'CHTCollectionViewWaterfallLayout', '~> 0.9'

pod 'pop', '~> 1.0'

pod 'TwitterKit'

pod 'FBSDKCoreKit'

pod 'FBSDKLoginKit'

pod 'FBSDKShareKit'

pod 'FBSDKMessengerShareKit'

pod 'Inapptics'

pod 'Firebase/Core'

pod 'Firebase/Auth'

pod 'Firebase/Storage'

pod 'FirebaseUI/Storage'

pod 'Firebase/Database'

pod 'Firebase/Messaging'

pod 'SwiftKeychainWrapper'

pod 'DeviceKit', '~> 1.0'

pod 'WSCoachMarksView'

pod 'IQKeyboardManagerSwift'

pod 'FLAnimatedImage', '~> 1.0'

pod 'GBDeviceInfo'

pod 'SDWebImage', '~> 4.0'

pod 'SDWebImage/GIF'

pod 'MagazineLayout'

pod 'Toucan'

答:
You can remove the cocoapods but in order for your project to build, You will have to add the dependances to your project one by one.

Personally I don't recommend doing that. it's a lot of work and if you changed your developer in the future you might need to re-add them once more.


问:
How to exclude some files from the loop in shell script
```<code>#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done
</code>```

It will give permission 777 to all .txt files but I've 7 other .txt file for which I don't want to give 777 permission. How can I do that?

答:
A POSIX sh solution.</p>

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

for file in $Files/*.txt; do
   case $file in
    foo.txt|bar.txt|more.txt) continue;;   ##: Skip files that matched.
    *) chmod 777 "$file";;                 ##: Change permission to the rest.
   esac
done
</code>```

Body:
#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done

It will give permission 777 to all .txt files but I've 7 other .txt file for which I don't want to give 777 permission. How can I do that?

Body:
A POSIX sh solution.

#! /bin/sh

for file in $Files/*.txt; do
   case $file in
    foo.txt|bar.txt|more.txt) continue;;   ##: Skip files that matched.
    *) chmod 777 "$file";;                 ##: Change permission to the rest.
   esac
done


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
I assume you mean "fully denormalized database design rather than a normalized (e.g., third or fourth normal form) model", because a relational model is managed by an RDBMS regardless of how normalized it is.

Can't judge without knowing more about your requirements, your abilities, and those of your teammates.

I fear that your KISS admonition might not work in this case, because one big, denormalized table might be defended as the simplest thing possible.

How does anybody solve these kinds of problems?  Communication, persuasion, better data, prototypes of alternative technologies and techniques.  This is what makes software development so hard.  If there was only one way to do these things, and everyone agreed on them, we truly could script it or get anyone to develop systems and be done with it.

Get some data.  Your words might not be enough.  If a quick prototype can demonstrate your point, create it.

"Strong opinions, lightly held" should be your motto.

Sometimes a technical point isn't worth alienating your entire team.  Sometimes it is.  Your call.

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe


问:
Python or Java for text processing (text mining, information retrieval, natural language processing)
I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.

There's going to be a huge amount of documents that need to be processed; probably millions of documents. After the initial processing, it also has to be able to be updated daily with multiple new documents.

Can I use Python to do this, or is Python too slow? Is it best to use Java?

If possible, I would prefer Python since that's what I have been using lately. Plus, I would finish the coding part much faster. But it all depends on Python's speed. I have used Python for some small scale text processing tasks with only a couple of thousand documents, but I am not sure how well it scales up.

答:
It's very difficult to answer questions like this without trying. So why don't you

Figure out what would be a difficult operation

Implement that (and I mean the simplest, quickest hack that you can make work)

Run it with a lot of data, and see how long it takes

Figure out if it's too slow

I've done this in the past and it's really the way to see if something performs well enough for something.


问:
Rails jobs with Sidekiq in Google Cloud Run not working
I've a working Rails application in Google Cloud Run using:

Cloud Build

Cloud Registry

Cloud Run

Cloud SQL

Cloud Storage

Cloud Key Management Service

Cloud Scheduler

I've configured Sidekiq to execute some jobs in background but I get this error in Cloud Run logs when I'm trying to execute Sidekiq jobs.

```<code>Redis::CannotConnectError (Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)):
</code>```

I let you here my deployment setup:

cloudbuild.yaml

```<code>steps:

# Decrypt Rails Master key file
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/master.key.enc",
         "--plaintext-file=./config/master.key",
         "--location=us-central1","--keyring=project_name",
         "--key=rails_master_key"]

# Decrypt Whale on Rails service account credentials
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/project_name_runner.key.enc",
         "--plaintext-file=./config/project_name_runner.key",
         "--location=us-central1","--keyring=project_name",
         "--key=project_name_runner_key"]

# Build image with tag 'latest' and pass decrypted Rails DB password as argument
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build',
    '--tag', 'gcr.io/$PROJECT_ID/project_name:latest',
    '--build-arg', 'DB_PWD',
    '--build-arg', 'RUBY_VERSION=${_RUBY_VERSION}',
    '--build-arg', 'PG_MAJOR=${_PG_MAJOR}',
    '--build-arg', 'NODE_MAJOR=${_NODE_MAJOR}',
    '--build-arg', 'BUNDLER_VERSION=${_BUNDLER_VERSION}',
    '--build-arg', 'RAILS_ENV=${_RAILS_ENV}',
    '--build-arg', 'REDIS_URL=${_REDIS_URL}',
    '--build-arg', 'DATABASE_HOST=${_DATABASE_HOST}',
    '--build-arg', 'DATABASE_USER=${_DATABASE_USER}',
    '--build-arg', 'DATABASE_NAME=${_DATABASE_NAME}',
    '.'
  ]
  secretEnv: ['DB_PWD']

# Push new image to Google Cloud Registry
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/$PROJECT_ID/project_name:latest']

secrets:
- kmsKeyName: projects/project_name/locations/us-central1/keyRings/project_name/cryptoKeys/db_pwd_key
  secretEnv:
    DB_PWD: "db_password"

substitutions:
  _RUBY_VERSION: '2.7.0'
  _PG_MAJOR: '11'
  _NODE_MAJOR: '12'
  _BUNDLER_VERSION: '2.1.2'
  _RAILS_ENV: production
  _REDIS_URL: redis://redis:6379/
  _DATABASE_HOST: /cloudsql/project_name:us-central1:project_name-production
  _DATABASE_USER: production_user
  _DATABASE_NAME: project_name-production
</code>```

entrypoint.sh

#!/usr/bin/env bash

cd /usr/src/app

# Create the Rails production DB on first run
bundle exec rake db:prepare

# Do some protective cleanup
> log/production.log
rm -f tmp/pids/server.pid

# Run the web service on container startup
# $PORT is provided as an environment variable by Cloud Run
bundle exec rails server -b 0.0.0.0 -p $PORT

# Run sidekiq in production
bundle exec sidekiq -C config/sidekiq.yml
```

<p><strong>Dockerfile</strong></p>

```# Leverage the official Ruby image from Docker Hub
# https://hub.docker.com/_/ruby
ARG RUBY_VERSION
FROM ruby:$RUBY_VERSION

LABEL maintainer="myemail@gmail.com"

ARG PG_MAJOR
ARG NODE_MAJOR
ARG BUNDLER_VERSION
ARG RAILS_ENV

# Add PostgreSQL to sources list
RUN curl -sSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - \
  && echo 'deb http://apt.postgresql.org/pub/repos/apt/ stretch-pgdg main' $PG_MAJOR > /etc/apt/sources.list.d/pgdg.list

# Install recent versions of nodejs (10.x) and yarn pkg manager
# Needed to properly pre-compile Rails assets
RUN (curl -sL https://deb.nodesource.com/setup_$NODE_MAJOR.x | bash -) && apt-get update && apt-get install -y nodejs

# Add Yarn to the sources list
RUN (curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -) && \
    echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
    apt-get update && apt-get install -y yarn

# Install production dependencies (Gems installation in
# local vendor directory)
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
ENV BUNDLE_FROZEN=true
RUN gem update --system && \
    gem install bundler:$BUNDLER_VERSION
RUN bundle install

# Copy application code to the container image.
# Note: files listed in .gitignore are not copied
# (e.g.secret files)
COPY . .

# Pre-compile Rails assets (master key needed)
RUN yarn install
RUN RAILS_ENV=production bundle exec rake assets:precompile

# Set Google App Credentials environment variable with Service Account
ENV GOOGLE_APPLICATION_CREDENTIALS=/usr/src/app/config/sunne_cms_api_runner.key

# Setup Rails DB password passed on docker command line (see Cloud Build file)
ARG DATABASE_NAME
ARG DATABASE_HOST
ARG DATABASE_USER
ARG DB_PWD
ENV DATABASE_PASSWORD=${DB_PWD}
ENV DATABASE_NAME=${DATABASE_NAME}
ENV DATABASE_HOST=${DATABASE_HOST}
ENV DATABASE_USER=${DATABASE_USER}

# Setting up Rails environment
ENV RAILS_ENV=${RAILS_ENV}

# For now we don't have a Nginx/Apache frontend so tell
# the Puma HTTP server to serve static content
# (e.g. CSS and Javascript files)
ENV RAILS_SERVE_STATIC_FILES=true

# Redirect Rails log to STDOUT for Cloud Run to capture
ENV RAILS_LOG_TO_STDOUT=true

# Designate the initial sript to run on container startup
RUN chmod +x /usr/src/app/entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]
```

答:
Cloud Run does not support background jobs. Your container starts with an HTTP request and ends when the request returns. Do not expect anything more after the request returns.

Cloud Run is not an operating system, task scheduler, background thread processor, etc.

Read this to understand what Cloud Run can/cannot do:

Cloud Run Container Contract

Body:
I've a working Rails application in Google Cloud Run using:

Cloud Build

Cloud Registry

Cloud Run

Cloud SQL

Cloud Storage

Cloud Key Management Service

Cloud Scheduler

I've configured Sidekiq to execute some jobs in background but I get this error in Cloud Run logs when I'm trying to execute Sidekiq jobs.

Redis::CannotConnectError (Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)):

I let you here my deployment setup:

cloudbuild.yaml

steps:

# Decrypt Rails Master key file
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/master.key.enc",
         "--plaintext-file=./config/master.key",
         "--location=us-central1","--keyring=project_name",
         "--key=rails_master_key"]

# Decrypt Whale on Rails service account credentials
- name: gcr.io/cloud-builders/gcloud
  args: ["kms", "decrypt", "--ciphertext-file=./config/project_name_runner.key.enc",
         "--plaintext-file=./config/project_name_runner.key",
         "--location=us-central1","--keyring=project_name",
         "--key=project_name_runner_key"]

# Build image with tag 'latest' and pass decrypted Rails DB password as argument
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build',
    '--tag', 'gcr.io/$PROJECT_ID/project_name:latest',
    '--build-arg', 'DB_PWD',
    '--build-arg', 'RUBY_VERSION=${_RUBY_VERSION}',
    '--build-arg', 'PG_MAJOR=${_PG_MAJOR}',
    '--build-arg', 'NODE_MAJOR=${_NODE_MAJOR}',
    '--build-arg', 'BUNDLER_VERSION=${_BUNDLER_VERSION}',
    '--build-arg', 'RAILS_ENV=${_RAILS_ENV}',
    '--build-arg', 'REDIS_URL=${_REDIS_URL}',
    '--build-arg', 'DATABASE_HOST=${_DATABASE_HOST}',
    '--build-arg', 'DATABASE_USER=${_DATABASE_USER}',
    '--build-arg', 'DATABASE_NAME=${_DATABASE_NAME}',
    '.'
  ]
  secretEnv: ['DB_PWD']

# Push new image to Google Cloud Registry
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/$PROJECT_ID/project_name:latest']

secrets:
- kmsKeyName: projects/project_name/locations/us-central1/keyRings/project_name/cryptoKeys/db_pwd_key
  secretEnv:
    DB_PWD: "db_password"

substitutions:
  _RUBY_VERSION: '2.7.0'
  _PG_MAJOR: '11'
  _NODE_MAJOR: '12'
  _BUNDLER_VERSION: '2.1.2'
  _RAILS_ENV: production
  _REDIS_URL: redis://redis:6379/
  _DATABASE_HOST: /cloudsql/project_name:us-central1:project_name-production
  _DATABASE_USER: production_user
  _DATABASE_NAME: project_name-production

entrypoint.sh

#!/usr/bin/env bash

cd /usr/src/app

# Create the Rails production DB on first run
bundle exec rake db:prepare

# Do some protective cleanup
> log/production.log
rm -f tmp/pids/server.pid

# Run the web service on container startup
# $PORT is provided as an environment variable by Cloud Run
bundle exec rails server -b 0.0.0.0 -p $PORT

# Run sidekiq in production
bundle exec sidekiq -C config/sidekiq.yml

Dockerfile

# Leverage the official Ruby image from Docker Hub
# https://hub.docker.com/_/ruby
ARG RUBY_VERSION
FROM ruby:$RUBY_VERSION

LABEL maintainer="myemail@gmail.com"

ARG PG_MAJOR
ARG NODE_MAJOR
ARG BUNDLER_VERSION
ARG RAILS_ENV

# Add PostgreSQL to sources list
RUN curl -sSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - \
  && echo 'deb http://apt.postgresql.org/pub/repos/apt/ stretch-pgdg main' $PG_MAJOR > /etc/apt/sources.list.d/pgdg.list

# Install recent versions of nodejs (10.x) and yarn pkg manager
# Needed to properly pre-compile Rails assets
RUN (curl -sL https://deb.nodesource.com/setup_$NODE_MAJOR.x | bash -) && apt-get update && apt-get install -y nodejs

# Add Yarn to the sources list
RUN (curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -) && \
    echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
    apt-get update && apt-get install -y yarn

# Install production dependencies (Gems installation in
# local vendor directory)
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
ENV BUNDLE_FROZEN=true
RUN gem update --system && \
    gem install bundler:$BUNDLER_VERSION
RUN bundle install

# Copy application code to the container image.
# Note: files listed in .gitignore are not copied
# (e.g.secret files)
COPY . .

# Pre-compile Rails assets (master key needed)
RUN yarn install
RUN RAILS_ENV=production bundle exec rake assets:precompile

# Set Google App Credentials environment variable with Service Account
ENV GOOGLE_APPLICATION_CREDENTIALS=/usr/src/app/config/sunne_cms_api_runner.key

# Setup Rails DB password passed on docker command line (see Cloud Build file)
ARG DATABASE_NAME
ARG DATABASE_HOST
ARG DATABASE_USER
ARG DB_PWD
ENV DATABASE_PASSWORD=${DB_PWD}
ENV DATABASE_NAME=${DATABASE_NAME}
ENV DATABASE_HOST=${DATABASE_HOST}
ENV DATABASE_USER=${DATABASE_USER}

# Setting up Rails environment
ENV RAILS_ENV=${RAILS_ENV}

# For now we don't have a Nginx/Apache frontend so tell
# the Puma HTTP server to serve static content
# (e.g. CSS and Javascript files)
ENV RAILS_SERVE_STATIC_FILES=true

# Redirect Rails log to STDOUT for Cloud Run to capture
ENV RAILS_LOG_TO_STDOUT=true

# Designate the initial sript to run on container startup
RUN chmod +x /usr/src/app/entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]


问:
Is there a `not` ArgumentMatcher for mockito stubbing
I am trying to verify that a method is called with a long having any value but a given one.

I thus would like to know if there is an ArgumentMatcher that fits to my use case, such as:

verify(mObject).verifiedMethod(notEq(longValueThatShouldBeAvoided));
```

<hr>

<p>I found this workaround:</p>

<pre class="lang-java prettyprint-override"><code>verify(mObject).method(longThat(arg -> arg != longValueThatShouldBeAvoided));
</code>```

But I find weird that such simple ArgumentMatcher has to be written from scratch.

Additional question:
How to proceed when checking for multiple values to avoid ?

Similarly, I found the workaround of using arg -> arg != val0 && arg != val1 lambda as parameter of ArgumentsMatcher.longThat method to achieve this.

答:
I think you might be looking for the "not" matcher in AdditionalMatchers.

However, I think that is dealt with more extensively in this other question.

Body:
I am trying to verify that a method is called with a long having any value but a given one.

I thus would like to know if there is an ArgumentMatcher that fits to my use case, such as:

verify(mObject).verifiedMethod(notEq(longValueThatShouldBeAvoided));

I found this workaround:

verify(mObject).method(longThat(arg -> arg != longValueThatShouldBeAvoided));

But I find weird that such simple ArgumentMatcher has to be written from scratch.

Additional question:
How to proceed when checking for multiple values to avoid ?

Similarly, I found the workaround of using arg -> arg != val0 && arg != val1 lambda as parameter of ArgumentsMatcher.longThat method to achieve this.


问:
Double Jump Unity 2D
i want to make a 2D platformer game in Unity 2D and I'd like a system where my player can do a double jump, so he can jump and jump once more in the air, but can't jump anymore than that until hes landed back down, and i have no idea how to do this</p>

答:
emphasized textThere are a lot of ways to implement the "double jump" feature. The most straight forward would be this one:

```<code>public int maxJumps = 2;

private int jumps;
private float jumpForce = 5f;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
    {
        this.Jump ();
    }
}

private void Jump()
{
    if (jumps > 0)
    {
        gameObject.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0, jumpForce), ForceMode2D.Impulse);
        grounded = false;
        jumps = jumps - 1;
    }
    if (jumps == 0)
    {
        return;
    }
}
void OnCollisionEnter2D(Collision2D collider)
{
    if(collider.gameObject.tag == "Ground")
    {
        jumps = maxJumps;
        grounded = true;
        movespeed = 2.0F;
     }
 }
</code>```

Note that you could have another bool field in order to check if the player has already jumped twice, but using an integer gives you a more flexible solution in case you want to change the game design in the future (ex: letting the user jump three times when using a power-up).

Hope this helps!

Title: Double Jump Unity 2D

Body:
emphasized textThere are a lot of ways to implement the "double jump" feature. The most straight forward would be this one:

public int maxJumps = 2;

private int jumps;
private float jumpForce = 5f;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
    {
        this.Jump ();
    }
}

private void Jump()
{
    if (jumps > 0)
    {
        gameObject.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0, jumpForce), ForceMode2D.Impulse);
        grounded = false;
        jumps = jumps - 1;
    }
    if (jumps == 0)
    {
        return;
    }
}
void OnCollisionEnter2D(Collision2D collider)
{
    if(collider.gameObject.tag == "Ground")
    {
        jumps = maxJumps;
        grounded = true;
        movespeed = 2.0F;
     }
 }

Note that you could have another bool field in order to check if the player has already jumped twice, but using an integer gives you a more flexible solution in case you want to change the game design in the future (ex: letting the user jump three times when using a power-up).

Hope this helps!


问:
Use Jest for a method in typescript
I'm using for the first time jest.
So I want to test this method:

```<code>public static getProjectBranch(toto: any): string {
    if ("branch" in toto) {
        return toto.branch;
    } else {
        return "master";
    }
}
</code>```

This method is inside a class totoService.ts

What I'm doing in totoService.spec.ts :

```<code>describe("Test get Project Branch", () => {
test("branch is in component", () => expect(getProjectBranch()).toBe(""));
});
</code>```

I want to know if what i'm doing is good or no
And how can I import the method getProjectBranch in the file ?

答:
As your method getProjectBranch is static you could simply do like shown below:

```<code>describe("TotoService",() => {
  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''}; //create your test object here
      expect(totoService.getProjectBranch(toto)).toEqual(''); //call static method of TotoService
    })
  })
})
</code>```

If you would like to call non static methods you need to create an instance of the totoService beforeEach test:

```<code>describe("TotoService",() => {

  let totoService;

  beforeEach(() => {
    totoService = new TotoService();
  })

  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''};
      expect(totoService.getProjectBranch(toto)).toEqual('');
    })
  })
})
</code>```

Title: Use Jest for a method in typescript

Body:
I'm using for the first time jest.
So I want to test this method:

public static getProjectBranch(toto: any): string {
    if ("branch" in toto) {
        return toto.branch;
    } else {
        return "master";
    }
}

This method is inside a class totoService.ts

What I'm doing in totoService.spec.ts :

describe("Test get Project Branch", () => {
test("branch is in component", () => expect(getProjectBranch()).toBe(""));
});

I want to know if what i'm doing is good or no
And how can I import the method getProjectBranch in the file ?

Body:
As your method getProjectBranch is static you could simply do like shown below:

describe("TotoService",() => {
  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''}; //create your test object here
      expect(totoService.getProjectBranch(toto)).toEqual(''); //call static method of TotoService
    })
  })
})

If you would like to call non static methods you need to create an instance of the totoService beforeEach test:

describe("TotoService",() => {

  let totoService;

  beforeEach(() => {
    totoService = new TotoService();
  })

  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''};
      expect(totoService.getProjectBranch(toto)).toEqual('');
    })
  })
})


问:
jQuery Smooth Scroll making the page jump with tab is clicked
Currently designing a Wordpress site using the Easy Smooth Scroll Links plugin. I am also using the SiteOrigin Page Builder with the Tabs widget. The Tabs widget changes the URL in the address bar when you click on different tabs. Example: example.com/#tab1 , example.com/#tab2 etc. My issue is that the page jumps around when I click on the tabs. But only happens if the tabs are in the middle of the screen but not at the top of the screen or bottom of the screen.

Here is the code the smooth scroll plugin uses:

```<code>            <script type="text/javascript">
            jQuery.noConflict();
            (function($){

                var jump=function(e)
                {
                   if (e){
                       var target = $(this).attr("href");
                   }else{
                       var target = location.hash;
                   }

                    var scrollToPosition = $(target).offset().top - 90;

                   $('html,body').animate({scrollTop: scrollToPosition },900 ,'easeInSine' );

                }

                $('html, body').hide()

                $(document).ready(function()
                {
                    $("area[href*=\\#],a[href*=\\#]:not([href=\\#]):not([href^='\\#tab']):not([href^='\\#quicktab']):not([href^='\\#pane']):not([href^='#dryer']):not([href^='#pet']):not([href^='#tile']):not([href='#upholstery-cleaning']):not([href='#pet-odor-removal']):not([href='#tile-grout-cleaning'])").bind("click", jump);

                    if (location.hash){
                        setTimeout(function(){
                            $('html, body').scrollTop(0).show()
                            jump();
                        }, 0);
                    }else{
                      $('html, body').show()
                    }
                });

            })(jQuery);
        </script>
<?php  } else {  ?>
        <script type="text/javascript">
            jQuery.noConflict();
            (function( $ ) {
                $(function() {
                    // More code using $ as alias to jQuery
                    $("area[href*=\\#],a[href*=\\#]:not([href=\\#]):not([href^='\\#tab']):not([href^='\\#quicktab']):not([href^='\\#pane'])<?php if($essl_exclude_begin) echo $essl_exclude_begin; ?><?php if($essl_exclude_match) echo $essl_exclude_match; ?>").click(function() {
                        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
                            var target = $(this.hash);
                            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                            if (target.length) {
                            $('html,body').animate({
                            scrollTop: target.offset().top - <?php if (get_option('essl_offset')!='') {echo get_option('essl_offset');} else {echo '20';} ?>
                            },<?php if (get_option('essl_speed')!='') {echo get_option('essl_speed');} else {echo '900';} ?> ,'<?php echo  get_option('essl_easing','easeInQuint');?>');
                            return false;
                            }
                        }
                    });
                });
            })(jQuery);
        </script>
            <?php }
    }
}
endif;
?>
</code>```

As you can see I've added some exemptions on anchors or hashes I do not want the smooth scroll action to happen on. It works fine in Firefox but not in Chrome for some reason. I've cleared cache a few times to ensure it isn't that.

Any help would be appreciated. Thank you!

答: Disabling "Enable Scrolling from One Page to Another" setting in Easy Smooth Scroll Links plugin should resolve the issue. Alternatively, consider using the Page Scroll to ID plugin which doesn't suffer from this issue.</p>

Body:
Currently designing a Wordpress site using the Easy Smooth Scroll Links plugin. I am also using the SiteOrigin Page Builder with the Tabs widget. The Tabs widget changes the URL in the address bar when you click on different tabs. Example: example.com/#tab1 , example.com/#tab2 etc. My issue is that the page jumps around when I click on the tabs. But only happens if the tabs are in the middle of the screen but not at the top of the screen or bottom of the screen.

Here is the code the smooth scroll plugin uses:

<?php  } else {  ?>

            <?php }
    }
}
endif;
?>

As you can see I've added some exemptions on anchors or hashes I do not want the smooth scroll action to happen on. It works fine in Firefox but not in Chrome for some reason. I've cleared cache a few times to ensure it isn't that.

Any help would be appreciated. Thank you!


问:
connecting to AWS Elasticsearch to reboot?
I am getting my hands in AWS hosted Elastic search. Is it possible for me to connect to the ES via the instance its linked? and is it possible to reboot my elastic search cluster?

The AWS Cli don't have anything related to reboot and all i can try is http curl to my ES.

答: I had a "1 node ES" in a testing environment that was not connectable. I was able to get the "1 node cluster" to "reboot" by increasing the number of nodes from 1 to 2. Then reducing the number of nodes from 2 to 1, and hoping it removed the one I wanted.  </p>


问:
Memory leaks when starting Activity in AsyncTask (changed from Thread)
I'm quite new to Android development and was about to finish my first application when I noticed that I have a huge memory leak.

The leak occurs when I start a new activity from within a thread:

```<code>private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));

        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        try
        {
            new Thread()
            {

                public void run()
                {
                    initializeApp();

                }
                public void initializeApp()
                {
                    // Initialize application data here

                    FItemListStore.getItemsFromWebservice(fhitem);
                    boolean isArticleOverview = false;

                    for(FItem item: FItemListStore.fItemViewStorage)
                    {
                        if( item instanceof fiArticle )
                        {
                            isArticleOverview = true;
                            break;
                        }
                    }

                    Intent intent = new Intent();
                    intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
                    Bundle bundle = new Bundle();

                    if(isArticleOverview)
                    {
                        bundle.putInt("OverviewNr", 1);
                    }
                    else
                    {
                        bundle.putInt("OverviewNr", 0);
                    }
                    intent.putExtras(bundle);

                    //if( mActivity.get() != null )
                        mActivity.get().startActivity(intent);

                    mActivity.clear();

                }
            }.start();
        }
        catch (Exception e) {}

        //Debug.stopMethodTracing();
        //android.os.Debug.stopMethodTracing();
    }
</code>```

A HPROF dump of the app after executing this code shows that the thread will always be retained in the heap and grow exponentially. Researching this points towards referencing a context inside a thread causing leaks. So I changed this code a few times until it became this version with only a weak reference in a static class (that's some things that were mentioned in other posts)

The reason why I want to start the Activity in a thread is because I need to read data from a slow and big webservice, which takes some time. I displayed a loading bar in the activity, highlighting the selected item until the XMLparser is done, and started a new activity afterwards.

Might it be that there is no correct way to start an activity within a thread without causing a memory leak? And, if so, is there another way for me to have the intent started after the xml parser finishes his job?

On advice of Vladimir and Heiko, I changed my thread to a AnyncTask. The grow of my retained heap has stopped but the AsyncTask threads I started still remain in the heap. Here's my new code:

```<code>private static class QueryFHTask extends AsyncTask<FredHopperItem, Integer, Boolean>
 {

     WeakReference<CatalogViewActivity> mActivity;

     QueryFHTask(WeakReference<CatalogViewActivity> mActivity)
     {
        this.mActivity = mActivity;

     }

     protected void onPreExecute()
     {

     }
     protected Boolean doInBackground(FItem... items) {
         int count = items.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             FItemListStore.getItemsFromWebservice(items[i]);
             boolean isArticleOverview = false;

             for(FItem item: FItemListStore.fhItemViewStorage)
             {
                if( item instanceof FArticle )
                {
                    isArticleOverview = true;
                    break;
                }
             }

             Intent intent = new Intent();
             intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
             Bundle bundle = new Bundle();

             if(isArticleOverview)
             {
                bundle.putInt("OverviewNr", 1);
             }
             else
             {
                bundle.putInt("OverviewNr", 0);
             }
             intent.putExtras(bundle);
             mActivity.get().startActivity(intent);

         }
         return true;
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);

     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));
        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        new QueryFHTask(mActivity).execute(fhitem);

    }
</code>```

To clarify my problem, here's a copy of one of my HPROF thread overview heap dumps (it's very hard to read because I was not allowed to post html with links and images like in MAT because of my user level...). The AsyncTask threads retain a heap of 376 or 344. As I browser the application longer, there will be more and more retained heaps from AsyncActivity threads...

```<code>Name Instance Shallow Heap Retained Heap Context Class Loader
main java.lang.Thread @ 0x40027550 80 1.464 dalvik.system.PathClassLoader @ 0x4051ce30
JDWP java.lang.Thread @ 0x40515838 80 384
AsyncTask #6 java.lang.Thread @ 0x406ea788 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #7 java.lang.Thread @ 0x40690178 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #4 java.lang.Thread @ 0x4068a630 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #3 java.lang.Thread @ 0x406851f0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #5 java.lang.Thread @ 0x405d9f28 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #2 java.lang.Thread @ 0x40539db0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #1 java.lang.Thread @ 0x40517180 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #8 java.lang.Thread @ 0x4068cdb0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #9 java.lang.Thread @ 0x4068b558 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #10 java.lang.Thread @ 0x4068a178 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #11 java.lang.Thread @ 0x406639f0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #12 java.lang.Thread @ 0x40661b00 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
Binder Thread #2 java.lang.Thread @ 0x40519b20 80 344
Binder Thread #1 java.lang.Thread @ 0x40516868 80 344
Thread-2 java.util.logging.LogManager$2$1 @ 0x40195298 80 168 dalvik.system.PathClassLoader @ 0x400277f8
Signal Catcher java.lang.Thread @ 0x40515778 80 160
Compiler java.lang.Thread @ 0x405158e8 80 152
HeapWorker java.lang.Thread @ 0x40515618 80 152
GC java.lang.Thread @ 0x405156d0 80 136
Total: 21 entries  1.680 7.656
</code>```

答: You should look at AsyncTask , where you do the loading in doInBackground(), set up the status bar in onPreExecute, publish progress updates with publishProgess and then remove the progress bar in onPostExecute.

Body:
I'm quite new to Android development and was about to finish my first application when I noticed that I have a huge memory leak.

The leak occurs when I start a new activity from within a thread:

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));

        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        try
        {
            new Thread()
            {

                public void run()
                {
                    initializeApp();

                }
                public void initializeApp()
                {
                    // Initialize application data here

                    FItemListStore.getItemsFromWebservice(fhitem);
                    boolean isArticleOverview = false;

                    for(FItem item: FItemListStore.fItemViewStorage)
                    {
                        if( item instanceof fiArticle )
                        {
                            isArticleOverview = true;
                            break;
                        }
                    }

                    Intent intent = new Intent();
                    intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
                    Bundle bundle = new Bundle();

                    if(isArticleOverview)
                    {
                        bundle.putInt("OverviewNr", 1);
                    }
                    else
                    {
                        bundle.putInt("OverviewNr", 0);
                    }
                    intent.putExtras(bundle);

                    //if( mActivity.get() != null )
                        mActivity.get().startActivity(intent);

                    mActivity.clear();

                }
            }.start();
        }
        catch (Exception e) {}

        //Debug.stopMethodTracing();
        //android.os.Debug.stopMethodTracing();
    }

A HPROF dump of the app after executing this code shows that the thread will always be retained in the heap and grow exponentially. Researching this points towards referencing a context inside a thread causing leaks. So I changed this code a few times until it became this version with only a weak reference in a static class (that's some things that were mentioned in other posts)

The reason why I want to start the Activity in a thread is because I need to read data from a slow and big webservice, which takes some time. I displayed a loading bar in the activity, highlighting the selected item until the XMLparser is done, and started a new activity afterwards.

Might it be that there is no correct way to start an activity within a thread without causing a memory leak? And, if so, is there another way for me to have the intent started after the xml parser finishes his job?

On advice of Vladimir and Heiko, I changed my thread to a AnyncTask. The grow of my retained heap has stopped but the AsyncTask threads I started still remain in the heap. Here's my new code:

private static class QueryFHTask extends AsyncTask<FredHopperItem, Integer, Boolean>
 {

     WeakReference<CatalogViewActivity> mActivity;

     QueryFHTask(WeakReference<CatalogViewActivity> mActivity)
     {
        this.mActivity = mActivity;

     }

     protected void onPreExecute()
     {

     }
     protected Boolean doInBackground(FItem... items) {
         int count = items.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             FItemListStore.getItemsFromWebservice(items[i]);
             boolean isArticleOverview = false;

             for(FItem item: FItemListStore.fhItemViewStorage)
             {
                if( item instanceof FArticle )
                {
                    isArticleOverview = true;
                    break;
                }
             }

             Intent intent = new Intent();
             intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
             Bundle bundle = new Bundle();

             if(isArticleOverview)
             {
                bundle.putInt("OverviewNr", 1);
             }
             else
             {
                bundle.putInt("OverviewNr", 0);
             }
             intent.putExtras(bundle);
             mActivity.get().startActivity(intent);

         }
         return true;
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);

     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));
        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        new QueryFHTask(mActivity).execute(fhitem);

    }

To clarify my problem, here's a copy of one of my HPROF thread overview heap dumps (it's very hard to read because I was not allowed to post html with links and images like in MAT because of my user level...). The AsyncTask threads retain a heap of 376 or 344. As I browser the application longer, there will be more and more retained heaps from AsyncActivity threads...

Name Instance Shallow Heap Retained Heap Context Class Loader
main java.lang.Thread @ 0x40027550 80 1.464 dalvik.system.PathClassLoader @ 0x4051ce30
JDWP java.lang.Thread @ 0x40515838 80 384
AsyncTask #6 java.lang.Thread @ 0x406ea788 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #7 java.lang.Thread @ 0x40690178 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #4 java.lang.Thread @ 0x4068a630 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #3 java.lang.Thread @ 0x406851f0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #5 java.lang.Thread @ 0x405d9f28 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #2 java.lang.Thread @ 0x40539db0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #1 java.lang.Thread @ 0x40517180 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #8 java.lang.Thread @ 0x4068cdb0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #9 java.lang.Thread @ 0x4068b558 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #10 java.lang.Thread @ 0x4068a178 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #11 java.lang.Thread @ 0x406639f0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #12 java.lang.Thread @ 0x40661b00 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
Binder Thread #2 java.lang.Thread @ 0x40519b20 80 344
Binder Thread #1 java.lang.Thread @ 0x40516868 80 344
Thread-2 java.util.logging.LogManager$2$1 @ 0x40195298 80 168 dalvik.system.PathClassLoader @ 0x400277f8
Signal Catcher java.lang.Thread @ 0x40515778 80 160
Compiler java.lang.Thread @ 0x405158e8 80 152
HeapWorker java.lang.Thread @ 0x40515618 80 152
GC java.lang.Thread @ 0x405156d0 80 136
Total: 21 entries  1.680 7.656


问:
merge 2 values and put in a v-data-table column (Vuetify)
Is it possible to merge to values and put into one column in v-data-table?

List.vue

```<code><template>
  <v-app>
        <v-data-table
          :items="items"
          :headers="headers"
        />
  </v-app>
</template>

<script>
export default {
  data() {
    return {
      items: [
         { first_name: "Peter", last_name: "Johnson" },
         { first_name: "Simon", last_name: "Walker" }
       ],
      headers: [
        { text: "first_name", value: "first_name" },
        { text: "last_name", value: "last_name" },
      ]
    };
  }
};
</script>
</code>```

For example I want to put Peter Johnson in Full name column of my v-data-table, While it doesn't have Full name column.

答:
You can render a virtual column with the use of slots with v-data-table. But you need to have a column full_name.

<v-data-table :headers="headers" :items="items">
  <template #item.full_name="{ item }">{{ item.first_name }} {{ item.last_name }}</template>
</v-data-table>
```

<pre class="lang-js prettyprint-override"><code>export default {
  data() {
    return {
      items: [
        { first_name: "Peter", last_name: "Johnson" },
        { first_name: "Simon", last_name: "Walker" }
      ],
      headers: [{ text: "Full Name", value: "full_name" }]
    };
  }
};
</code>```

https://vuetifyjs.com/en/components/data-tables#slots

Body:
Is it possible to merge to values and put into one column in v-data-table?

List.vue

<template>
  <v-app>
        <v-data-table
          :items="items"
          :headers="headers"
        />
  </v-app>
</template>

For example I want to put Peter Johnson in Full name column of my v-data-table, While it doesn't have Full name column.

Body:
You can render a virtual column with the use of slots with v-data-table. But you need to have a column full_name.

<v-data-table :headers="headers" :items="items">
  <template #item.full_name="{ item }">{{ item.first_name }} {{ item.last_name }}</template>
</v-data-table>

export default {
  data() {
    return {
      items: [
        { first_name: "Peter", last_name: "Johnson" },
        { first_name: "Simon", last_name: "Walker" }
      ],
      headers: [{ text: "Full Name", value: "full_name" }]
    };
  }
};

https://vuetifyjs.com/en/components/data-tables#slots