问:
Is it possible to transfer caches/artifacts between pipelines?
In Gitlab, is it possible to transfer caches or artifacts between pipelines?
I am building a library in one pipeline and I want to build an application with the library in another pipeline.</p>

答:
Yes, it is possible. There are a couple of options to achieve this:

Using Job API and GitLab Premium

The first option is to use Job API to fetch artifacts. This method is available only if you have GitLab Premium. In this option, you use CI_JOB_TOKEN in Job API to fetch artifacts from another pipeline. Read more here.

Here is quick example of a job you would put in your application pipeline configuration:

build_application:
  image: debian
  stage: build
  script:
  - apt update && apt install -y unzip
  - curl --location --output artifacts.zip "https://gitlab.example.com/api/v4/projects/${PROJECT_ID}/jobs/artifacts/master/download?job=build&job_token=$CI_JOB_TOKEN"
  - unzip artifacts.zip
```

<hr>

<h1>Using S3</h1>

<p>The second option is to use some third-party intermediate storage, for instance, AWS S3. To pass artifacts follow below example.</p>

<p>In your <em>library</em> pipeline configuration create the following job:</p>

<pre class="lang-yaml prettyprint-override"><code>variables:
  TARGET_PROJECT_TOKEN: [get token from Settings -> CI/CD -> Triggers]
  TARGET_PROJECT_ID: [get project id from project main page]

publish-artifact:
  image: "python:latest"
  stage: publish
  before_script:
    - pip install awscli
  script:
    - aws s3 cp output/artifact.zip s3://your-s3-bucket-name/artifact.zip.${CI_JOB_ID}
    - "curl -X POST -F token=${TARGET_PROJECT_TOKEN} -F ref=master -F variables[ARTIFACT_ID]=${CI_JOB_ID} https://gitlab.com/api/v4/projects/${TARGET_PROJECT_ID}/trigger/pipeline"
</code>```

Then in your application pipeline configuration retrieve the artifact from the s3 bucket:

fetch-artifact-from-s3:
  image: "python:latest"
  stage: prepare
  artifacts:
    paths:
      - artifact/
  before_script:
    - pip install awscli
  script:
    - mkdir artifact
    - aws s3 cp s3://your-s3-bucket-name/artifact.zip.${ARTIFACT_ID} artifact/artifact.zip
  only:
    variables:
      - $ARTIFACT_ID
```

Once fetch-artifact-from-s3 job is completed you will have your artifact available in artifact/ directory. It can now be consumed in other jobs within application pipeline.

Body:
Yes, it is possible. There are a couple of options to achieve this:

Using Job API and GitLab Premium

The first option is to use Job API to fetch artifacts. This method is available only if you have GitLab Premium. In this option, you use CI_JOB_TOKEN in Job API to fetch artifacts from another pipeline. Read more here.

Here is quick example of a job you would put in your application pipeline configuration:

build_application:
  image: debian
  stage: build
  script:
  - apt update && apt install -y unzip
  - curl --location --output artifacts.zip "https://gitlab.example.com/api/v4/projects/${PROJECT_ID}/jobs/artifacts/master/download?job=build&job_token=$CI_JOB_TOKEN"
  - unzip artifacts.zip

Using S3

The second option is to use some third-party intermediate storage, for instance, AWS S3. To pass artifacts follow below example.

In your library pipeline configuration create the following job:

variables:
  TARGET_PROJECT_TOKEN: [get token from Settings -> CI/CD -> Triggers]
  TARGET_PROJECT_ID: [get project id from project main page]

publish-artifact:
  image: "python:latest"
  stage: publish
  before_script:
    - pip install awscli
  script:
    - aws s3 cp output/artifact.zip s3://your-s3-bucket-name/artifact.zip.${CI_JOB_ID}
    - "curl -X POST -F token=${TARGET_PROJECT_TOKEN} -F ref=master -F variables[ARTIFACT_ID]=${CI_JOB_ID} https://gitlab.com/api/v4/projects/${TARGET_PROJECT_ID}/trigger/pipeline"

Then in your application pipeline configuration retrieve the artifact from the s3 bucket:

fetch-artifact-from-s3:
  image: "python:latest"
  stage: prepare
  artifacts:
    paths:
      - artifact/
  before_script:
    - pip install awscli
  script:
    - mkdir artifact
    - aws s3 cp s3://your-s3-bucket-name/artifact.zip.${ARTIFACT_ID} artifact/artifact.zip
  only:
    variables:
      - $ARTIFACT_ID

Once fetch-artifact-from-s3 job is completed you will have your artifact available in artifact/ directory. It can now be consumed in other jobs within application pipeline.


来源: stackexchange

问:
R Tidy solution to select from group_by output based on a column's data availability
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

```<code>df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected
</code>```

答:
Try this. Might not be the most concise code, but I think it solves your question.

# Sample dataframe
  pmid   email No
1    1    <NA>  1
2    1    <NA>  2
3    1    <NA>  3
4    2 a@b.com  4
5    2    <NA>  5

# Logic
val <- df$pmid[!is.na(df$email)] %>% unique()
df[!df$pmid %in% val, ] %>%
  group_by(pmid) %>%
  slice(n()) %>%
  ungroup()

# Result
# A tibble: 2 x 3
   pmid email      No
  <dbl> <fct>   <int>
1     1 NA          3
```

ContentLicense: CC BY-SA 4.0

Body:
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected


问:
Reading / Writing files in Javascript - IE6
I need a database storage system for Javascript where the state can be maintained on the local disk.

Here comes the spanners in the works :-

It only needs to support Internet Explorer but the minimum version must be IE6

Files need to be written so they can be read in again later (upon closing and re-opening of browser)

There can be no web server (unless it's extremely easy to distribute and does not require a install) since the HTML pages will be distributed on USB.

Does anyone know of any solutions that might help here?

答:
I don't know if it's supported in IE6, but JScript appears to have some level of support for this through FileSystemObject.

```<code>var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
</code>```

According to Write binary data with FileSystemObject write(), ADODB.Stream appears to be an alternative.

ContentLicense: CC BY-SA 3.0

Body:
I don't know if it's supported in IE6, but JScript appears to have some level of support for this through FileSystemObject.

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

According to Write binary data with FileSystemObject write(), ADODB.Stream appears to be an alternative.


问:
Dynamic google visualization in typescript/angular
I want to make it dynamic. Please anyone can help me to do this . Actually i am new in to angular & Typescript.

Code Snippet Here:
 Manually I am adding  row column. How to make it dynamic. Is it possible to iterate in loop.

We are using google charts.

```<code>const data = google.visualization.arrayToDataTable([
['Encounter Type', 'No of Encounters'],
[this.dataList[0][0], this.dataList[0][1]],
[this.dataList[3][0], this.dataList[3][1]],
[this.dataList[1][0], this.dataList[1][1]],
[this.dataList[2][0], this.dataList[2][1]],
]);
</code>```

答:
if you simply want to add the rows from dataList,

use a forEach statement

first, create an array with the column headings...

```<code>let arrayData = [
  ['Encounter Type', 'No of Encounters']
];
</code>```

use forEach to load the rows...

```<code>this.dataList.forEach(function (row) {
  arrayData.push([row[0], row[1]]);
});
</code>```

then create the data table from the array...

```<code>const data = google.visualization.arrayToDataTable(arrayData);
</code>```

Body:
I want to make it dynamic. Please anyone can help me to do this . Actually i am new in to angular & Typescript.

Code Snippet Here:
 Manually I am adding  row column. How to make it dynamic. Is it possible to iterate in loop.

We are using google charts.

const data = google.visualization.arrayToDataTable([
['Encounter Type', 'No of Encounters'],
[this.dataList[0][0], this.dataList[0][1]],
[this.dataList[3][0], this.dataList[3][1]],
[this.dataList[1][0], this.dataList[1][1]],
[this.dataList[2][0], this.dataList[2][1]],
]);

Body:
if you simply want to add the rows from dataList,

use a forEach statement

first, create an array with the column headings...

let arrayData = [
  ['Encounter Type', 'No of Encounters']
];

use forEach to load the rows...

this.dataList.forEach(function (row) {
  arrayData.push([row[0], row[1]]);
});

then create the data table from the array...

const data = google.visualization.arrayToDataTable(arrayData);


问:
Android Studio : Failed to create JVM error code : -1
Please dont mark it as duplicate.

I did make changes as per other answers available when error code was -4.
Now it is showing error code : -1.

Kindly give me some direction.

here is my studio.exe.vmoptions file

```<code> server
-Xms256m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio
</code>```

答:
And for those who just edited their .vmoptions and messed it up, this is where that file is (according to this documentation):

Both configuration files are stored in the configuration folder for
  Android Studio. The name of the folder depends on your Studio version.
  For example, Android Studio 3.3 has the folder name AndroidStudio3.3.
  The location of this folder depends on your operating system:

```<code>Windows: %USERPROFILE%\.CONFIGURATION_FOLDER
macOS: ~/Library/Preferences/CONFIGURATION_FOLDER
Linux: ~/.CONFIGURATION_FOLDER
</code>```

Body:
Please dont mark it as duplicate.

I did make changes as per other answers available when error code was -4.
Now it is showing error code : -1.

Kindly give me some direction.

here is my studio.exe.vmoptions file

 server
-Xms256m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio

Body:
And for those who just edited their .vmoptions and messed it up, this is where that file is (according to this documentation):

Both configuration files are stored in the configuration folder for
  Android Studio. The name of the folder depends on your Studio version.
  For example, Android Studio 3.3 has the folder name AndroidStudio3.3.
  The location of this folder depends on your operating system:

Windows: %USERPROFILE%\.CONFIGURATION_FOLDER
macOS: ~/Library/Preferences/CONFIGURATION_FOLDER
Linux: ~/.CONFIGURATION_FOLDER


问:
How test a React Loadable component
I have this component:

```<code>import React from 'react';

const UploadAsync = Loadable({
  loader: () => import('components/Upload'),
  loading: () => <LoadingComponent full />
});

const Component = () => {
  return <UploadAsync />
}

export default Component
</code>```

And the test:

```<code>import React from 'react';
import Component from './index';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});
</code>```

How I can see the Upload component and not the Loading component in the snapshot?

```<code>exports[`Content should render correctly with form component 1`] = `
  <div>
    <Loading
      full={true}
    />
  </div>
`;
</code>```

So far I have tried setTimeOut and Promises.

答:
Here is how you test the loaded component:</p>

```<code>import {LoadableFoo} from './loadable-foo';
import {Foo} from './Foo';

it('should load the Foo component', async () => {
  // usual shallow render
  const component = shallow(<LoadableFoo/>);

  // prerender the Loadable component
  const loadedComponent = await component.preload();

  expect(loadedComponent.Foo).toEqual(Foo);
});
</code>```

Title: How test a React Loadable component

Body:
I have this component:

import React from 'react';

const UploadAsync = Loadable({
  loader: () => import('components/Upload'),
  loading: () => <LoadingComponent full />
});

const Component = () => {
  return <UploadAsync />
}

export default Component

And the test:

import React from 'react';
import Component from './index';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});

