问:
How can I use the logic in a Laravel policy class to protect a vue router route?
My application consists of an API built with Laravel, and a front-end SPA using Vue.js and Vue Router.

I've written a policy class in Laravel that has some logic to determine if a user is able to create/read/update/delete a resource. The pages to perform these actions are Vue Router routes, and are defined in my routes.js file following the normal url scheme:

```<code>GET  /tasks (all tasks)
GET  /tasks/:task (show task)
GET  /tasks/create (create task)
GET  /tasks/:task/edit (edit task)
...
</code>```

Take for example the edit task route: I'd like to use the Vue Router navigation guards to redirect the user if they do not have permission to edit the task. That logic is defined in my API policy class with something like this:

```<code>// App\Policies\TaskPolicy

public function update(User $user, Task $task)
{
    return $user->hasRole('foo') && ($task->owner === $user->id);
}
</code>```

In my Vue Router routes file how can I utilize the TaskPolicy logic and check if the user is able to edit a task without duplicating it in Vue.js?

答:
I recommend calling an initial endpoint when Vue.JS first starts/loads. This endpoint should include a list of permissions that user has. Those permissions should define what user can see on the FE.

Regarding permissions for things such as update, one of the permissions can be called task.update if it's present within the initial endpoint then Vue.JS will know that logged in user can update a task.

Also, if user does call an endpoint for whatever reason, your Laravel App, thanks to Policy you created, should respond with 403 code.

Example permissions management plugin: Spatie Permission or you can create your own one... it depends on difficulty of your software

UPDATE

If you are listing all tasks from list endpoint, event the ones that dont belong to logged in user, than you can always add an extra attribute to the Task model that will indicate if logged in user can update the task. This attribute can be called editable and will be a boolean. If editable is false then Vue.JS knows not to display edit button and so onwrads.

Body:
My application consists of an API built with Laravel, and a front-end SPA using Vue.js and Vue Router.

I've written a policy class in Laravel that has some logic to determine if a user is able to create/read/update/delete a resource. The pages to perform these actions are Vue Router routes, and are defined in my routes.js file following the normal url scheme:

GET  /tasks (all tasks)
GET  /tasks/:task (show task)
GET  /tasks/create (create task)
GET  /tasks/:task/edit (edit task)
...

Take for example the edit task route: I'd like to use the Vue Router navigation guards to redirect the user if they do not have permission to edit the task. That logic is defined in my API policy class with something like this:

// App\Policies\TaskPolicy

public function update(User $user, Task $task)
{
    return $user->hasRole('foo') && ($task->owner === $user->id);
}

In my Vue Router routes file how can I utilize the TaskPolicy logic and check if the user is able to edit a task without duplicating it in Vue.js?


来源: stackexchange

问:
TypeError when parsing Blogger API response: Cannot read property 'url' of undefined
I'm parsing JSON feed from the blogger API but its throwing following error:

37:59 Uncaught TypeError: Cannot read property 'url' of undefined

Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.

Javascript Code:

```

JsFiddle: https://jsfiddle.net/645pg9rz/

答:
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.

Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.

ContentLicense: CC BY-SA 4.0

Body:
I'm parsing JSON feed from the blogger API but its throwing following error:

37:59 Uncaught TypeError: Cannot read property 'url' of undefined

Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.

Javascript Code:

JsFiddle: https://jsfiddle.net/645pg9rz/


问:
findOneandUpdate mongoose
I am trying to insert a document only if it does not exist.

The following is my code:

```<code>export const login = ({ bodymen: { body } }, res, next) =>
    Login.findOneAndUpdate(
      {phoneNumber:body.phoneNumber},
      { $set: {phoneNumber:body.phoneNumber }},
      {new: true, upsert: true }
    )
    .then((login) => login.view(true))
    .then(success(res, 201))
    .catch(next)
</code>```

In my index.js, I have the routes like this

```<code>router.post('/login', body({ phoneNumber }), login)
</code>```

The problem is that it ends up adding a null value for Phone Number. Any help is much appreciated

答:
Try This</p>

```<code>router.post('/login', (req, res) => {
Login.findOneAndUpdate(
      {phoneNumber: req.body.phoneNumber},
      { $set: {phoneNumber: req.body.phoneNumber }},
      {new: true, upsert: true }
    )
    .then((login) => login.view(true))
    .then(success(res, 201))
    .catch(next)
})
}
</code>```

Title: findOneandUpdate mongoose

Body:
I am trying to insert a document only if it does not exist.

The following is my code:

export const login = ({ bodymen: { body } }, res, next) =>
    Login.findOneAndUpdate(
      {phoneNumber:body.phoneNumber},
      { $set: {phoneNumber:body.phoneNumber }},
      {new: true, upsert: true }
    )
    .then((login) => login.view(true))
    .then(success(res, 201))
    .catch(next)

In my index.js, I have the routes like this

router.post('/login', body({ phoneNumber }), login)

The problem is that it ends up adding a null value for Phone Number. Any help is much appreciated

Body:
Try This

router.post('/login', (req, res) => {
Login.findOneAndUpdate(
      {phoneNumber: req.body.phoneNumber},
      { $set: {phoneNumber: req.body.phoneNumber }},
      {new: true, upsert: true }
    )
    .then((login) => login.view(true))
    .then(success(res, 201))
    .catch(next)
})
}


问:
Why is this for loop skipping the second part sometimes?
This is part of a minimax function that I'm trying to write for tic tac toe. Specifically, this is part of the "maxi" function that the max player calls, which calls mini, which calls maxi, etc. The program is not finding the optimal way of playing. When I run the debugger, sometimes it runs through the whole for loop, and other times, after calling mini on the third line, it will go back to the first line for no reason. Is there some syntactic reason I missed?</p>

```<code>    for i in acts:
        res = result(board, i)
        minboard = mini(res, alpha, beta)
        if utility(minboard) > maxv:
            maxv = utility(minboard)
            x = i
        if maxv > alpha:
            alpha = maxv
        if beta <= alpha:
            break
</code>```

答:
I am not fully aware of how the mini and utility functions work but my gut feeling is that the loop stops as none of your if conditions are met. The usual structure would be, if, elif, else, not just 3 if statements.</p>

```<code>for i in acts:
    res = result(board, i)
    minboard = mini(res, alpha, beta)
    if utility(minboard) > maxv:
        maxv = utility(minboard)
        x = i
    elif maxv > alpha:
        alpha = maxv
    else:
        break
