问:
Uncaught ReferenceError: require is not defined, I am using dojo1.7.2
I am using dojo1.7.2 I got firebug error: Uncaught ReferenceError: require is not defined

Here is my piece of code:

```<code><script type="text/javascript" src="../js/release/dojo/dojo.js"
 data-dojo-config="packages:[ {'name':'com','location':'/myApp/js/com'}], async: false, parseOnLoad: true, isDebug: true">
</script>
<script language="JavaScript" type="text/javascript">
    require(['dojo/dojo', "dijit/dijit", "dojox/dojox"], function () {
    require(["dojox/mobile", "dojo/parser"], function(mobile, parser){
        })
    });
</script>
</code>```

Where did I wrong here? Thank in advance.

答:
We got that same issue at work, just to let other people know that if you got that error

```<code>Uncaught ReferenceError:require is not defined                at dojo.js:29
dojo.js:29
</code>```

and you are using single-spa or importing a fixed version of SystemJS, like so

 that may be the cause.
So having the production build was throwing this exception in development in our case, this was use for {mountParcel} with single-spa.

You can specify a non-production ready systemjs from index.html or use a better approach to don't have a  that inject systemjs in your html.

Body:
I am using dojo1.7.2 I got firebug error: Uncaught ReferenceError: require is not defined

Here is my piece of code:

Where did I wrong here? Thank in advance.

Body:
We got that same issue at work, just to let other people know that if you got that error

Uncaught ReferenceError:require is not defined                at dojo.js:29
dojo.js:29

and you are using single-spa or importing a fixed version of SystemJS, like so
 <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.21.5/system-production.js"></script>
 that may be the cause.
So having the production build was throwing this exception in development in our case, this was use for {mountParcel} with single-spa.

You can specify a non-production ready systemjs from index.html or use a better approach to don't have a  that inject systemjs in your html.


来源: stackexchange

问:
Why does my website scroll slowly, and why are its hover effects laggy? How can I fix this?
So I have this site here which has major performance issues. Scrolling is very slow, hover effects have a bit of lag and other similar issue. Unfortunately right now I am working off a cheap host so I don't have the option to gzip my files and I am not sure how big a contributing factor that is, though. For what it's worth, I am using Drupal as a CMS.

I would like to know the various reasons for the lag and what I can do to fix it.

Some about:memory stats for the homepage :

Memory:

- Private:49664k

- Shared:13052k

- Total: 62716k

Virtual Memory:

- Private : 53400k

- Mapped : 10412;

Let me know if you need any more information.

答:
I removed the background image and positioning using Firebug and the scrolling instantly speeded up.

Part of the speed will be the various JavaScript components, but the most noticable 'lag' was the fixed 2000x2000 image specified in the CSS for the HTML element.

ContentLicense: CC BY-SA 3.0


问:
Microsoft Bot Framework (SDK4 Nodejs) : How to make the bot perform some action like customer authentication using api?
I want the Microsoft Bot Framework Chat Bot to verify my customer using freshservice api.

I have already asked the user for their username and password (corresponding to the : company-domain.freshservice.com) and stored the customers details using state accessor (As shown in the docs provided for SDK4 of Microsoft Bot Framework). Now after obtaining the details, I want the bot to send a http request to freshservice api and authenticate the customer. And display the result of the authentication of the bot to the Chat window (Currently the Bot Framework Emulator). Please help as I am not able to figure out a way to do it.

答:
The Freshservice API is built around CURL, so it's a little difficult to see how to use it in Node. I've taken the first example and converted it for you:

From:

curl -u user@yourcompany.com:test -H "Content-Type: application/json" -X GET https://domain.freshservice.com/helpdesk/tickets.json

To:

// Convert to base64
const loginInfo = Buffer.from(`${ username }:${ password }`).toString('base64');
const response = await axios.get(`https://<yourDomain>.freshservice.com/helpdesk/tickets.json`, {
    headers: {
        'Content-Type': 'application/json',
        Authorization: `Basic ${ loginInfo }`
    }
});
await context.sendActivity(JSON.stringify(response.data, null, 2));
```

This will result in the full JSON response:

How you choose to display that will be up to you.

Notes:

You'll need to install axios (or some other service that can make GET requests) npm i axios

Freshservice supports OAuth, which is also supported in BotFramework

I HIGHLY recommend going this route because it will mean you don't have to figure out storing and encrypting user login information. It's significantly more secure and less of a headache for you. Basically, instead of storing user/pass, it will present the user with a login prompt. When logged it, it returns a token that you'll store and use that to make requests. Now, if an attacker wanted to steal usernames and passwords, their only route to do so is the Freshservice API. If you're storing user/pass yourself, they can also try to attack your bot client, bot conversation history, and your bot storage.

To get started, read Add authentication to your bot and use the Bot Authentication Sample as a guide.

ContentLicense: CC BY-SA 4.0

Body:
The Freshservice API is built around CURL, so it's a little difficult to see how to use it in Node. I've taken the first example and converted it for you:

From:

curl -u user@yourcompany.com:test -H "Content-Type: application/json" -X GET https://domain.freshservice.com/helpdesk/tickets.json

To:

// Convert to base64
const loginInfo = Buffer.from(`${ username }:${ password }`).toString('base64');
const response = await axios.get(`https://<yourDomain>.freshservice.com/helpdesk/tickets.json`, {
    headers: {
        'Content-Type': 'application/json',
        Authorization: `Basic ${ loginInfo }`
    }
});
await context.sendActivity(JSON.stringify(response.data, null, 2));

This will result in the full JSON response:

How you choose to display that will be up to you.

Notes:

You'll need to install axios (or some other service that can make GET requests) npm i axios

Freshservice supports OAuth, which is also supported in BotFramework

I HIGHLY recommend going this route because it will mean you don't have to figure out storing and encrypting user login information. It's significantly more secure and less of a headache for you. Basically, instead of storing user/pass, it will present the user with a login prompt. When logged it, it returns a token that you'll store and use that to make requests. Now, if an attacker wanted to steal usernames and passwords, their only route to do so is the Freshservice API. If you're storing user/pass yourself, they can also try to attack your bot client, bot conversation history, and your bot storage.

To get started, read Add authentication to your bot and use the Bot Authentication Sample as a guide.


问:
No permissions to change tty mode inside a docker container
I'm trying to run some software inside a docker container, which wants to do VT_SETMODE for the tty currently in use. This will always fail with an error saying "Operation not permitted".

I've tried playing around with permissions/groups with no luck.

Finally I created a small snippet to reproduce the error:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <linux/vt.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

int main() {
        const char *tty_path;
        tty_path = "/dev/tty1";

        int fd = open(tty_path, O_RDWR | O_CLOEXEC);

        if (fd < 0) {
                printf("ERROR: Failed to open %s\n", strerror(errno));
                return 1;
        }

        struct vt_mode mode = {
                .mode = VT_AUTO,
        };
        errno = 0;

        ioctl(fd, VT_SETMODE, &mode);

        if (errno) {
                printf("ERROR: %s\n", strerror(errno));
                return 1;
        }

        return 0;
}
```

<p>I ran the code inside a docker container with a simple dockerfile:</p>

```FROM archlinux/base

RUN pacman -Sy --noconfirm gcc
```

<p>That was started with command:</p>

```docker build -f Dockerfile -t tty-test . && docker run --device /dev/tty1 -v $HOME/tty-test:/volume -it tty-test /bin/bash -c 'cd /volume && gcc tty_r.c && ./a.out ; /bin/bash'
```

<p>Output is this:</p>

```ERROR: Operation not permitted
```

Can anyone explain why the tty is not accessible from the container, or is there some way to give more control to the container?

答: Okay it seems that I have solved my own problem. I was trying to run the code inside a container which had no privilege to do tty-configuration. Adding --cap-add SYS_TTY_CONFIG to the docker run command fixed the issue.

Body:
I'm trying to run some software inside a docker container, which wants to do VT_SETMODE for the tty currently in use. This will always fail with an error saying "Operation not permitted".

I've tried playing around with permissions/groups with no luck.

Finally I created a small snippet to reproduce the error:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <linux/vt.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

int main() {
        const char *tty_path;
        tty_path = "/dev/tty1";

        int fd = open(tty_path, O_RDWR | O_CLOEXEC);

        if (fd < 0) {
                printf("ERROR: Failed to open %s\n", strerror(errno));
                return 1;
        }

        struct vt_mode mode = {
                .mode = VT_AUTO,
        };
        errno = 0;

        ioctl(fd, VT_SETMODE, &mode);

        if (errno) {
                printf("ERROR: %s\n", strerror(errno));
                return 1;
        }

        return 0;
}

I ran the code inside a docker container with a simple dockerfile:

FROM archlinux/base

RUN pacman -Sy --noconfirm gcc

That was started with command:

docker build -f Dockerfile -t tty-test . && docker run --device /dev/tty1 -v $HOME/tty-test:/volume -it tty-test /bin/bash -c 'cd /volume && gcc tty_r.c && ./a.out ; /bin/bash'

Output is this:

ERROR: Operation not permitted

Can anyone explain why the tty is not accessible from the container, or is there some way to give more control to the container?


问:
Why do I have to use ref when matching on a dereferenced enum?
Why do I have to use ref s and not only s in destruct method of impl Keys?

```<code>#[derive(Debug)]
enum Direction {
    Up(Point),
    Down(Point),
    Right(Point),
    Left(Point),
}

#[derive(Debug)]
struct Point {
    x: u32,
    y: u32,
}

#[derive(Debug)]
enum Keys {
    Up_key(String),
    Down_key(String),
    Right_key(String),
    Left_key(String),
}

impl Direction {
    fn match_direction(&self) -> Keys {
        match *self {
            Direction::Up(_) => Keys::Up_key(String::from("Up key is pressed")),
            Direction::Down(_) => Keys::Down_key(String::from("Down key is pressed")),
            Direction::Right(_) => Keys::Right_key(String::from("Right key is pressed")),
            Direction::Left(_) => Keys::Left_key(String::from("Left key is pressed")),
        }
    }
}