How I can see the Upload component and not the Loading component in the snapshot?

exports[`Content should render correctly with form component 1`] = `

    <Loading
      full={true}
    />

`;

So far I have tried setTimeOut and Promises.

Body:
Here is how you test the loaded component:

import {LoadableFoo} from './loadable-foo';
import {Foo} from './Foo';

it('should load the Foo component', async () => {
  // usual shallow render
  const component = shallow(<LoadableFoo/>);

  // prerender the Loadable component
  const loadedComponent = await component.preload();

  expect(loadedComponent.Foo).toEqual(Foo);
});


问:
Is there another way to set cookies than through HTTP headers?
I'm writing some http client code to interact with a website, and I need to set some cookies. Simply visiting the website sets 4 cookies (as seen in Chrome Settings).

However, when I look at the HTTP response headers for when those cookies were set (using Live HTTP Headers extension), there is no Set-Cookie header anywhere. How were those cookies set? Is there another way than through Set-Cookie?

Edit: Some of the cookies are HttpOnly.

答:
If you load a site in your browser, it might also load other assets that can also set cookies (given that they are on the same domain).

But there is a second way to set cookies: with Javascript via document.cookies.


问:
How do I get the average of each similar column value?
Say I have this:

```<code>     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2
</code>```

How can I have a query get the average of each value with respect to the tags?

So like:

```<code>    tag      value

1   apple    3.5

2   banana   3.5
</code>```

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.

答:
I agree with all of the above replies. I am adding dense rank function. you can try it just for your understanding.
Query:

SELECT tag,
  value,
  avg(value) over (partition by tag) tot_avgerage,
  DENSE_RANK()
  OVER (PARTITION BY tag order by value asc) AS drank
  FROM
  TABLE  ;

Body:
Say I have this:

     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2

How can I have a query get the average of each value with respect to the tags?

So like:

    tag      value

1   apple    3.5

2   banana   3.5

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.


问:
useState changing even without setting the value
I am totally confused about this scenario , I am having a state variable called listItems setting the value for listItems using the api call inside useEffect now in the handleChange I am changing the particular object value inside the listItems but I didn't change the actual listItems value but if i console the listItems it's showing as updated value even without setList how come it happens?

```<code>import React, { useState, useEffect } from 'react';
import axios from 'axios';
import OrderSummary from './orderSummary'

export default function displayItems() {
  const [listItems, setList] = useState([]);
  const [order, setorder] = useState([]);
  var newarr = [];

  useEffect(() => {
    axios.post('http://localhost:3006/listItem', {

    })
      .then(function (resp) {
        let res = resp.data.sendList.response;
        let newRes = res.map((item) => {
          return item;
        })
        setList(newRes);
      })
      .catch(function (error) {
        console.log(error);
      });

  }, [])

  function handleChange(type,item) {
    var arrList=item;
    var newAr=[];
    if (type === 1) {
      arrList.quantity=arrList.quantity+1;
    }
    else if (type === 0 && item.quantity > 1) {
      arrList.quantity=arrList.quantity-1;
    }
    newAr.push(arrList);
    console.log("test",listItems) // value changes here dont know how
    //  setList(listItems);
  }

  function placeOrder(item) {
    newarr.push(...order, item);
    setorder(newarr)
  }

  return (
    <div className="col">
      <div className="row">
        <div classname="col-md-6">
        <p><b>Available Items</b> </p>
          {listItems && listItems.map((item) => {
            return (
              <div key={item._id}>
                <p>Name:{item.name}</p>
                <p>Description:{item.description}</p>
                <p>Cost:{'₹'}{' '}{item.cost}</p>
                <p>Quantity:{' '}
                  <i onClick={() => handleChange(1,item)} className="fa fa-plus-circle" />
                  <span className="text-center"><b>{item.quantity}</b></span><i onClick={() => handleChange(0,item)} className="fa fa-minus-circle" /></p>
                <div>
                  <button onClick={() => placeOrder(item)}>Add to order</button>
                </div>
              </div>)
          })}
        </div>
        {order && <OrderSummary orderItems={order} />}
      </div>
    </div>
  )
}
</code>```

sandox

答:
The following code var arrList=item; is an assignment by reference, it means that arrList and item are both references to the same object which explains the modification of the second when modifying the first, if you want to clone an object you can use Object.assign() or the Spread operator or another solution:

```<code>var arrList = Object.assign({}, item);
// Or
var arrList = {...item};
</code>```

Working demo:

Body:
I am totally confused about this scenario , I am having a state variable called listItems setting the value for listItems using the api call inside useEffect now in the handleChange I am changing the particular object value inside the listItems but I didn't change the actual listItems value but if i console the listItems it's showing as updated value even without setList how come it happens?

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import OrderSummary from './orderSummary'

export default function displayItems() {
  const [listItems, setList] = useState([]);
  const [order, setorder] = useState([]);
  var newarr = [];

  useEffect(() => {
    axios.post('http://localhost:3006/listItem', {

    })
      .then(function (resp) {
        let res = resp.data.sendList.response;
        let newRes = res.map((item) => {
          return item;
        })
        setList(newRes);
      })
      .catch(function (error) {
        console.log(error);
      });

  }, [])

  function handleChange(type,item) {
    var arrList=item;
    var newAr=[];
    if (type === 1) {
      arrList.quantity=arrList.quantity+1;
    }
    else if (type === 0 && item.quantity > 1) {
      arrList.quantity=arrList.quantity-1;
    }
    newAr.push(arrList);
    console.log("test",listItems) // value changes here dont know how
    //  setList(listItems);
  }

  function placeOrder(item) {
    newarr.push(...order, item);
    setorder(newarr)
  }

  return (

Available Items

          {listItems && listItems.map((item) => {
            return (

Name:{item.name}

Description:{item.description}

Cost:{'₹'}{' '}{item.cost}

Quantity:{' '}
                   handleChange(1,item)} className="fa fa-plus-circle" />
                  {item.quantity} handleChange(0,item)} className="fa fa-minus-circle" />

                  <button onClick={() => placeOrder(item)}>Add to order</button>

)
          })}

        {order && <OrderSummary orderItems={order} />}

  )
}

sandox

Body:
The following code var arrList=item; is an assignment by reference, it means that arrList and item are both references to the same object which explains the modification of the second when modifying the first, if you want to clone an object you can use Object.assign() or the Spread operator or another solution:

var arrList = Object.assign({}, item);
// Or
var arrList = {...item};

Working demo:


问:
How can I delete the line below in Font Awesome icon?
I placed an icon cart from Font Awesome in my Navigation Bar. The problem is that this line appears to the left below in the cart icon when I go over with my mouse. I tried a lot of things but I could not find a way to remove this line:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="main.css">

        <title>Σκοτεινή Πλευρά</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

                        2

```

<pre class="lang-css prettyprint-override"><code>.Basket {
    display: inline-block;
    text-align: center;
    margin-right: 11px;
    margin-bottom: -6px;
}

.Basket a {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    margin-top: 100px;
    font-size: 30px;
    width: 40px;
    height: 40px;
    color: #332f25;
    transition: color 0.3s ease;
    text-decoration: none;
}

.Basket_Number {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: -15px;
    left: 35px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fe4c50;
    font-size: 12px;
    color: white;
}
</code>```

答:
Just add this css in to alter the hover state:</p>

```<code>.Basket :hover {
  text-decoration: none;
}
</code>```

Body:
I placed an icon cart from Font Awesome in my Navigation Bar. The problem is that this line appears to the left below in the cart icon when I go over with my mouse. I tried a lot of things but I could not find a way to remove this line:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="main.css">

        <title>Σκοτεινή Πλευρά</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

                        2

.Basket {
    display: inline-block;
    text-align: center;
    margin-right: 11px;
    margin-bottom: -6px;
}

.Basket a {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    margin-top: 100px;
    font-size: 30px;
    width: 40px;
    height: 40px;
    color: #332f25;
    transition: color 0.3s ease;
    text-decoration: none;
}

.Basket_Number {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: -15px;
    left: 35px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fe4c50;
    font-size: 12px;
    color: white;
}

Body:
Just add this css in to alter the hover state:

.Basket :hover {
  text-decoration: none;
}


问:
tcl string map exact values
I have a converted hex string which I'm wanting to replace.

```<code>Hello %user and %user2
</code>```

I am wanting to replace %user and %user2 with the populated variable result in this case, Willma and Fred.

Where I use the tags %user and %user2 which both represent the same hexadecimal values they both get replaced with "Willma" How can I do an exact replace on a set of hexadecimal characters?

The code I am using:

```<code>set example "48656c6c6f20257573657220616e6420257573657232" ;# Hello %user and %user2 converted to hex
set modify [list "2575736572" "Willma"] ;#replace the tagSymbol as defined from the single entry %user1 | %user2
set hexData [string map $modify $example] ;#preform the swap
</code>```