</code>```

Body:
This is part of a minimax function that I'm trying to write for tic tac toe. Specifically, this is part of the "maxi" function that the max player calls, which calls mini, which calls maxi, etc. The program is not finding the optimal way of playing. When I run the debugger, sometimes it runs through the whole for loop, and other times, after calling mini on the third line, it will go back to the first line for no reason. Is there some syntactic reason I missed?

    for i in acts:
        res = result(board, i)
        minboard = mini(res, alpha, beta)
        if utility(minboard) > maxv:
            maxv = utility(minboard)
            x = i
        if maxv > alpha:
            alpha = maxv
        if beta <= alpha:
            break

Body:
I am not fully aware of how the mini and utility functions work but my gut feeling is that the loop stops as none of your if conditions are met. The usual structure would be, if, elif, else, not just 3 if statements.

for i in acts:
    res = result(board, i)
    minboard = mini(res, alpha, beta)
    if utility(minboard) > maxv:
        maxv = utility(minboard)
        x = i
    elif maxv > alpha:
        alpha = maxv
    else:
        break


问:
How to use the Time period in date time
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:

```<code>const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
</code>```

And then in the values I am using it like this.

```<code>StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),
</code>```

In that case It is sending the value like this:

```<code>startDate: "2021-01-01T00:00:00"
</code>```

Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...

答:
Its because you are only setting year, month and date while creating moment object. You are not setting time

You should do something like

```<code>const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.year(year);
    currDate.month(month - 1);
    currDate.date(day);
    return currDate.toISOString(true).split('.')[0];
}
</code>```

Or simply use set function

```<code>const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.set({
        'year': year,
        'month': (month - 1),
        'date': day
    });
    return currDate.toISOString(true).split('.')[0];
}
</code>```

Title: How to use the Time period in date time

Body:
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:

const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];

And then in the values I am using it like this.

StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),

In that case It is sending the value like this:

startDate: "2021-01-01T00:00:00"

Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...

Body:
Its because you are only setting year, month and date while creating moment object. You are not setting time

You should do something like

const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.year(year);
    currDate.month(month - 1);
    currDate.date(day);
    return currDate.toISOString(true).split('.')[0];
}

Or simply use set function

const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.set({
        'year': year,
        'month': (month - 1),
        'date': day
    });
    return currDate.toISOString(true).split('.')[0];
}


问:
Apache not starting in linux mint
Ok, so, I'm fairly new to Apache: I was trying to create a local website (created the .conf file in sites-available folder, created the folder in var/www/mysite/ etc.) then, I stopped Apache (with systemctl stop apache2.service) but now if I try to restart (systemctl restart apache2.service) it throws this error:

Job for apache2.service failed because the control process exited with >error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

This is the result of journalctl -xe:

```<code>Mar 22 16:33:13 user-xxx apache2[10403]:  * Starting Apache httpd web server apach
Mar 22 16:33:13 user-xxx apache2[10403]:  *
Mar 22 16:33:13 user-xxx apache2[10403]:  * The apache2 configtest failed.
Mar 22 16:33:13 user-xxx apache2[10403]: Output of config test was:
Mar 22 16:33:13 user-xxx apache2[10403]: apache2: Syntax error on line 140 of /etc/apache2/apache2.conf:
Mar 22 16:33:13 user-xxx apache2[10403]: Action 'configtest' failed.
</code>```

And the line 140 in /etc/apache2/apache2.conf:

```<code># Include module configuration:
IncludeOptional mods-enabled/*.load <--This one
IncludeOptional mods-enabled/*.conf
</code>```

So I tried:

```<code>sudo apt-get install libapache2-mod-php
</code>```

And I get:

```<code>libapache2-mod-php is already the newest version (1:7.2+60+ubuntu16.04.1+deb.sury.org+1).
</code>```

What else I tried: removing Apache and installing again, installing lamp (sudo apt-get install lamp-server^).
I already removed: mysite.conf from available.sites ...

Nothing seems to make it work, I keep getting "Job for apache2.service failed".

答:
I faced the error:

Syntax error on line 146 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/

after upgrading from Ubuntu 18.04 to 20.04 (php 7.3 to php 7.4)

I solved it by running

```<code>sudo apt install libapache2-mod-php7.4
</code>```

ContentLicense: CC BY-SA 3.0

Title: Apache not starting in linux mint

Body:
Ok, so, I'm fairly new to Apache: I was trying to create a local website (created the .conf file in sites-available folder, created the folder in var/www/mysite/ etc.) then, I stopped Apache (with systemctl stop apache2.service) but now if I try to restart (systemctl restart apache2.service) it throws this error:

Job for apache2.service failed because the control process exited with >error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

This is the result of journalctl -xe:

Mar 22 16:33:13 user-xxx apache2[10403]:  * Starting Apache httpd web server apach
Mar 22 16:33:13 user-xxx apache2[10403]:  *
Mar 22 16:33:13 user-xxx apache2[10403]:  * The apache2 configtest failed.
Mar 22 16:33:13 user-xxx apache2[10403]: Output of config test was:
Mar 22 16:33:13 user-xxx apache2[10403]: apache2: Syntax error on line 140 of /etc/apache2/apache2.conf:
Mar 22 16:33:13 user-xxx apache2[10403]: Action 'configtest' failed.

And the line 140 in /etc/apache2/apache2.conf:

# Include module configuration:
IncludeOptional mods-enabled/*.load <--This one
IncludeOptional mods-enabled/*.conf

So I tried:

sudo apt-get install libapache2-mod-php

And I get:

libapache2-mod-php is already the newest version (1:7.2+60+ubuntu16.04.1+deb.sury.org+1).

What else I tried: removing Apache and installing again, installing lamp (sudo apt-get install lamp-server^).
I already removed: mysite.conf from available.sites ...

Nothing seems to make it work, I keep getting "Job for apache2.service failed".

Body:
I faced the error:

Syntax error on line 146 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/

after upgrading from Ubuntu 18.04 to 20.04 (php 7.3 to php 7.4)

I solved it by running

sudo apt install libapache2-mod-php7.4


问:
matplotlib plots 2 line instead of 1
I have this python array:

when I use this code:

```<code>plt.plot(t, 10 * t)
</code>```

I get the following line:

But when I use this code:

```<code>plt.plot(t, t**2)
</code>```

I get 2 lines:

What am I doing wrong here, why is it plotting 2 lines instead of 1??

答:
Your array is not in sorted order.  Most values are not displayed in the string representation that you show, but the fact that it is not sorted can be seen from the last two values that are displayed.  Exactly what it does contain is unclear - maybe it turns round and backtracks on itself - but if in some place it contains the largest value immediately followed by the smallest value (or values close to these) then this will result in a straight line connecting them, which will be obvious in the quadratic plot, but which in the linear case will not be distinguishable separately from the rest of the plot.

It would be worth plotting simply plt.plot(t) to see what you actually have.  Also try

```<code>t = numpy.sort(t)
plt.plot(t, t**2)
</code>```

Title: matplotlib plots 2 line instead of 1

Body:
I have this python array:

when I use this code:

plt.plot(t, 10 * t)

I get the following line:

But when I use this code:

plt.plot(t, t**2)

I get 2 lines:

What am I doing wrong here, why is it plotting 2 lines instead of 1??

Body:
Your array is not in sorted order.  Most values are not displayed in the string representation that you show, but the fact that it is not sorted can be seen from the last two values that are displayed.  Exactly what it does contain is unclear - maybe it turns round and backtracks on itself - but if in some place it contains the largest value immediately followed by the smallest value (or values close to these) then this will result in a straight line connecting them, which will be obvious in the quadratic plot, but which in the linear case will not be distinguishable separately from the rest of the plot.

It would be worth plotting simply plt.plot(t) to see what you actually have.  Also try

t = numpy.sort(t)
plt.plot(t, t**2)


问:
Postman request to PHP using POST
This is my code:

<?php
    if(isset($_POST["test"]))
        echo $_POST["test"];
    if(isset($_GET["test"]))
        echo $_GET["test"];
?>
```

My question is: why POST request doesn't work?

I have tried different parameters in the body and the header and nothing works.

GET request in Postman works:

POST request in Postman fails:

答:
```<code><?php
  $name = $_POST['name'];
  echo $name;
?>
</code>```

Title: Postman request to PHP using POST

Body:
This is my code:

<?php
    if(isset($_POST["test"]))
        echo $_POST["test"];
    if(isset($_GET["test"]))
        echo $_GET["test"];
?>

My question is: why POST request doesn't work?

I have tried different parameters in the body and the header and nothing works.

GET request in Postman works:

POST request in Postman fails:


问:
"There was an error running the selected code generator" in VS 2013 scaffolding
I'm creating a new view off of a model.

The error message I am getting is

Error

  There was an error running the selected code generator:

  'Access to the path

  'C:\Users\XXXXXXX\AppData\Local\Temp\SOMEGUID\EntityFramework.dll' is denied'.

I am running VS 2013 as administrator.

I looked at Is MvcScaffolding compatible with VS 2013 RC by command line? but this didn't seem to resolve the issue.

VS2013
C#5
MVC5
Brand new project started in VS 2013.

答: It may be due to differences in the versions of nuget packages. See if you have this by going to dependencies->nuget packages folder in your solution. Try installing all of them of a single version and restart the visual studio after cleaning the componentmodelcache folder as mentioned above. This should the get the work done for you.</p>


问:
How can i change value ListPreference from another Activity
I have Activity for ListPreference and i can change any values in it , but my question i want to change a value in ListPreference first time without the user enters to activity that there is ListPreference .
First time a user enters to an app i want to save default value depend on location the user.</p>

答:
I found the solution </p>

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(getString(R.string.settings_method_key),repear);
        editor.commit();
</code>```

Body:
I found the solution

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(getString(R.string.settings_method_key),repear);
        editor.commit();


问:
Adding column conditioning on the other columns
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

```<code>x  y
3  4
5  2
6  6
1  7
9  4
</code>```

Output required:

```<code>x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4
</code>```

答:
If I get it correctly, you are looking for minimum value out of several columns. You can use pmin function:

```<code>library(dplyr)
df <- data.frame(x = c(3,5,6,1,9),
                 y = c(4,2,6,7,4))

df <- df %>% mutate(z = pmin(x, y))
</code>```

result:

```<code>> df
  x y z
1 3 4 3
2 5 2 2
3 6 6 6
4 1 7 1
5 9 4 4
</code>```

It will count minimum value in a data frame row wise and will simplify syntax if you would like to include more than 2 columns:

```<code>df <- data.frame(x = c(3, 5, 6, 1, 9),
                 y = c(4, 2, 6, 7, 4),
                 a = c(2, 5, 7, 3, 3))

df <- df %>% mutate(z = pmin(x, y, a))
</code>```

result:

```<code>> df
  x y a z
1 3 4 2 2
2 5 2 5 2
3 6 6 7 6
4 1 7 3 1
5 9 4 3 3
</code>```

Body:
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

x  y
3  4
5  2
6  6
1  7
9  4

Output required:

x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4

Body:
If I get it correctly, you are looking for minimum value out of several columns. You can use pmin function:

library(dplyr)
df <- data.frame(x = c(3,5,6,1,9),
                 y = c(4,2,6,7,4))

df <- df %>% mutate(z = pmin(x, y))

result:

> df
  x y z
1 3 4 3
2 5 2 2
3 6 6 6
4 1 7 1
5 9 4 4

It will count minimum value in a data frame row wise and will simplify syntax if you would like to include more than 2 columns:

df <- data.frame(x = c(3, 5, 6, 1, 9),
                 y = c(4, 2, 6, 7, 4),
                 a = c(2, 5, 7, 3, 3))

df <- df %>% mutate(z = pmin(x, y, a))

result:

> df
  x y a z
1 3 4 2 2
2 5 2 5 2
3 6 6 7 6
4 1 7 3 1
5 9 4 3 3


问:
whoami command is showing different user name in jenkins cli and linux cli although workspace i
enter image description hereHi All,

"whoami" command is showing as different user. when I am giving this command in jenkins cli it is showing as jenkins but in the same workspace when I am giving this command in linux CLI it is showing as lokeshk.I have followed many forum, link and community in the internet but still I am facing this issue. I have attached screenshot please have a look.Any leads will be appreciated.

enter image description here

答:
Let's understand it using example. I am using CentOS 7. If you have installed Jenkins using all defaults, it will create a user jenkins. You can check it using:

```<code>[centos@infra ~]$ grep jenkins /etc/passwd
jenkins:x:996:993:Jenkins Automation Server:/var/lib/jenkins:/bin/false
</code>```

Now, if you run a Jenkins job, it will display output similar to the following:

As you can see above, i ran two commands, ps -ef and whoami. We can see that Jenkins application is running as user jenkins. Output of whoami is also jenkins.

Now, i logged into the machine as user centos. You can see that by the output shown below:

```<code>[centos@infra ~]$ whoami
centos
</code>```

Switching directory doesn't affect the output of whoami

```<code>[centos@infra ~]$ pwd
/home/centos
[centos@infra ~]$ whoami
centos
[centos@infra ~]$ cd /var/lib/jenkins/workspace/job-a
[centos@infra job-a]$ whoami
centos
</code>```

Now, if i want to see the same output on command line for whoami as i am seeing in the Jenkins log, then i will first have to switch to jenkins user. Since jenkins, by default, is configured to run as a service account, no shell (/bin/false) is assigned to it as you can see in the first output above. Just to clear your doubt, i will change the shell to /bin/bash temporarily.

```<code>[centos@infra job-a]$ sudo vim /etc/passwd
[centos@infra job-a]$ grep jenkins /etc/passwd
jenkins:x:996:993:Jenkins Automation Server:/var/lib/jenkins:/bin/bash
</code>```

Now if i try to switch to jenkins user and observe the output of whoami, you will see what you wanted to see. :)

```<code>[centos@infra job-a]$ sudo su - jenkins
Last login: Sat May 30 09:48:56 UTC 2020 on pts/0
-bash-4.2$ whoami
jenkins
-bash-4.2$ cd /var/lib/jenkins/workspace/job-a
-bash-4.2$ whoami
jenkins
</code>```

Hope that clears your doubt.

Body:
Let's understand it using example. I am using CentOS 7. If you have installed Jenkins using all defaults, it will create a user jenkins. You can check it using:

[centos@infra ~]$ grep jenkins /etc/passwd
jenkins:x:996:993:Jenkins Automation Server:/var/lib/jenkins:/bin/false

Now, if you run a Jenkins job, it will display output similar to the following:

As you can see above, i ran two commands, ps -ef and whoami. We can see that Jenkins application is running as user jenkins. Output of whoami is also jenkins.

Now, i logged into the machine as user centos. You can see that by the output shown below:

[centos@infra ~]$ whoami
centos

Switching directory doesn't affect the output of whoami

[centos@infra ~]$ pwd
/home/centos
[centos@infra ~]$ whoami
centos
[centos@infra ~]$ cd /var/lib/jenkins/workspace/job-a
[centos@infra job-a]$ whoami
centos

Now, if i want to see the same output on command line for whoami as i am seeing in the Jenkins log, then i will first have to switch to jenkins user. Since jenkins, by default, is configured to run as a service account, no shell (/bin/false) is assigned to it as you can see in the first output above. Just to clear your doubt, i will change the shell to /bin/bash temporarily.

[centos@infra job-a]$ sudo vim /etc/passwd
[centos@infra job-a]$ grep jenkins /etc/passwd
jenkins:x:996:993:Jenkins Automation Server:/var/lib/jenkins:/bin/bash

Now if i try to switch to jenkins user and observe the output of whoami, you will see what you wanted to see. :)

[centos@infra job-a]$ sudo su - jenkins
Last login: Sat May 30 09:48:56 UTC 2020 on pts/0
-bash-4.2$ whoami
jenkins
-bash-4.2$ cd /var/lib/jenkins/workspace/job-a
-bash-4.2$ whoami
jenkins

Hope that clears your doubt.


问:
Calling stored procedure with return value
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

```<code>ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end
</code>```

Code calling the stored procedure:

```<code>SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();
</code>```

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.

答: ExecuteScalar(); will work, but an output parameter would be a superior solution.

Body:
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end

Code calling the stored procedure:

SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.


问:
Next.js: one page that match root '/' and dynamic route '/param'
I have a website as a single page that is using Next.js. I have the home page on route / that show a list of products. The code of this page is located in pages/index.js. Each product has an id so I can jump to it using /#product-id.

To make it more url friendly I replicate this behaviour using the product-id as a second param in the route like that: /product-id.

What I do is simply looking on the product-id param using useRouter():

const selectedProductId = useRouter().query['product-id']
```

<p>And then scroll to the element with this id using <code>js</code>:</p>

<pre class="lang-js prettyprint-override"><code>document.getElementById(selectedProductId ).scrollIntoView()
</code>```

So I to change my script name from /pages/index.js to /pages/[product-id].js.

So now the route /1234 work has expected but if I go to / I get error 404.

So has someone an idea how I can match / and /param using one js file?

答:
Nextjs has file system based routing, so if you remove /pages/index.js of course you will get an 404 error. Also /pages/index.js and /pages/[product-id].js will render two separate pages.

To answer your question, if it is possible to match two routes like / and /[productId] in one file using nextjs I don't think that is possible however similar results can be achieved by using shallow routing specific to your use case.

So for your use case, I suggest using shallow routing unless you want to render the same component in both pages just to get the product-id or want to make use of hash URLs.

You can make product-id a query string parameter and update it using shallow-routing. Here is an example,

Keep /pages/index.js

import { useRouter } from 'next/router';

const router = useRouter()

// when want to change the productId call
router.push('/?productId=1234', undefined, { shallow: true })

// call the scrollToView inside a useEffect hook
useEffect(() => {
    const productId = router.query.productId
    // get the element using the productId above then call scrollIntoView()
})

// if using useEffect with the dependency router.query.productId,
// when you change the productId once and scroll up and try to change to the same -
// productId again it will not scroll to view, hence not using the dependency array
// at all
```

To explain more on what shallow routing does

Shallow routing will allow the change of URL without running the data fetching methods i.e getStaticProps or getServerSideProps again. Which will make the updated query and pathname available without changing the state. Read more about it nextjs docs.

Body:
I have a website as a single page that is using Next.js. I have the home page on route / that show a list of products. The code of this page is located in pages/index.js. Each product has an id so I can jump to it using /#product-id.

To make it more url friendly I replicate this behaviour using the product-id as a second param in the route like that: /product-id.

What I do is simply looking on the product-id param using useRouter():

const selectedProductId = useRouter().query['product-id']

And then scroll to the element with this id using js:

document.getElementById(selectedProductId ).scrollIntoView()

So I to change my script name from /pages/index.js to /pages/[product-id].js.

So now the route /1234 work has expected but if I go to / I get error 404.

So has someone an idea how I can match / and /param using one js file?

Body:
Nextjs has file system based routing, so if you remove /pages/index.js of course you will get an 404 error. Also /pages/index.js and /pages/[product-id].js will render two separate pages.

To answer your question, if it is possible to match two routes like / and /[productId] in one file using nextjs I don't think that is possible however similar results can be achieved by using shallow routing specific to your use case.

So for your use case, I suggest using shallow routing unless you want to render the same component in both pages just to get the product-id or want to make use of hash URLs.

You can make product-id a query string parameter and update it using shallow-routing. Here is an example,

Keep /pages/index.js

import { useRouter } from 'next/router';

const router = useRouter()

// when want to change the productId call
router.push('/?productId=1234', undefined, { shallow: true })

// call the scrollToView inside a useEffect hook
useEffect(() => {
    const productId = router.query.productId
    // get the element using the productId above then call scrollIntoView()
})

// if using useEffect with the dependency router.query.productId,
// when you change the productId once and scroll up and try to change to the same -
// productId again it will not scroll to view, hence not using the dependency array
// at all

To explain more on what shallow routing does

Shallow routing will allow the change of URL without running the data fetching methods i.e getStaticProps or getServerSideProps again. Which will make the updated query and pathname available without changing the state. Read more about it nextjs docs.


问:
Audio files multiple upload not working with php
I created the PHP form below to send mp3 files to a database.

```<code><form action="" method="post" id="audioForm" enctype="multipart/form-data">
    <div class="form-group">
        <div class="row audiosRow">
            <div class="col s12">
                <div class="file-field input-field">
                    <div class="btn btn-small">
                        <span>Track</span>
                        <input type="file" name="file-1">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">
                    </div>
                </div>
            </div>
            <div class="col s12">
                <div class="file-field input-field">
                    <div class="btn btn-small">
                        <span>Track</span>
                        <input type="file" name="file-2">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">
                    </div>
                </div>
            </div>
            <div class="col s12">
                <div class="file-field input-field">
                    <div class="btn btn-small">
                        <span>Track</span>
                        <input type="file" name="file-3">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">
                    </div>
                </div>
            </div>
            <div class="col s12">
                <div class="file-field input-field">
                    <div class="btn btn-small">
                        <span>Track</span>
                        <input type="file" name="file-4">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">
                    </div>
                </div>
            </div>
            <div class="col s12">
                <div class="file-field input-field">
                    <div class="btn btn-small">
                        <span>Track</span>
                        <input type="file" name="file-5">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">
                    </div>
                </div>
            </div>
            <div class="col s12">
                <button class="btn btn-small" type="submit" name="submit">Save</button>
            </div>
        </div>
    </div>
</form>
</code>```

The form works fine when I send images, but when I send audio files, it doesn't work with three or more. When I make a var_dump($_FILES) it displays array(0){}.

So I think it's probably a limitation, but I don't see that anywhere. I checked the php.ini configuration file, I have upload_max_filesize = 200M and max_file_uploads = 20.

So where can the problem be? Please help me.

答: I just saw where the problem was. post_max_size was limited to 8. It had to be reduced to 0 post_max_size=0 to make it unlimited. See the php documentation

Body:
I created the PHP form below to send mp3 files to a database.

<form action="" method="post" id="audioForm" enctype="multipart/form-data">

                        Track
                        <input type="file" name="file-1">

                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">

                        Track
                        <input type="file" name="file-2">

                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">

                        Track
                        <input type="file" name="file-3">

                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">

                        Track
                        <input type="file" name="file-4">

                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">

                        Track
                        <input type="file" name="file-5">

                        <input class="file-path validate" type="text" placeholder="Upload audio files* (.mp3)" readonly="">

                <button class="btn btn-small" type="submit" name="submit">Save</button>

</form>

The form works fine when I send images, but when I send audio files, it doesn't work with three or more. When I make a var_dump($_FILES) it displays array(0){}.

So I think it's probably a limitation, but I don't see that anywhere. I checked the php.ini configuration file, I have upload_max_filesize = 200M and max_file_uploads = 20.

So where can the problem be? Please help me.


问:
how to hold a session with passport?
So, i'd like my user session to persist upon login/signup, which it does not.

The official documentation says to add this to start with :

```<code>  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
</code>```

which I did. Then it goes on to specify :

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

```<code>passport.serializeUser(function(user, done) {
  console.log("serialize user: ", user);
  done(null, user[0]._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
</code>```

If I understand correctly, upon login, the user should see a new cookie being set.
My serialize and deserialize functions seem to work. The console will log the user details after I login a user. No error message in the console.
However, I don't see any cookie when I login a user.

Am I supposed to add an additional command manually ? something like this :

```<code>res.cookie('userid', user.id, { maxAge: 2592000000 });
</code>```

I am using Redux, so am I supposed to deal with the persistent session via the reducer instead, with my authenticated (true or false) variable ?

I think I am a bit confused right now between what is supposed to be done on the server side and what is supposed to be done on the client side.

答:
1
Check hostname.
In my case, cookie was set on 127.0.0.1, not localhost.

2
Make sure express session is called before passport session.

Title: how to hold a session with passport?

Body:
So, i'd like my user session to persist upon login/signup, which it does not.

The official documentation says to add this to start with :

  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());

which I did. Then it goes on to specify :

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

passport.serializeUser(function(user, done) {
  console.log("serialize user: ", user);
  done(null, user[0]._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

If I understand correctly, upon login, the user should see a new cookie being set.
My serialize and deserialize functions seem to work. The console will log the user details after I login a user. No error message in the console.
However, I don't see any cookie when I login a user.

Am I supposed to add an additional command manually ? something like this :

res.cookie('userid', user.id, { maxAge: 2592000000 });

I am using Redux, so am I supposed to deal with the persistent session via the reducer instead, with my authenticated (true or false) variable ?

I think I am a bit confused right now between what is supposed to be done on the server side and what is supposed to be done on the client side.


问:
Why doesn't ~= work on enums and strings?
While I was trying to answer another question, I found out that this code doesn't work:

```<code>enum Response {
    case positive
    case negative
    case neutral
}

func ~=(pattern: Response, value: String) -> Bool {
    switch pattern {
    case .positive:
        return ["yep", "yes", "yay", "definitely", "ok", "correct"]
            .contains(value.lowercased())
    case .negative:
        return ["no", "nope", "nah", "definitely not", "no way"]
            .contains(value.lowercased())
    case .neutral:
        return ["meh", "don't know", "indifferent", "don't care"]
            .contains(value.lowercased())
    }
}

switch "yep" {
case Response.positive:
    print("That was a positive response")
case Response.negative:
    print("That was a negative response")
case Response.neutral:
    print("That was a neutral response")
default:
    print("Something else")
}
</code>```

I was trying to use the ~= operator to allow pattern matching between strings and the Response enum, so that I can classify strings as a positive, negative, or neutral response (to a prompt).

Yes, I could have written the string values I accept for each kind of response directly into the switch cases, like

```<code>case "yep", "yes", "yay", "definitely", "ok", "correct":
    print("That was a positive response")
</code>```

But I think saying case Response.positive creates another layer of abstraction, and allows late binding. I can read the acceptable responses from a file, for example.

From my knowledge, the first code snippet should work. I've defined a ~= operator. I've unambiguously stated the enum values in the switch cases. The documentation doesn't say ~= is not allowed on enums. Even print(Response.positive ~= "yep") prints true. But the switch cases emit the error of:

Enum case 'positive' is not a member of type 'String'

(Of course it's not! You dummy! :D)

Why does it not work and how can I fix it?

答:
Works in the following notation. Tested with Xcode 11.4</p>

```<code>switch "yep" {
case .positive:
    print("That was a positive response")
case .negative:
    print("That was a negative response")
case .neutral:
    print("That was a neutral response")
default:
    print("Something else")
}
</code>```

Body:
While I was trying to answer another question, I found out that this code doesn't work:

enum Response {
    case positive
    case negative
    case neutral
}

func ~=(pattern: Response, value: String) -> Bool {
    switch pattern {
    case .positive:
        return ["yep", "yes", "yay", "definitely", "ok", "correct"]
            .contains(value.lowercased())
    case .negative:
        return ["no", "nope", "nah", "definitely not", "no way"]
            .contains(value.lowercased())
    case .neutral:
        return ["meh", "don't know", "indifferent", "don't care"]
            .contains(value.lowercased())
    }
}

switch "yep" {
case Response.positive:
    print("That was a positive response")
case Response.negative:
    print("That was a negative response")
case Response.neutral:
    print("That was a neutral response")
default:
    print("Something else")
}

I was trying to use the ~= operator to allow pattern matching between strings and the Response enum, so that I can classify strings as a positive, negative, or neutral response (to a prompt).

Yes, I could have written the string values I accept for each kind of response directly into the switch cases, like

case "yep", "yes", "yay", "definitely", "ok", "correct":
    print("That was a positive response")

But I think saying case Response.positive creates another layer of abstraction, and allows late binding. I can read the acceptable responses from a file, for example.

From my knowledge, the first code snippet should work. I've defined a ~= operator. I've unambiguously stated the enum values in the switch cases. The documentation doesn't say ~= is not allowed on enums. Even print(Response.positive ~= "yep") prints true. But the switch cases emit the error of:

Enum case 'positive' is not a member of type 'String'

(Of course it's not! You dummy! :D)

Why does it not work and how can I fix it?

Body:
Works in the following notation. Tested with Xcode 11.4

switch "yep" {
case .positive:
    print("That was a positive response")
case .negative:
    print("That was a negative response")
case .neutral:
    print("That was a neutral response")
default:
    print("Something else")
}


问:
How to install dotnetnuke in local system?
Can anyone please guide me how to install dnn in local system. How to setup code files and database? I have windows vista os and sql server Express database installed in my system

Thanks,
Merry

答:
To know more about how to install DNN please flow the below link
https://mydnn.blogspot.com/2017/09/how-to-install-dotnetnuke.html
https://www.c-sharpcorner.com/blogs/how-to-install-dotnetnuke</p>

ContentLicense: CC BY-SA 2.5


问:
In App Purchase
in the App Store Review Guidelines is stated in section that "Apps using IAP to purchase physical goods or  goods and services used outside of the application will be rejected."

Looking also into iOS Developer Program License Agreement referenced in 11.12 of the App Store Review Guidelines I can see there in Attachment 2, section 1. 1.11 that  "You may not use the In  App Purchase API to offer goods or services to be used outside of Your  Application."

1/According to my  understanding everything which is not consumed within the application like  ordering of e.g. paper books, food delivery, flight tickets, electronics cannot  be done via the In App Purchase mechanism. Everything which is consumed within  the application like e-books, video streams, audio streams, new game levels,  etc. (when the provided content is in accordance with App Store Review  Guidelines and iOS Developer Program License Agreement) and user is charged for  this content, the IAP must be used or can be an option to other payment system  as stated in 11.3.

2/ For the In App  Purchase there is not any limit for the 30% fee for the Apple, e.g. theoretically if the content is charged for 10.000USD, Apple takes 3.000USD.

Are my assumptions correct?

BR
STeN

答: I believe your interpretation is correct. Although in-app purchases have to be set at price poitns as well, you can't simply enter an amount.</p>

Title: In App Purchase


问:
Issue with UIProgressView not running smoothly once height is increased and corners are rounded
I'm experiencing an issue with a UIProgressView (using Xcode 11.5 and current Swift version). My aim is to create a progress bar with an increased height (vs. the Apple standard height) and rounded corners, which represents the progress of a played audio file smoothly.

intended progress bar style

I can easily achieve the desired look by combining a height constraint in interface builder with the following code:

```<code>audioProgress.layer.cornerRadius = bubble.frame.size.height / 3
audioProgress.clipsToBounds = true
</code>```

However, the issue I'm experiencing is that the progress bar does not start smoothy from the beginning – instead it jumps to about 1/3 of the bar (changes depending on device size) and stops there, until the audio "catches up" on that position, from where it continues running smoothly until the end.

I made sure this is not an error in my code re audiofiles, timer etc. but some layout issue. E.g. once I change the height of the bar back to Apple's standard height, the progress shows as it should.

I can avoid this odd behaviour by using the below code to increase the bar's height (instead of a constraint):

```<code>let transform: CGAffineTransform = CGAffineTransform(scaleX: 1.0, y: transformFactor)
audioProgress.transform = transform
</code>```

However, this no longer allows me to round the corners as shown above, as the combination of layer.cornerRadius and the CGAffineTransform commands leads to oddly skewed corners, as shown in other posts.

So my 2 questions are:

Can anyone explain what causes this weird behavior of the bar jumping and stopping for a while in the first place? And how to avoid it?

If using the CGAffineTransform command is the only way to go – is there some other way to achieve the rounded corners? E.g. sth along the lines of "first transform the height, and only THEN round the corners" (as opposed to doing it the other way around, which, in my understanding, causes the skewed look...)

答:
Try this - </p>

```<code>    audioProgress?.layer.cornerRadius = bubble.frame.size.height / 3
    audioProgress?.layer.masksToBounds = true
</code>```

Body:
I'm experiencing an issue with a UIProgressView (using Xcode 11.5 and current Swift version). My aim is to create a progress bar with an increased height (vs. the Apple standard height) and rounded corners, which represents the progress of a played audio file smoothly.

intended progress bar style

I can easily achieve the desired look by combining a height constraint in interface builder with the following code:

audioProgress.layer.cornerRadius = bubble.frame.size.height / 3
audioProgress.clipsToBounds = true

However, the issue I'm experiencing is that the progress bar does not start smoothy from the beginning – instead it jumps to about 1/3 of the bar (changes depending on device size) and stops there, until the audio "catches up" on that position, from where it continues running smoothly until the end.

I made sure this is not an error in my code re audiofiles, timer etc. but some layout issue. E.g. once I change the height of the bar back to Apple's standard height, the progress shows as it should.

I can avoid this odd behaviour by using the below code to increase the bar's height (instead of a constraint):

let transform: CGAffineTransform = CGAffineTransform(scaleX: 1.0, y: transformFactor)
audioProgress.transform = transform

However, this no longer allows me to round the corners as shown above, as the combination of layer.cornerRadius and the CGAffineTransform commands leads to oddly skewed corners, as shown in other posts.

So my 2 questions are:

Can anyone explain what causes this weird behavior of the bar jumping and stopping for a while in the first place? And how to avoid it?

If using the CGAffineTransform command is the only way to go – is there some other way to achieve the rounded corners? E.g. sth along the lines of "first transform the height, and only THEN round the corners" (as opposed to doing it the other way around, which, in my understanding, causes the skewed look...)

Body:
Try this -

    audioProgress?.layer.cornerRadius = bubble.frame.size.height / 3
    audioProgress?.layer.masksToBounds = true


问:
Flutter how to handle image with fixed size inside box?
I am new to Flutter and I like it but I am not comfortable building layouts.

I am working on an app that contains a ListView of Cards.
Each card is inside a Container and contains an image (with fixed height and width) and a text.

I am not able to place the image correctly inside the Card. I want the image to cover the width of box.
Thanks.

This is the code:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'MyApp';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView(
          children: <Widget>[
              Container(
                    margin:EdgeInsets.all(8.0),
                    child: Card(
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
                        child: InkWell(
                           onTap: () => print("ciao"),
                           child: Column(
                                children: <Widget>[
                                    ClipRRect(
                                      borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(8.0),
                                        topRight: Radius.circular(8.0),
                                      ),
                                      child: Image.asset(
                                        'img/britannia.jpg',
                                        width: 300,
                                        height: 150,
                                        fit:BoxFit.fill

                                      ),
                                    ),
                                    ListTile(
                                      title: Text('Pub 1'),
                                      subtitle: Text('Location 1'),
                                    ),
                                ],
                           ),
                        ),
                    ),
              ),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
I don't know how.. But this really worked to keep image with fixed size in container
Just add Alignment in container

    Container(
      height: double.infinity,
      alignment: Alignment.center, // This is needed
      child: Image.asset(
        Constants.ASSETS_IMAGES + "logo.png",
        fit: BoxFit.contain,
        width: 300,
      ),
    );
```

Body:
I am new to Flutter and I like it but I am not comfortable building layouts.

I am working on an app that contains a ListView of Cards.
Each card is inside a Container and contains an image (with fixed height and width) and a text.

I am not able to place the image correctly inside the Card. I want the image to cover the width of box.
Thanks.

This is the code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'MyApp';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView(
          children: <Widget>[
              Container(
                    margin:EdgeInsets.all(8.0),
                    child: Card(
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
                        child: InkWell(
                           onTap: () => print("ciao"),
                           child: Column(
                                children: <Widget>[
                                    ClipRRect(
                                      borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(8.0),
                                        topRight: Radius.circular(8.0),
                                      ),
                                      child: Image.asset(
                                        'img/britannia.jpg',
                                        width: 300,
                                        height: 150,
                                        fit:BoxFit.fill

                                      ),
                                    ),
                                    ListTile(
                                      title: Text('Pub 1'),
                                      subtitle: Text('Location 1'),
                                    ),
                                ],
                           ),
                        ),
                    ),
              ),
          ],
        ),
      ),
    );
  }
}


问:
kubernetes cronjob dont works correctly when values are customized
I am using rancher 2.3.3
When I config cronjob with schedule values like @hourly and @daily, works fine.
but when I config it with values like "6 1 * * *" , doesn't work.

OS times are sync between all cluster nodes

My config file

```<code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: samplename
  namespace: samplenamespace
spec:
  schedule: "6 1 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: samplename
              image: myimageaddress:1.0
          restartPolicy: OnFailure
</code>```

答:
I find the root cause
scheduler container has different timezone, so it run with a few hours delay </p>

Body:
I am using rancher 2.3.3
When I config cronjob with schedule values like @hourly and @daily, works fine.
but when I config it with values like "6 1 * * *" , doesn't work.

OS times are sync between all cluster nodes

My config file

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: samplename
  namespace: samplenamespace
spec:
  schedule: "6 1 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: samplename
              image: myimageaddress:1.0
          restartPolicy: OnFailure


问:
Button and Label won't center in Tkinter (Python 3.8)
I'm writing a login interface, my problem is that the login button, and two other labels (one has an image attached to it) won't center in the window. I included a link to an image of the window in this question so you can get a better understanding of what's happening. The problem is in the loginButton, poweredByLabel
 and the gmailLabel. Here is my code:

```<code>emailLabel = Label(contactDeveloperWindow, font = (contactDeveloperFont), text = "Your email:", bg = "#DCDCDC")
emailLabel.grid(row = 1, column = 0, sticky = "w")

emailEntry = Entry(contactDeveloperWindow, font = (contactDeveloperFont), width = 40, borderwidth = 2, relief = "groove")
emailEntry.grid(row = 1, column = 1, columnspan = 3, sticky = "w")
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(contactDeveloperWindow, font = (contactDeveloperFont), text = "Password:  ", bg = "#DCDCDC")
passwordLabel.grid(row = 2, column  = 0, sticky = "w")

passwordEntry = Entry(contactDeveloperWindow, font = (contactDeveloperFont), width = 37, borderwidth = 2, relief = "groove", show = "*")
passwordEntry.grid(row = 2, column = 1, sticky = "w")

hidePassword = ImageTk.PhotoImage(Image.open("hide.png"), master = contactDeveloperWindow)
togglePassword = Button(contactDeveloperWindow, image = hidePassword, relief = "groove", bg = "#DCDCDC", command = updatePassword)
togglePassword.image = hidePassword
togglePassword.grid(row = 2, column = 3, sticky = "w")

loginButton = Button(contactDeveloperWindow, font = (contactDeveloperFont), text = "Login", width = 17, padx = 5, pady = 5, relief = "groove", bg = "#DCDCDC")
loginButton.grid(row = 5, column = 0, columnspan = 3)

poweredByLabel = Label(contactDeveloperWindow, font = ('Consolas', 10), text = "powered by", bg = "#DCDCDC")
poweredByLabel.grid(row = 7, column = 0, columnspan = 3)

gmailLogo = ImageTk.PhotoImage(Image.open("powered by.png"), master = contactDeveloperWindow)
gmailLabel = Label(contactDeveloperWindow, image = gmailLogo, bg = "#DCDCDC")
gmailLabel.image = gmailLogo
gmailLabel.grid(row = 8, column = 0, columnspan = 3)

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 0, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 3, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 4, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 6, column = 0, columnspan = 3, sticky = "we")
</code>```

答:
I can't run code so I only guess

You have to use column=2 instead of column=3 for togglePassword

If you want to keep column=3 then you have to use columnspan=4 instead of columnspan=3 because you will have from column=0 to column=3 which gives 4 columns.

EDIT: More complex change is to use two Frames. At the top Frame with Entries using grid(). At the bottom Frame with login button and image using pack().

In example I keep only important elements. And I use pack(pady=...) to create spaces between elements instead of using empty labels.

```<code>from tkinter import *

contactDeveloperWindow = Tk()

# --- top ---

top_frame = Frame(contactDeveloperWindow)
top_frame.pack(pady=10)

emailLabel = Label(top_frame, text="Your email:")
emailLabel.grid(row=1, column=0)

emailEntry = Entry(top_frame)
emailEntry.grid(row=1, column=1)
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(top_frame, text="Password:")
passwordLabel.grid(row=2, column=0, sticky="w")

passwordEntry = Entry(top_frame, show="*")
passwordEntry.grid(row=2, column=1)

togglePassword = Button(top_frame, text="O")
togglePassword.grid(row=2, column=2)

# --- bottom ---

bottom_frame = Frame(contactDeveloperWindow)
bottom_frame.pack()

loginButton = Button(bottom_frame, text="Login")
loginButton.pack(pady=(0,10))

poweredByLabel = Label(bottom_frame, text="powered by")
poweredByLabel.pack(pady=(0,10))

gmailLabel = Label(bottom_frame, text="[place for logo]" )
gmailLabel.pack(pady=(0,10))

contactDeveloperWindow.mainloop()
</code>```

You can do it even without bottom frame:

```<code>from tkinter import *

contactDeveloperWindow = Tk()

# --- top ---

top_frame = Frame(contactDeveloperWindow)
top_frame.pack(pady=10)

emailLabel = Label(top_frame, text="Your email:")
emailLabel.grid(row=1, column=0)

emailEntry = Entry(top_frame)
emailEntry.grid(row=1, column=1)
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(top_frame, text="Password:")
passwordLabel.grid(row=2, column=0, sticky="w")

passwordEntry = Entry(top_frame, show="*")
passwordEntry.grid(row=2, column=1)

togglePassword = Button(top_frame, text="O")
togglePassword.grid(row=2, column=2)

# --- bottom ---

loginButton = Button(contactDeveloperWindow, text="Login")
loginButton.pack(pady=(0,10))

poweredByLabel = Label(contactDeveloperWindow, text="powered by")
poweredByLabel.pack(pady=(0,10))

gmailLabel = Label(contactDeveloperWindow, text="[place for logo]" )
gmailLabel.pack(pady=(0,10))

contactDeveloperWindow.mainloop()
</code>```

Body:
I'm writing a login interface, my problem is that the login button, and two other labels (one has an image attached to it) won't center in the window. I included a link to an image of the window in this question so you can get a better understanding of what's happening. The problem is in the loginButton, poweredByLabel
 and the gmailLabel. Here is my code:

emailLabel = Label(contactDeveloperWindow, font = (contactDeveloperFont), text = "Your email:", bg = "#DCDCDC")
emailLabel.grid(row = 1, column = 0, sticky = "w")

emailEntry = Entry(contactDeveloperWindow, font = (contactDeveloperFont), width = 40, borderwidth = 2, relief = "groove")
emailEntry.grid(row = 1, column = 1, columnspan = 3, sticky = "w")
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(contactDeveloperWindow, font = (contactDeveloperFont), text = "Password:  ", bg = "#DCDCDC")
passwordLabel.grid(row = 2, column  = 0, sticky = "w")

passwordEntry = Entry(contactDeveloperWindow, font = (contactDeveloperFont), width = 37, borderwidth = 2, relief = "groove", show = "*")
passwordEntry.grid(row = 2, column = 1, sticky = "w")

hidePassword = ImageTk.PhotoImage(Image.open("hide.png"), master = contactDeveloperWindow)
togglePassword = Button(contactDeveloperWindow, image = hidePassword, relief = "groove", bg = "#DCDCDC", command = updatePassword)
togglePassword.image = hidePassword
togglePassword.grid(row = 2, column = 3, sticky = "w")

loginButton = Button(contactDeveloperWindow, font = (contactDeveloperFont), text = "Login", width = 17, padx = 5, pady = 5, relief = "groove", bg = "#DCDCDC")
loginButton.grid(row = 5, column = 0, columnspan = 3)

poweredByLabel = Label(contactDeveloperWindow, font = ('Consolas', 10), text = "powered by", bg = "#DCDCDC")
poweredByLabel.grid(row = 7, column = 0, columnspan = 3)

gmailLogo = ImageTk.PhotoImage(Image.open("powered by.png"), master = contactDeveloperWindow)
gmailLabel = Label(contactDeveloperWindow, image = gmailLogo, bg = "#DCDCDC")
gmailLabel.image = gmailLogo
gmailLabel.grid(row = 8, column = 0, columnspan = 3)

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 0, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 3, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 4, column = 0, columnspan = 3, sticky = "we")

hiddenLabel = Label(contactDeveloperWindow, font = ('Consolas', 1), text = "", bg = "#DCDCDC")
hiddenLabel.grid(row = 6, column = 0, columnspan = 3, sticky = "we")

Body:
I can't run code so I only guess

You have to use column=2 instead of column=3 for togglePassword

If you want to keep column=3 then you have to use columnspan=4 instead of columnspan=3 because you will have from column=0 to column=3 which gives 4 columns.

EDIT: More complex change is to use two Frames. At the top Frame with Entries using grid(). At the bottom Frame with login button and image using pack().

In example I keep only important elements. And I use pack(pady=...) to create spaces between elements instead of using empty labels.

from tkinter import *

contactDeveloperWindow = Tk()

# --- top ---

top_frame = Frame(contactDeveloperWindow)
top_frame.pack(pady=10)

emailLabel = Label(top_frame, text="Your email:")
emailLabel.grid(row=1, column=0)

emailEntry = Entry(top_frame)
emailEntry.grid(row=1, column=1)
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(top_frame, text="Password:")
passwordLabel.grid(row=2, column=0, sticky="w")

passwordEntry = Entry(top_frame, show="*")
passwordEntry.grid(row=2, column=1)

togglePassword = Button(top_frame, text="O")
togglePassword.grid(row=2, column=2)

# --- bottom ---

bottom_frame = Frame(contactDeveloperWindow)
bottom_frame.pack()

loginButton = Button(bottom_frame, text="Login")
loginButton.pack(pady=(0,10))

poweredByLabel = Label(bottom_frame, text="powered by")
poweredByLabel.pack(pady=(0,10))

gmailLabel = Label(bottom_frame, text="[place for logo]" )
gmailLabel.pack(pady=(0,10))

contactDeveloperWindow.mainloop()

You can do it even without bottom frame:

from tkinter import *

contactDeveloperWindow = Tk()

# --- top ---

top_frame = Frame(contactDeveloperWindow)
top_frame.pack(pady=10)

emailLabel = Label(top_frame, text="Your email:")
emailLabel.grid(row=1, column=0)

emailEntry = Entry(top_frame)
emailEntry.grid(row=1, column=1)
emailEntry.insert(0, "example@gmail.com")

passwordLabel = Label(top_frame, text="Password:")
passwordLabel.grid(row=2, column=0, sticky="w")

passwordEntry = Entry(top_frame, show="*")
passwordEntry.grid(row=2, column=1)

togglePassword = Button(top_frame, text="O")
togglePassword.grid(row=2, column=2)

# --- bottom ---

loginButton = Button(contactDeveloperWindow, text="Login")
loginButton.pack(pady=(0,10))

poweredByLabel = Label(contactDeveloperWindow, text="powered by")
poweredByLabel.pack(pady=(0,10))

gmailLabel = Label(contactDeveloperWindow, text="[place for logo]" )
gmailLabel.pack(pady=(0,10))

contactDeveloperWindow.mainloop()


问:
Why does copy constructor not need to check whether the input object pointers to itself or not？
As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.

I am novice in C++.I would be grateful to have some help on this question.

```<code>  class rule_of_three
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void init(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        rule_of_three(const char* s = "") { init(s); }

        ~rule_of_three()
        {
            delete[] cstring;  // deallocate
        }

        rule_of_three(const rule_of_three& other) // copy constructor
        {
            init(other.cstring);
        }

        rule_of_three& operator=(const rule_of_three& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                init(other.cstring);
            }
            return *this;
        }
    };
</code>```

答:
Self-assignment sometimes happens, it's a part of a normal use of a class.

Passing a not-yet-constructed object as a parameter to its own copy (or move) constructor is not normal. While not undefined behavior per se1, there are no good reasons to do it, and it normally doesn't happen. It can happen accidentally, or if someone is deliberately trying to break your class.

Because of that, traditionally copy (and move) constructors don't check for &other != this.

But nothing stops you from doing it, if you want some extra safety:

```<code>rule_of_three(const rule_of_three& other) // copy constructor
{
    assert(&other != this);
    init(other.cstring);
}
</code>```

1 [basic.life]/7 seems to allow that, as long as you don't access the not-yet-constructed object itself. Taking an address of it using & is allowed.

Body:
As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.

I am novice in C++.I would be grateful to have some help on this question.

  class rule_of_three
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void init(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        rule_of_three(const char* s = "") { init(s); }

        ~rule_of_three()
        {
            delete[] cstring;  // deallocate
        }

        rule_of_three(const rule_of_three& other) // copy constructor
        {
            init(other.cstring);
        }

        rule_of_three& operator=(const rule_of_three& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                init(other.cstring);
            }
            return *this;
        }
    };

Body:
Self-assignment sometimes happens, it's a part of a normal use of a class.

Passing a not-yet-constructed object as a parameter to its own copy (or move) constructor is not normal. While not undefined behavior per se1, there are no good reasons to do it, and it normally doesn't happen. It can happen accidentally, or if someone is deliberately trying to break your class.

Because of that, traditionally copy (and move) constructors don't check for &other != this.

But nothing stops you from doing it, if you want some extra safety:

rule_of_three(const rule_of_three& other) // copy constructor
{
    assert(&other != this);
    init(other.cstring);
}

1 [basic.life]/7 seems to allow that, as long as you don't access the not-yet-constructed object itself. Taking an address of it using & is allowed.


问:
How to fix the '\r' function Windows/Mac OS
I have an issue where I wish to get rid of some print, but it's ignored entirely and several lines are printed out. I have always used \r for these solutions. Is there a way round this scenario? (I'm using Mac OS for now, but guaranteed, will switch over to Windows soon.) @Feodoran told me that the \r only really works for Linux computers, which is an issue. The code for this is:

```<code>print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
  sys.stdout.write(str(i)+'\r')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
for i in range(1):
sys.stdout.write(str(i)+'\r')
</code>```

And the output is the following:

```<code>virus_prevention.fix.virus.|attempt_enter
0
virus_prevention.fix.virus|.attempt_enter
0
</code>```

I've tried sys.stdout.write rather than print but nothing seems to have changed. I'm not sure what to do in this situation, but if anyone could give me some tips please do. It's deleting the printed line which entirely does NOT work.

答:
```<code>import time
import sys
sys.stdout.write('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))
</code>```

Does this solve your problem?

Body:
I have an issue where I wish to get rid of some print, but it's ignored entirely and several lines are printed out. I have always used \r for these solutions. Is there a way round this scenario? (I'm using Mac OS for now, but guaranteed, will switch over to Windows soon.) @Feodoran told me that the \r only really works for Linux computers, which is an issue. The code for this is:

print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
  sys.stdout.write(str(i)+'\r')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
for i in range(1):
sys.stdout.write(str(i)+'\r')

And the output is the following:

virus_prevention.fix.virus.|attempt_enter
0
virus_prevention.fix.virus|.attempt_enter
0

I've tried sys.stdout.write rather than print but nothing seems to have changed. I'm not sure what to do in this situation, but if anyone could give me some tips please do. It's deleting the printed line which entirely does NOT work.

Body:
import time
import sys
sys.stdout.write('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))

Does this solve your problem?


答: Yes, that is correct. Note however, that if you use an alternative payment mechanism, Apple still wants their 30% cut.</p>

Title: In App Purchase

Body:
in the App Store Review Guidelines is stated in section that "Apps using IAP to purchase physical goods or  goods and services used outside of the application will be rejected."

Looking also into iOS Developer Program License Agreement referenced in 11.12 of the App Store Review Guidelines I can see there in Attachment 2, section 1. 1.11 that  "You may not use the In  App Purchase API to offer goods or services to be used outside of Your  Application."

1/According to my  understanding everything which is not consumed within the application like  ordering of e.g. paper books, food delivery, flight tickets, electronics cannot  be done via the In App Purchase mechanism. Everything which is consumed within  the application like e-books, video streams, audio streams, new game levels,  etc. (when the provided content is in accordance with App Store Review  Guidelines and iOS Developer Program License Agreement) and user is charged for  this content, the IAP must be used or can be an option to other payment system  as stated in 11.3.

2/ For the In App  Purchase there is not any limit for the 30% fee for the Apple, e.g. theoretically if the content is charged for 10.000USD, Apple takes 3.000USD.

Are my assumptions correct?

BR
STeN


问:
Split String using backslash in javascript
This is my Temp url and I'm trying to get image name

```<code>var str='C:\fakepath\alfa_company.png';
</code>```

my expected out put like this:

```<code>var url='alfa_company.png';
</code>```

答:
You don't need any jQuery for that :)

```<code>const path = 'C:\\fakepath\\alfa_company.png';
const filename = path.split('\\').pop(); // alfa_company.png
</code>```

You need to use double backlashes because JavaScript treats them as escape characters.

Body:
This is my Temp url and I'm trying to get image name

var str='C:\fakepath\alfa_company.png';

my expected out put like this:

var url='alfa_company.png';

Body:
You don't need any jQuery for that :)

const path = 'C:\\fakepath\\alfa_company.png';
const filename = path.split('\\').pop(); // alfa_company.png

You need to use double backlashes because JavaScript treats them as escape characters.


问:
The connection was reset - Wordpress Permalinks
I migrate a Wordpress webpage from one hosting to a DigitalOcean Ubuntu 14.04 droplet using All-in-One WP Migration and now I have problems with Permalinks.

Home page, pages and admin panel are working but if I want to go in a Post all of them show this:
Firefox error image

I activate mod_rewrite, check on .htaccess Wordpress rules, I test all permalinks configurations and also check /var/log/apache2/error.log

Apache VirtualHost configuration

```<code>  <VirtualHost *:80>
     ServerAdmin myemail@my-domain.com
     ServerName my-domain.com
     ServerAlias www.my-domain.com
     DocumentRoot /var/www/my-domain/my-domain.com

     <Directory /var/www/my-domain/my-domain.com>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
     </Directory>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>
</code>```

.htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

/var/log/apache2/error.log

```<code>[Sun Oct 18 08:37:06.217695 2015] [core:notice] [pid 20185] AH00051: child pid 29727 exit signal Segmentation fault (11), possible coredump in /etc/apache2
</code>```

Any suggestions?

答:
In my case it was weird.

i got error when i run the url

http://mysite.org.in/wp-admin/

The connection was reset

The connection to the server was reset while the page was loading.

then i tried

https://mysite.org.in/wp-admin/

and it start working.
i don't know how it happened but it's working now.

Body:
I migrate a Wordpress webpage from one hosting to a DigitalOcean Ubuntu 14.04 droplet using All-in-One WP Migration and now I have problems with Permalinks.

Home page, pages and admin panel are working but if I want to go in a Post all of them show this:
Firefox error image

I activate mod_rewrite, check on .htaccess Wordpress rules, I test all permalinks configurations and also check /var/log/apache2/error.log

Apache VirtualHost configuration

  <VirtualHost *:80>
     ServerAdmin myemail@my-domain.com
     ServerName my-domain.com
     ServerAlias www.my-domain.com
     DocumentRoot /var/www/my-domain/my-domain.com

     <Directory /var/www/my-domain/my-domain.com>
         Options Indexes FollowSymLinks
         AllowOverride All
         Require all granted
     </Directory>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

.htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

/var/log/apache2/error.log

[Sun Oct 18 08:37:06.217695 2015] [core:notice] [pid 20185] AH00051: child pid 29727 exit signal Segmentation fault (11), possible coredump in /etc/apache2

Any suggestions?


问:
The state variable returned after using useState react hook shows .map is not a function
This code gives me error when I try to map the state variable returned after calling useEffect hook.
On console, when I print the myAppointment it shows two values one is empty ([]) and other (Array[25]) I want to extract the petname values from this array . But getting error "map is not a function" Please look into it and help me!</p>

```<code>function App() {
  const [myAppointment, setmyAppointment] = useState([])
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        const apts=result.map(item=>{
          return item
        })
        setmyAppointment(state=>({...state,
          myAppointment:apts
        }))
      })**strong text**
  },[])

  console.log(myAppointment)
  const listItem = myAppointment.map((item)=>{
    return(
      <div>{item.petName}</div>
    )
  })

  return (
    <main className="page bg-white" id="petratings">
    <div className="container">
      <div className="row">
        <div className="col-md-12 bg-white">
          <div className="container">
            {/* {listItem} */}
            <div><AddAppointment /></div>
            <div><SearchAppointment /></div>
            <div><ListAppointment /></div>
          </div>
        </div>
      </div>
    </div>
  </main>
  );
}
</code>```

答:
The problem is from the way you're setting your state after the data is fetched.

You're setting the state as an object by instead of an array.

Let's Take a look at the line where you set the state.

setmyAppointment(state=>({...state,
          myAppointment:apts
        }))

```
<p>Using the spread operator with curly braces tells JavaScript compiler to spread an object, and obviously that's not what you want.</p>
<p>What you ought to do is instead of curly braces, use square brackets. That will tell the compiler you want to spread an array.</p>
<p>So it should be something like this .</p>
<pre class="lang-js prettyprint-override"><code>
setmyAppointment(state=>([...state
        ]))

