问:
Incorrect integrity when fetching from the cache
When running yarn add --dev jest, I got error Incorrect integrity when fetching from the cache.

Full output:

tests (master)$ yarn add --dev jest
yarn add v1.19.0
info No lockfile found.
[1/4] Resolving packages...
warning jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > left-pad@1.3.0: use String.prototype.padStart()
[2/4] Fetching packages...
error Incorrect integrity when fetching from the cache
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
```

I tried removed node_modules, re-ran yarn install and yarn add --dev jest to no avail.

How do I fix this?

答:
Tried to upgrade yarn and it solved my problem. It may be due to the compatibility issue

```<code>yarn policies set-version
</code>```

Will download the latest stable release

Reference : yarn docs https://yarnpkg.com/lang/en/docs/cli/policies/#toc-policies-set-version

Body:
When running yarn add --dev jest, I got error Incorrect integrity when fetching from the cache.

Full output:

tests (master)$ yarn add --dev jest
yarn add v1.19.0
info No lockfile found.
[1/4] Resolving packages...
warning jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > left-pad@1.3.0: use String.prototype.padStart()
[2/4] Fetching packages...
error Incorrect integrity when fetching from the cache
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

I tried removed node_modules, re-ran yarn install and yarn add --dev jest to no avail.

How do I fix this?

Body:
Tried to upgrade yarn and it solved my problem. It may be due to the compatibility issue

yarn policies set-version

Will download the latest stable release

Reference : yarn docs https://yarnpkg.com/lang/en/docs/cli/policies/#toc-policies-set-version


来源: stackexchange

问:
Is it possible to indirectly index an array in structured text (IEC 61131-3 standard)
I have an array of a structure:  myStructure[0..100]

I would like to index that structure by name.

It works by giving each index a name:

```<code>P101_AI := 9
P102_AI := 10
P103_AI := 11
P104_AI := 12
</code>```

So indexing a member in the structure: myStructure[P103_AI].value  (i.e. indexing myStructure[11].value)

However, is it possible to index this indirectly?

i.e. if delcaring TempString : STRING[30];

altering TempString at runtime to index the array.

Here is some pseudocade to describe what I would like to do:

```<code>FOR i:=101 TO 104 DO
   TempString := CONCAT('P',i);
   TempString := CONCAT(TempString,'_AI');
   MyStructure[ indirect(TempString)].value := 'some value';
END_FOR;
</code>```

答:
This is how i solved it.</p>

```<code>TYPE infoType: STRUCT
    name: STRING[20];
    END_STRUCT
END_TYPE
</code>```

```<code>TYPE sensorType: STRUCT
    value: INT;
    info:  infoType;
    END_STRUCT
END_TYPE
</code>```

```<code>TYPE IO_Type: STRUCT
    AI: ARRAY[1..100] OF sensorType;
    END_STRUCT
END_TYPE
</code>```

```<code>TYPE E_AnalogInput :
(
    P101_AI := 9,
    P102_AI,
    P103_AI,
    P104_AI
);
END_TYPE
</code>```

```<code>PROGRAM PLC_PRG:
    VAR
        IOs: IO_Type;
    END_VAR

    IOs.AI[P101_AI].info.name := 'P101_AI';

    FOR i:=101 TO 104 DO
        TempString := CONCAT('P',i);
        TempString := CONCAT(TempString,'_AI');
        FOR i:=0 TO SIZE_OF(ADR(IOs.AI)) / SIZE_OF(ADR(IOs.AI[0]))  DO
            IF TempString = IOs.AI[i].info.name THEN
                IOs.AI[i].value := 123; // Some value
                EXIT;
            END_IF;
        END_FOR;
    END_FOR;

END_PROGRAM
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of a structure:  myStructure[0..100]

I would like to index that structure by name.

It works by giving each index a name:

P101_AI := 9
P102_AI := 10
P103_AI := 11
P104_AI := 12

So indexing a member in the structure: myStructure[P103_AI].value  (i.e. indexing myStructure[11].value)

However, is it possible to index this indirectly?

i.e. if delcaring TempString : STRING[30];

altering TempString at runtime to index the array.

Here is some pseudocade to describe what I would like to do:

FOR i:=101 TO 104 DO
   TempString := CONCAT('P',i);
   TempString := CONCAT(TempString,'_AI');
   MyStructure[ indirect(TempString)].value := 'some value';
END_FOR;

Body:
This is how i solved it.

TYPE infoType: STRUCT
    name: STRING[20];
    END_STRUCT