impl Keys {
    fn destruct(&self) -> &String {
        match *self {
            Keys::Up_key(ref s) => s,
            Keys::Down_key(ref s) => s,
            Keys::Left_key(ref s) => s,
            Keys::Right_key(ref s) => s,
        }
    }
}

fn main() {
    let test_1 = Direction::Right(Point { x: 1, y: 0 });
    let x = test_1.match_direction();
    println!("{:#?}", x);
    let k = x.destruct();
    println!("{}", k);
}
</code>```

Output:

Right_key(
    "Right key is pressed",
)
Right key is pressed
```

答: Using ref prevents the pattern matching from taking ownership of s.

Body:
Why do I have to use ref s and not only s in destruct method of impl Keys?

#[derive(Debug)]
enum Direction {
    Up(Point),
    Down(Point),
    Right(Point),
    Left(Point),
}

#[derive(Debug)]
struct Point {
    x: u32,
    y: u32,
}

#[derive(Debug)]
enum Keys {
    Up_key(String),
    Down_key(String),
    Right_key(String),
    Left_key(String),
}

impl Direction {
    fn match_direction(&self) -> Keys {
        match *self {
            Direction::Up(_) => Keys::Up_key(String::from("Up key is pressed")),
            Direction::Down(_) => Keys::Down_key(String::from("Down key is pressed")),
            Direction::Right(_) => Keys::Right_key(String::from("Right key is pressed")),
            Direction::Left(_) => Keys::Left_key(String::from("Left key is pressed")),
        }
    }
}

impl Keys {
    fn destruct(&self) -> &String {
        match *self {
            Keys::Up_key(ref s) => s,
            Keys::Down_key(ref s) => s,
            Keys::Left_key(ref s) => s,
            Keys::Right_key(ref s) => s,
        }
    }
}

fn main() {
    let test_1 = Direction::Right(Point { x: 1, y: 0 });
    let x = test_1.match_direction();
    println!("{:#?}", x);
    let k = x.destruct();
    println!("{}", k);
}

Output:

Right_key(
    "Right key is pressed",
)
Right key is pressed


问:
remove elements from list of strings while traversing
how to remove elements from a list of strings while traversing through it.
I have a list

```<code>list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']
</code>```

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.

expected output is :

```<code>['', '32,324', '32', '(35)', '32,321']
</code>```

what i have tried is

```<code>for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)
</code>```

but the output i am getting is

```<code>['', '32,324', '32', '(35)', '$', '32,321']
</code>```

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

答:
What Green Cloak Guy said is mostly correct. Editing the size of the list (by calling .pop()) is causing you to have an unexpected j value. To me, the easiest way to fix this problem while keeping your existing code is to simply not mutate your list, and build up a new one instead:

new_list = []
for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      ret[len(ret) - 1] += element  # add at the end of the previous element
   elif element != '$':
      new_list.push(element)
```

However, I would encourage you to think about your edge cases here. What happens when a ')' is followed by another ')' in your list? This may be a special case in your if statement. Hope this helped!

Body:
how to remove elements from a list of strings while traversing through it.
I have a list

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.

expected output is :

['', '32,324', '32', '(35)', '32,321']

what i have tried is

for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)

but the output i am getting is

['', '32,324', '32', '(35)', '$', '32,321']

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

Body:
What Green Cloak Guy said is mostly correct. Editing the size of the list (by calling .pop()) is causing you to have an unexpected j value. To me, the easiest way to fix this problem while keeping your existing code is to simply not mutate your list, and build up a new one instead:

new_list = []
for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      ret[len(ret) - 1] += element  # add at the end of the previous element
   elif element != '$':
      new_list.push(element)

However, I would encourage you to think about your edge cases here. What happens when a ')' is followed by another ')' in your list? This may be a special case in your if statement. Hope this helped!


问:
How do I get the currently used code page in UWP?
I want to know which character set is currently used. I'm using c++/winrt to build an UWP app.

Thanks in advance

答:
Universal Windows Platform (UWP) apps generally use Unicode. A few "A" versions of functions (like CreateEventA, CreateMutexA, OutputDebugStringA, etc.) are available because those strings are purely internal and not localized.

The recommendation is to build with UNICODE and _UNICODE enabled, use the W versions of Win32 APIs, and void using TCHAR and all multibyte C/C++ Runtime functions.

That said, recent versions of the Windows 10 SDK have added more of the ASCII functions back to the UWP API partition in order to support more 3rd party libraries. GetACP is supported.

This was not supported in the Windows 10 Anniversary Update SDK (14393) which was the last Windows 10 SDK to officially support VS 2015, but if you are using VS 2017 or later with a newer Windows 10 SDK you should have it defined for the WINAPI_FAMILY_PARTITION for WINAPI_FAMILY_APP in winnls.h.


问:
Subversion - problem creating a new repository
I have recently taken over a linux box running subversion.

The folder where the the repos look like they are installed is in: /home/svn

In this folder I see a folder named web_projects and in that folder I see conf dev db etc etc

I am trying to add a new repository to this server, but I'm getting the following error:

`svnadmin: '/home/svn/web_projects/my_project' is a subdirectoy of an existing repository rooted at '/home/svn/web_projects'

Does anyone know why I can't seem to add a new repository?

答:
Because /home/svn/web_projects/ is already a repository (as explained by the tool).

You cannot create a repository inside this folder. You can however do that just next to this one:

```<code>svnadmin create /home/svn/other_project
</code>```

hth :)

Body:
Because /home/svn/web_projects/ is already a repository (as explained by the tool).

You cannot create a repository inside this folder. You can however do that just next to this one:

svnadmin create /home/svn/other_project

hth :)


问:
AWS CodeBuild Docker images as Base Image
Are these images availabe to be used as base image in my own Dockerfile?</p>

答:
They are not published anywhere as of yet. There is a ticket that claims they will publish Amazon Linux 2 based images once they are ready:

https://github.com/aws/aws-codebuild-docker-images/issues/199

If you want to use them as a base image you need to check out the project yourself and build them locally:

```<code>$ git clone https://github.com/aws/aws-codebuild-docker-images.git
$ cd aws-codebuild-docker-images
$ cd ubuntu/standard/2.0
$ docker build -t aws/codebuild/standard:2.0 .
</code>```

Once you have it built locally, you can reference it from your local Dockerfile:

```<code>FROM aws/codebuild/standard:2.0
</code>```

and it will use your local cached image. You can then publish your image to ECR to use for your codebuild projects.

Body:
They are not published anywhere as of yet. There is a ticket that claims they will publish Amazon Linux 2 based images once they are ready:

https://github.com/aws/aws-codebuild-docker-images/issues/199

If you want to use them as a base image you need to check out the project yourself and build them locally:

$ git clone https://github.com/aws/aws-codebuild-docker-images.git
$ cd aws-codebuild-docker-images
$ cd ubuntu/standard/2.0
$ docker build -t aws/codebuild/standard:2.0 .

Once you have it built locally, you can reference it from your local Dockerfile:

FROM aws/codebuild/standard:2.0

and it will use your local cached image. You can then publish your image to ECR to use for your codebuild projects.


问:
Doing a cross pivot in Google BigQuery
I have asked a previous question about doing a multi-level aggregation query on the X-axis here: Get the top patent countries, codes in a BQ public dataset.

Here is how the query (copied from the accepted answer works) to get:

Top 2 Countries by Count, and within those countries, top 2 Codes by Count

```<code>WITH A AS (
  SELECT country_code
  FROM `patents-public-data.patents.publications`
  GROUP BY country_code
  ORDER BY COUNT(1) DESC
  LIMIT 2
), B AS (
  SELECT
    country_code,
    application_kind,
    COUNT(1) application_kind_count
  FROM `patents-public-data.patents.publications`
  WHERE country_code IN (SELECT country_code FROM A)
  GROUP BY country_code, application_kind
), C AS (
  SELECT
    country_code,
    application_kind,
    application_kind_count,
    DENSE_RANK() OVER(PARTITION BY country_code ORDER BY application_kind_count DESC) AS application_kind_rank
  FROM B
)
SELECT
  country_code,
  application_kind,
  application_kind_count
FROM C
WHERE application_kind_rank <= 2
</code>```

And I get something like:

```<code>country_code     application_kind   count
JP               A                  125
JP               U                  124
CN               A                  118
CN               U                  101
</code>```

Now I would like to add the following pivot on the y-axis: to get the following:

X: Top 2 Countries by Count, and within those countries, top 2 Codes by Count

Y: Top 2 family_id by Count, Top 2 priority_date by Count

The final results would then look like:

I am able to build the Y-query in a second query --

```<code>WITH A AS (
  SELECT family_id
  FROM `patents-public-data.patents.publications`
  GROUP BY family_id
  ORDER BY COUNT(1) DESC
  LIMIT 2
), B AS (
  SELECT
    family_id,
    priority_date,
    COUNT(1) priority_date_count
  FROM `patents-public-data.patents.publications`
  WHERE family_id IN (SELECT family_id FROM A)
  GROUP BY family_id, priority_date
), C AS (
  SELECT
    family_id,
    priority_date,
    priority_date_count,
    DENSE_RANK() OVER(PARTITION BY family_id ORDER BY priority_date_count DESC) AS priority_date_rank
  FROM B
)
SELECT
  family_id,
  priority_date,
  priority_date_count
FROM C
WHERE priority_date_rank <= 2
</code>```

However, I am not quite sure how to merge them together, in a single query or in two.

答:
Below is for BigQuery Standard SQL and is just demo of the approach and not pretending to be 100% representing requested logic