</code>```

And if I were you, I will do this a little bit different.
I will set the state like this

setmyAppointment(apt)

```

I hope this helps

Body:
This code gives me error when I try to map the state variable returned after calling useEffect hook.
On console, when I print the myAppointment it shows two values one is empty ([]) and other (Array[25]) I want to extract the petname values from this array . But getting error "map is not a function" Please look into it and help me!

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        const apts=result.map(item=>{
          return item
        })
        setmyAppointment(state=>({...state,
          myAppointment:apts
        }))
      })**strong text**
  },[])

  console.log(myAppointment)
  const listItem = myAppointment.map((item)=>{
    return(

{item.petName}

    )
  })

  return (

            {/* {listItem} */}

<AddAppointment />

<SearchAppointment />

<ListAppointment />

  );
}

Body:
The problem is from the way you're setting your state after the data is fetched.

You're setting the state as an object by instead of an array.

Let's Take a look at the line where you set the state.

setmyAppointment(state=>({...state,
          myAppointment:apts
        }))

Using the spread operator with curly braces tells JavaScript compiler to spread an object, and obviously that's not what you want.

What you ought to do is instead of curly braces, use square brackets. That will tell the compiler you want to spread an array.

So it should be something like this .

setmyAppointment(state=>([...state
        ]))