%user is 2575736572 in hex.
32 being the hex value for number 2. The next hex string becomes 257573657232

However when I preform the string map, it swaps %user2 leaving 32 as per design. However this isn't what I want. Below is what I am looking for.

The final output:

```<code>48656c6c6f20Willma20616e6420Willma32
</code>```

when I would like it to be

```<code>48656c6c6f20Willma20616e6420257573657232
</code>```

How would I do a exact swap?
thanks

答:
The order of substitutions in the map of string map matters. In particular, at each character position it does the first transform in the map, and then doesn't apply any further transforms at that point. This means that %user2 gets masked by %user unless it goes first. (In general, if you want to figure out an automatic order, just sort all the from-values by length, longest first. Tcl doesn't do this for you. In most cases where string map is used, either the masking effect is irrelevant or sorting at the source code level is viable.)

```<code>set example "48656c6c6f20257573657220616e6420257573657232"
set modify {}
lappend modify [binary encode hex "%user2"] "Fred"
lappend modify [binary encode hex "%user"] "Willma"
set hexData [string map $modify $example]
# ==> 48656c6c6f20Willma20616e6420Fred
</code>```

Note that I used binary encode hex there. That's a feature of Tcl 8.6; if you're using an older Tcl, you need this little helper procedure instead:

```<code>proc HexOf {str} {
    binary scan $str H* hexdigits
    return $hexdigits
}
</code>```

Title: tcl string map exact values

Body:
I have a converted hex string which I'm wanting to replace.

Hello %user and %user2

I am wanting to replace %user and %user2 with the populated variable result in this case, Willma and Fred.

Where I use the tags %user and %user2 which both represent the same hexadecimal values they both get replaced with "Willma" How can I do an exact replace on a set of hexadecimal characters?

The code I am using:

set example "48656c6c6f20257573657220616e6420257573657232" ;# Hello %user and %user2 converted to hex
set modify [list "2575736572" "Willma"] ;#replace the tagSymbol as defined from the single entry %user1 | %user2
set hexData [string map $modify $example] ;#preform the swap

%user is 2575736572 in hex.
32 being the hex value for number 2. The next hex string becomes 257573657232

However when I preform the string map, it swaps %user2 leaving 32 as per design. However this isn't what I want. Below is what I am looking for.

The final output:

48656c6c6f20Willma20616e6420Willma32

when I would like it to be

48656c6c6f20Willma20616e6420257573657232

How would I do a exact swap?
thanks

Body:
The order of substitutions in the map of string map matters. In particular, at each character position it does the first transform in the map, and then doesn't apply any further transforms at that point. This means that %user2 gets masked by %user unless it goes first. (In general, if you want to figure out an automatic order, just sort all the from-values by length, longest first. Tcl doesn't do this for you. In most cases where string map is used, either the masking effect is irrelevant or sorting at the source code level is viable.)

set example "48656c6c6f20257573657220616e6420257573657232"
set modify {}
lappend modify [binary encode hex "%user2"] "Fred"
lappend modify [binary encode hex "%user"] "Willma"
set hexData [string map $modify $example]
# ==> 48656c6c6f20Willma20616e6420Fred

Note that I used binary encode hex there. That's a feature of Tcl 8.6; if you're using an older Tcl, you need this little helper procedure instead:

proc HexOf {str} {
    binary scan $str H* hexdigits
    return $hexdigits
}


问:
Date Not display in proper Format
```<code><b>View Code</b><br><br>
 @Html.TextBoxFor(model => model.start_date, "{0:dd-MMM-yyyy}", new { onclick = "javascript:NewCssCal( this.Id,'ddMMMyyyy','arrow','','','','future')" })
</code>```

when return Model from the controller if start_date is null or empty it shows default date in textbox like "01-Jan-0001" . I just show Textbox field blank.what will i do.

i was try many solution from net but not get any proper solution

eg, changes in model

```<code>[DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dd-MMM-yyyy}",
        ApplyFormatInEditMode = true)]
</code>```

Expected Result

1. if model start_date is blank then it show blank textbox not to show default value like  "01-Jan-0001".

2. if model start_date field contain value then show that value for eg. 23-Mar-2019

答:
In the model you can make the property nullable by adding a '?' behind the type</p>

```<code>public Date? start_date { get; set; }
</code>```

Title: Date Not display in proper Format

Body:
View Code

 @Html.TextBoxFor(model => model.start_date, "{0:dd-MMM-yyyy}", new { onclick = "javascript:NewCssCal( this.Id,'ddMMMyyyy','arrow','','','','future')" })

when return Model from the controller if start_date is null or empty it shows default date in textbox like "01-Jan-0001" . I just show Textbox field blank.what will i do.

i was try many solution from net but not get any proper solution

eg, changes in model

[DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dd-MMM-yyyy}",
        ApplyFormatInEditMode = true)]

Expected Result

1. if model start_date is blank then it show blank textbox not to show default value like  "01-Jan-0001".

2. if model start_date field contain value then show that value for eg. 23-Mar-2019

Body:
In the model you can make the property nullable by adding a '?' behind the type

public Date? start_date { get; set; }


问:
c++11 list push_back() instanciation fault?
I am adding elements to a c++11 list via push_back(). Before adding an element I am printing out a debug message via cout. When I now remove the cout statement, the values in the element I append to the list with push_back are corrupted. I can test this with googletest.

Following you see the working code. When i comment out the cout statement the values in the last element of the sensor_scan_list get seemingly corrupted. The error lies in my opinion either in the instanciation of the list or in the code of the test. Only the state variable of the current_sensor.state seems corrupted (see below).

When I leave the cout statement in, everything works perfectly fine. It is such a weird issue, has someone a clue why this could happen?

code snippet:

```<code>void MessageHandler::processSensorHeader(TelemetryMessageInterface * p_Message)
{
    cout << "DEBUG: sensor header element added\n";
    addSensorHeader(p_Message);
    send_message(encoder->confirm(((SensorHeaderMessage *)p_Message)->getMessageId())); //ACK
}

void MessageHandler::addSensorHeader(TelemetryMessageInterface * p_message)
{
    Sensor new_sensor;

    new_sensor.manufacturerId = ((SensorHeaderMessage *)p_message)->getManufacturerId();
    new_sensor.deviceId = ((SensorHeaderMessage *)p_message)->getDeviceId();
    new_sensor.state |= SENSOR_HEADER_DETECTED;

    sensor_scan_list.push_back(new_sensor);
}
</code>```

Googletest code:

```<code>TEST(MessageHandlerTest, processSensorHeader)
{
TelemetryEncoder * encoder = new TelemetryEncoder();
TelemetryMessageInterface * p_Message;
MessageHandler message_handler;
Sensor current_sensor;

list <Sensor> :: iterator p_List;

p_Message = encoder->encodeSensorHeader(0x0101,0x0202,0x0303);
//add sensor
message_handler.processSensorHeader(p_Message);

p_List = message_handler.sensor_scan_list.begin();

current_sensor = *p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0203,0x0302,0x0403);
//add new sensor
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0403);
EXPECT_EQ(current_sensor.manufacturerId, 0x0302);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0102,0x0202,0x0303);
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);
}
</code>```

Sensor class:

```<code>class Sensor : public sensor_interface {
public:
Sensor();
virtual ~Sensor();

uint16_t manufacturerId;
uint16_t deviceId;

char name[SENSOR_INFORMATION_LENGTH];

uint8_t state;
};
</code>```

Googletest output for broken code (cout commented out):

```<code>[ RUN      ] MessageHandlerTest.processSensorHeader
../test/inc/test_messageHandler.cpp:77: Failure
  Expected: current_sensor.state
  Which is: '\xC1' (193)
To be equal to: 1
../test/inc/test_messageHandler.cpp:93: Failure
  Expected: current_sensor.state
  Which is: '\xF1' (241)
To be equal to: 1
[  FAILED  ] MessageHandlerTest.processSensorHeader (0 ms)
</code>```

答:
The issue of the state member variable having wrong values is probably due to the Sensor class not initializing state on construction.

Thus applying |= on an uninitialized variable will result in inconsistent or wrong results.

The fix of course is to ensure the members have a known initial value on construction, in this case, state should be 0 on initialization of Sensor.

Body:
I am adding elements to a c++11 list via push_back(). Before adding an element I am printing out a debug message via cout. When I now remove the cout statement, the values in the element I append to the list with push_back are corrupted. I can test this with googletest.

Following you see the working code. When i comment out the cout statement the values in the last element of the sensor_scan_list get seemingly corrupted. The error lies in my opinion either in the instanciation of the list or in the code of the test. Only the state variable of the current_sensor.state seems corrupted (see below).

When I leave the cout statement in, everything works perfectly fine. It is such a weird issue, has someone a clue why this could happen?

code snippet:

void MessageHandler::processSensorHeader(TelemetryMessageInterface * p_Message)
{
    cout << "DEBUG: sensor header element added\n";
    addSensorHeader(p_Message);
    send_message(encoder->confirm(((SensorHeaderMessage *)p_Message)->getMessageId())); //ACK
}

void MessageHandler::addSensorHeader(TelemetryMessageInterface * p_message)
{
    Sensor new_sensor;

    new_sensor.manufacturerId = ((SensorHeaderMessage *)p_message)->getManufacturerId();
    new_sensor.deviceId = ((SensorHeaderMessage *)p_message)->getDeviceId();
    new_sensor.state |= SENSOR_HEADER_DETECTED;

    sensor_scan_list.push_back(new_sensor);
}

Googletest code:

TEST(MessageHandlerTest, processSensorHeader)
{
TelemetryEncoder * encoder = new TelemetryEncoder();
TelemetryMessageInterface * p_Message;
MessageHandler message_handler;
Sensor current_sensor;

list <Sensor> :: iterator p_List;

p_Message = encoder->encodeSensorHeader(0x0101,0x0202,0x0303);
//add sensor
message_handler.processSensorHeader(p_Message);

p_List = message_handler.sensor_scan_list.begin();

current_sensor = *p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0203,0x0302,0x0403);
//add new sensor
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0403);
EXPECT_EQ(current_sensor.manufacturerId, 0x0302);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0102,0x0202,0x0303);
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);
}

Sensor class:

class Sensor : public sensor_interface {
public:
Sensor();
virtual ~Sensor();

uint16_t manufacturerId;
uint16_t deviceId;

char name[SENSOR_INFORMATION_LENGTH];

uint8_t state;
};

Googletest output for broken code (cout commented out):

[ RUN      ] MessageHandlerTest.processSensorHeader
../test/inc/test_messageHandler.cpp:77: Failure
  Expected: current_sensor.state
  Which is: '\xC1' (193)
To be equal to: 1
../test/inc/test_messageHandler.cpp:93: Failure
  Expected: current_sensor.state
  Which is: '\xF1' (241)
To be equal to: 1
[  FAILED  ] MessageHandlerTest.processSensorHeader (0 ms)


问:
Pig installation not working
I have installed Pig 0.12.0 on my box. I have also installed Java and Hadoop and have set JAVA_HOME and HADOOP_HOME paths. When Igo to the bin directory of pig installation and type the following command on my command prompt:

pig -help

it errors out with the following message:

```<code>The system cannot find the path specified.
'-Xmx1000M' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Whats wrong?
Should I be using cygwin? (that didnt work either)

答:
```<code>This will solve your problem...

1.Download PIG ->http://mirrors.estointernet.in/apache/pig/pig-0.16.0/
2.Set properties->
  PIG_HOME=C:\Users\lenovo\Downloads\pig-0.16.0\pig-0.16.0
  path=C:\Users\lenovo\Downloads\pig-0.16.0\pig-0.16.0\bin
  PIG_CLASSPATH=C:\Users\lenovo\Downloads\hadoop-2.7.3\hadoop-2.7.3\etc\hadoop(Where
                core-site.xml,mapred-site.xml are present)
3.
  ->open the file pig.cmd(From bin directory of PIG)
  ->look for the line set HADOOP_BIN_PATH=%HADOOP_HOME%\bin
  ->replace this with set HADOOP_BIN_PATH=%HADOOP_HOME%\libexec
4.Now in command prompt give->pig    `enter code here`
</code>```

Title: Pig installation not working

Body:
I have installed Pig 0.12.0 on my box. I have also installed Java and Hadoop and have set JAVA_HOME and HADOOP_HOME paths. When Igo to the bin directory of pig installation and type the following command on my command prompt:

pig -help

it errors out with the following message:

The system cannot find the path specified.
'-Xmx1000M' is not recognized as an internal or external command,
operable program or batch file.

Whats wrong?
Should I be using cygwin? (that didnt work either)


问:
LEFT Join does not pull record from main table if the JOINED value is null
Say I have a tableA that looks like this:

```<code> ID         Name         IssueID
 1          Bob          2
 2          John         Null
</code>```

I have my Reference table called tblRef that includes these columns:

```<code> IssueID       IssueDesc
 2             Not Completed
 3             Completed
</code>```

My query looks something like this,

```<code>Select a.Id,a.Name, I.IssueDesc from tableA a Left Join tblRef I on a.issueId =
I.IssueDesc where IssueID not in (2)
</code>```

If I do this, I do not see the record from tableA where the IssueID is NULL, is there any way to pull it up? Or rather why isn't it pulling up the record?

答:
NULL "fails" almost all comparisons.  What actually happens is that the result is NULL, and the rows get filtered out.

In SQL Server, you need to test for this explicitly:

```<code>where IssueID not in (2) OR IssueID is null
</code>```

Remember that the semantics of NULL generally have it meaning "unknown" value rather than "missing" value.  When you have NULL not in (2), the semantics are " not in (2)".  The result is "unknown", because the value could be 2.

Body:
Say I have a tableA that looks like this:

 ID         Name         IssueID
 1          Bob          2
 2          John         Null

I have my Reference table called tblRef that includes these columns:

 IssueID       IssueDesc
 2             Not Completed
 3             Completed

My query looks something like this,

Select a.Id,a.Name, I.IssueDesc from tableA a Left Join tblRef I on a.issueId =
I.IssueDesc where IssueID not in (2)

If I do this, I do not see the record from tableA where the IssueID is NULL, is there any way to pull it up? Or rather why isn't it pulling up the record?

Body:
NULL "fails" almost all comparisons.  What actually happens is that the result is NULL, and the rows get filtered out.

In SQL Server, you need to test for this explicitly:

where IssueID not in (2) OR IssueID is null

Remember that the semantics of NULL generally have it meaning "unknown" value rather than "missing" value.  When you have NULL not in (2), the semantics are " not in (2)".  The result is "unknown", because the value could be 2.


问:
pyautogui.press() causing lag when called
I have been working on a project where I need to call pyautogui.press('space'), however, when this is called, there is a noticable amount of lag. I need to try and keep the code running fairly fast because OpenCV is being used. If anyone knows how I can try to stop the code from slowing down when pyautogui.press('space') is called, that would be amazing. You can also see the lag in this video whenever the dinosaur jumps: https://www.youtube.com/watch?v=vceDabnT3OE.

Here is the code:

```<code>import numpy as np
import cv2
import pyautogui
import time
from PIL import ImageGrab

# Defining Template Images
gameOver = cv2.imread('GameOver.png')
dino = cv2.imread('Dino.png')
smallCactus = cv2.imread('SmallCactus.png')
bigCactus = cv2.imread('BigCactus.png')
ptero = cv2.imread('Ptero.png')

# Assigning Sample Image Dimensions
h, w = dino.shape[:-1]
sch, scw = smallCactus.shape[:-1]
bch, bcw = bigCactus.shape[:-1]
ph, pw = ptero.shape[:-1]

# Time Variables
lastTime = time.time()
runningTime = 0

# Key Variables
keyDown = False

pyautogui.keyDown('space')

while True:
    # Capturing Screen
    # 'bbox' Is Rectangle Around The Game
    screen = np.array(ImageGrab.grab(bbox=(150,125,800,300)))

    # Time stuff
    #print('Loop took {} seconds'.format(time.time() - lastTime))
    runningTime += time.time() - lastTime
    lastTime = time.time()

    # Checking If Game Over
    gameOverRes = cv2.matchTemplate(screen, gameOver, cv2.TM_CCOEFF_NORMED)
    minValG, maxValG, minLocG, maxLocG = cv2.minMaxLoc(gameOverRes)

    if maxValG >= 0.9 and runningTime > 4:
        print('Game Ended In ', int(round(runningTime)), ' Seconds')
        pyautogui.press('space')
        runningTime = 0

    # Finding Dinosaur
    dinoRes = cv2.matchTemplate(screen, dino, cv2.TM_CCOEFF_NORMED)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(dinoRes)

    # Finding Small Cacti
    smallCactusRes = cv2.matchTemplate(screen, smallCactus, cv2.TM_CCOEFF_NORMED)
    smallCactusThreshhold = 0.725
    smallCactusLoc = np.where(smallCactusRes >= smallCactusThreshhold)

    # Finding Big Cacti
    bigCactusRes = cv2.matchTemplate(screen, bigCactus, cv2.TM_CCOEFF_NORMED)
    bigCactusThreshhold = 0.725
    bigCactusLoc = np.where(bigCactusRes >= bigCactusThreshhold)

    # Finding Pterodactyls
    pteroRes = cv2.matchTemplate(screen, ptero, cv2.TM_CCOEFF_NORMED)
    minValP, maxValP, minLocP, maxLocP = cv2.minMaxLoc(pteroRes)

    # Drawing Box Around Dinosaur
    cv2.rectangle(screen, maxLoc, (maxLoc[0] + w, maxLoc[1] + h), (0, 255, 0), 2)

    # Avoiding Closest Small Cactus
    if smallCactusLoc[0].size > 0:
        leftmostXS = min(smallCactusLoc[1])
        leftmostYS = min(smallCactusLoc[0])

        distS = (leftmostXS - maxLoc[0])

        if (distS < 175 and distS > 0):
            pyautogui.press('space')

        cv2.rectangle(screen, (leftmostXS, leftmostYS), (leftmostXS+scw, leftmostYS+sch), (255, 160, 0), 2)

    # Avoiding Closest Big Cactus
    if bigCactusLoc[0].size > 0:
        leftmostXB = min(bigCactusLoc[1])
        leftmostYB = min(bigCactusLoc[0])

        distB = (leftmostXB - maxLoc[0])

        if distB < 175 and distB > 0:
            pyautogui.press('space')

        cv2.rectangle(screen, (leftmostXB, leftmostYB), (leftmostXB+bcw, leftmostYB+bch), (255, 0, 0), 2)

    # Avoiding Pterodactyls
    # Check 'maxValP' Because Otherwise Dino Gets Mistaken As Pterodactyl
    # 'keyDown' Is Needed For Down Arrow, Otherwise It Doesn't Work Properly
    if maxValP >= 0.60:

        distP = maxLocP[0] - maxLoc[0]
        heightP = maxLoc[1] - maxLocP[1]

        if distP < 190 and distP > 0:
            if heightP > 10:
                keyDown = True
                pyautogui.keyDown('down')
            else:
                pyautogui.press('space')

        cv2.rectangle(screen, maxLocP, (maxLocP[0] + pw, maxLocP[1] + ph), (0, 0, 255), 2)

    # elif keyDown == True:
        # pyautogui.keyUp('down')
        # keyDown = False

    # Showing Image
    cv2.imshow('Dino Game', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))

    # Quit
    if cv2.waitKey(1) & 0xFF == 27:
        cv2.destroyAllWindows()
        break