```<code>WITH A_X AS (
  SELECT country_code FROM `patents-public-data.patents.publications`
  GROUP BY country_code ORDER BY COUNT(1) DESC LIMIT 2
), B_X AS (
  SELECT country_code, application_kind, COUNT(1) application_kind_count
  FROM `patents-public-data.patents.publications` WHERE country_code IN (SELECT country_code FROM A_X)
  GROUP BY country_code, application_kind
), C_X AS (
  SELECT country_code, application_kind, application_kind_count,
    DENSE_RANK() OVER(PARTITION BY country_code ORDER BY application_kind_count DESC) AS application_kind_rank
  FROM B_X
), X AS (
  SELECT country_code, application_kind, application_kind_count
  FROM C_X WHERE application_kind_rank <= 2
), A_Y AS (
  SELECT family_id FROM `patents-public-data.patents.publications`
  JOIN X USING(country_code, application_kind)
  GROUP BY family_id
  ORDER BY COUNT(1) DESC LIMIT 2
), B_Y AS (
  SELECT family_id, priority_date, COUNT(1) priority_date_count
  FROM `patents-public-data.patents.publications` WHERE family_id IN (SELECT family_id FROM A_Y)
  GROUP BY family_id, priority_date
), C_Y AS (
  SELECT family_id, priority_date, priority_date_count,
    DENSE_RANK() OVER(PARTITION BY family_id ORDER BY priority_date_count DESC) AS pos_date
  FROM B_Y
), Y AS (
  SELECT family_id, priority_date, pos_date, DENSE_RANK() OVER(ORDER BY family_id) pos_family
  FROM C_Y WHERE pos_date <= 2
)
SELECT country_code, application_kind,
  COUNTIF(pos_family = 1 AND pos_date = 1) `family1_date1`,
  COUNTIF(pos_family = 1 AND pos_date = 2) `family1_date2`,
  COUNTIF(pos_family = 2 AND pos_date = 1) `family2_date1`,
  COUNTIF(pos_family = 2 AND pos_date = 2) `family2_date2`
FROM `patents-public-data.patents.publications`
JOIN Y USING(family_id, priority_date)
WHERE country_code IN (SELECT country_code FROM X)
AND application_kind IN (SELECT application_kind FROM x)
GROUP BY country_code, application_kind
</code>```

the result is

Obviously, there are number of zeroes above because of intersection logic

Title: Doing a cross pivot in Google BigQuery

Body:
I have asked a previous question about doing a multi-level aggregation query on the X-axis here: Get the top patent countries, codes in a BQ public dataset.

Here is how the query (copied from the accepted answer works) to get:

Top 2 Countries by Count, and within those countries, top 2 Codes by Count

WITH A AS (
  SELECT country_code
  FROM `patents-public-data.patents.publications`
  GROUP BY country_code
  ORDER BY COUNT(1) DESC
  LIMIT 2
), B AS (
  SELECT
    country_code,
    application_kind,
    COUNT(1) application_kind_count
  FROM `patents-public-data.patents.publications`
  WHERE country_code IN (SELECT country_code FROM A)
  GROUP BY country_code, application_kind
), C AS (
  SELECT
    country_code,
    application_kind,
    application_kind_count,
    DENSE_RANK() OVER(PARTITION BY country_code ORDER BY application_kind_count DESC) AS application_kind_rank
  FROM B
)
SELECT
  country_code,
  application_kind,
  application_kind_count
FROM C
WHERE application_kind_rank <= 2

And I get something like:

country_code     application_kind   count
JP               A                  125
JP               U                  124
CN               A                  118
CN               U                  101

Now I would like to add the following pivot on the y-axis: to get the following:

X: Top 2 Countries by Count, and within those countries, top 2 Codes by Count

Y: Top 2 family_id by Count, Top 2 priority_date by Count

The final results would then look like:

I am able to build the Y-query in a second query --

WITH A AS (
  SELECT family_id
  FROM `patents-public-data.patents.publications`
  GROUP BY family_id
  ORDER BY COUNT(1) DESC
  LIMIT 2
), B AS (
  SELECT
    family_id,
    priority_date,
    COUNT(1) priority_date_count
  FROM `patents-public-data.patents.publications`
  WHERE family_id IN (SELECT family_id FROM A)
  GROUP BY family_id, priority_date
), C AS (
  SELECT
    family_id,
    priority_date,
    priority_date_count,
    DENSE_RANK() OVER(PARTITION BY family_id ORDER BY priority_date_count DESC) AS priority_date_rank
  FROM B
)
SELECT
  family_id,
  priority_date,
  priority_date_count
FROM C
WHERE priority_date_rank <= 2

However, I am not quite sure how to merge them together, in a single query or in two.

Body:
Below is for BigQuery Standard SQL and is just demo of the approach and not pretending to be 100% representing requested logic

WITH A_X AS (
  SELECT country_code FROM `patents-public-data.patents.publications`
  GROUP BY country_code ORDER BY COUNT(1) DESC LIMIT 2
), B_X AS (
  SELECT country_code, application_kind, COUNT(1) application_kind_count
  FROM `patents-public-data.patents.publications` WHERE country_code IN (SELECT country_code FROM A_X)
  GROUP BY country_code, application_kind
), C_X AS (
  SELECT country_code, application_kind, application_kind_count,
    DENSE_RANK() OVER(PARTITION BY country_code ORDER BY application_kind_count DESC) AS application_kind_rank
  FROM B_X
), X AS (
  SELECT country_code, application_kind, application_kind_count
  FROM C_X WHERE application_kind_rank <= 2
), A_Y AS (
  SELECT family_id FROM `patents-public-data.patents.publications`
  JOIN X USING(country_code, application_kind)
  GROUP BY family_id
  ORDER BY COUNT(1) DESC LIMIT 2
), B_Y AS (
  SELECT family_id, priority_date, COUNT(1) priority_date_count
  FROM `patents-public-data.patents.publications` WHERE family_id IN (SELECT family_id FROM A_Y)
  GROUP BY family_id, priority_date
), C_Y AS (
  SELECT family_id, priority_date, priority_date_count,
    DENSE_RANK() OVER(PARTITION BY family_id ORDER BY priority_date_count DESC) AS pos_date
  FROM B_Y
), Y AS (
  SELECT family_id, priority_date, pos_date, DENSE_RANK() OVER(ORDER BY family_id) pos_family
  FROM C_Y WHERE pos_date <= 2
)
SELECT country_code, application_kind,
  COUNTIF(pos_family = 1 AND pos_date = 1) `family1_date1`,
  COUNTIF(pos_family = 1 AND pos_date = 2) `family1_date2`,
  COUNTIF(pos_family = 2 AND pos_date = 1) `family2_date1`,
  COUNTIF(pos_family = 2 AND pos_date = 2) `family2_date2`
FROM `patents-public-data.patents.publications`
JOIN Y USING(family_id, priority_date)
WHERE country_code IN (SELECT country_code FROM X)
AND application_kind IN (SELECT application_kind FROM x)
GROUP BY country_code, application_kind

the result is

Obviously, there are number of zeroes above because of intersection logic


问:
PrestaShop - Update a Product using Web-service and t-sql stored procedures / XML
I want to update a PrestaShop product using web services from tsql.

I have already the xml variable created in sql.

According to the PrestaShop documentation, I have to:

[...] Send POST HTTP request with the whole XML as body content [...]

Using Get isn't any problem with oa_mothods from sql, but what is the syntax for POST/PUT any xml variables to Create or Update an existing product?

```<code>declare @xmlRIA xml

set @xmlRIA = CAST('<?xml version="1.0" encoding="UTF-8"?>
<prestashop>
    <customer>
        <id></id>
        <id_default_group>3</id_default_group>
        <id_lang>1</id_lang>
        <newsletter_date_add>0000-00-00 00:00:00</newsletter_date_add>
        <ip_registration_newsletter></ip_registration_newsletter>
        <last_passwd_gen>2017-04-29 05:34:22</last_passwd_gen>
        <secure_key></secure_key>
        <deleted>0</deleted>
        <passwd></passwd>
        <lastname>test</lastname>
        <firstname>test</firstname>
        <email>kow@testde.com</email>
        <id_gender>2</id_gender>
        <birthday>0000-00-00</birthday>
        <newsletter>0</newsletter>
        <optin>0</optin>
        <website></website>
        <company></company>
        <siret></siret>
        <ape></ape>
        <outstanding_allow_amount>0.000000</outstanding_allow_amount>
        <show_public_prices>0</show_public_prices>
        <id_risk>0</id_risk>
        <max_payment_days>0</max_payment_days>
        <active>1</active>
        <note></note>
        <is_guest>0</is_guest>
        <id_shop>1</id_shop>
        <id_shop_group>1</id_shop_group>
        <date_add>2017-04-29 11:34:22</date_add>
        <date_upd>2017-04-29 11:34:22</date_upd>
        <reset_password_token></reset_password_token>
        <reset_password_validity>0000-00-00 00:00:00</reset_password_validity>
        <associations>
            <groups>
                <group>
                    <id>3</id>
                </group>
            </groups>
        </associations>
    </customer>
</prestashop>
 'as XML)

-- Open a connection
EXEC @ret = sp_OACreate 'MSXML2.ServerXMLHTTP', @token OUT;
if @ret <> 0 begin set @MessageError = 'sp_OACreate MSXML2.ServerXMLHttp.3.0 failed' goto final end

EXEC @ret = sp_OAMethod @token, 'open', NULL, 'POST', @url, 'false';
if @ret <> 0 begin set @MessageError = 'sp_OACreate open' goto final end

EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Authentication', @authHeader;
if @ret <> 0 begin set @MessageError = 'sp_OACreate Authentication failed' goto final end

EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Content-type', @contentType;
if @ret <> 0 begin set @MessageError = 'sp_OACreate Content-type failed' goto final end

EXEC @ret = sp_OAMethod @token, 'send', NULL, '';
if @ret <> 0 begin set @MessageError = 'sp_OAMethod send failed' goto final end

-- Handle response
EXEC @ret = sp_OAGetProperty @token, 'status', @status OUT;
if @ret <> 0 begin set @MessageError = 'sp_OAGetProperty status' goto final end

EXEC @ret = sp_OAGetProperty @token, 'statusText', @statusText OUT;
if @ret <> 0 begin set @MessageError = 'sp_OAGetProperty statusText failed' goto final end

EXEC @ret = sp_OAMethod @token, 'send', NULL, @xmlria
IF @ret <> 0 RAISERROR('sp_OAMethod SEND 2 failed.', 10, 1);
</code>```