And if I were you, I will do this a little bit different.
I will set the state like this

setmyAppointment(apt)

I hope this helps


问:
How do I prevent Docker from source NAT'ing traffic on Synology NAS
On a Synology NAS, it appears the default setup for docker/iptables is to source NAT traffic going to the container to the gateway IP.  This fundamentally causes problems when the container needs to see the correct/real client IP. I do not see this issue when running on an ubuntu system, for example.

Let me walk you though what I'm seeing.  On the Synology NAS, I'll run a simple nginx container:

```<code>docker run --rm -ti -p 80:80 nginx
</code>```

(I have disabled the Synology NAS from using port 80)

I'll do a curl from my laptop and I see the following log line:

```<code>172.17.0.1 - - [05/May/2020:17:02:44 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.1" "-"
</code>```

Hm... the client IP (172.17.0.1) is the docker0 interface on the NAS.

```<code>user@synology:~$ ifconfig docker0
docker0   Link encap:Ethernet  HWaddr 02:42:B5:BE:C5:51
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
          <snip>
</code>```

When I first saw this, I was quite confused because I did not recall docker networking working this way.  So I fired up my ubuntu VM and tried the same test (same docker run command from earlier).

The log line from my curl test off box:

```<code>172.16.207.1 - - [05/May/2020:17:12:04 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.1" "-"
</code>```