</code>```

答:
I think there is some glitch in functions like click or typewrite. I discovered that if you use them in cycle you can get empty mouse clicks or misswrites, e.g. if you want to write 1001, you can get only 101. At the moment testing raw functions like mouseDown and mouseUp and it seems they tend to work better.
Hope that helps someone.</p>

Body:
I have been working on a project where I need to call pyautogui.press('space'), however, when this is called, there is a noticable amount of lag. I need to try and keep the code running fairly fast because OpenCV is being used. If anyone knows how I can try to stop the code from slowing down when pyautogui.press('space') is called, that would be amazing. You can also see the lag in this video whenever the dinosaur jumps: https://www.youtube.com/watch?v=vceDabnT3OE.

Here is the code:

import numpy as np
import cv2
import pyautogui
import time
from PIL import ImageGrab

# Defining Template Images
gameOver = cv2.imread('GameOver.png')
dino = cv2.imread('Dino.png')
smallCactus = cv2.imread('SmallCactus.png')
bigCactus = cv2.imread('BigCactus.png')
ptero = cv2.imread('Ptero.png')

# Assigning Sample Image Dimensions
h, w = dino.shape[:-1]
sch, scw = smallCactus.shape[:-1]
bch, bcw = bigCactus.shape[:-1]
ph, pw = ptero.shape[:-1]

# Time Variables
lastTime = time.time()
runningTime = 0

# Key Variables
keyDown = False

pyautogui.keyDown('space')

while True:
    # Capturing Screen
    # 'bbox' Is Rectangle Around The Game
    screen = np.array(ImageGrab.grab(bbox=(150,125,800,300)))

    # Time stuff
    #print('Loop took {} seconds'.format(time.time() - lastTime))
    runningTime += time.time() - lastTime
    lastTime = time.time()

    # Checking If Game Over
    gameOverRes = cv2.matchTemplate(screen, gameOver, cv2.TM_CCOEFF_NORMED)
    minValG, maxValG, minLocG, maxLocG = cv2.minMaxLoc(gameOverRes)

    if maxValG >= 0.9 and runningTime > 4:
        print('Game Ended In ', int(round(runningTime)), ' Seconds')
        pyautogui.press('space')
        runningTime = 0

    # Finding Dinosaur
    dinoRes = cv2.matchTemplate(screen, dino, cv2.TM_CCOEFF_NORMED)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(dinoRes)

    # Finding Small Cacti
    smallCactusRes = cv2.matchTemplate(screen, smallCactus, cv2.TM_CCOEFF_NORMED)
    smallCactusThreshhold = 0.725
    smallCactusLoc = np.where(smallCactusRes >= smallCactusThreshhold)

    # Finding Big Cacti
    bigCactusRes = cv2.matchTemplate(screen, bigCactus, cv2.TM_CCOEFF_NORMED)
    bigCactusThreshhold = 0.725
    bigCactusLoc = np.where(bigCactusRes >= bigCactusThreshhold)

    # Finding Pterodactyls
    pteroRes = cv2.matchTemplate(screen, ptero, cv2.TM_CCOEFF_NORMED)
    minValP, maxValP, minLocP, maxLocP = cv2.minMaxLoc(pteroRes)

    # Drawing Box Around Dinosaur
    cv2.rectangle(screen, maxLoc, (maxLoc[0] + w, maxLoc[1] + h), (0, 255, 0), 2)

    # Avoiding Closest Small Cactus
    if smallCactusLoc[0].size > 0:
        leftmostXS = min(smallCactusLoc[1])
        leftmostYS = min(smallCactusLoc[0])

        distS = (leftmostXS - maxLoc[0])

        if (distS < 175 and distS > 0):
            pyautogui.press('space')

        cv2.rectangle(screen, (leftmostXS, leftmostYS), (leftmostXS+scw, leftmostYS+sch), (255, 160, 0), 2)

    # Avoiding Closest Big Cactus
    if bigCactusLoc[0].size > 0:
        leftmostXB = min(bigCactusLoc[1])
        leftmostYB = min(bigCactusLoc[0])

        distB = (leftmostXB - maxLoc[0])

        if distB < 175 and distB > 0:
            pyautogui.press('space')

        cv2.rectangle(screen, (leftmostXB, leftmostYB), (leftmostXB+bcw, leftmostYB+bch), (255, 0, 0), 2)

    # Avoiding Pterodactyls
    # Check 'maxValP' Because Otherwise Dino Gets Mistaken As Pterodactyl
    # 'keyDown' Is Needed For Down Arrow, Otherwise It Doesn't Work Properly
    if maxValP >= 0.60:

        distP = maxLocP[0] - maxLoc[0]
        heightP = maxLoc[1] - maxLocP[1]

        if distP < 190 and distP > 0:
            if heightP > 10:
                keyDown = True
                pyautogui.keyDown('down')
            else:
                pyautogui.press('space')

        cv2.rectangle(screen, maxLocP, (maxLocP[0] + pw, maxLocP[1] + ph), (0, 0, 255), 2)

    # elif keyDown == True:
        # pyautogui.keyUp('down')
        # keyDown = False

    # Showing Image
    cv2.imshow('Dino Game', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))

    # Quit
    if cv2.waitKey(1) & 0xFF == 27:
        cv2.destroyAllWindows()
        break


答:
Here is one way using scala reflection API withing a UDF function. The udf handles both cases for int and string values:

import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

val tb = currentMirror.mkToolBox()

val df = Seq(("0","value==0"),
("1", "value==0"),
("6", """value>0 && value<10"""),
("7", """value>0 && value<10"""),
("0", """value>0 && value<10"""),
("A", """Set("A","B").contains(value.toString)"""),
("C", """Set("A","B").contains(value.toString)""")).toDF("value", "condition")

def isAllDigits(x: String) = x.forall(Character.isDigit)

val evalExpressionUDF = udf((value: String, expr: String) => {
  val result =  isAllDigits(value) match {
    case true => tb.eval(tb.parse(expr.replace("value", s"""${value.toInt}""")))
    case false => tb.eval(tb.parse(expr.replace("value", s""""${value}"""")))
  }

  result.asInstanceOf[Boolean]
})

df.withColumn("eval", evalExpressionUDF($"value", $"condition"))
  .where($"eval" === true)
  .show(false)
```

<p>Cases for <code>evalExpressionUDF</code>:</p>

<ul>
<li>int: replace expression with the actual int value then execute string code with <code>mkToolBox</code></li>
<li>string: enclose string value into <code>""</code> then replace expression with the double quoted string and execute the string code</li>
</ul>

<p>Output:</p>

```+-----+-------------------------------------+----+
|value|                           condition |eval|
+-----+-------------------------------------+----+
|0    |value==0                             |true|
|6    |value>0 && value<10                  |true|
|7    |value>0 && value<10                  |true|
|A    |Set("A","B").contains(value.toString)|true|
+-----+-------------------------------------+----+
```

PS: I know that the performance of the above solution may be bad since it invokes reflection although I am not aware of an alternative.

Title: Spark: Aggregation with dynamic filter on a dataframe in scala

Body:
I have a dataframe like

scala> testDf.show()
+------+--------+---------+------------+----------------------------------------+
|    id|    item|    value|  value_name|                               condition|
+------+--------+---------+------------+----------------------------------------+
|    11|    3210|        0|         OFF|                                value==0|
|    12|    3210|        1|         OFF|                                value==0|
|    13|    3210|        0|         OFF|                                value==0|
|    14|    3210|        0|         OFF|                                value==0|
|    15|    3210|        1|         OFF|                                value==0|
|    16|    5440|        5|          ON|                     value>0 && value<10|
|    17|    5440|        0|          ON|                     value>0 && value<10|
|    18|    5440|        6|          ON|                     value>0 && value<10|
|    19|    5440|        7|          ON|                     value>0 && value<10|
|    20|    5440|        0|          ON|                     value>0 && value<10|
|    21|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    22|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    23|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    24|    7780|        C|        TYPE|   Set("A","B").contains(value.toString)|
|    25|    7780|        C|        TYPE|   Set("A","B").contains(value.toString)|
+------+--------+---------+------------+----------------------------------------+

scala> testDf.printSchema
root
 |-- id: string (nullable = true)
 |-- item: string (nullable = true)
 |-- value: string (nullable = true)
 |-- value_name: string (nullable = true)
 |-- condition: string (nullable = true)

I want to remove some rows with 'condition' column.
But I am in trouble.

I tried with below test code.
But it does not seem to work properly.

import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.Row
import scala.collection.mutable

val encoder = RowEncoder(testDf.schema);

testDf.flatMap(row => {
  val result = new mutable.MutableList[Row];
  val setting_value = row.getAs[String]("setting_value").toInt
  val condition = row.getAs[String]("condition").toBoolean
  if (condition){
      result+=row;
  };
  result;
})(encoder).show();

And This is error.

19/05/30 02:04:31 ERROR TaskSetManager: Task 0 in stage 267.0 failed 4 times; aborting job
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 267.0 failed 4 times, most recent failure: Lost task 0.3 in stage 267.0 (TID 3763, .compute.internal, executor 1): java.lang.IllegalArgumentException: For input string: "setting_value==0"
        at scala.collection.immutable.StringLike$class.parseBoolean(StringLike.scala:291)
        at scala.collection.immutable.StringLike$class.toBoolean(StringLike.scala:261)
        at scala.collection.immutable.StringOps.toBoolean(StringOps.scala:29)
        at $anonfun$1.apply(<console>:40)
        at $anonfun$1.apply(<console>:37)
        at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:435)
        at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:441)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
        at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage3.processNext(Unknown Source)
        at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
        at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$11$$anon$1.hasNext(WholeStageCodegenExec.scala:619)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:255)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:247)
        at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
        at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
        at org.apache.spark.scheduler.Task.run(Task.scala:121)
        at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
        at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

I want to keep rows that match the value of the condition column.
This is the desired result.