答:
Updating an existing Product using PrestaShop Web-service

This assumes your XML is stored in a SimpleXML object (in PHP) and the existing Product ID is 1.

```<code><?php

include(__DIR__.'/config/config.inc.php');
include(__DIR__.'/init.php');
include(__DIR__.'/PSWebServiceLibrary.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURWSKEY');
$ws = new PrestaShopWebservice(PS_SHOP_URL, PS_WS_AUTH_KEY, false);

$result = $ws->edit(['resource' => 'products', 'id' => 1, 'putXml' => $xml->asXML()]);
echo '```';
print_r($result);
echo '```';
</code>```

More examples and links

You can find the PrestaShop web-service documentation here:
https://devdocs.prestashop.com/1.7/development/webservice/

You can find the library here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php

You can find more examples (retrieve, add, update, delete, etc.) here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/tree/master/examples

I hope this helps!

Body:
I want to update a PrestaShop product using web services from tsql.

I have already the xml variable created in sql.

According to the PrestaShop documentation, I have to:

[...] Send POST HTTP request with the whole XML as body content [...]

Using Get isn't any problem with oa_mothods from sql, but what is the syntax for POST/PUT any xml variables to Create or Update an existing product?

declare @xmlRIA xml

set @xmlRIA = CAST('<?xml version="1.0" encoding="UTF-8"?>
<prestashop>
    <customer>
        <id></id>
        <id_default_group>3</id_default_group>
        <id_lang>1</id_lang>
        <newsletter_date_add>0000-00-00 00:00:00</newsletter_date_add>
        <ip_registration_newsletter></ip_registration_newsletter>
        <last_passwd_gen>2017-04-29 05:34:22</last_passwd_gen>
        <secure_key></secure_key>
        <deleted>0</deleted>
        <passwd></passwd>
        <lastname>test</lastname>
        <firstname>test</firstname>
        <email>kow@testde.com</email>
        <id_gender>2</id_gender>
        <birthday>0000-00-00</birthday>
        <newsletter>0</newsletter>
        <optin>0</optin>
        <website></website>
        <company></company>
        <siret></siret>
        <ape></ape>
        <outstanding_allow_amount>0.000000</outstanding_allow_amount>
        <show_public_prices>0</show_public_prices>
        <id_risk>0</id_risk>
        <max_payment_days>0</max_payment_days>
        <active>1</active>
        <note></note>
        <is_guest>0</is_guest>
        <id_shop>1</id_shop>
        <id_shop_group>1</id_shop_group>
        <date_add>2017-04-29 11:34:22</date_add>
        <date_upd>2017-04-29 11:34:22</date_upd>
        <reset_password_token></reset_password_token>
        <reset_password_validity>0000-00-00 00:00:00</reset_password_validity>
        <associations>
            <groups>
                <group>
                    <id>3</id>
                </group>
            </groups>
        </associations>
    </customer>
</prestashop>
 'as XML)

-- Open a connection
EXEC @ret = sp_OACreate 'MSXML2.ServerXMLHTTP', @token OUT;
if @ret <> 0 begin set @MessageError = 'sp_OACreate MSXML2.ServerXMLHttp.3.0 failed' goto final end

EXEC @ret = sp_OAMethod @token, 'open', NULL, 'POST', @url, 'false';
if @ret <> 0 begin set @MessageError = 'sp_OACreate open' goto final end

EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Authentication', @authHeader;
if @ret <> 0 begin set @MessageError = 'sp_OACreate Authentication failed' goto final end

EXEC @ret = sp_OAMethod @token, 'setRequestHeader', NULL, 'Content-type', @contentType;
if @ret <> 0 begin set @MessageError = 'sp_OACreate Content-type failed' goto final end

EXEC @ret = sp_OAMethod @token, 'send', NULL, '';
if @ret <> 0 begin set @MessageError = 'sp_OAMethod send failed' goto final end

-- Handle response
EXEC @ret = sp_OAGetProperty @token, 'status', @status OUT;
if @ret <> 0 begin set @MessageError = 'sp_OAGetProperty status' goto final end

EXEC @ret = sp_OAGetProperty @token, 'statusText', @statusText OUT;
if @ret <> 0 begin set @MessageError = 'sp_OAGetProperty statusText failed' goto final end

EXEC @ret = sp_OAMethod @token, 'send', NULL, @xmlria
IF @ret <> 0 RAISERROR('sp_OAMethod SEND 2 failed.', 10, 1);

Body:
Updating an existing Product using PrestaShop Web-service

This assumes your XML is stored in a SimpleXML object (in PHP) and the existing Product ID is 1.

<?php

include(__DIR__.'/config/config.inc.php');
include(__DIR__.'/init.php');
include(__DIR__.'/PSWebServiceLibrary.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURWSKEY');
$ws = new PrestaShopWebservice(PS_SHOP_URL, PS_WS_AUTH_KEY, false);

$result = $ws->edit(['resource' => 'products', 'id' => 1, 'putXml' => $xml->asXML()]);
echo '<pre>';
print_r($result);
echo '</pre>';

More examples and links

You can find the PrestaShop web-service documentation here:
https://devdocs.prestashop.com/1.7/development/webservice/

You can find the library here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php

You can find more examples (retrieve, add, update, delete, etc.) here:
https://github.com/PrestaShop/PrestaShop-webservice-lib/tree/master/examples

I hope this helps!


问:
How to find n-th element of Fibonacci sequence in assembly using stack and recursion
I am trying to write classical fib(n) function in assembly (intel x86) that is returning a n-th element of Fibonacci sequence.

I have written iterative version quite easily, but I'm having trouble trying to manipulate with recursion. This is what I tried:

```<code>.intel_syntax noprefix

.text

# unsigned fib(unsigned)
.globl fib

fib_n:
    enter 0, 0

    mov eax, 0

    # n = 0 or n = 1
    cmp edi, 1
    jbe end

    mov eax, 1

    # n == 2
    cmp edi, 2
    je end

    # n > 2, entering recursion

    # fib(n-1)
    push rdi
    dec edi

    call fib_n
    mov r8d, eax

    pop rdi

    # fib(n-2)
    push rdi
    sub edi, 2

    call fib_n
    mov r9d, eax

    pop rdi

    # fib(n) = fib(n-1) + fib(n-2)
    mov eax, r8d
    add eax, r9d

end:
    leave
    ret
</code>```

I am expecting for calls marked #fib(n-1) and #fib(n-1) to store local eax results in r8d and r9d registers, and then just add them and return through eax, but this is what I get as output:

n = 1 (1st el): 0 (works fine)

n = 2: 1 (works fine)

n = 3: 1 (works fine)

(wrong results)

n = 4: 2

n = 5: 2

n = 6: 3

n = 7: 3

...

I also tried pushing rax to the stack as well as rdi, but I still get wrong results. What am I missing?

答:
What am I missing?

Register r8d is not preserved across recursive calls.

You don't need enter nor leave. No parameters were pushed.

It's easier to preserve the index rdi at the entry of fib_n.

```<code>fib_n:
    push    rdi
    xor     eax, eax
    cmp     edi, 2
    jb      end            ; fib(1) = 0
    mov     eax, 1
    je      end            ; fib(2) = 1
    dec     edi
    call    fib_n          ; -> EAX
    push    rax            ; (1) Preserve intermediate result!
    dec     edi
    call    fib_n          ; -> EAX
    add     eax, [rsp]     ; fib(n) = fib(n-2) + fib(n-1)
    add     rsp, 8         ; (1)
end:
    pop     rdi
    ret
</code>```

EDIT

The below version of the code incorporates comments made by rcgldr and Peter Cordes.

This code now removes 5 base-cases and is much cleaner.

```<code>fib_n:
    cmp     edi, 5         ; n
    jb      .LT5           ; Base-cases
    push    rdi            ; (1) Preserve n
    dec     edi            ; n-1
    call    fib_n          ; -> EAX
    push    rax            ; (2) Preserve intermediate result!
    dec     edi            ; n-2
    call    fib_n          ; -> EAX
    pop     rdi            ; (2) Restore intermediate result
    add     eax, edi       ; fib(n) = fib(n-2) + fib(n-1)
    pop     rdi            ; (1) Restore n
    ret
.LT5:
    mov     eax, edi       ; n < 5
    cmp     edi, 2
    cmc
    sbb     eax, 0         ; fib(0) = 0, fib(1) = 1
    ret                    ; fib(2) = 1, fib(3) = 2, fib(4) = 3