END_TYPE

TYPE sensorType: STRUCT
    value: INT;
    info:  infoType;
    END_STRUCT
END_TYPE

TYPE IO_Type: STRUCT
    AI: ARRAY[1..100] OF sensorType;
    END_STRUCT
END_TYPE

TYPE E_AnalogInput :
(
    P101_AI := 9,
    P102_AI,
    P103_AI,
    P104_AI
);
END_TYPE

PROGRAM PLC_PRG:
    VAR
        IOs: IO_Type;
    END_VAR

    IOs.AI[P101_AI].info.name := 'P101_AI';

    FOR i:=101 TO 104 DO
        TempString := CONCAT('P',i);
        TempString := CONCAT(TempString,'_AI');
        FOR i:=0 TO SIZE_OF(ADR(IOs.AI)) / SIZE_OF(ADR(IOs.AI[0]))  DO
            IF TempString = IOs.AI[i].info.name THEN
                IOs.AI[i].value := 123; // Some value
                EXIT;
            END_IF;
        END_FOR;
    END_FOR;

END_PROGRAM


问:
Replacing --cluster-config with --profile in snakemake
Recent version of Snakemake (v5.10.10) says cluster configuration has been deprecated and recommends to use profiles instead. However, I don't see any documentation on how to go about this.

How do I convert the following cluster config (example used in snakemake doc) into profiles?

```<code>{
    "__default__" :
    {
        "account" : "my account",
        "time" : "00:15:00",
        "n" : 1,
        "partition" : "core"
    },
    "compute1" :
    {
        "time" : "00:20:00"
    }
}

</code>```

答:
Using this link you should be able to find the right profile for you. I agree the documentation is not amazingly clear how to go about migrating.

https://github.com/snakemake-profiles/doc

Body:
Recent version of Snakemake (v5.10.10) says cluster configuration has been deprecated and recommends to use profiles instead. However, I don't see any documentation on how to go about this.

How do I convert the following cluster config (example used in snakemake doc) into profiles?

{
    "__default__" :
    {
        "account" : "my account",
        "time" : "00:15:00",
        "n" : 1,
        "partition" : "core"
    },
    "compute1" :
    {
        "time" : "00:20:00"
    }
}


问:
what is the import for CallableContext
I have simple google cloud function as follows

```<code>import * as functions from 'firebase-functions';
var util = require('util')

export const repeat = functions.https.onCall(
    function (data, context) {
        console.log(' repeat1 '+ util.inspect(data) + util.inspect(context) );
        return { fld1: 'xyz', fld2: 10};
    }
);
</code>```

I want to separate the function o I am trying as follows

```<code>import * as functions from 'firebase-functions';
var util = require('util')

export const repeat = functions.https.onCall(
    xyzFunction
);

function xyzFunction(data: any, context: CallableContext)
{
    console.log(' repeat1 '+ util.inspect(data) + util.inspect(context) );
        return { fld1: 'xyz', fld2: 10};
}
</code>```

but I get error ,I can solve it by using any, but https.d.ts declare it as CallableContext, so I want to keep same type. I am coming from java background. So what import should I use ?

TS2304: Cannot find name 'CallableContext'

答:
The CallableContext type is exported via functions.https:

```<code>function xyzFunction(data: any, context: functions.https.CallableContext) {
    ...
}
</code>```

Title: what is the import for CallableContext

Body:
I have simple google cloud function as follows

import * as functions from 'firebase-functions';
var util = require('util')

export const repeat = functions.https.onCall(
    function (data, context) {
        console.log(' repeat1 '+ util.inspect(data) + util.inspect(context) );
        return { fld1: 'xyz', fld2: 10};
    }
);

I want to separate the function o I am trying as follows

import * as functions from 'firebase-functions';
var util = require('util')

export const repeat = functions.https.onCall(
    xyzFunction
);

function xyzFunction(data: any, context: CallableContext)
{
    console.log(' repeat1 '+ util.inspect(data) + util.inspect(context) );
        return { fld1: 'xyz', fld2: 10};
}

but I get error ,I can solve it by using any, but https.d.ts declare it as CallableContext, so I want to keep same type. I am coming from java background. So what import should I use ?

TS2304: Cannot find name 'CallableContext'

Body:
The CallableContext type is exported via functions.https:

function xyzFunction(data: any, context: functions.https.CallableContext) {
    ...
}


问:
Why do you need div in the render function for ReactJS components?
I just started learning web dev and I'm a little confused by this one thing in ReactJS. In my App component's render function, if I return JSX without an overarching div:

```<code>render() {
  return (
    <h1 style={headerStyle}>Todo List</h1>
    <Todo todos={this.state.todos}/>
  );
 }
</code>```

I get an error:

```<code>./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |         <h1 style={headerStyle}>Todo List</h1>
> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }
</code>```

but once I add a div:

```<code>render() {
     return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );
  }
}
</code>```

everything works fine.

Why is the div necessary? Or if its not actually necessary, what else could I be doing wrong?

答:
Please use React Fragment to avoid additional element to render in the dom like div element.

```<code>class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <h2>Hello</h2>
        <p>How you doin'?</p>
      </React.Fragment>
    );
  }
}
</code>```

Body:
I just started learning web dev and I'm a little confused by this one thing in ReactJS. In my App component's render function, if I return JSX without an overarching div:

render() {
  return (

Todo List

    <Todo todos={this.state.todos}/>
  );
 }

I get an error:

./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |
Todo List

> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }

but once I add a div:

render() {
     return (

Todo List

          <Todo todos={this.state.todos}/>

     );
  }
}

everything works fine.

Why is the div necessary? Or if its not actually necessary, what else could I be doing wrong?

Body:
Please use React Fragment to avoid additional element to render in the dom like div element.

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <h2>Hello</h2>
        <p>How you doin'?</p>
      </React.Fragment>
    );
  }
}


问:
How to publish my WCF service to my website on remote server plesk panel
I prepared the wcf service application and it works on the localhost side, there is no problem here, but I cannot connect from my computer when I publish it at my address on the remote server via ftp method.
I transfer my wcf service to my destination address via FTP method and the index.html page works where I transfer, but when I write the .svc file it gives 404 not found error.
The company hosting the website where I will publish my wcf service provides shared hosting.
I couldn't find anything in the settings section on my plesk panel.
IIS settings of the remote server where my website is located cannot be changed.
I wonder if I need to make a setting in the config file of the wcf service, such as the address or endpoint, or I do not know.
I need your help on how I can run my wcf service that runs smoothly on my own computer but not working on my remote server website.</p>

答:
I don’t know the plesk. But if we host the WCF service in windows IIS web server, we need to enable certain Windows feature to process SVC extension.

Feel free to let me know if there is anything I can help with.


问:
new thread is created, but doesn't run (java)
here's a little code I wrote. This next class waits for a connection and creates a new thread upon receiving one:

```<code>    ServerSocket serverSocket = null;
    ExecutorService serv = Executors.newCachedThreadPool();
    serv.execute(new UserThread());
    try {
        serverSocket = new ServerSocket(FMDataManager.getPort());
        serverSocket.setSoTimeout(0);
        while (_listening){
            System.out.println("Listening on port "+FMDataManager.getPort());
            System.out.println("Waiting for connections.");
            serv.execute(new UploadThread(serverSocket.accept()));
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port: "+FMDataManager.getPort()+".");
        System.exit(-1);
    }
</code>```

as you can see i am using ServerSocket.accept() method to wait for a connection.
The thread is indeed created, but it won't run. I put a little "thread created" in its constructor and another message "starting thread" in run(), but I only got the  first message. After that it didn't do anything, I didn't even get "thread created".
Any ideas please?

I've add the implementation of the UploadThread I am trying to start, maybe It'll help

```<code>public class UploadThread extends Thread{

Socket _socket;

public UploadThread(Socket socket) {
    super("UserThread");
    _socket = socket;
}
public void run(Socket socket) {
    System.out.println("entred upload thread");
    DataOutputStream out = null;
    DataInputStream in = null;
    try {
        out = new DataOutputStream(_socket.getOutputStream());
        in = new DataInputStream(_socket.getInputStream());
        FileMessage inputMessage;
        SendFile outputMessage;
        inputMessage = (FileMessage) CommandEnum.readMessage(in);
        System.out.println("F: "+inputMessage.getCaption());
        File file = null;
        Iterator<File> itr = FMDataManager.getFiles().iterator();
        while (itr.hasNext()){
            File temp = itr.next();
            if (temp.getName().equals(inputMessage.getFile()))
                file = temp;
        }
        outputMessage = new SendFile(file);
        outputMessage.send(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            _socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}
</code>```

答:
Without seeing the part of the code that actually constructs the thread, I'll guess you're NOT calling the 'start()' method on the thread object.

Needs to be something like this:

```<code>Thread thr = new Thread(new Runnable() { void run() { /* do stuff */ }) ;

thr.start() // GO!
</code>```

ContentLicense: CC BY-SA 3.0

Body:
here's a little code I wrote. This next class waits for a connection and creates a new thread upon receiving one:

    ServerSocket serverSocket = null;
    ExecutorService serv = Executors.newCachedThreadPool();
    serv.execute(new UserThread());
    try {
        serverSocket = new ServerSocket(FMDataManager.getPort());
        serverSocket.setSoTimeout(0);
        while (_listening){
            System.out.println("Listening on port "+FMDataManager.getPort());
            System.out.println("Waiting for connections.");
            serv.execute(new UploadThread(serverSocket.accept()));
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port: "+FMDataManager.getPort()+".");
        System.exit(-1);
    }

as you can see i am using ServerSocket.accept() method to wait for a connection.
The thread is indeed created, but it won't run. I put a little "thread created" in its constructor and another message "starting thread" in run(), but I only got the  first message. After that it didn't do anything, I didn't even get "thread created".
Any ideas please?

I've add the implementation of the UploadThread I am trying to start, maybe It'll help

public class UploadThread extends Thread{

Socket _socket;

public UploadThread(Socket socket) {
    super("UserThread");
    _socket = socket;
}
public void run(Socket socket) {
    System.out.println("entred upload thread");
    DataOutputStream out = null;
    DataInputStream in = null;
    try {
        out = new DataOutputStream(_socket.getOutputStream());
        in = new DataInputStream(_socket.getInputStream());
        FileMessage inputMessage;
        SendFile outputMessage;
        inputMessage = (FileMessage) CommandEnum.readMessage(in);
        System.out.println("F: "+inputMessage.getCaption());
        File file = null;
        Iterator<File> itr = FMDataManager.getFiles().iterator();
        while (itr.hasNext()){
            File temp = itr.next();
            if (temp.getName().equals(inputMessage.getFile()))
                file = temp;
        }
        outputMessage = new SendFile(file);
        outputMessage.send(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            _socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

Body:
Without seeing the part of the code that actually constructs the thread, I'll guess you're NOT calling the 'start()' method on the thread object.

Needs to be something like this:

Thread thr = new Thread(new Runnable() { void run() { /* do stuff */ }) ;

thr.start() // GO!


问:
Visualize countplot like linegraph python
I have a data frame for customer transactions:

```<code>     customer_id|tier |transaction_type|year|no_of_purchases
       1353455  |1    |online          |2012|5
       1353455  |1    |retail          |2012|8
       1353455  |1    |retail          |2014|10
       1543798  |2    |retail          |2012|1
</code>```

The tier is their loyalty program tier. I want to see if there is difference in the transaction_type and no_of_purchases between each tier.

I did a countplot for this:

sns.countplot(x="transaction_type", y="no_of_purchase", hue"tier")

Goal: I want show for each year (x-axis) what is the count of the no_purchases for each transaction_type and how does this differ for each tier. Here is an example of how I want it to look. Ideally we would have 4 graphs, one for each of the transaction type. It would be great if we can show the count at each point too.

答:
You can use seaborn catplot.

First, you can aggregate your data, then do the vizualization using seaborn.

```<code>data_viz = df.groupby(['year','transaction_type','tier'], as_index=False)['no_of_purchases'].sum()

sns.catplot(data=data_viz, x='year', y='no_of_purchases', hue='tier', col='transaction_type', kind='bar')
</code>```

But unfortunately based on the documentation, you cannot plot the data using line plot.

There is a work around though, you can do something like this.

```<code>import matplotlib.pyplot as plt

data_viz = df.groupby(['year','transaction_type','tier'], as_index=False)['no_of_purchases'].sum()

for i in list(data_viz['transaction_type'].unique()):
    viz = sns.lineplot(data=data_viz[data_viz['transaction_type'] == i], x='year', y='no_of_purchases', hue='tier')
    plt.title(i)
    plt.show()
</code>```

Body:
I have a data frame for customer transactions:

     customer_id|tier |transaction_type|year|no_of_purchases
       1353455  |1    |online          |2012|5
       1353455  |1    |retail          |2012|8
       1353455  |1    |retail          |2014|10
       1543798  |2    |retail          |2012|1

The tier is their loyalty program tier. I want to see if there is difference in the transaction_type and no_of_purchases between each tier.

I did a countplot for this:

sns.countplot(x="transaction_type", y="no_of_purchase", hue"tier")

Goal: I want show for each year (x-axis) what is the count of the no_purchases for each transaction_type and how does this differ for each tier. Here is an example of how I want it to look. Ideally we would have 4 graphs, one for each of the transaction type. It would be great if we can show the count at each point too.

Body:
You can use seaborn catplot.

First, you can aggregate your data, then do the vizualization using seaborn.

data_viz = df.groupby(['year','transaction_type','tier'], as_index=False)['no_of_purchases'].sum()

sns.catplot(data=data_viz, x='year', y='no_of_purchases', hue='tier', col='transaction_type', kind='bar')

But unfortunately based on the documentation, you cannot plot the data using line plot.

There is a work around though, you can do something like this.

import matplotlib.pyplot as plt

data_viz = df.groupby(['year','transaction_type','tier'], as_index=False)['no_of_purchases'].sum()

for i in list(data_viz['transaction_type'].unique()):
    viz = sns.lineplot(data=data_viz[data_viz['transaction_type'] == i], x='year', y='no_of_purchases', hue='tier')
    plt.title(i)
    plt.show()


问:
Realloc returns invalid pointer when char array is passed into another function
I have a short snippet where I am passing a char array into another function and changing the size in memory.

```<code>// in main
char *str = argv[1];
find(&str);

void func(char **str){
  // some code
  *str = realloc(*str, 10+1);
}
</code>```

This gives the error

```<code>realloc(): invalid pointer
Aborted (core dumped)
</code>```

What did I do wrong here? In order to change the value of str in another function, I am using a double pointer.

答:
What did I do wrong here?

*str in realloc(*str, 10+1) was not allocated by this process. @Barmar

Your code could have used the below or equivalent to allocate its own copy to later reallocate it.  As strdup() is not in C STL as of C17, a sample implementation.

```<code>char *str = strdup(argv[1]);
</code>```

Body:
I have a short snippet where I am passing a char array into another function and changing the size in memory.

// in main
char *str = argv[1];
find(&str);

void func(char **str){
  // some code
  *str = realloc(*str, 10+1);
}

This gives the error

realloc(): invalid pointer
Aborted (core dumped)

What did I do wrong here? In order to change the value of str in another function, I am using a double pointer.

Body:
What did I do wrong here?

*str in realloc(*str, 10+1) was not allocated by this process. @Barmar

Your code could have used the below or equivalent to allocate its own copy to later reallocate it.  As strdup() is not in C STL as of C17, a sample implementation.

char *str = strdup(argv[1]);


问:
How to I save a list group in SQL database?
I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.</p>

```<code>  <h4>Subjects</h4>
  <ul class="list-group list" id='subjectlist' name='subjectlist' >
  </ul>

  <div class="form-group">
    <input class="submit" name="submit" type="submit" value="Save">
  </div>

</form>

<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>

<script>

  function getsubject(){
    var ul = document.getElementById("subjectlist");
    var candidate = document.getElementById("st");
    var SelectedValue = candidate.options[candidate.selectedIndex].text;
    var li = document.createElement("li");

    li.setAttribute('class',"list-group-item");
    li.setAttribute('id',"subjectlistitem");
    li.appendChild(document.createTextNode(SelectedValue));
    ul.appendChild(li);
  }
</script>

<?php
 if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
   $sectioncode = $_POST['sc'];
   $sectiongroup = $_POST['ccg'];
   $selectedsubject = $_POST['st'];
   $subjectlist = $_POST['subjectlist'];
   $i = 0;
   foreach ($subjectlist as $qst) {
     $sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
     '" . $subjectlist[$i] . "')";
    if ($link->query($sql) === TRUE) {
        echo "success";
    } else {echo "error" . $link->error;}
    $i++;}
 }
?>
</code>```

答:
because $_POST,$_GET only deal with <input>  tags and
,
 are not input methods.

Body:
I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.

Subjects

    <input class="submit" name="submit" type="submit" value="Save">

</form>

<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>

<?php
 if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
   $sectioncode = $_POST['sc'];
   $sectiongroup = $_POST['ccg'];
   $selectedsubject = $_POST['st'];
   $subjectlist = $_POST['subjectlist'];
   $i = 0;
   foreach ($subjectlist as $qst) {
     $sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
     '" . $subjectlist[$i] . "')";
    if ($link->query($sql) === TRUE) {
        echo "success";
    } else {echo "error" . $link->error;}
    $i++;}
 }
?>

Body: because $_POST,$_GET only deal with <input>  tags and <ul>,<li> are not input methods.