In this case the docker0 IP was not the source of the traffic as seen by the container.

```<code>user@ubuntu-vm:~# ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        <snip>
</code>```

So it appears that the docker network setup for a Synolgy NAS is different vs a more standard ubuntu deployment. Okay, neat.  So how does one fix this?

This is where I'm struggling. Clearly something is happening with iptables. Running the same iptables -t nat -L -n command on both systems shows vastly different results.

```<code>user@synology:~$ iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DEFAULT_OUTPUT  all  --  0.0.0.0/0            0.0.0.0/0

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
DEFAULT_POSTROUTING  all  --  0.0.0.0/0            0.0.0.0/0

Chain DEFAULT_OUTPUT (1 references)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain DEFAULT_POSTROUTING (1 references)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:80

Chain DOCKER (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.2:80
</code>```

```<code>user@ubuntu-vm:~# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0
MASQUERADE  all  --  172.18.0.0/16        0.0.0.0/0
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:80

Chain DOCKER (2 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.2:80
</code>```

I do not really understand how these chains work or why they're different for different systems. I haven't changed any docker level settings on either system, these are default configs.

Has anyone ran into this before?  Is there a quick way to toggle this?

答:
I've experienced this issue myself while using Pi-hole (described here) and this iptables rule seems to fix it:

```<code>sudo iptables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
</code>```

Be aware that this is not permanent, so if you reboot the NAS you will have to apply it again.

Update: Here's a more "permanent" fix: https://gist.github.com/PedroLamas/db809a2b9112166da4a2dbf8e3a72ae9

Body:
On a Synology NAS, it appears the default setup for docker/iptables is to source NAT traffic going to the container to the gateway IP.  This fundamentally causes problems when the container needs to see the correct/real client IP. I do not see this issue when running on an ubuntu system, for example.

Let me walk you though what I'm seeing.  On the Synology NAS, I'll run a simple nginx container:

docker run --rm -ti -p 80:80 nginx

(I have disabled the Synology NAS from using port 80)

I'll do a curl from my laptop and I see the following log line:

172.17.0.1 - - [05/May/2020:17:02:44 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.1" "-"

Hm... the client IP (172.17.0.1) is the docker0 interface on the NAS.

user@synology:~$ ifconfig docker0
docker0   Link encap:Ethernet  HWaddr 02:42:B5:BE:C5:51
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
          <snip>

When I first saw this, I was quite confused because I did not recall docker networking working this way.  So I fired up my ubuntu VM and tried the same test (same docker run command from earlier).

The log line from my curl test off box:

172.16.207.1 - - [05/May/2020:17:12:04 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.1" "-"

In this case the docker0 IP was not the source of the traffic as seen by the container.

user@ubuntu-vm:~# ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        <snip>

So it appears that the docker network setup for a Synolgy NAS is different vs a more standard ubuntu deployment. Okay, neat.  So how does one fix this?

This is where I'm struggling. Clearly something is happening with iptables. Running the same iptables -t nat -L -n command on both systems shows vastly different results.

user@synology:~$ iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DEFAULT_OUTPUT  all  --  0.0.0.0/0            0.0.0.0/0

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
DEFAULT_POSTROUTING  all  --  0.0.0.0/0            0.0.0.0/0

Chain DEFAULT_OUTPUT (1 references)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain DEFAULT_POSTROUTING (1 references)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:80

Chain DOCKER (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.2:80

user@ubuntu-vm:~# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0
MASQUERADE  all  --  172.18.0.0/16        0.0.0.0/0
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:80

Chain DOCKER (2 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
RETURN     all  --  0.0.0.0/0            0.0.0.0/0
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.2:80

I do not really understand how these chains work or why they're different for different systems. I haven't changed any docker level settings on either system, these are default configs.

Has anyone ran into this before?  Is there a quick way to toggle this?

Body:
I've experienced this issue myself while using Pi-hole (described here) and this iptables rule seems to fix it:

sudo iptables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER

Be aware that this is not permanent, so if you reboot the NAS you will have to apply it again.

Update: Here's a more "permanent" fix: https://gist.github.com/PedroLamas/db809a2b9112166da4a2dbf8e3a72ae9


问:
Dynamically change SVG image color in android
I know that using third party library, it is possible to use SVG image in Android.
Library like: svg-android

The code to load SVG image is like below:

```<code> public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Create a new ImageView
    ImageView imageView = new ImageView(this);
    // Set the background color to white
    imageView.setBackgroundColor(Color.WHITE);
    // Parse the SVG file from the resource
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android);
    // Get a drawable from the parsed SVG and set it as the drawable for the ImageView
    imageView.setImageDrawable(svg.createPictureDrawable());
    // Set the ImageView as the content view for the Activity
    setContentView(imageView);
}
</code>```

It's working fine. I'm able to see the image. But now I want to change the color for the svg image at runtime.
For that I tried the code below as mentioned in the same project description.

```<code>  // 0xFF9FBF3B is the hex code for the existing Android green, 0xFF1756c9 is the new blue color
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android, 0xFF9FBF3B, 0xFF1756c9);
</code>```

But with that I am not able to see the change in the color. So I would like to know how it is possible to change the color dynamically in Java file.

答: You can use: drawableTint to change the color </p>

Body:
I know that using third party library, it is possible to use SVG image in Android.
Library like: svg-android

The code to load SVG image is like below:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Create a new ImageView
    ImageView imageView = new ImageView(this);
    // Set the background color to white
    imageView.setBackgroundColor(Color.WHITE);
    // Parse the SVG file from the resource
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android);
    // Get a drawable from the parsed SVG and set it as the drawable for the ImageView
    imageView.setImageDrawable(svg.createPictureDrawable());
    // Set the ImageView as the content view for the Activity
    setContentView(imageView);
}

It's working fine. I'm able to see the image. But now I want to change the color for the svg image at runtime.
For that I tried the code below as mentioned in the same project description.

  // 0xFF9FBF3B is the hex code for the existing Android green, 0xFF1756c9 is the new blue color
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android, 0xFF9FBF3B, 0xFF1756c9);

But with that I am not able to see the change in the color. So I would like to know how it is possible to change the color dynamically in Java file.