</code>```

Body:
I am trying to write classical fib(n) function in assembly (intel x86) that is returning a n-th element of Fibonacci sequence.

I have written iterative version quite easily, but I'm having trouble trying to manipulate with recursion. This is what I tried:

.intel_syntax noprefix

.text

# unsigned fib(unsigned)
.globl fib

fib_n:
    enter 0, 0

    mov eax, 0

    # n = 0 or n = 1
    cmp edi, 1
    jbe end

    mov eax, 1

    # n == 2
    cmp edi, 2
    je end

    # n > 2, entering recursion

    # fib(n-1)
    push rdi
    dec edi

    call fib_n
    mov r8d, eax

    pop rdi

    # fib(n-2)
    push rdi
    sub edi, 2

    call fib_n
    mov r9d, eax

    pop rdi

    # fib(n) = fib(n-1) + fib(n-2)
    mov eax, r8d
    add eax, r9d

end:
    leave
    ret

I am expecting for calls marked #fib(n-1) and #fib(n-1) to store local eax results in r8d and r9d registers, and then just add them and return through eax, but this is what I get as output:

n = 1 (1st el): 0 (works fine)

n = 2: 1 (works fine)

n = 3: 1 (works fine)

(wrong results)

n = 4: 2

n = 5: 2

n = 6: 3

n = 7: 3

...

I also tried pushing rax to the stack as well as rdi, but I still get wrong results. What am I missing?

Body:
What am I missing?

Register r8d is not preserved across recursive calls.

You don't need enter nor leave. No parameters were pushed.

It's easier to preserve the index rdi at the entry of fib_n.

fib_n:
    push    rdi
    xor     eax, eax
    cmp     edi, 2
    jb      end            ; fib(1) = 0
    mov     eax, 1
    je      end            ; fib(2) = 1
    dec     edi
    call    fib_n          ; -> EAX
    push    rax            ; (1) Preserve intermediate result!
    dec     edi
    call    fib_n          ; -> EAX
    add     eax, [rsp]     ; fib(n) = fib(n-2) + fib(n-1)
    add     rsp, 8         ; (1)
end:
    pop     rdi
    ret

EDIT

The below version of the code incorporates comments made by rcgldr and Peter Cordes.

This code now removes 5 base-cases and is much cleaner.

fib_n:
    cmp     edi, 5         ; n
    jb      .LT5           ; Base-cases
    push    rdi            ; (1) Preserve n
    dec     edi            ; n-1
    call    fib_n          ; -> EAX
    push    rax            ; (2) Preserve intermediate result!
    dec     edi            ; n-2
    call    fib_n          ; -> EAX
    pop     rdi            ; (2) Restore intermediate result
    add     eax, edi       ; fib(n) = fib(n-2) + fib(n-1)
    pop     rdi            ; (1) Restore n
    ret
.LT5:
    mov     eax, edi       ; n < 5
    cmp     edi, 2
    cmc
    sbb     eax, 0         ; fib(0) = 0, fib(1) = 1
    ret                    ; fib(2) = 1, fib(3) = 2, fib(4) = 3


问:
Empty string results in "Errors were detected in the command line arguments, please make sure all arguments are set correctly"
On a SQL 2016 Server I have a job that calls an SSIS package.  That package is in a project in the SSISDB and has parameters.   One of those parameters is a string type that is blank as a default.

I ran the job with the blank value for this parameter, and it ran successfully.

I then opened the job properties, went to the step that calls that package and went into the configuration and gave that parameter a value.

I ran the job again and it ran successfully, and the parameter value had the expected effect on the results.

Now I want to modify the job and set the parameter back to a blank string.  Repeating what I did above, I open the configuration and completely delete the value of the parameter.

When I then try to save the Job Step properties, I get an error dialog with the message in my subject line.

If I put a non-empty value back in for that parameter, the job step can be saved.

When I first created the job, I was able to save it with an empty string for that value.  It's just when I change the value to a non-empty string, run the job, and then try to change it back to empty, that I encounter this error.

I'm aware that I can run an alter job script or delete and re-create the job step to work around this.  I'm not interested in knowing how to work around this problem.

My question is:  Is this a known bug, or is there a trick to using the GUI to change the value of a parameter for execution from a string value to an empty string?

Can any of you do it, or is my issue reproducible?  I've found nothing in my searches so far.

EDIT: following Aaron's comment, I tried entering a pair of single-quotes for the value of the parameter. The job accepted it and saved successfully. But then when I ran the job, the pair of single quotes were used literally as the value of the parameter, instead of an empty string.

答:
I've solved with this workaround tested on SSMS version 17.9.1

Change back the value to an empty string and then move to the next step by clicking "Next" button.

Then the job can be saved without any errors.


问:
Why VBA doubleclick stopped working suddenly?
Below piece of code suddenly stopped working, please help?</p>

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

On Error Resume Next
If Target.Column = 2 And Target.Row > 27 And Target.Row < 70 Then
        UserForm1.Show
        Target.Value = returnvalue
        Cancel = True
    End If
End Sub
</code>```

答: Thank you everyone for your help. I was using a dictionary to populate a list box in the initialize block of the form. The range used to build the dictionary had duplicates causing the code to fail. Updating the code to handle duplicates solved my problem.</p>

Body:
Below piece of code suddenly stopped working, please help?

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

On Error Resume Next
If Target.Column = 2 And Target.Row > 27 And Target.Row < 70 Then
        UserForm1.Show
        Target.Value = returnvalue
        Cancel = True
    End If
End Sub


问:
Parse JSON property during deserialization
With the following portion of a JSON:

```<code>"tags":
{
  "tiger:maxspeed": "65 mph"
}
</code>```

And I have the corresponding C# class I am using to deserialize:

```<code>public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

}
</code>```

I would like to deserialize it into an integer property instead:

```<code>public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed { get; set; }

}
</code>```

Is it possible to parse the numeric part of the string from the JSON to an int during deserialization?

I think I want something like:

```<code>public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed
    {
        get
        {
            return _maxspeed;
        }
        set
        {
            _maxspeed = Maxspeed.Parse(<incoming string>.split(" ")[0]);
        }
    }
}
</code>```

答:
Can you just use a different property to return the int portion of the string?</p>

```<code>public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

    [JsonIgnore]
    public int MaxSpeedInt => int.Parse(Maxspeed.Split(' ')[0]);

}
</code>```

Body:
With the following portion of a JSON:

"tags":
{
  "tiger:maxspeed": "65 mph"
}

And I have the corresponding C# class I am using to deserialize:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

}

I would like to deserialize it into an integer property instead:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed { get; set; }

}

Is it possible to parse the numeric part of the string from the JSON to an int during deserialization?

I think I want something like:

public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed
    {
        get
        {
            return _maxspeed;
        }
        set
        {
            _maxspeed = Maxspeed.Parse(<incoming string>.split(" ")[0]);
        }
    }
}

Body:
Can you just use a different property to return the int portion of the string?

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

    [JsonIgnore]
    public int MaxSpeedInt => int.Parse(Maxspeed.Split(' ')[0]);

}


问:
Is there any way to connect to specific readonly replica in Azure SQL DB Premium Read Scale-Out?
I would like to know is there any way to connect to one of readonly replicas?

I know if Azure SQL data base is Premium type and Read Scale-out is Enabled, I can have two readnonly replicas. For connecting to ANY of those replicas, I just need to put ApplicationIntent=ReadOnly; in my connection string.

Attached link about Read scale-out replicas
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out

Also I know that there are some load balancer that can switch from request from one readonly replica to another.

So, is there some approach to define what replica should I use, Replica1 or Replica2 for (for ex.) Analytics and PowerBi reports accordingly at the same time?

Server=tcp:.database.windows.net;Database=;ApplicationIntent=ReadOnly;User ID=;Password=;Trusted_Connection=False; Encrypt=True;

答: At any given time only one of the replicas is accessible by the ReadOnly sessions and you cannot specify which one.</p>


答: It is saying that /home/svn/web_projects is (the top level of) an existing repository, and will not let you create one inside that. You need to create yours at /home/svn/my_project.</p>

Title: Subversion - problem creating a new repository

Body:
I have recently taken over a linux box running subversion.

The folder where the the repos look like they are installed is in: /home/svn

In this folder I see a folder named web_projects and in that folder I see conf dev db etc etc

I am trying to add a new repository to this server, but I'm getting the following error:

`svnadmin: '/home/svn/web_projects/my_project' is a subdirectoy of an existing repository rooted at '/home/svn/web_projects'

Does anyone know why I can't seem to add a new repository?


问:
Symfony2 - Change Migration Directory
How can I change the default migration dirctory in the config.yml?
Right now I am using 2 bundles with different db-connections and I would like to create migrations files and store them in different directories to use the doctrine:migrations:migrate --em=whatever function in depency of the bundle.

For example:

```<code>doctrine:migrate:diff --em=whatever #creating a version file in the DoctrineMigrationsWhatever directory

php app/console doctrine:migrations:status --em=whatever # shows only the version files, that belong to the bundle
</code>```

答:
For Symfony 4, the recommended approach is to use %kernel.project_dir% instead, and put it in the src/ folder namespaced by App\:

```<code>doctrine_migrations:
    dir_name: '%kernel.project_dir%/src/DoctrineMigrations'
    namespace: 'App\DoctrineMigrations'