+------+--------+---------+------------+----------------------------------------+
|    id|    item|    value|  value_name|                               condition|
+------+--------+---------+------------+----------------------------------------+
|    11|    3210|        0|         OFF|                                value==0|
|    13|    3210|        0|         OFF|                                value==0|
|    14|    3210|        0|         OFF|                                value==0|
|    16|    5440|        5|          ON|                     value>0 && value<10|
|    18|    5440|        6|          ON|                     value>0 && value<10|
|    19|    5440|        7|          ON|                     value>0 && value<10|
|    21|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    22|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    23|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
+------+--------+---------+------------+----------------------------------------+

Please help me if you have a good idea.
Thanks.

Body:
Here is one way using scala reflection API withing a UDF function. The udf handles both cases for int and string values:

import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

val tb = currentMirror.mkToolBox()

val df = Seq(("0","value==0"),
("1", "value==0"),
("6", """value>0 && value<10"""),
("7", """value>0 && value<10"""),
("0", """value>0 && value<10"""),
("A", """Set("A","B").contains(value.toString)"""),
("C", """Set("A","B").contains(value.toString)""")).toDF("value", "condition")

def isAllDigits(x: String) = x.forall(Character.isDigit)

val evalExpressionUDF = udf((value: String, expr: String) => {
  val result =  isAllDigits(value) match {
    case true => tb.eval(tb.parse(expr.replace("value", s"""${value.toInt}""")))
    case false => tb.eval(tb.parse(expr.replace("value", s""""${value}"""")))
  }

  result.asInstanceOf[Boolean]
})

df.withColumn("eval", evalExpressionUDF($"value", $"condition"))
  .where($"eval" === true)
  .show(false)

Cases for evalExpressionUDF:

int: replace expression with the actual int value then execute string code with mkToolBox

string: enclose string value into "" then replace expression with the double quoted string and execute the string code

Output:

+-----+-------------------------------------+----+
|value|                           condition |eval|
+-----+-------------------------------------+----+
|0    |value==0                             |true|
|6    |value>0 && value<10                  |true|
|7    |value>0 && value<10                  |true|
|A    |Set("A","B").contains(value.toString)|true|
+-----+-------------------------------------+----+

PS: I know that the performance of the above solution may be bad since it invokes reflection although I am not aware of an alternative.


问:
How to copy a nodelist?
I am trying to set up a search feature for a large table that has about 1000 rows. The problem with this is that the rendering eats up performance by a lot. This is because I am iterating through all the rows in the table and setting the style of the ones that do not contain the search query to 'none'.

For some reason, the browser renders all the elements again each time I make a change. I am getting the table data as a nodelist via document.quesrtySelectorAll('tbody tr'). My solution is to copy this to a new object, do the search and style changes on the new object, and then copy it back, causing the browser to only have to re-render the table once.

```<code>let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];

for (let ele of itemsArr) {
    . . .

    if (!lower_case_table_value.match(lower_case_search_value)) {
        ele.style.display = 'none';
    }
    else {
        ele.style.display = 'table-row';
    }
}

let list = document.querySelector('tbody');
for (let i = 0; i < items.length; i++) {
    list.appendChild(itemsArr[i]);
}
</code>```

No matter what I do, though, any changes I make on the new object also makes the changes to the old. I removed the second for loop and it behaves like nothing happened. It is like it is not a copy, but a pointer.

Does anybody know who to copy a nodelist to a new object and make sure they are separate and not pointers to one another?

答:
```<code>let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];
</code>```

here items is a nodeList
so itemsArray stores also a nodeList
now if you try to iterate over itemsArray
there is only one thing in there which is the nodeList you put in there
insted if you add spread items into itemsArray you'll be storing elements not the entire odeList

Title: How to copy a nodelist?

Body:
I am trying to set up a search feature for a large table that has about 1000 rows. The problem with this is that the rendering eats up performance by a lot. This is because I am iterating through all the rows in the table and setting the style of the ones that do not contain the search query to 'none'.

For some reason, the browser renders all the elements again each time I make a change. I am getting the table data as a nodelist via document.quesrtySelectorAll('tbody tr'). My solution is to copy this to a new object, do the search and style changes on the new object, and then copy it back, causing the browser to only have to re-render the table once.

let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];

for (let ele of itemsArr) {
    . . .

    if (!lower_case_table_value.match(lower_case_search_value)) {
        ele.style.display = 'none';
    }
    else {
        ele.style.display = 'table-row';
    }
}

let list = document.querySelector('tbody');
for (let i = 0; i < items.length; i++) {
    list.appendChild(itemsArr[i]);
}

No matter what I do, though, any changes I make on the new object also makes the changes to the old. I removed the second for loop and it behaves like nothing happened. It is like it is not a copy, but a pointer.

Does anybody know who to copy a nodelist to a new object and make sure they are separate and not pointers to one another?

Body:
let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];

here items is a nodeList
so itemsArray stores also a nodeList
now if you try to iterate over itemsArray
there is only one thing in there which is the nodeList you put in there
insted if you add spread items into itemsArray you'll be storing elements not the entire odeList


问:
Time series in R: How to set week period across two years?
I have time series with week period (7 days) across two years. I have 58 values. Start is: 2017-08-05, end: 2018-09-08. I need work with this time series in R - make predictions with SARIMA model etc. But I have problem with define period/frequency in R. When I use decompose function I get error: "time series has no or less than 2 periods". Arima function does not work properly. Detailed information are bellow. What way I can import my data for use in R with requested frequency please?

My data (short example):

File: sessions2.csv

```<code>date        count
11.11.2017  55053
18.11.2017  45256
25.11.2017  59091
2.12.2017   50030
9.12.2017   41769
16.12.2017  63042
23.12.2017  51838
30.12.2017  47652
6.1.2018    18731
13.1.2018   54470
20.1.2018   22514
27.1.2018   63818
3.2.2018    51605
10.2.2018   26312
17.2.2018   11111
</code>```

data1.csv contains only values. For example:

```<code>53053
45256
59091
50045
41769
65042
51838
</code>```

I tried in R:

```<code>sessions1 <- scan("data1.csv")
sessionsTS <- ts(sessions1, frequency=52, start=decimal_date(ymd("2017-11-11")))
</code>```

Output sessionsTS and errors:

```<code>> sessionsTS
Time Series:
Start = 2017.59178082192
End = 2018.68418328598
Frequency = 52
</code>```

What time format represent these numbers (Start, End) please? And what way I can use for convert to decimal date?

```<code>> sessionsComponents <- decompose(sessionsTS)
Error in decompose(sessionsTS) :
  time series has no or less than 2 periods

> arima(sessionsTS, order = c(0, 1, 0), seasonal = list(order = c(2, 0, 0), period = 52), xreg = NULL, include.mean = TRUE)
Error in optim(init[mask], armaCSS, method = optim.method, hessian = FALSE,  :
  initial value in 'vmmin' is not finite

> fit <- Arima(sessionsTS, order = c(0, 1, 0), seasonal = list(order = c(2, 0, 0), period = 52))
Error in optim(init[mask], armaCSS, method = optim.method, hessian = FALSE,  :
  initial value in 'vmmin' is not finite

> sarima(sessionsTS,1,1,0,2,0,0,52)
Error in sarima(sessionsTS, 1, 1, 0, 2, 0, 0, 52) :
  unused arguments (0, 0, 52)
</code>```

Next I tried:

```<code>dataSeries <- read.table("sessions2.csv", header=TRUE, sep = ";", row.names=1)
dataTS <- as.xts(dataSeries , frequency=52, start=decimal_date(ymd("2017-11-11")))

> sessionsComponents2 <- decompose(dataTS)
Error in decompose(dataTS) : time series has no or less than 2 periods

> model = Arima(dataTS, order=c(0,1,0), seasonal = c(2,0,0))
> model
Series: dataTS
ARIMA(0,1,0)
</code>```

In this case Arima is used without seasonality...

Many thanks for help.

答:
Your data is sampled weekly, so if the period also is one week you need to set frequency=1, but at that point there is no point in doing seasonal modeling. It makes sense to have a yearly period, as you have done by setting frequency=52, but then you don't have enough periods for doing any estimations, you'd need at least 104 observations (at least two periods, as the error message explains) for that.

So in short, you can't do what you want to do do unless you get more data.

A partial answer for your questions about ts() and the time format. If you do it like this:

```<code>tt <- read.table(text="
date        count
11.11.2017  55053
18.11.2017  45256
25.11.2017  59091
2.12.2017   50030
9.12.2017   41769
16.12.2017  63042
23.12.2017  51838
30.12.2017  47652
6.1.2018    18731
13.1.2018   54470
20.1.2018   22514
27.1.2018   63818
3.2.2018    51605
10.2.2018   26312
17.2.2018   11111", header=TRUE)

tt$date <- as.Date(tt$date, format="%d.%m.%Y")

ts(tt$count, frequency=52, start=c(2017, 45))
# Time Series:
# Start = c(2017, 45)
# End = c(2018, 7)
# Frequency = 52
#  [1] 55053 45256 59091 50030 41769 63042 51838 47652 18731
#      54470 22514 63818 51605 26312 11111
</code>```

The start is at the 45'th week of 2017, and the end is at the 7'th week of 2018.

You can find the weeknumbers using format(tt$date, "%W"). Look at ?strptime for more details and to see what %W means.

Body:
I have time series with week period (7 days) across two years. I have 58 values. Start is: 2017-08-05, end: 2018-09-08. I need work with this time series in R - make predictions with SARIMA model etc. But I have problem with define period/frequency in R. When I use decompose function I get error: "time series has no or less than 2 periods". Arima function does not work properly. Detailed information are bellow. What way I can import my data for use in R with requested frequency please?

My data (short example):

File: sessions2.csv

date        count
11.11.2017  55053
18.11.2017  45256
25.11.2017  59091
2.12.2017   50030
9.12.2017   41769
16.12.2017  63042
23.12.2017  51838
30.12.2017  47652
6.1.2018    18731
13.1.2018   54470
20.1.2018   22514
27.1.2018   63818
3.2.2018    51605
10.2.2018   26312
17.2.2018   11111

data1.csv contains only values. For example:

53053
45256
59091
50045
41769
65042
51838

I tried in R:

sessions1 <- scan("data1.csv")
sessionsTS <- ts(sessions1, frequency=52, start=decimal_date(ymd("2017-11-11")))

Output sessionsTS and errors:

> sessionsTS
Time Series:
Start = 2017.59178082192
End = 2018.68418328598
Frequency = 52

What time format represent these numbers (Start, End) please? And what way I can use for convert to decimal date?

> sessionsComponents <- decompose(sessionsTS)
Error in decompose(sessionsTS) :
  time series has no or less than 2 periods

> arima(sessionsTS, order = c(0, 1, 0), seasonal = list(order = c(2, 0, 0), period = 52), xreg = NULL, include.mean = TRUE)
Error in optim(init[mask], armaCSS, method = optim.method, hessian = FALSE,  :
  initial value in 'vmmin' is not finite

> fit <- Arima(sessionsTS, order = c(0, 1, 0), seasonal = list(order = c(2, 0, 0), period = 52))
Error in optim(init[mask], armaCSS, method = optim.method, hessian = FALSE,  :
  initial value in 'vmmin' is not finite

> sarima(sessionsTS,1,1,0,2,0,0,52)
Error in sarima(sessionsTS, 1, 1, 0, 2, 0, 0, 52) :
  unused arguments (0, 0, 52)

Next I tried:

dataSeries <- read.table("sessions2.csv", header=TRUE, sep = ";", row.names=1)
dataTS <- as.xts(dataSeries , frequency=52, start=decimal_date(ymd("2017-11-11")))

> sessionsComponents2 <- decompose(dataTS)
Error in decompose(dataTS) : time series has no or less than 2 periods

> model = Arima(dataTS, order=c(0,1,0), seasonal = c(2,0,0))
> model
Series: dataTS
ARIMA(0,1,0)

In this case Arima is used without seasonality...

Many thanks for help.

Body:
Your data is sampled weekly, so if the period also is one week you need to set frequency=1, but at that point there is no point in doing seasonal modeling. It makes sense to have a yearly period, as you have done by setting frequency=52, but then you don't have enough periods for doing any estimations, you'd need at least 104 observations (at least two periods, as the error message explains) for that.

So in short, you can't do what you want to do do unless you get more data.

A partial answer for your questions about ts() and the time format. If you do it like this:

tt <- read.table(text="
date        count
11.11.2017  55053
18.11.2017  45256
25.11.2017  59091
2.12.2017   50030
9.12.2017   41769
16.12.2017  63042
23.12.2017  51838
30.12.2017  47652
6.1.2018    18731
13.1.2018   54470
20.1.2018   22514
27.1.2018   63818
3.2.2018    51605
10.2.2018   26312
17.2.2018   11111", header=TRUE)

tt$date <- as.Date(tt$date, format="%d.%m.%Y")

ts(tt$count, frequency=52, start=c(2017, 45))
# Time Series:
# Start = c(2017, 45)
# End = c(2018, 7)
# Frequency = 52
#  [1] 55053 45256 59091 50030 41769 63042 51838 47652 18731
#      54470 22514 63818 51605 26312 11111

The start is at the 45'th week of 2017, and the end is at the 7'th week of 2018.

You can find the weeknumbers using format(tt$date, "%W"). Look at ?strptime for more details and to see what %W means.


问:
Unexpected call to method or property access in IE 7
For work, I need to get our site working in IE7.  Because, as we all know, the corporate world can't upgrade.

I am using IE8's IE7 emulation mode to test the site, and using IE8's wonderful debugger has been a nightmare.

My most recent problem is the following error:

```<code>Unexpected call to method or property access.  jquery.js, line 113 character 460
</code>```

I've put console.log commands on every line of my function, and figured out the line that's causing the error.

```<code>var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('Loading...');
</code>```

This line works fine in Firefox and Chrome.  Oh, and it works fine when entering it into IE8's JavaScript console.

Why would this line give Unexpected call to method or property access?  I think the call to the method or property was totally expected.

UPDATE: As per @Pointy's suggestion I broke that line into 3 lines.

```<code>var $loading = $('<span/>');
$loading.addClass('span-icon icon-ajax-loader');
$loading.html('Loading...');
</code>```

Now I'm getting the error on this call $loading.html('Loading...');.  Again, if I paste this code into IE8's developer tools and run it, it works fine.

答:
Thanks to @daniellmb and @yoavmatchulsky for helping me fix this issue.

There are actually 3 separate solutions.

Use .text() instead of .html().

```<code>var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').text('Loading...');
</code>```

Wrap the .html() in span tags.

```<code>var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('<span>Loading...</span>');
</code>```

Or replace $('') with $('').

```<code>var $loading = $('<span></span>').addClass('span-icon icon-ajax-loader').html('Loading...');
</code>```

Body:
For work, I need to get our site working in IE7.  Because, as we all know, the corporate world can't upgrade.

I am using IE8's IE7 emulation mode to test the site, and using IE8's wonderful debugger has been a nightmare.

My most recent problem is the following error:

Unexpected call to method or property access.  jquery.js, line 113 character 460

I've put console.log commands on every line of my function, and figured out the line that's causing the error.

var $loading = $('').addClass('span-icon icon-ajax-loader').html('Loading...');

This line works fine in Firefox and Chrome.  Oh, and it works fine when entering it into IE8's JavaScript console.

Why would this line give Unexpected call to method or property access?  I think the call to the method or property was totally expected.

UPDATE: As per @Pointy's suggestion I broke that line into 3 lines.

var $loading = $('');
$loading.addClass('span-icon icon-ajax-loader');
$loading.html('Loading...');

Now I'm getting the error on this call $loading.html('Loading...');.  Again, if I paste this code into IE8's developer tools and run it, it works fine.

Body:
Thanks to @daniellmb and @yoavmatchulsky for helping me fix this issue.

There are actually 3 separate solutions.

Use .text() instead of .html().

var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').text('Loading...');

Wrap the .html() in span tags.

var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('<span>Loading...</span>');

Or replace $('<span/>') with $('<span></span>').

var $loading = $('<span></span>').addClass('span-icon icon-ajax-loader').html('Loading...');


问:
I've to create a deepArray2String method that expects a 2D int array 'x' and returns its string representation
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

```<code>public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}
</code>```

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

答:
You have got wrong the places where you should put square brackets. To find out where you should put them, try to think of how many nested brackets you can have? Since the array is 2-dimensional, the answer is 2, so it is enough to surround the loops with the brackets.

Modify the code like this:

```<code>public static String deepArray2String(int[][] a1){
    StringBuffer result = new StringBuffer();
    result.append("[");
    for (int i = 0; i < a1.length; i++) {
        result.append("[");
        for (int j = 0; j < a1[i].length; j++) {
            result.append(a1[i][j]);
            if (j != a1[i].length - 1 ) {
                result.append(",");
            }
        }
        result.append("]");
        if(i != a1.length - 1) {
            result.append(",");
        }
    }
    result.append("]");
    return result.toString();
}
</code>```

Body:
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

Body:
You have got wrong the places where you should put square brackets. To find out where you should put them, try to think of how many nested brackets you can have? Since the array is 2-dimensional, the answer is 2, so it is enough to surround the loops with the brackets.

Modify the code like this:

public static String deepArray2String(int[][] a1){
    StringBuffer result = new StringBuffer();
    result.append("[");
    for (int i = 0; i < a1.length; i++) {
        result.append("[");
        for (int j = 0; j < a1[i].length; j++) {
            result.append(a1[i][j]);
            if (j != a1[i].length - 1 ) {
                result.append(",");
            }
        }
        result.append("]");
        if(i != a1.length - 1) {
            result.append(",");
        }
    }
    result.append("]");
    return result.toString();
}


问:
How to redirect old to new URLs in PrestaShop after modifying SEO patterns
I've changed the SEO Schema settings in the PrestaShop back office (e.g. added .html extension for Product URLs).

Now, the old URLs don't work anymore and they are not redirect to the new URLs (the ones with .html extension).

I'd like that whenever I change the settings for Products or Categories URLs, the previous URLs are redirected to the new ones (301 permanent redirects).

Any solutions?

答:
By default, PrestaShop does not generate redirect rules based on your changes to handle old URLs (that would be complex to manage, especially in case you make multiples changes in a row).

You will have to launch a one-time script to generate these permanent redirect rules (301).

Here's a example

The code below assumes that your old URLs were in this format: /category/product, adapt it if needed.

```<code><?php

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

$context = Context::getContext();

$products = Db::getInstance()->ExecuteS('
SELECT p.id_product, pl.link_rewrite prod_url, cl.link_rewrite cat_url
FROM '._DB_PREFIX_.'product p
LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default)
WHERE p.active = 1 AND cl.id_lang = 1 AND cl.id_shop = 1 AND pl.id_lang = 1 AND cl.id_shop = 1');

foreach ($products as $p)
{
    $new_url = $context->link->getProductLink(new Product((int)$p['id_product']));
    echo 'RewriteRule ^'.$p['cat_url'].'/'.$p['prod_url'].'$ '.$new_url.' [L,R=301]<br />';
}
</code>```

Place this script in your PrestaShop root folder and launch it. Then, copy and paste the result into your .htaccess file.

You can also check this related question:
PrestaShop - RedirectMatch old product urls (without ID) to new url

I hope this helps!

Body:
By default, PrestaShop does not generate redirect rules based on your changes to handle old URLs (that would be complex to manage, especially in case you make multiples changes in a row).

You will have to launch a one-time script to generate these permanent redirect rules (301).

Here's a example

The code below assumes that your old URLs were in this format: /category/product, adapt it if needed.

<?php

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

$context = Context::getContext();

$products = Db::getInstance()->ExecuteS('
SELECT p.id_product, pl.link_rewrite prod_url, cl.link_rewrite cat_url
FROM '._DB_PREFIX_.'product p
LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default)
WHERE p.active = 1 AND cl.id_lang = 1 AND cl.id_shop = 1 AND pl.id_lang = 1 AND cl.id_shop = 1');

foreach ($products as $p)
{
    $new_url = $context->link->getProductLink(new Product((int)$p['id_product']));
    echo 'RewriteRule ^'.$p['cat_url'].'/'.$p['prod_url'].'$ '.$new_url.' [L,R=301]<br />';
}

Place this script in your PrestaShop root folder and launch it. Then, copy and paste the result into your .htaccess file.

You can also check this related question:
PrestaShop - RedirectMatch old product urls (without ID) to new url

I hope this helps!


问:
How to render method from handle submit of a stateful component
I am trying to redirect a page on datepicker submit, the problem is I get Unexpected token expected ";"

I have tried suggestions from users and React Docs as well as Datepicker Docs This is where I am now coming from In JSX How to redirect on Handlesubmit from DataPicker? But when applied to my code I get the error

```<code>./src/components/Toolbar/SearchCard/Datepicker/Datepicker.jsx
  Line 42:  Parsing error: Unexpected token, expected ";"

  40 |   }
  41 |   state = {};
> 42 |   render() {
     |            ^
  43 |     return (
  44 |       <>
  45 |         <FormGroup>
</code>```

Here is the whole file

```<code>import React from "react";
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";

// reactstrap components
import {
  FormGroup,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col,
  Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit = event => {
    event.preventDefault();
    this.setState({wasSubmitted: true});
}

render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
        return //... your normal component
    }
}
  }
  state = {};
  render() {
    return (
      <>
        <FormGroup>
          <InputGroup className="input-group-alternative">
            <InputGroupAddon addonType="prepend">
              <InputGroupText
              >
                <i className="ni ni-calendar-grid-58" />
              </InputGroupText>
            </InputGroupAddon>
            <ReactDatetime
            value={this.state.value}
            onChange={this.handleChange}
            inputProps={{
              placeholder: "Date Picker Here"
            }}
            timeFormat={false}
            />
          </InputGroup>
        </FormGroup>
        <form onSubmit={this.handleSubmit}>
        <Btnsearch  type="submit" value={this.state.value}/>
        </form>
      </>
    );
  }
}

export default Datepicker;
</code>```

I expect the app to render the hanndleSubmit and redirect to a new page

答:
Your exception is because your parser / bundler cannot handle inline properties on the class.

You could try and set that up, however because you are defining state in the constructor, line 41 (state = {};) is not needed.

aka state is assigned to the class instance here

```<code>constructor(props) {
  super(props);
  this.state = {
    value: ""
  };
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}
</code>```

In addition to that, this looks like an issue with copy pasting code
You have two render methods in this class with unmatching curly brackets. as you can see here

```<code>render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
        return //... your normal component
    }
}
  }
  state = {};
  render() {
    return (
</code>```

This should work

```<code>import React from "react";
import { Redirect } from 'react-router-dom';
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";

// reactstrap components
import {
  FormGroup,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col,
  Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    // this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit = event => {
    event.preventDefault();
    this.setState({wasSubmitted: true});
}

render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
      return (
        <>
          <FormGroup>
            <InputGroup className="input-group-alternative">
              <InputGroupAddon addonType="prepend">
                <InputGroupText
                >
                  <i className="ni ni-calendar-grid-58" />
                </InputGroupText>
              </InputGroupAddon>
              <ReactDatetime
              value={this.state.value}
              onChange={this.handleChange}
              inputProps={{
                placeholder: "Date Picker Here"
              }}
              timeFormat={false}
              />
            </InputGroup>
          </FormGroup>
          <form onSubmit={this.handleSubmit}>
          <Btnsearch  type="submit" value={this.state.value}/>
          </form>
        </>
      );
    }
  }
}

export default Datepicker;
</code>```

Body:
I am trying to redirect a page on datepicker submit, the problem is I get Unexpected token expected ";"

I have tried suggestions from users and React Docs as well as Datepicker Docs This is where I am now coming from In JSX How to redirect on Handlesubmit from DataPicker? But when applied to my code I get the error

./src/components/Toolbar/SearchCard/Datepicker/Datepicker.jsx
  Line 42:  Parsing error: Unexpected token, expected ";"

  40 |   }
  41 |   state = {};
> 42 |   render() {
     |            ^
  43 |     return (
  44 |       <>
  45 |         <FormGroup>

Here is the whole file

import React from "react";
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";

// reactstrap components
import {
  FormGroup,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col,
  Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit = event => {
    event.preventDefault();
    this.setState({wasSubmitted: true});
}

render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
        return //... your normal component
    }
}
  }
  state = {};
  render() {
    return (
      <>
        <FormGroup>
          <InputGroup className="input-group-alternative">
            <InputGroupAddon addonType="prepend">
              <InputGroupText
              >

              </InputGroupText>
            </InputGroupAddon>
            <ReactDatetime
            value={this.state.value}
            onChange={this.handleChange}
            inputProps={{
              placeholder: "Date Picker Here"
            }}
            timeFormat={false}
            />
          </InputGroup>
        </FormGroup>
        <form onSubmit={this.handleSubmit}>
        <Btnsearch  type="submit" value={this.state.value}/>
        </form>
      </>
    );
  }
}

export default Datepicker;

I expect the app to render the hanndleSubmit and redirect to a new page

Body:
Your exception is because your parser / bundler cannot handle inline properties on the class.

You could try and set that up, however because you are defining state in the constructor, line 41 (state = {};) is not needed.

aka state is assigned to the class instance here

constructor(props) {
  super(props);
  this.state = {
    value: ""
  };
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}

In addition to that, this looks like an issue with copy pasting code
You have two render methods in this class with unmatching curly brackets. as you can see here

render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
        return //... your normal component
    }
}
  }
  state = {};
  render() {
    return (

This should work

import React from "react";
import { Redirect } from 'react-router-dom';
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";

// reactstrap components
import {
  FormGroup,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col,
  Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    // this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit = event => {
    event.preventDefault();
    this.setState({wasSubmitted: true});
}

render() {
    const { value, wasSubmitted } = this.state;

    if (wasSubmitted) {
        return <Redirect to='/Bookingpage' />
    } else {
      return (
        <>
          <FormGroup>
            <InputGroup className="input-group-alternative">
              <InputGroupAddon addonType="prepend">
                <InputGroupText
                >
                  <i className="ni ni-calendar-grid-58" />
                </InputGroupText>
              </InputGroupAddon>
              <ReactDatetime
              value={this.state.value}
              onChange={this.handleChange}
              inputProps={{
                placeholder: "Date Picker Here"
              }}
              timeFormat={false}
              />
            </InputGroup>
          </FormGroup>
          <form onSubmit={this.handleSubmit}>
          <Btnsearch  type="submit" value={this.state.value}/>
          </form>
        </>
      );
    }
  }
}

export default Datepicker;


问:
How to remove seasonality and trend from GDP time series data in R
I am doing a time series analysis to forecast the GDP for the next years and in order to get a good forecasting model I need to remove the trend and the seasonality.

I have used the seasonally adjusted data but it did not completely remove the trend and seasonality of the data. I am using the multiplicative method to remove trend and seasonality.

Seasonally adjusted GDP

```<code>decmopose_GDP <- decompose(GDP, 'multiplicative')
adjustGDP <- GDP/decmopose_GDP$seasonal
plot(adjustGDP)
</code>```

Does anyone know any other method to remove trend and seasonality from the time series ?

答:
You can try categorical variable of seasons and splines for time. For example, the model can be . In the model, X contains indicator variable of seasons and also splines for time (you can give them specific degree of freedom). Then the GDP with seasonality and time trend removed will be obtained, i.e., residuals of the model. The code can be as follows.

```<code>  ##Fitting a model with season and time variable
  model1 <- lm(gdp ~ cat_season + ns(time, df = n))
  ##Extract the GDP without time trend
  GDP_withouttrend <- resid(model1)
  ##Plot the GDP without trend
  plot(GDP_withouttrend)
</code>```

Body:
I am doing a time series analysis to forecast the GDP for the next years and in order to get a good forecasting model I need to remove the trend and the seasonality.

I have used the seasonally adjusted data but it did not completely remove the trend and seasonality of the data. I am using the multiplicative method to remove trend and seasonality.

Seasonally adjusted GDP

decmopose_GDP <- decompose(GDP, 'multiplicative')
adjustGDP <- GDP/decmopose_GDP$seasonal
plot(adjustGDP)

Does anyone know any other method to remove trend and seasonality from the time series ?

Body:
You can try categorical variable of seasons and splines for time. For example, the model can be . In the model, X contains indicator variable of seasons and also splines for time (you can give them specific degree of freedom). Then the GDP with seasonality and time trend removed will be obtained, i.e., residuals of the model. The code can be as follows.

  ##Fitting a model with season and time variable
  model1 <- lm(gdp ~ cat_season + ns(time, df = n))
  ##Extract the GDP without time trend
  GDP_withouttrend <- resid(model1)
  ##Plot the GDP without trend
  plot(GDP_withouttrend)


问:
Is there another way to set cookies than through HTTP headers?
I'm writing some http client code to interact with a website, and I need to set some cookies. Simply visiting the website sets 4 cookies (as seen in Chrome Settings).

However, when I look at the HTTP response headers for when those cookies were set (using Live HTTP Headers extension), there is no Set-Cookie header anywhere. How were those cookies set? Is there another way than through Set-Cookie?

Edit: Some of the cookies are HttpOnly.

答:
As far as I know, if your javascript or python code sets a cookie for that domain, then the response will include the SET-COOKIE field. You can view that from at least the inspect console.

So I see that you're using HTTP live extension, but it doesn't look like it shows that field in the response.

I tried looking for other extensions that could show it, but I wasn't able to find one as far as I know. I suppose we both can always fall back to the chrome inspect console. If you go to the network tab, you should actually see the req-resp.