</code>```

Title: Symfony2 - Change Migration Directory

Body:
How can I change the default migration dirctory in the config.yml?
Right now I am using 2 bundles with different db-connections and I would like to create migrations files and store them in different directories to use the doctrine:migrations:migrate --em=whatever function in depency of the bundle.

For example:

doctrine:migrate:diff --em=whatever #creating a version file in the DoctrineMigrationsWhatever directory

php app/console doctrine:migrations:status --em=whatever # shows only the version files, that belong to the bundle

Body:
For Symfony 4, the recommended approach is to use %kernel.project_dir% instead, and put it in the src/ folder namespaced by App\:

doctrine_migrations:
    dir_name: '%kernel.project_dir%/src/DoctrineMigrations'
    namespace: 'App\DoctrineMigrations'


问:
Error: Could not find or load main class sample.Main when creating JavaFX project on IntelliJ
I am using IntelliJ and I am trying to learn some JavaFX after covering some parts of Java. I am trying to create a simple HelloWorld application first. When I create a new project, it creates some things automatically, but there are errors and I can't run it:

```<code>Error: Could not find or load main class sample.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
Process finished with exit code 1
</code>```

What can I do to fix it? I tried to update IntelliJ and to update to JDK 12 and I am still getting this error.

答: If you're using JavaFx 11 12 or 13 then you have to import the jar files inside the lib folder of the specified javafx folder.Go to configure -> Structure for New Projects-> under the section of Platform settings go to Global Libraries hit the + sign and then browse to the lib folder of your javafx installation.Then you select all the files inside the lib folder and add them except the "src.zip" and name the library something like "Java Fx" or whatever you want.Afterwards you normally create a javafx project and you right click the project folder and go to module settings.Go again to the global libraries right click and add this library to the module.Now you can compile the code and it runs.</p>

Body:
I am using IntelliJ and I am trying to learn some JavaFX after covering some parts of Java. I am trying to create a simple HelloWorld application first. When I create a new project, it creates some things automatically, but there are errors and I can't run it:

Error: Could not find or load main class sample.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
Process finished with exit code 1

What can I do to fix it? I tried to update IntelliJ and to update to JDK 12 and I am still getting this error.


问:
Is there any database model having these "no-sql", "schema free" & "relational" ? is it support c++?
I need schema free db with relational features for my C++ application.

I already using PostgreSQL and Mysql in my project.

I want to store data relationally in document and need CRUD using SQL.

答:
Please take a look at AgensGraph database. AgensGraph is the only true multi model database supporting Relational Database and Graph Database(Schema Free). It is as well supporting Key-Value and document model. Also its based on C language.

AgensGraph


问:
IIS Buffering Requests Content Before Controller Action
I am trying to setup an "external" web api that will be able to receive in large http posts (+1GB) and forward the stream to another "internal" web api that writes the request contents to a file. I have model my implementation based on examples of using a custom WebHostBufferPolicySelector and using the UseBufferedInputStream method in the controller method. It works as expected when using IIS Express, no significate increase in memory footprint, but as soon as my code is deployed to IIS, the memory footprint is substantial and results in OOM.

I have put tracing statements in my controller methods and in my WebHostBufferPolicySelector.UseBufferedInputStream, and have verified that UseBufferedInputStream always is returning false and that my controller methods are getting hit. The only difference that I noticed is that when I debug, the time stamps between UseBufferedInputStream and my controller method are very close. Where hosted on IIS, the time stamps are very far apart, suggesting that something in between when UseBufferedInputStream is called and my controller method is called is buffering up the request entirely.

I am looking for some tips on to find out what that is causing the request to get buffered and how for it not to buffer and using streaming all the way.

Client is coming at the external web api with a content type of application/octet-stream with Transfer Encoding of Chucked.

Used to build out implementation

https://forums.asp.net/t/2018289.aspx?Web+API2+WebHostBufferPolicySelector+UseBufferedInputStream+override

https://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/

Proxy Web Api Controller Method

```<code>        <HttpPost, Route("postLargeFile")>
        Protected Overridable Async Function PostLargeFile() As Threading.Tasks.Task(Of IHttpActionResult)
            Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyProxyController)}", "Started {0}", NameOf(MyProxyController.PostLargeFile))

            Dim internalHttpClient As HttpClient
            Dim fowardingContent As StreamContent = Nothing
            Dim fowardingMessage As HttpRequestMessage = Nothing
            Dim fowardingResponse As HttpResponseMessage = Nothing
            Dim externalResponse As HttpResponseMessage = Nothing

            Try
                internalHttpClient = New HttpClient()
                internalHttpClient.BaseAddress = "https://myinternalService.com"

                fowardingMessage = New HttpRequestMessage(HttpMethod.Post, "https://myinternalService.com/saveLargeFile")
                fowardingContent = New StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(True))
                CopyContentHeaders(Request.Content, fowardingContent)

                fowardingMessage.Headers.TransferEncodingChunked = True
                fowardingMessage.Content = fowardingContent

                fowardingResponse = Await internalHttpClient.SendAsync(fowardingMessage, HttpCompletionOption.ResponseHeadersRead)

                externalResponse = New HttpResponseMessage(fowardingResponse.StatusCode)
                externalResponse.Content = New StreamContent(Await fowardingResponse.Content.ReadAsStreamAsync)
                CopyContentHeaders(fowardingResponse.Content, externalResponse.Content)

                Return New Results.ResponseMessageResult(externalResponse)

            Catch ex As Exception
                Return InternalServerError(ex)
            Finally
                Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyProxyController)}", "Finished {0}", NameOf(MyProxyController.PostLargeFile))
            End Try
        End Function
</code>```

Internal Web Api Controller Method

```<code>        <HttpPost, Route("saveLargeFile")>
        Protected Overridable Async Function SaveLargeFile() As Threading.Tasks.Task(Of IHttpActionResult)
            Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyInternalController)}", "Started {0}", NameOf(MyInternalController.PostLargeFile))

            Dim bufferlessStream As IO.Stream
            Dim fowardingContent As StreamContent = Nothing

            Try

                bufferlessStream = HttpContext.Current.Request.GetBufferlessInputStream()
                Using fileStream As IO.FileStream = IO.File.Create("MyFile.txt")
                    bufferlessStream.CopyTo(fileStream)
                    fileStream.Flush()
                End Using

                Return New Results.StatusCodeResult(Net.HttpStatusCode.Created, Me)

            Catch ex As Exception
                Return InternalServerError(ex)
            Finally
                Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyInternalController)}", "Finished {0}", NameOf(MyInternalController.PostLargeFile))
            End Try
        End Function
</code>```

Policy Selector Configuration

```<code>Public Class MyBufferPolicySelector
    Inherits Http.WebHost.WebHostBufferPolicySelector

    Public Property Tracer As ITraceWriter

    Public Overrides Function UseBufferedInputStream(hostContext As Object) As Boolean
        UseBufferedInputStream = False
        Tracer?.Info(Nothing, $"{Me.GetType.Namespace}.{NameOf(MyBufferPolicySelector)}", "{0} UseBufferedInputStream={1}", HttpContext.Current?.Request?.Url?.AbsoluteUri, UseBufferedInputStream)
        Return UseBufferedInputStream
    End Function
End Class
</code>```

WebApiConfig for both Internal and External Web APIs

```<code>Public Module WebApiConfig

    Public Sub Register(ByVal config As HttpConfiguration)
        Dim tracer As SystemDiagnosticsTraceWriter

        ' Web API configuration and services

        ' Web API routes
        config.MapHttpAttributeRoutes()

        tracer = config.EnableSystemDiagnosticsTracing
        tracer.IsVerbose = True
        tracer.MinimumLevel = Tracing.TraceLevel.Debug

        GlobalConfiguration.Configuration.Services.Replace(GetType(IHostBufferPolicySelector), New MyBufferPolicySelector() With {.Tracer = tracer})

    End Sub

End Module
</code>```

答:
I was able to figure out what was causing the the buffering in IIS. The below link lead me to the uploadReadAheadSize setting in IIS. This was maxed out. So this would cause IIS to fully read in/buffer in the request before passing it into the module where the web api pipeline exists (web api controllers). After setting it to the default, I saw my large file posts not get buffered, the app pool memory footprint remained low, no more out of memory exceptions, and a large performance boost. Great!

But now I have the same issue as described in the below link. When SSL is required, set in IIS, which it is required in our non development environments, the uploadReadAheadSize needs to be increased so the ssl can work in the ssl module I guess. It might have to do with some SSL renegotiation.

Can anybody describe a way to prevent the buffering in SSL to keep the memory footprint low and prevent out of memory exceptions for large http posts?

Large file upload when using ssl and client certificates (uploadReadAheadSize) but dont want all data to be readahead

Body:
I am trying to setup an "external" web api that will be able to receive in large http posts (+1GB) and forward the stream to another "internal" web api that writes the request contents to a file. I have model my implementation based on examples of using a custom WebHostBufferPolicySelector and using the UseBufferedInputStream method in the controller method. It works as expected when using IIS Express, no significate increase in memory footprint, but as soon as my code is deployed to IIS, the memory footprint is substantial and results in OOM.

I have put tracing statements in my controller methods and in my WebHostBufferPolicySelector.UseBufferedInputStream, and have verified that UseBufferedInputStream always is returning false and that my controller methods are getting hit. The only difference that I noticed is that when I debug, the time stamps between UseBufferedInputStream and my controller method are very close. Where hosted on IIS, the time stamps are very far apart, suggesting that something in between when UseBufferedInputStream is called and my controller method is called is buffering up the request entirely.

I am looking for some tips on to find out what that is causing the request to get buffered and how for it not to buffer and using streaming all the way.

Client is coming at the external web api with a content type of application/octet-stream with Transfer Encoding of Chucked.

Used to build out implementation

https://forums.asp.net/t/2018289.aspx?Web+API2+WebHostBufferPolicySelector+UseBufferedInputStream+override

https://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/

Proxy Web Api Controller Method

        <HttpPost, Route("postLargeFile")>
        Protected Overridable Async Function PostLargeFile() As Threading.Tasks.Task(Of IHttpActionResult)
            Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyProxyController)}", "Started {0}", NameOf(MyProxyController.PostLargeFile))

            Dim internalHttpClient As HttpClient
            Dim fowardingContent As StreamContent = Nothing
            Dim fowardingMessage As HttpRequestMessage = Nothing
            Dim fowardingResponse As HttpResponseMessage = Nothing
            Dim externalResponse As HttpResponseMessage = Nothing

            Try
                internalHttpClient = New HttpClient()
                internalHttpClient.BaseAddress = "https://myinternalService.com"

                fowardingMessage = New HttpRequestMessage(HttpMethod.Post, "https://myinternalService.com/saveLargeFile")
                fowardingContent = New StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(True))
                CopyContentHeaders(Request.Content, fowardingContent)

                fowardingMessage.Headers.TransferEncodingChunked = True
                fowardingMessage.Content = fowardingContent

                fowardingResponse = Await internalHttpClient.SendAsync(fowardingMessage, HttpCompletionOption.ResponseHeadersRead)

                externalResponse = New HttpResponseMessage(fowardingResponse.StatusCode)
                externalResponse.Content = New StreamContent(Await fowardingResponse.Content.ReadAsStreamAsync)
                CopyContentHeaders(fowardingResponse.Content, externalResponse.Content)

                Return New Results.ResponseMessageResult(externalResponse)

            Catch ex As Exception
                Return InternalServerError(ex)
            Finally
                Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyProxyController)}", "Finished {0}", NameOf(MyProxyController.PostLargeFile))
            End Try
        End Function

Internal Web Api Controller Method

        <HttpPost, Route("saveLargeFile")>
        Protected Overridable Async Function SaveLargeFile() As Threading.Tasks.Task(Of IHttpActionResult)
            Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyInternalController)}", "Started {0}", NameOf(MyInternalController.PostLargeFile))

            Dim bufferlessStream As IO.Stream
            Dim fowardingContent As StreamContent = Nothing

            Try

                bufferlessStream = HttpContext.Current.Request.GetBufferlessInputStream()
                Using fileStream As IO.FileStream = IO.File.Create("MyFile.txt")
                    bufferlessStream.CopyTo(fileStream)
                    fileStream.Flush()
                End Using

                Return New Results.StatusCodeResult(Net.HttpStatusCode.Created, Me)

            Catch ex As Exception
                Return InternalServerError(ex)
            Finally
                Configuration.Services.GetTraceWriter.Info(Request, $"{Me.GetType.Namespace}.{NameOf(MyInternalController)}", "Finished {0}", NameOf(MyInternalController.PostLargeFile))
            End Try
        End Function

Policy Selector Configuration

Public Class MyBufferPolicySelector
    Inherits Http.WebHost.WebHostBufferPolicySelector

    Public Property Tracer As ITraceWriter

    Public Overrides Function UseBufferedInputStream(hostContext As Object) As Boolean
        UseBufferedInputStream = False
        Tracer?.Info(Nothing, $"{Me.GetType.Namespace}.{NameOf(MyBufferPolicySelector)}", "{0} UseBufferedInputStream={1}", HttpContext.Current?.Request?.Url?.AbsoluteUri, UseBufferedInputStream)
        Return UseBufferedInputStream
    End Function
End Class

WebApiConfig for both Internal and External Web APIs

Public Module WebApiConfig

    Public Sub Register(ByVal config As HttpConfiguration)
        Dim tracer As SystemDiagnosticsTraceWriter

        ' Web API configuration and services

        ' Web API routes
        config.MapHttpAttributeRoutes()

        tracer = config.EnableSystemDiagnosticsTracing
        tracer.IsVerbose = True
        tracer.MinimumLevel = Tracing.TraceLevel.Debug

        GlobalConfiguration.Configuration.Services.Replace(GetType(IHostBufferPolicySelector), New MyBufferPolicySelector() With {.Tracer = tracer})

    End Sub

End Module


问:
How to redirect http:// to https:// like firebase hosting
Firebase hosting already had https:// redirects, in the firebase.json. I have an Angular app, and to prepare for SSR, I migrated from firebase hosting to Cloud Run. At first I didn't know whether I was supposed to mess with Angular Universal or something to do this, I seen a similar question on here but it was answered with Nginx, which is not what I need.

I tried to do really dumb things with the server.ts file and that was not the answer at all. I honestly do not know exactly where to start. I have scoured google for the answer, including of google cloud run docs here:

https://cloud.google.com/run/docs/authenticating/public

but I have no idea where to go from here.

答:
If you're allowed to make a .htaccess file, try this:

Create a .htaccess in your site's home directory

Add these lines:

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Reload your website, and give it a minute to register the changes.

Basically this forces any URL used to access the site, to an HTTPS:// URL.

https://www.siteground.com/kb/how-to-force-ssl-with-htaccess/

Body:
If you're allowed to make a .htaccess file, try this:

Create a .htaccess in your site's home directory

Add these lines:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Reload your website, and give it a minute to register the changes.

Basically this forces any URL used to access the site, to an HTTPS:// URL.

https://www.siteground.com/kb/how-to-force-ssl-with-htaccess/


答:
I think this list comprehension works (haven't seen an example of how % is handled):

```<code>[ (a+b if b in (')',')%','%') else a) for a,b in zip(list1,list1[1:]+['']) if a not in ('$',')',')%','%')]
</code>```

The idea is to:

make a list of pairings of elements and their successors

filter out elements that should be removed

add the successor as appropriate to those that we keep

Title: remove elements from list of strings while traversing

Body:
how to remove elements from a list of strings while traversing through it.
I have a list

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.

expected output is :

['', '32,324', '32', '(35)', '32,321']

what i have tried is

for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)

but the output i am getting is

['', '32,324', '32', '(35)', '$', '32,321']

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

Body:
I think this list comprehension works (haven't seen an example of how % is handled):

[ (a+b if b in (')',')%','%') else a) for a,b in zip(list1,list1[1:]+['']) if a not in ('$',')',')%','%')]

The idea is to:

make a list of pairings of elements and their successors

filter out elements that should be removed

add the successor as appropriate to those that we keep


问:
In a regular table, is there a way to put an outer border on a table and leave out the table header?
I have a table, and at the top of the table is the table header with some text. I want to be able to only put a border on the table body, and leave the table header untouched, but I don't know how.

I have only tried applying a border to the default class for table body.

    This is some text I want outside of the border

    This is some cell data I want inside the border

```

All I need is for the tbody to be the only bordered thing in the table, and when I try and give it a border, nothing happens.

答:
tbody, tbody th, tbody td, tbody tr {
    border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="float-left">
 <thead>
  <tr class="text-center">
   <th>header</th>
   <th>header</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>content</td>
   <td>content</td>
  </tr>
  <tr>
   <td>content</td>
   <td>content</td>
  </tr>
 </tbody>
</table></code>```

This creates a border for tbody as well as all th, tr and td elements inside the tbody.

Body:
I have a table, and at the top of the table is the table header with some text. I want to be able to only put a border on the table body, and leave the table header untouched, but I don't know how.

I have only tried applying a border to the default class for table body.

    This is some text I want outside of the border

    This is some cell data I want inside the border

All I need is for the tbody to be the only bordered thing in the table, and when I try and give it a border, nothing happens.

Body:
tbody, tbody th, tbody td, tbody tr {
    border: 1px solid black;
}

<table class="float-left">
 <thead>
  <tr class="text-center">
   <th>header</th>
   <th>header</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>content</td>
   <td>content</td>
  </tr>
  <tr>
   <td>content</td>
   <td>content</td>
  </tr>
 </tbody>
</table>

This creates a border for tbody as well as all th, tr and td elements inside the tbody.


问:
get() in picasso cannot be applied to (android.content.context)
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

Adapter Class

```<code>public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}
</code>```

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!

答:
Since Picasso 2.71828 you dont need to supply Context in Picasso.get()

For more information see the ChangeLog

Body:
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

implementation 'com.squareup.picasso:picasso:2.71828'

Adapter Class

public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!


问:
Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"?
To prevent actions from happening, I frequently type

```<code>function(){return false;}
</code>```

Is there a shortcut?

答:
You could declare a named function like this:

```<code>function always_false() { return false; }
</code>```

then use always_false() wherever you would have previously created the anonymous function.

OwnerDisplayName: Steven Noble

Body:
To prevent actions from happening, I frequently type

function(){return false;}

Is there a shortcut?

Body:
You could declare a named function like this:

function always_false() { return false; }

then use always_false() wherever you would have previously created the anonymous function.

OwnerDisplayName: Greg Hewgill


问:
How can I unify the number of decimal places in ggplot?
I have a more complex code compared to the examples provided and cannot imagine how I have to change the code to obtain the same number of decimal places for all bars of my bar chart. For most of the bars, R already shows two decimal places. Whenever the second decimal place is a "0", however, R only shows one decimal place. Can someone please show me how to standardize the decimal place to 2 and how to integrate the command in my code?

I already tried "digits" and specify_decimal but failed to correctly integrate it into my code (in scale_x_continuous).

```<code>df1_long %.>%
  ggplot(
    data = .,
    aes(
      x = xpos,
      y = val,
      fill = Ebene
  )) +
  geom_rect(aes(
      xmin = xpos - .5,
      xmax = xpos + .5,
      ymin = -Inf,
      ymax = Inf,
      fill = Problemzahl
    ),
    alpha = .3
  ) +
  geom_col(
    position = position_dodge(.5),
    colour="black",
    width = .5
  ) +
  geom_errorbar(aes(
      ymin = val - SE,
      ymax = val + SE
    ),
    position = position_dodge(.5),
    width = .2
  ) +
  geom_text(aes(
      y = val + SE + .02,
      label = val %>% str_replace('\\.', ',')
    ),
    position = position_dodge(.5)
  ) +
  scale_fill_manual(
    values = c(
      '#aaaaaa',  # Beide Problemarten
      '#000000',  # Co
      '#dddddd',  # Keine Probleme
      '#CCCCCC',  # Motivationale Probleme
      '#333333',  # Self
      '#666666',  # Shared
      '#bbbbbb'   # Verständnisbezogene Probleme
    ),
    breaks = c(
      'Self',
      'Co',
      'Shared'
    )
  ) +
  scale_x_continuous(
    breaks = .$xpos %>% unique(),
    labels = .$Problemzahl %>% unique(),
    expand = c(0, 0)
  ) +
  scale_y_continuous(
    labels = function(x) str_replace(x, '\\.', ','),
    limits = c(0, 1.0),
    expand = c(0, 0)
  ) +
  ylab('Allgemeine Regulationsaktivität auf der Self-, Co-, und Shared Ebene\n(KI 95%)') +
  theme_classic() +
  theme(
    legend.position = 'top',
    legend.title = element_blank(),
    legend.spacing.x = unit(1, 'mm'),
    axis.title.x = element_blank()
  )
</code>```

答:
I would alter the code in your pipe before calling ggplot. Here's a nice example using the formattable package.

```<code>library(tidyverse)
library(formattable)

df1_long %>%
  mutate(val = formattable(val, digits = 2, format = "f")) %>%
  ggplot(
  ...
)
</code>```

You can substitute whatever variable name for val, depending on which one you want to standardize to two decimal places.

Body:
I have a more complex code compared to the examples provided and cannot imagine how I have to change the code to obtain the same number of decimal places for all bars of my bar chart. For most of the bars, R already shows two decimal places. Whenever the second decimal place is a "0", however, R only shows one decimal place. Can someone please show me how to standardize the decimal place to 2 and how to integrate the command in my code?

I already tried "digits" and specify_decimal but failed to correctly integrate it into my code (in scale_x_continuous).

df1_long %.>%
  ggplot(
    data = .,
    aes(
      x = xpos,
      y = val,
      fill = Ebene
  )) +
  geom_rect(aes(
      xmin = xpos - .5,
      xmax = xpos + .5,
      ymin = -Inf,
      ymax = Inf,
      fill = Problemzahl
    ),
    alpha = .3
  ) +
  geom_col(
    position = position_dodge(.5),
    colour="black",
    width = .5
  ) +
  geom_errorbar(aes(
      ymin = val - SE,
      ymax = val + SE
    ),
    position = position_dodge(.5),
    width = .2
  ) +
  geom_text(aes(
      y = val + SE + .02,
      label = val %>% str_replace('\\.', ',')
    ),
    position = position_dodge(.5)
  ) +
  scale_fill_manual(
    values = c(
      '#aaaaaa',  # Beide Problemarten
      '#000000',  # Co
      '#dddddd',  # Keine Probleme
      '#CCCCCC',  # Motivationale Probleme
      '#333333',  # Self
      '#666666',  # Shared
      '#bbbbbb'   # Verständnisbezogene Probleme
    ),
    breaks = c(
      'Self',
      'Co',
      'Shared'
    )
  ) +
  scale_x_continuous(
    breaks = .$xpos %>% unique(),
    labels = .$Problemzahl %>% unique(),
    expand = c(0, 0)
  ) +
  scale_y_continuous(
    labels = function(x) str_replace(x, '\\.', ','),
    limits = c(0, 1.0),
    expand = c(0, 0)
  ) +
  ylab('Allgemeine Regulationsaktivität auf der Self-, Co-, und Shared Ebene\n(KI 95%)') +
  theme_classic() +
  theme(
    legend.position = 'top',
    legend.title = element_blank(),
    legend.spacing.x = unit(1, 'mm'),
    axis.title.x = element_blank()
  )

Body:
I would alter the code in your pipe before calling ggplot. Here's a nice example using the formattable package.

library(tidyverse)
library(formattable)

df1_long %>%
  mutate(val = formattable(val, digits = 2, format = "f")) %>%
  ggplot(
  ...
)

You can substitute whatever variable name for val, depending on which one you want to standardize to two decimal places.


问:
How can I render Map() items into React jsx by forEach loop?
I've a Map() object in state and that store some names and options for list filter. but I can't render Map items in JSX by forEach like this :

{
    this.state.items.forEach((value, key) => (

{value}

    ))
}

```

Apparently I can't access to Map items without forEach and in this case Array.map() is not usable.

What's the best practice to handle this issue ? I should use entries() and then Array.map() and then render the list ?

Thanks

答:
Option 1: if you cannot use map then use a variable

```<code>const elems = []
this.state.items.forEach((value, idx) => (
  elems.push(<li key={idx}>{value}</li>)
))
</code>```

then when rendering

```<code><ul>
  {elems}
</ul>
</code>```

Option 2: if you can use map then just do it inline

```<code><ul>
  {
    this.state.items.map((value, idx) => <li key={idx}>{value}</li>)
  }
</ul>
</code>```

Body:
I've a Map() object in state and that store some names and options for list filter. but I can't render Map items in JSX by forEach like this :

{
    this.state.items.forEach((value, key) => (

{value}

    ))
}

Apparently I can't access to Map items without forEach and in this case Array.map() is not usable.

What's the best practice to handle this issue ? I should use entries() and then Array.map() and then render the list ?

Thanks

Body:
Option 1: if you cannot use map then use a variable

const elems = []
this.state.items.forEach((value, idx) => (
  elems.push(<li key={idx}>{value}</li>)
))

then when rendering

<ul>
  {elems}
</ul>

Option 2: if you can use map then just do it inline

<ul>
  {
    this.state.items.map((value, idx) => <li key={idx}>{value}</li>)
  }
</ul>


问:
Laravel Carbon, how do I get all the dates between two date ranges?
Explame Code:

$start_date = Carbon::createFromDate(2019, 05, 30);
$end_date   = Carbon::createFromDate(2019, 06, 03);
```

<p>Desired result：</p>

<pre class="lang-sh prettyprint-override"><code>array:4 [▼
  0 => "2019-05-30"
  1 => "2019-05-31"
  2 => "2019-06-01"
  3 => "2019-06-02"
  4 => "2019-06-03"
]
</code>```

IDEA:

I saw that the documentation didn't find a way to handle similar requirements. Currently my idea is to use a foreach implementation, but I feel that this is not the best.

答:
You can indeed use CarbonPeriod for this.

```<code>$period = CarbonPeriod::create('2019-05-30', '2019-06-03');
$period->toArray();
</code>```

This should already return the desired result for you.
Check the docs for some nice features and options such as excluding start/end dates if needed.

Body:
Explame Code:

$start_date = Carbon::createFromDate(2019, 05, 30);
$end_date   = Carbon::createFromDate(2019, 06, 03);

Desired result：

array:4 [▼
  0 => "2019-05-30"
  1 => "2019-05-31"
  2 => "2019-06-01"
  3 => "2019-06-02"
  4 => "2019-06-03"
]

IDEA:

I saw that the documentation didn't find a way to handle similar requirements. Currently my idea is to use a foreach implementation, but I feel that this is not the best.

Body:
You can indeed use CarbonPeriod for this.

$period = CarbonPeriod::create('2019-05-30', '2019-06-03');
$period->toArray();

This should already return the desired result for you.
Check the docs for some nice features and options such as excluding start/end dates if needed.


问:
Apply multiple times a Product Partner Fixed Price Promotion
In SAP Commerce v1811 I configured a product partner fixed price promotion such us
"Buy 2 of Product A and get product B at USD 100"
In order to do this I used the Product perfect partner fixed price and configured

```<code>Conditions
CONTAINER_X: Qualifying Products -> A qty >= 1
CONTAINER_Y: Qualifying Products -> B qty >= 1

Actions
target price -> USD 100
qualifying container -> CONTAINER_X->2
target container -> CONTAINER_Y->1
</code>```

I also set the execution max times at 3 but when the promotion it's applied the first time it works perfectly (when I add 2A and 1B) but the second time it's not apllied (when I add 4A and 2B) is not applied.

Thanks!

答: I had to upgrade my version to 1811.6 and it was fixed</p>

Body:
In SAP Commerce v1811 I configured a product partner fixed price promotion such us
"Buy 2 of Product A and get product B at USD 100"
In order to do this I used the Product perfect partner fixed price and configured

Conditions
CONTAINER_X: Qualifying Products -> A qty >= 1
CONTAINER_Y: Qualifying Products -> B qty >= 1

Actions
target price -> USD 100
qualifying container -> CONTAINER_X->2
target container -> CONTAINER_Y->1

I also set the execution max times at 3 but when the promotion it's applied the first time it works perfectly (when I add 2A and 1B) but the second time it's not apllied (when I add 4A and 2B) is not applied.

Thanks!


问:
text inside the mat-progress-bar in angular material
In the mat-progress-bar  I have to display the text inside the progress-bar not value any other percentage. can any one help to display text inside the progress-bar?</p>

```<code><mat-progress-bar mode="determinate" class="progress-bar" [color]="color " [value]="progress" ></mat-progress-bar>
</code>```

答:
You can use css to do this. This way, your content is always in the centralized progress bar. The only condition is the width and height of the mat-progress-spinner being the same as the parent div:

```<code><div style="position: relative; width: 100px; height: 100px; display: flex; align-items: center; justify-content: center;">
  <mat-progress-spinner style="width: 100px;height: 100px;position: absolute;top: 0;left: 0;" [color]="'primary'" [mode]="'determinate'" [value]="60">
  </mat-progress-spinner>
  <h1 >69%</h1>
</div>
</code>```

Body:
In the mat-progress-bar  I have to display the text inside the progress-bar not value any other percentage. can any one help to display text inside the progress-bar?

<mat-progress-bar mode="determinate" class="progress-bar" [color]="color " [value]="progress" ></mat-progress-bar>

Body:
You can use css to do this. This way, your content is always in the centralized progress bar. The only condition is the width and height of the mat-progress-spinner being the same as the parent div:

<div style="position: relative; width: 100px; height: 100px; display: flex; align-items: center; justify-content: center;">
  <mat-progress-spinner style="width: 100px;height: 100px;position: absolute;top: 0;left: 0;" [color]="'primary'" [mode]="'determinate'" [value]="60">
  </mat-progress-spinner>
  <h1 >69%</h1>
</div>


问:
data dateTime to only date to draw line chart
i want to draw line chart but my date get value including time from sql-server data
how can i remove time

```<code>            console.log(json);
            if (json.length > 0) {

                var datagraph = [];
                datagraph.push(['Date', 'Point']);
                for (i = 0; i < json.length; i++) {
                    var smalldata = [];
                    var date = json[i].Date;
                    var point = json[i].Point;
                    smalldata.push(date, point);
                    datagraph.push(smalldata);

                }
            }
</code>```

console.log(json)
here is the result

```<code>0: {DateTime: "2019-05-31T00:00:00", Point: 1}
length: 1
__proto__: Array(0)
</code>```

答:
Use the function 'split' to divide the string by the character 'T'</p>

```<code>let parts = json[i].Date.split('T');
let date = parts[0];
</code>```

Body:
i want to draw line chart but my date get value including time from sql-server data
how can i remove time

            console.log(json);
            if (json.length > 0) {

                var datagraph = [];
                datagraph.push(['Date', 'Point']);
                for (i = 0; i < json.length; i++) {
                    var smalldata = [];
                    var date = json[i].Date;
                    var point = json[i].Point;
                    smalldata.push(date, point);
                    datagraph.push(smalldata);

                }
            }

console.log(json)
here is the result

0: {DateTime: "2019-05-31T00:00:00", Point: 1}
length: 1
__proto__: Array(0)

Body:
Use the function 'split' to divide the string by the character 'T'

let parts = json[i].Date.split('T');
let date = parts[0];


问:
TextBox inside eclipse's draw2d figure
Is there any way to include a Text Box inside a draw2d figure? (a code example would be nice)</p>

答:
Not easily, and if you're just using Draw2d without GEF, then I don't think it's possible.

With GEF, you can make use of a DirectEditManager in an Edit Part, and create an Edit Policy (extending DirectEditPolicy, installed with the key EditPolicy.DIRECT_EDIT_ROLE) to allow a direct edit to be performed on a figure.

You could create a figure which extends Label that is styled to look like a text box, and activate (by overriding performRequest in the Edit Part) editing upon selection.

This Schema Diagram example contains this type of functionality (and more importantly, the code!), although the figure used for edit (EditableLabel) isn't styled to look like a text box, and the activation itself is on double-click rather than selection.

It may point you in the right direction though.

Title: TextBox inside eclipse's draw2d figure