问:
Zip file path separator
I am delivering zip files to a company that has a Unix environment and they tell me that the path separator is wrong. I have found a solution that works but when i put it into production the path separator is wrong again.

Is it possible for me to see which path separator a zip-file has when i am using a Windows environment?

No matter how i have tried to open the file the path separator shows up the same even if i know that one file has backslash and another has forward slash i cannot tell them apart.strong text

答:
The path separator in a zip file MUST always be /. Here is what the spec (APPNOTE.TXT) for zip files says

```<code>   4.4.17.1 The name of the file, with optional relative path.
   The path stored MUST NOT contain a drive or
   device letter, or a leading slash.  All slashes
   MUST be forward slashes '/' as opposed to
   backwards slashes '\' for compatibility with Amiga
   and UNIX file systems etc.  If input came from standard
   input, there is no file name field.
</code>```

On Windows the unzip program will transform paths with / into native windows paths that use \.

To view what path separator is actually being used inside the zip file, you could try running zipdetails on it. The Filename fields show what is actually being stored internally in the file. The zip file below has a single file tmp/abc

```<code>$ zipdetails /tmp/abc.zip

0000 LOCAL HEADER #1       04034B50
0004 Extract Zip Spec      0A '1.0'
0005 Extract OS            00 'MS-DOS'
0006 General Purpose Flag  0000
0008 Compression Method    0000 'Stored'
000A Last Mod Time         505246C0 'Tue Feb 18 08:54:00 2020'
000E CRC                   4788814E
0012 Compressed Length     00000004
0016 Uncompressed Length   00000004
001A Filename Length       0007
001C Extra Length          001C
001E Filename              'tmp/abc'
0025 Extra ID #0001        5455 'UT: Extended Timestamp'
0027   Length              0009
0029   Flags               '03 mod access'
002A   Mod Time            5E4BA627 'Tue Feb 18 08:53:59 2020'
002E   Access Time         5E4BA627 'Tue Feb 18 08:53:59 2020'
0032 Extra ID #0002        7875 'ux: Unix Extra Type 3'
0034   Length              000B
0036   Version             01
0037   UID Size            04
0038   UID                 0000245B
003C   GID Size            04
003D   GID                 00005208
0041 PAYLOAD               abc.

0045 CENTRAL HEADER #1     02014B50
0049 Created Zip Spec      1E '3.0'
004A Created OS            03 'Unix'
004B Extract Zip Spec      0A '1.0'
004C Extract OS            00 'MS-DOS'
004D General Purpose Flag  0000
004F Compression Method    0000 'Stored'
0051 Last Mod Time         505246C0 'Tue Feb 18 08:54:00 2020'
0055 CRC                   4788814E
0059 Compressed Length     00000004
005D Uncompressed Length   00000004
0061 Filename Length       0007
0063 Extra Length          0018
0065 Comment Length        0000
0067 Disk Start            0000
0069 Int File Attributes   0001
     [Bit 0]               1 Text Data
006B Ext File Attributes   81A40000
006F Local Header Offset   00000000
0073 Filename              'tmp/abc'
007A Extra ID #0001        5455 'UT: Extended Timestamp'
007C   Length              0005
007E   Flags               '03 mod access'
007F   Mod Time            5E4BA627 'Tue Feb 18 08:53:59 2020'
0083 Extra ID #0002        7875 'ux: Unix Extra Type 3'
0085   Length              000B
0087   Version             01
0088   UID Size            04
0089   UID                 0000245B
008D   GID Size            04
008E   GID                 00005208

0092 END CENTRAL HEADER    06054B50
0096 Number of this disk   0000
0098 Central Dir Disk no   0000
009A Entries in this disk  0001
009C Total Entries         0001
009E Size of Central Dir   0000004D
00A2 Offset to Central Dir 00000045
00A6 Comment Length        0000
Done
</code>```

Title: Zip file path separator

Body:
The path separator in a zip file MUST always be /. Here is what the spec (APPNOTE.TXT) for zip files says

   4.4.17.1 The name of the file, with optional relative path.
   The path stored MUST NOT contain a drive or
   device letter, or a leading slash.  All slashes
   MUST be forward slashes '/' as opposed to
   backwards slashes '\' for compatibility with Amiga
   and UNIX file systems etc.  If input came from standard
   input, there is no file name field.

On Windows the unzip program will transform paths with / into native windows paths that use \.

To view what path separator is actually being used inside the zip file, you could try running zipdetails on it. The Filename fields show what is actually being stored internally in the file. The zip file below has a single file tmp/abc

$ zipdetails /tmp/abc.zip

0000 LOCAL HEADER #1       04034B50
0004 Extract Zip Spec      0A '1.0'
0005 Extract OS            00 'MS-DOS'
0006 General Purpose Flag  0000
0008 Compression Method    0000 'Stored'
000A Last Mod Time         505246C0 'Tue Feb 18 08:54:00 2020'
000E CRC                   4788814E
0012 Compressed Length     00000004
0016 Uncompressed Length   00000004
001A Filename Length       0007
001C Extra Length          001C
001E Filename              'tmp/abc'
0025 Extra ID #0001        5455 'UT: Extended Timestamp'
0027   Length              0009
0029   Flags               '03 mod access'
002A   Mod Time            5E4BA627 'Tue Feb 18 08:53:59 2020'
002E   Access Time         5E4BA627 'Tue Feb 18 08:53:59 2020'
0032 Extra ID #0002        7875 'ux: Unix Extra Type 3'
0034   Length              000B
0036   Version             01
0037   UID Size            04
0038   UID                 0000245B
003C   GID Size            04
003D   GID                 00005208
0041 PAYLOAD               abc.

0045 CENTRAL HEADER #1     02014B50
0049 Created Zip Spec      1E '3.0'
004A Created OS            03 'Unix'
004B Extract Zip Spec      0A '1.0'
004C Extract OS            00 'MS-DOS'
004D General Purpose Flag  0000
004F Compression Method    0000 'Stored'
0051 Last Mod Time         505246C0 'Tue Feb 18 08:54:00 2020'
0055 CRC                   4788814E
0059 Compressed Length     00000004
005D Uncompressed Length   00000004
0061 Filename Length       0007
0063 Extra Length          0018
0065 Comment Length        0000
0067 Disk Start            0000
0069 Int File Attributes   0001
     [Bit 0]               1 Text Data
006B Ext File Attributes   81A40000
006F Local Header Offset   00000000
0073 Filename              'tmp/abc'
007A Extra ID #0001        5455 'UT: Extended Timestamp'
007C   Length              0005
007E   Flags               '03 mod access'
007F   Mod Time            5E4BA627 'Tue Feb 18 08:53:59 2020'
0083 Extra ID #0002        7875 'ux: Unix Extra Type 3'
0085   Length              000B
0087   Version             01
0088   UID Size            04
0089   UID                 0000245B
008D   GID Size            04
008E   GID                 00005208

0092 END CENTRAL HEADER    06054B50
0096 Number of this disk   0000
0098 Central Dir Disk no   0000
009A Entries in this disk  0001
009C Total Entries         0001
009E Size of Central Dir   0000004D
00A2 Offset to Central Dir 00000045
00A6 Comment Length        0000
Done


来源: stackexchange

问:
Apache Spark driver memory
I've been trying to install and run a simple Java Apache Spark in intellij on windows but i have an error I can't solve. I have installed spark via maven. I get this error:

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
19/03/20 23:53:23 INFO SparkContext: Running Spark version 2.0.0-cloudera1-SNAPSHOT
19/03/20 23:53:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/03/20 23:53:24 INFO SecurityManager: Changing view acls to: Drakker
19/03/20 23:53:24 INFO SecurityManager: Changing modify acls to: Drakker
19/03/20 23:53:24 INFO SecurityManager: Changing view acls groups to:
19/03/20 23:53:24 INFO SecurityManager: Changing modify acls groups to:
19/03/20 23:53:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(Drakker); groups with view permissions: Set(); users  with modify permissions: Set(Drakker); groups with modify permissions: Set()
19/03/20 23:53:25 INFO Utils: Successfully started service 'sparkDriver' on port 50007.
19/03/20 23:53:25 INFO SparkEnv: Registering MapOutputTracker
19/03/20 23:53:25 ERROR SparkContext: Error initializing SparkContext.
java.lang.IllegalArgumentException: System memory 259522560 must be at least 471859200. Please increase heap size using the --driver-memory option or spark.driver.memory in Spark configuration.
    at org.apache.spark.memory.UnifiedMemoryManager$.getMaxMemory(UnifiedMemoryManager.scala:212)
    at org.apache.spark.memory.UnifiedMemoryManager$.apply(UnifiedMemoryManager.scala:194)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:308)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:165)
    at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:260)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:429)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at Spark.App.main(App.java:16)
19/03/20 23:53:25 INFO SparkContext: Successfully stopped SparkContext
Exception in thread "main" java.lang.IllegalArgumentException: System memory 259522560 must be at least 471859200. Please increase heap size using the --driver-memory option or spark.driver.memory in Spark configuration.
    at org.apache.spark.memory.UnifiedMemoryManager$.getMaxMemory(UnifiedMemoryManager.scala:212)
    at org.apache.spark.memory.UnifiedMemoryManager$.apply(UnifiedMemoryManager.scala:194)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:308)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:165)
    at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:260)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:429)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at Spark.App.main(App.java:16)
</code>```

I tried setting driver memory manually but it didn't work. I also tried installing spark locally but changing driver memory from command prompt didn't help.

This is the code:

```<code>package Spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import java.util.Arrays;
import java.util.List;

public class App
{
    public static void main( String[] args )
    {
        SparkConf conf = new SparkConf().setAppName("Spark").setMaster("local");
//        conf.set("spark.driver.memory","471859200");
        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Integer> data= Arrays.asList(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);
        JavaRDD<Integer> rdd=sc.parallelize(data);
        JavaRDD<Integer> list=rdd.map(s->s);
        int totalLines=list.reduce((a,b)->a+b);
        System.out.println(totalLines);
    }
}
</code>```

I get the error when instantiating JavaSparkContext. Does anyone have any idea how to solve this?

Thanks!

答:
Driver Memory Exception

This occurs when the Spark driver runs out of memory. That is when the application master that launches the driver exceeds the limit and terminates the yarn process.

Error Msg: Java.lang.OutOfMemoryError

Solution: Increase your driver memory by setting up the below:

```<code>    conf spark.driver.memory = <XY>g
</code>```

ContentLicense: CC BY-SA 4.0

Title: Apache Spark driver memory

Body:
I've been trying to install and run a simple Java Apache Spark in intellij on windows but i have an error I can't solve. I have installed spark via maven. I get this error:

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
19/03/20 23:53:23 INFO SparkContext: Running Spark version 2.0.0-cloudera1-SNAPSHOT
19/03/20 23:53:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/03/20 23:53:24 INFO SecurityManager: Changing view acls to: Drakker
19/03/20 23:53:24 INFO SecurityManager: Changing modify acls to: Drakker
19/03/20 23:53:24 INFO SecurityManager: Changing view acls groups to:
19/03/20 23:53:24 INFO SecurityManager: Changing modify acls groups to:
19/03/20 23:53:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(Drakker); groups with view permissions: Set(); users  with modify permissions: Set(Drakker); groups with modify permissions: Set()
19/03/20 23:53:25 INFO Utils: Successfully started service 'sparkDriver' on port 50007.
19/03/20 23:53:25 INFO SparkEnv: Registering MapOutputTracker
19/03/20 23:53:25 ERROR SparkContext: Error initializing SparkContext.
java.lang.IllegalArgumentException: System memory 259522560 must be at least 471859200. Please increase heap size using the --driver-memory option or spark.driver.memory in Spark configuration.
    at org.apache.spark.memory.UnifiedMemoryManager$.getMaxMemory(UnifiedMemoryManager.scala:212)
    at org.apache.spark.memory.UnifiedMemoryManager$.apply(UnifiedMemoryManager.scala:194)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:308)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:165)
    at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:260)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:429)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at Spark.App.main(App.java:16)
19/03/20 23:53:25 INFO SparkContext: Successfully stopped SparkContext
Exception in thread "main" java.lang.IllegalArgumentException: System memory 259522560 must be at least 471859200. Please increase heap size using the --driver-memory option or spark.driver.memory in Spark configuration.
    at org.apache.spark.memory.UnifiedMemoryManager$.getMaxMemory(UnifiedMemoryManager.scala:212)
    at org.apache.spark.memory.UnifiedMemoryManager$.apply(UnifiedMemoryManager.scala:194)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:308)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:165)
    at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:260)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:429)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at Spark.App.main(App.java:16)

I tried setting driver memory manually but it didn't work. I also tried installing spark locally but changing driver memory from command prompt didn't help.

This is the code:

package Spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import java.util.Arrays;
import java.util.List;

public class App
{
    public static void main( String[] args )
    {
        SparkConf conf = new SparkConf().setAppName("Spark").setMaster("local");
//        conf.set("spark.driver.memory","471859200");
        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Integer> data= Arrays.asList(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);
        JavaRDD<Integer> rdd=sc.parallelize(data);
        JavaRDD<Integer> list=rdd.map(s->s);
        int totalLines=list.reduce((a,b)->a+b);
        System.out.println(totalLines);
    }
}

I get the error when instantiating JavaSparkContext. Does anyone have any idea how to solve this?

Thanks!

Body:
Driver Memory Exception

This occurs when the Spark driver runs out of memory. That is when the application master that launches the driver exceeds the limit and terminates the yarn process.

Error Msg: Java.lang.OutOfMemoryError

Solution: Increase your driver memory by setting up the below:

    conf spark.driver.memory = <XY>g


问:
I am trying to display data using fetch api but It doesn't display anything
```<code> window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});
</code>```

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

答:
You actually trying to destructure title and description from an array (data.articles). This cannot be done.

You should iterate through the array and then append the text nodes.

Change your code to this

```<code>window.addEventListener("load", () => {
  const results = document.getElementById("results");
  const api =
    "http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76";
  fetch(api)
    .then(response => response.json())
    .then(({ articles }) => {
      articles.forEach(article => {
        const { title, description } = article;

        //set dom elements

        const articleElement = document.createElement("article");
        const title_node = document.createTextNode(title);
        const title_element = document.createElement("P");
        title_element.classList.add("display");

        const description_node = document.createTextNode(description);
        const description_element = document.createElement("P");
        description_element.classList.add("description");

        title_element.appendChild(title_node);
        description_element.appendChild(description_node);

        articleElement.appendChild(title_element);
        articleElement.appendChild(description_element);
        results.appendChild(articleElement);
      });
    });
});
</code>```

and your HTML

```<code><div id="results"></div>
</code>```

Body:
 window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

Body:
You actually trying to destructure title and description from an array (data.articles). This cannot be done.

You should iterate through the array and then append the text nodes.

Change your code to this

window.addEventListener("load", () => {
  const results = document.getElementById("results");
  const api =
    "http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76";
  fetch(api)
    .then(response => response.json())
    .then(({ articles }) => {
      articles.forEach(article => {
        const { title, description } = article;

        //set dom elements

        const articleElement = document.createElement("article");
        const title_node = document.createTextNode(title);
        const title_element = document.createElement("P");
        title_element.classList.add("display");

        const description_node = document.createTextNode(description);
        const description_element = document.createElement("P");
        description_element.classList.add("description");

        title_element.appendChild(title_node);
        description_element.appendChild(description_node);

        articleElement.appendChild(title_element);
        articleElement.appendChild(description_element);
        results.appendChild(articleElement);
      });
    });
});

and your HTML

<div id="results"></div>


问:
Dart extensions are available for wrong data type in Visual Studio Code
I have two extensions for differente types String and DateTime. Could someone please to explain me the next behavour on the pictures?

Why extensions for String and DateTime are visible in suggestions for int type?!

答:
This was a bug in the SDK:

https://github.com/dart-lang/sdk/issues/40062

It's been fixed and the fix should be available in the next stable release of Dart/Flutter. It's likely already available in both Dart/Flutter dev versions as it's been a month or so since the fix.


问:
How can i make use of DOM Create Element to make the existing code more dynamic and concise?
I have built a utility which gathers users input data and then I am downloading the data in form of a YAML file. The format of the data is very particular, and hence I had to create data and hack in spaces to bring it to a proper format. This code is working fine till Number of Chais=2, now the problem is if the number of chasis will be increased to let's say 10 or 20 then the code will be so bulky and would consume a lot of memory. Hence can anyone tell me how I can make use of the DOM Create Elements to make this utility more dynamic? Attaching the code where the data is being formatted.
Attaching the entire code in the fiddle as the entire code is not fitting in here.
Any help is much appreciated

```<code>document.addEventListener('DOMContentLoaded', function() {
        const extra = {};

        const oForm = document.forms.myForm;
        const oSave = document.querySelector('input[name="save"]');
        const oSub = document.querySelector('input[name="submit"]');
        const oCtrl = document.querySelector('select[name="controller"]');
        const oTest = document.querySelector('select[name="test"]');
        const oProto = document.querySelector('select[name="protocol"]');
        const oiSCSI = document.querySelector('select[name="iSCSIip"]');
        //const oTmp = document.getElementsByClassName("tabcontent")
        const oTmp = document.getElementById("extra")

//formatting Data according to the contstraints of Controllers,
var step = oForm.chassis.value;

    let payload = '';
    //Creating the data elements to be cpatured in the downloaded yaml file

    for (let i = 0; i < step; i++) {
    //  console.log('Walking east one step');

        payload+= '\n -  # UUT ' + i + ' configuration'+'\n    -  # Chassis ' + i + ' configuration'+ String.fromCharCode(10);

        const addToPayload = (object, whitespace) => {

        for (const key of Object.keys(object)) {
            payload += key + '\n';
            const details = object[key];
            for (const key1 of Object.keys(details)){
            const value = details[key1];
            str=value[0];
            com=value[2];
            val=value[1];
            whitespace=value[3];
            var input= JSON.stringify(val);

    }
        }
        }

    if((document.getElementById("ip1").disabled || document.getElementById("ip2").disabled) && oForm.ctrls.value==1){
    if(i==0){
    let data = {
        "   PDU:": {
          "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  CONTROLLER: # Controller settings ": {
            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
            "Netmask IP_A":["           MC_IP",' '+document.getElementById('mc_ip').value,'  # RBOD MC IP',''+'\n'],
            "MC_Netmask_A": ["          MC_Netmask",' '+document.getElementById('netmask_ip1').value,'  # RBOD MC Netmask',''+'\n'],
            'MC_Gateway_A':['           MC_Gateway',' '+document.getElementById('gateway_ip1').value,'  # RBOD MC Gateway',''+'\n'],
            'MC_A': ['          MC',' '+document.getElementById('rbod_mc1').value,'  # RBOD MC port',''+'\n'],
            'SC_A':['           SC',' '+document.getElementById('rbod_sc1').value,'  # RBOD SC port',''+'\n'],
            'FU_A':['           FU',' '+document.getElementById('rbod_fu1').value,'  # RBOD FU port',''+'\n'],
            'EC_A':["           EC",' '+document.getElementById('rbod_ec1').value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
            'Controller_ID#2': ["           ID",' '+document.getElementById('Controller_ID1').value,"   #Controller ID, A or B",''+'\n'],
        }
      };
      addToPayload(data, ' ' );
        }

    if(i==1){
            let data1 = {
        "   PDU:": {
          "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  CONTROLLER: # Controller settings ": {
            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
            "Netmask IP_A":["           MC_IP",' '+document.getElementById('mc_ip_1').value,'  # RBOD MC IP',''+'\n'],
            "MC_Netmask_A": ["          MC_Netmask",' '+document.getElementById('netmask_ip1_1').value,'  # RBOD MC Netmask',''+'\n'],
            'MC_Gateway_A':['           MC_Gateway',' '+document.getElementById('gateway_ip1_1').value,'  # RBOD MC Gateway',''+'\n'],
            'MC_A': ['          MC',' '+document.getElementById('rbod_mc1_1').value,'  # RBOD MC port',''+'\n'],
            'SC_A':['           SC',' '+document.getElementById('rbod_sc1_1').value,'  # RBOD SC port',''+'\n'],
            'FU_A':['           FU',' '+document.getElementById('rbod_fu1_1').value,'  # RBOD FU port',''+'\n'],
            'EC_A':["           EC",' '+document.getElementById('rbod_ec1_1').value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
            'Controller_ID#2': ["           ID",' '+document.getElementById('Controller_ID1').value,"   #Controller ID, A or B",''+'\n'],
        }
            };
        addToPayload(data1, ' ' );
}
    }

//Converting the data into a yaml file and downloading it on button click
      const blob = new Blob([payload], {
        type: 'text/yaml'
      });

      var file =  oForm.test.value + "_" + oForm.protocol.value + "_UUT_Config" + '.yaml';

      let link = document.createElement('a');
      link.download = file;

      if (window.webkitURL != null) {
        link.href = window.webkitURL.createObjectURL(blob);
      } else {
        link.href = window.URL.createObjectURL(blob);
        link.style.display = "none";
        document.body.appendChild(link);
      }
      link.click();
    }

      oCtrl.addEventListener('change', changehandler);
      oTest.addEventListener('change', changehandler);
      oSave.addEventListener('click', savehandler);
      })
</code>```

Fiddle

答:
Rather than using separate IDs for each element, consider using classes instead. For example, rather than using

```<code>document.getElementById('mc_ip').value
</code>```

on the first iteration, and

```<code>document.getElementById('mc_ip_1').value
</code>```

on the second iteration, instead create a class of mc-ips, like:

<input class="mc_ip">

Use that same pattern everywhere - change the IDs to classes, and have each separate "section" use the same class name for the same types of inputs. Then, instead of using a repetitive

```<code>if(i==1){
  // lots of code referencing _1
</code>```

to check what you can call addToPayload with, simply access

```<code>collection[i]
</code>```

For example:

```<code>const mcIps = document.querySelectorAll('.mc-ip');
const mcNetmasks = document.querySelectorAll('.netmask_ip1');
const mcGateways = document.querySelectorAll('.gateway_ip1');
const mcAs = document.querySelectorAll('.rbod_mc1');
// ...

const data = {
  "   PDU:": {
    "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
    "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
    "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
  },
  "   \n  CONTROLLER: # Controller settings ": {
    "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
    "Netmask IP_A":["           MC_IP",' '+mcIps[i].value,'  # RBOD MC IP',''+'\n'],
    "MC_Netmask_A": ["          MC_Netmask",' '+mcNetmasks[i].value,'  # RBOD MC Netmask',''+'\n'],
    'MC_Gateway_A':['           MC_Gateway',' '+mcGateways[i].value,'  # RBOD MC Gateway',''+'\n'],
    'MC_A': ['          MC',' '+mcAs[i].value,'  # RBOD MC port',''+'\n'],
  // ...

  // ...

};
addToPayload(data, ' ');
</code>```

Body:
I have built a utility which gathers users input data and then I am downloading the data in form of a YAML file. The format of the data is very particular, and hence I had to create data and hack in spaces to bring it to a proper format. This code is working fine till Number of Chais=2, now the problem is if the number of chasis will be increased to let's say 10 or 20 then the code will be so bulky and would consume a lot of memory. Hence can anyone tell me how I can make use of the DOM Create Elements to make this utility more dynamic? Attaching the code where the data is being formatted.
Attaching the entire code in the fiddle as the entire code is not fitting in here.
Any help is much appreciated

document.addEventListener('DOMContentLoaded', function() {
        const extra = {};

        const oForm = document.forms.myForm;
        const oSave = document.querySelector('input[name="save"]');
        const oSub = document.querySelector('input[name="submit"]');
        const oCtrl = document.querySelector('select[name="controller"]');
        const oTest = document.querySelector('select[name="test"]');
        const oProto = document.querySelector('select[name="protocol"]');
        const oiSCSI = document.querySelector('select[name="iSCSIip"]');
        //const oTmp = document.getElementsByClassName("tabcontent")
        const oTmp = document.getElementById("extra")

//formatting Data according to the contstraints of Controllers,
var step = oForm.chassis.value;

    let payload = '';
    //Creating the data elements to be cpatured in the downloaded yaml file

    for (let i = 0; i < step; i++) {
    //  console.log('Walking east one step');

        payload+= '\n -  # UUT ' + i + ' configuration'+'\n    -  # Chassis ' + i + ' configuration'+ String.fromCharCode(10);

        const addToPayload = (object, whitespace) => {

        for (const key of Object.keys(object)) {
            payload += key + '\n';
            const details = object[key];
            for (const key1 of Object.keys(details)){
            const value = details[key1];
            str=value[0];
            com=value[2];
            val=value[1];
            whitespace=value[3];
            var input= JSON.stringify(val);

    }
        }
        }

    if((document.getElementById("ip1").disabled || document.getElementById("ip2").disabled) && oForm.ctrls.value==1){
    if(i==0){
    let data = {
        "   PDU:": {
          "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  CONTROLLER: # Controller settings ": {
            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
            "Netmask IP_A":["           MC_IP",' '+document.getElementById('mc_ip').value,'  # RBOD MC IP',''+'\n'],
            "MC_Netmask_A": ["          MC_Netmask",' '+document.getElementById('netmask_ip1').value,'  # RBOD MC Netmask',''+'\n'],
            'MC_Gateway_A':['           MC_Gateway',' '+document.getElementById('gateway_ip1').value,'  # RBOD MC Gateway',''+'\n'],
            'MC_A': ['          MC',' '+document.getElementById('rbod_mc1').value,'  # RBOD MC port',''+'\n'],
            'SC_A':['           SC',' '+document.getElementById('rbod_sc1').value,'  # RBOD SC port',''+'\n'],
            'FU_A':['           FU',' '+document.getElementById('rbod_fu1').value,'  # RBOD FU port',''+'\n'],
            'EC_A':["           EC",' '+document.getElementById('rbod_ec1').value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
            'Controller_ID#2': ["           ID",' '+document.getElementById('Controller_ID1').value,"   #Controller ID, A or B",''+'\n'],
        }
      };
      addToPayload(data, ' ' );
        }

    if(i==1){
            let data1 = {
        "   PDU:": {
          "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  CONTROLLER: # Controller settings ": {
            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
            "Netmask IP_A":["           MC_IP",' '+document.getElementById('mc_ip_1').value,'  # RBOD MC IP',''+'\n'],
            "MC_Netmask_A": ["          MC_Netmask",' '+document.getElementById('netmask_ip1_1').value,'  # RBOD MC Netmask',''+'\n'],
            'MC_Gateway_A':['           MC_Gateway',' '+document.getElementById('gateway_ip1_1').value,'  # RBOD MC Gateway',''+'\n'],
            'MC_A': ['          MC',' '+document.getElementById('rbod_mc1_1').value,'  # RBOD MC port',''+'\n'],
            'SC_A':['           SC',' '+document.getElementById('rbod_sc1_1').value,'  # RBOD SC port',''+'\n'],
            'FU_A':['           FU',' '+document.getElementById('rbod_fu1_1').value,'  # RBOD FU port',''+'\n'],
            'EC_A':["           EC",' '+document.getElementById('rbod_ec1_1').value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
            'Controller_ID#2': ["           ID",' '+document.getElementById('Controller_ID1').value,"   #Controller ID, A or B",''+'\n'],
        }
            };
        addToPayload(data1, ' ' );
}
    }

//Converting the data into a yaml file and downloading it on button click
      const blob = new Blob([payload], {
        type: 'text/yaml'
      });

      var file =  oForm.test.value + "_" + oForm.protocol.value + "_UUT_Config" + '.yaml';

      let link = document.createElement('a');
      link.download = file;

      if (window.webkitURL != null) {
        link.href = window.webkitURL.createObjectURL(blob);
      } else {
        link.href = window.URL.createObjectURL(blob);
        link.style.display = "none";
        document.body.appendChild(link);
      }
      link.click();
    }

      oCtrl.addEventListener('change', changehandler);
      oTest.addEventListener('change', changehandler);
      oSave.addEventListener('click', savehandler);
      })

Fiddle

Body:
Rather than using separate IDs for each element, consider using classes instead. For example, rather than using

document.getElementById('mc_ip').value

on the first iteration, and

document.getElementById('mc_ip_1').value

on the second iteration, instead create a class of mc-ips, like:

<input class="mc_ip">

Use that same pattern everywhere - change the IDs to classes, and have each separate "section" use the same class name for the same types of inputs. Then, instead of using a repetitive

if(i==1){
  // lots of code referencing _1

to check what you can call addToPayload with, simply access

collection[i]

For example:

const mcIps = document.querySelectorAll('.mc-ip');
const mcNetmasks = document.querySelectorAll('.netmask_ip1');
const mcGateways = document.querySelectorAll('.gateway_ip1');
const mcAs = document.querySelectorAll('.rbod_mc1');
// ...

const data = {
  "   PDU:": {
    "PDU_IP":['       PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
    "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
    "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
  },
  "   \n  CONTROLLER: # Controller settings ": {
    "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
    "Netmask IP_A":["           MC_IP",' '+mcIps[i].value,'  # RBOD MC IP',''+'\n'],
    "MC_Netmask_A": ["          MC_Netmask",' '+mcNetmasks[i].value,'  # RBOD MC Netmask',''+'\n'],
    'MC_Gateway_A':['           MC_Gateway',' '+mcGateways[i].value,'  # RBOD MC Gateway',''+'\n'],
    'MC_A': ['          MC',' '+mcAs[i].value,'  # RBOD MC port',''+'\n'],
  // ...

  // ...

};
addToPayload(data, ' ');


问:
Why Quartz Scheduler stops working on Heroku after x minutes?
I'm trying to create a similar application like the one mentioned here https://github.com/heroku/devcenter-java-quartz-rabbitmq suggested on Heroku by this article https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes-java-quartz-rabbitmq.
The only difference is that at the moment I have a web app doing nothing ("Hello World") and a scheduler app printing the current time.
Unfortunately, after 30 min that I'm not using the application, both web and scheduler stop working:

```<code>2020-02-09T15:20:17.911457+00:00 app[scheduler.1]: 15:20:17.911 [SpringContextShutdownHook] INFO  o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
2020-02-09T15:20:18.151399+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2020-02-09T15:20:18.151689+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  o.s.s.quartz.SchedulerFactoryBean - Shutting down Quartz Scheduler
2020-02-09T15:20:18.151775+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
2020-02-09T15:20:18.151840+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2020-02-09T15:20:18.152244+00:00 app[web.1]: 15:20:18.152 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.
2020-02-09T15:20:18.152871+00:00 app[web.1]: 15:20:18.152 [SpringContextShutdownHook] INFO  o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
2020-02-09T15:20:18.135436+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-02-09T15:20:18.247822+00:00 heroku[web.1]: Process exited with status 143
2020-02-09T15:20:18.123889+00:00 heroku[scheduler.1]: Process exited with status 143
</code>```

The Procfile is pretty simple:

```<code>web: java $JAVA_OPTS -Dserver.port=$PORT -jar target/*.jar
scheduler: java $JAVA_OPTS -cp target/*.jar -Dloader.main=algotrading.app.scheduler.SchedulerApp org.springframework.boot.loader.PropertiesLauncher
</code>```

Is there something I am missing in the example?
Regards
  R

答:
I opened a ticket as suggested by @codefinger and I received immediate support. The answer to my question is that when you are using a web dyno with free dynos, when it becomes idle (due to dyno sleeping) all other dynos will become idle too.

This is the expected behaviour.
They will update the documentation as soos as they can.

Body:
I'm trying to create a similar application like the one mentioned here https://github.com/heroku/devcenter-java-quartz-rabbitmq suggested on Heroku by this article https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes-java-quartz-rabbitmq.
The only difference is that at the moment I have a web app doing nothing ("Hello World") and a scheduler app printing the current time.
Unfortunately, after 30 min that I'm not using the application, both web and scheduler stop working:

2020-02-09T15:20:17.911457+00:00 app[scheduler.1]: 15:20:17.911 [SpringContextShutdownHook] INFO  o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
2020-02-09T15:20:18.151399+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2020-02-09T15:20:18.151689+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  o.s.s.quartz.SchedulerFactoryBean - Shutting down Quartz Scheduler
2020-02-09T15:20:18.151775+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
2020-02-09T15:20:18.151840+00:00 app[web.1]: 15:20:18.151 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2020-02-09T15:20:18.152244+00:00 app[web.1]: 15:20:18.152 [SpringContextShutdownHook] INFO  org.quartz.core.QuartzScheduler - Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.
2020-02-09T15:20:18.152871+00:00 app[web.1]: 15:20:18.152 [SpringContextShutdownHook] INFO  o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
2020-02-09T15:20:18.135436+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-02-09T15:20:18.247822+00:00 heroku[web.1]: Process exited with status 143
2020-02-09T15:20:18.123889+00:00 heroku[scheduler.1]: Process exited with status 143

The Procfile is pretty simple:

web: java $JAVA_OPTS -Dserver.port=$PORT -jar target/*.jar
scheduler: java $JAVA_OPTS -cp target/*.jar -Dloader.main=algotrading.app.scheduler.SchedulerApp org.springframework.boot.loader.PropertiesLauncher

Is there something I am missing in the example?
Regards
  R


问:
Redis script for memory flush
Is it possible to create a script for Redis that flush its memory when it is above a certain value?
In my specific case, I want a flush when the memory is above 90%.
What is the best way, via bash script or Lua script?</p>

答: That's the way to obtain the allocated memory redis-cli -h 1.2.3.4 -p 6379 memory stats | sed -n 4p. Now it's easy to create a bash script

Title: Redis script for memory flush


问:
How to add interface and class in proto 3 payload in gRPC communication
I need to write a framework and there are two app which are communicating using gRPC. They share some common proto payload. Now, challenge is this, I want to write some interface and implementation in that proto3 proto contract.It is c# based app so both will generate c# based proto type from .proto file.

Is there any way to achieve the same.

答:
In raw gRPC / .proto terms, this is service:

service MyService {
  rpc SomeMethod (SomeDtoDefinedSomewhere) returns (AnotherDtoDefinedSomewhere);
  rpc AnotherMethod (Blah) returns (Whatever);
}
```

Now; what happens next depends on the tools you're using; protoc will generate a client proxy and server stub for this, not a C# interface. You can either work with this "as is", or add your own interface as an abstraction.

However, protobuf-net (a separate implementation of protobuf on .NET) can work with this as a pure C# interface via protogen. Unfortunately, I have not yet updated the website with the tweaks to actually emit service definitions as interfaces. But it should work from the nuget preview drops.

Body:
In raw gRPC / .proto terms, this is service:

service MyService {
  rpc SomeMethod (SomeDtoDefinedSomewhere) returns (AnotherDtoDefinedSomewhere);
  rpc AnotherMethod (Blah) returns (Whatever);
}

Now; what happens next depends on the tools you're using; protoc will generate a client proxy and server stub for this, not a C# interface. You can either work with this "as is", or add your own interface as an abstraction.

However, protobuf-net (a separate implementation of protobuf on .NET) can work with this as a pure C# interface via protogen. Unfortunately, I have not yet updated the website with the tweaks to actually emit service definitions as interfaces. But it should work from the nuget preview drops.


问:
How can I randomize coordinates in javascript canvas?
Newbie here, currently learning how to code. My teacher gave me the task of proving myself in canvas by making a smiley face on my own.
This is the result so far.

Now he gave me the task of randomizing the coordinates, so that the smiley as a whole appears in a new place everytime (whether that happens on load or through a button is my decision).

Edit: to clarify, my problem lies more within the logic behind altering the coordinates of my canvas. I've tried to figure out how to do this, and know that I'll need Math.random for that.

Edit: to clarify, my problem lies more within the logic behind

My code:

```<code><body onload="draw();">
    <canvas id="canvas" width="150" height="150"></canvas>

    <script type="application/javascript">
        function draw() {
            var canvas = document.getElementById("canvas");
            var smiley = canvas.getContext("2d");

                //Face shape
                smiley.beginPath();
                smiley.arc(75, 75, 50, 0, Math.PI * 2, true);

                //Right eye
                smiley.moveTo(65,55);
                smiley.arc(55,55,10,0, Math.PI * 2, true);

                //Left eye
                smiley.moveTo(105,55);
                smiley.arc(95,55,10,0, Math.PI * 2, true);

                //Mouth
                smiley.moveTo(35,75);
                smiley.arc(75, 75, 40, 0, Math.PI, false);
                smiley.moveTo(36,81);
                smiley.lineTo(114,81);
                smiley.stroke();

                //Pupils
                smiley.beginPath(58,55);
                smiley.moveTo(58,55);
                smiley.arc(55,55,3,0, Math.PI*2,true);
                smiley.moveTo(98,55);
                smiley.arc(95,55,3,0, Math.PI*2, true);
                smiley.fill()

                //Hair
                smiley.beginPath(75,25);
                smiley.moveTo(75,25);
                smiley.lineTo(75,5);
                smiley.moveTo(79,5);
                smiley.lineTo(78,25);
                smiley.moveTo(72,25);
                smiley.lineTo(71,5);
                smiley.stroke();

                //Nose
                smiley.beginPath();
                smiley.moveTo(73,50);
                smiley.lineTo(67,67);
                smiley.lineTo(80,70);
                smiley.stroke();

                smiley.beginPath()
                smiley.moveTo(73,50);
                smiley.lineTo(63,69);
                smiley.lineTo(80,70);
                smiley.lineTo(67,67);
                smiley.lineTo(73,50);
                smiley.fill();
                smiley.endPath();
            }

    </script>
</body>
</code>```

Thank you for your help.

答:
```<code>function getRandom(from, to) {
  return Math.floor(Math.random() * to) + from
}

function normalise(px, shift) {
  return px - 75 + shift // moving it to 0 and then shifting it to anywhere
}

function draw() {
  var canvas = document.getElementById("canvas");
  var smiley = canvas.getContext("2d");
  const [startx, starty] = [getRandom(75, 100), getRandom(75, 100)];
  console.log(startx, starty);

  //Face shape
  smiley.beginPath();
  smiley.arc(normalise(75, startx), normalise(75, starty), 50, 0, Math.PI * 2, true);

  //Right eye
  smiley.moveTo(normalise(65, startx), normalise(55, starty));
  smiley.arc(normalise(55, startx), normalise(55, starty), 10, 0, Math.PI * 2, true);

  //Left eye
  smiley.moveTo(normalise(105, startx), normalise(55, starty));
  smiley.arc(normalise(95, startx), normalise(55, starty), 10, 0, Math.PI * 2, true);

  //Mouth
  smiley.moveTo(normalise(35, startx), normalise(75, starty));
  smiley.arc(normalise(75, startx), normalise(75, starty), 40, 0, Math.PI, false);
  smiley.moveTo(normalise(36, startx), normalise(81, starty));
  smiley.lineTo(normalise(114, startx), normalise(81, starty));
  smiley.stroke();

  //Pupils
  smiley.beginPath(normalise(58, startx), normalise(55, starty));
  smiley.moveTo(normalise(58, startx), normalise(55, starty));
  smiley.arc(normalise(55, startx), normalise(55, starty), 3, 0, Math.PI * 2, true);
  smiley.moveTo(normalise(98, startx), normalise(55, starty));
  smiley.arc(normalise(95, startx), normalise(55, starty), 3, 0, Math.PI * 2, true);
  smiley.fill()

  //Hair
  smiley.beginPath(normalise(75, startx), normalise(25, starty));
  smiley.moveTo(normalise(75, startx), normalise(25, starty));
  smiley.lineTo(normalise(75, startx), normalise(5, starty));
  smiley.moveTo(normalise(79, startx), normalise(5, starty));
  smiley.lineTo(normalise(78, startx), normalise(25, starty));
  smiley.moveTo(normalise(72, startx), normalise(25, starty));
  smiley.lineTo(normalise(71, startx), normalise(5, starty));
  smiley.stroke();

  //Nose
  smiley.beginPath();
  smiley.moveTo(normalise(73, startx), normalise(50, starty));
  smiley.lineTo(normalise(67, startx), normalise(67, starty));
  smiley.lineTo(normalise(80, startx), normalise(70, starty));
  smiley.stroke();

  smiley.beginPath()
  smiley.moveTo(normalise(73, startx), normalise(50, starty));
  smiley.lineTo(normalise(63, startx), normalise(69, starty));
  smiley.lineTo(normalise(80, startx), normalise(70, starty));
  smiley.lineTo(normalise(67, startx), normalise(67, starty));
  smiley.lineTo(normalise(73, startx), normalise(50, starty));
  smiley.fill();
  // smiley.endPath();
}
</code>```

Body:
Newbie here, currently learning how to code. My teacher gave me the task of proving myself in canvas by making a smiley face on my own.
This is the result so far.

Now he gave me the task of randomizing the coordinates, so that the smiley as a whole appears in a new place everytime (whether that happens on load or through a button is my decision).

Edit: to clarify, my problem lies more within the logic behind altering the coordinates of my canvas. I've tried to figure out how to do this, and know that I'll need Math.random for that.

Edit: to clarify, my problem lies more within the logic behind

My code:

    <canvas id="canvas" width="150" height="150"></canvas>

Thank you for your help.


问:
Perl : creating array of known size

I have to store data from request runned with Parallel::ForkManager.

But it comes not in order, I mean, I poll all ports of a switch, but some of them answer faster than others. So, I don't know how to save it, to display it later.

Can I do like that ?

```<code>my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
...
print @array;
</code>```

Or should I use a %hash with number of port as keys, but it seems not the best.

Thank you.

答:
You can do this:

```<code>my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
print @array;
</code>```

But if some ports do not respond you will have undef entries in the slots of the array that were not filled.  As you say, using a hash would be cleaner:

```<code>my %hash;
$hash{10} = "I am port 10";
$hash{2} = "I am port 2";

foreach my $key (keys %hash) {
   print "$key: $hash{$key}\n";
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Perl : creating array of known size

Body:
I have to store data from request runned with Parallel::ForkManager.

But it comes not in order, I mean, I poll all ports of a switch, but some of them answer faster than others. So, I don't know how to save it, to display it later.

Can I do like that ?

my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
...
print @array;

Or should I use a %hash with number of port as keys, but it seems not the best.

Thank you.

Body:
You can do this:

my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
print @array;

But if some ports do not respond you will have undef entries in the slots of the array that were not filled.  As you say, using a hash would be cleaner:

my %hash;
$hash{10} = "I am port 10";
$hash{2} = "I am port 2";

foreach my $key (keys %hash) {
   print "$key: $hash{$key}\n";
}


问:
Dealing with roles cross projects
This is one of the very important questions that I faced when I was doing the GCP data engineer practice exam:

As your organization expands its usage of GCP, many teams have started to create their own projects.
Projects are further multiplied to accommodate different stages of deployments and target
audiences. Each project requires unique access control configurations. The central IT team needs to
have access to all projects. Furthermore, data from Cloud Storage buckets and BigQuery datasets
must be shared for use in other projects in an ad hoc way. You want to simplify access control
management by minimizing the number of policies. Which two steps should you take? Choose 2
answers.

A. Use Cloud Deployment Manager to automate access provision.

B. Introduce resource hierarchy to leverage access control policy inheritance.

C. Create distinct groups for various teams, and specify groups in Cloud IAM policies.

D. Only use service accounts when sharing data for Cloud Storage buckets and BigQuery datasets.

E. For each Cloud Storage bucket or BigQuery dataset, decide which projects need access. Find all the
active members who have access to these projects, and create a Cloud IAM policy to grant access to
all these users.

According to this 1  A,B and C are all correct, but it seems we must choose only two of the options. So I was wondering what the correct answers are?

答: The correct answers are B and C. The key to this question is "You want to simplify access control management by minimizing the number of policies.". Deployment Manager is primarily used for creating related resources</p>

Title: Dealing with roles cross projects


问:
How to read a column of csv as dtype list using pandas?
I have a csv file with 3 columns, wherein each row of Column 3 has list of values in it. As you can see from the following table structure

```<code>Col1,Col2,Col3
1,a1,"['Proj1', 'Proj2']"
2,a2,"['Proj3', 'Proj2']"
3,a3,"['Proj4', 'Proj1']"
4,a4,"['Proj3', 'Proj4']"
5,a5,"['Proj5', 'Proj2']"
</code>```

Whenever I try to read this csv, Col3 is getting read as str object and not as list. I tried to alter the dtype of that column to list but got "Attribute Error" as below

```<code>df = pd.read_csv("inputfile.csv")
df.Col3.dtype = list

AttributeError                            Traceback (most recent call last)
<ipython-input-19-6f9ec76b1b30> in <module>()
----> 1 df.Col3.dtype = list

C:\Python27\lib\site-packages\pandas\core\generic.pyc in __setattr__(self,         name, value)
   1953                     object.__setattr__(self, name, value)
   1954             except (AttributeError, TypeError):
-> 1955                 object.__setattr__(self, name, value)
   1956
   1957     #----------------------------------------------------------------------
</code>```

AttributeError: can't set attribute

It would be really great if you can guide me how to go about it.

答:
@Padraic Cunningham's answer will not work if you have to parse lists of strings that do not have quotes. For example, literal_eval will successfully parse "['a', 'b', 'c']", but not "[a, b, c]". To load strings like this, use the PyYAML library.

```<code>import io
import pandas as pd

data = '''
A,B,C
"[1, 2, 3]",True,"[a, b, c]"
"[4, 5, 6]",False,"[d, e, f]"
'''

df = pd.read_csv(io.StringIO(data), sep=',')
df
           A      B          C
0  [1, 2, 3]   True  [a, b, c]
1  [4, 5, 6]  False  [d, e, f]

df['C'].tolist()
# ['[a, b, c]', '[d, e, f]']
</code>```

```<code>import yaml
df[['A', 'C']] = df[['A', 'C']].applymap(yaml.safe_load)

df['C'].tolist()
# [['a', 'b', 'c'], ['d', 'e', 'f']]
</code>```

yaml can be installed using pip install pyyaml.

Body:
I have a csv file with 3 columns, wherein each row of Column 3 has list of values in it. As you can see from the following table structure

Col1,Col2,Col3
1,a1,"['Proj1', 'Proj2']"
2,a2,"['Proj3', 'Proj2']"
3,a3,"['Proj4', 'Proj1']"
4,a4,"['Proj3', 'Proj4']"
5,a5,"['Proj5', 'Proj2']"

Whenever I try to read this csv, Col3 is getting read as str object and not as list. I tried to alter the dtype of that column to list but got "Attribute Error" as below

df = pd.read_csv("inputfile.csv")
df.Col3.dtype = list

AttributeError                            Traceback (most recent call last)
<ipython-input-19-6f9ec76b1b30> in <module>()
----> 1 df.Col3.dtype = list

C:\Python27\lib\site-packages\pandas\core\generic.pyc in __setattr__(self,         name, value)
   1953                     object.__setattr__(self, name, value)
   1954             except (AttributeError, TypeError):
-> 1955                 object.__setattr__(self, name, value)
   1956
   1957     #----------------------------------------------------------------------

AttributeError: can't set attribute

It would be really great if you can guide me how to go about it.

Body:
@Padraic Cunningham's answer will not work if you have to parse lists of strings that do not have quotes. For example, literal_eval will successfully parse "['a', 'b', 'c']", but not "[a, b, c]". To load strings like this, use the PyYAML library.

import io
import pandas as pd

data = '''
A,B,C
"[1, 2, 3]",True,"[a, b, c]"
"[4, 5, 6]",False,"[d, e, f]"
'''

df = pd.read_csv(io.StringIO(data), sep=',')
df
           A      B          C
0  [1, 2, 3]   True  [a, b, c]
1  [4, 5, 6]  False  [d, e, f]

df['C'].tolist()
# ['[a, b, c]', '[d, e, f]']

import yaml
df[['A', 'C']] = df[['A', 'C']].applymap(yaml.safe_load)

df['C'].tolist()
# [['a', 'b', 'c'], ['d', 'e', 'f']]

yaml can be installed using pip install pyyaml.


问:
What is the intuition behind flipping filters during convolution?
I saw that, while using the conv2d function of Theano, the filters were flipped both vertically and horizontally. Why is that? And does it matter in the case of a Convolutional Neural Network?</p>

答:
Because this is how convolution is defined mathematically. Without the flipping of filter, the operation is called cross-correlation. The advantage of convolution is that it has nicer mathematical properties.

However in the context of Convolutional Neural Network it doesn't matter whether you use convolution or cross-correlation, they are equivalent. This is because the weights of filters are learned during the training, i.e. they are updated to minimize a cost function. In a CNN that uses the cross-correlation operation, the learned filters will be equal to the flipped learned filters of a CNN that uses the convolution operation (assuming exactly the same training conditions for both, i.e. same initialization, inputs, number of epochs etc.). So the outputs of such two CNNs will be the same for the same inputs.

Cross-correlation operation is slightly more intuitive and simpler to implement (because no flipping is performed) and that's probably the reason why other frameworks like Tensorflow and Pytorch use it instead of the actual convolution (they still call it convolution though, probably due to historical reasons or to be consistent in terminology with other frameworks that use the actual convolution).


问:
Maintaining timestamp sequence of incoming streaming data
So I am pushing some json data from kafka to Spark using structured streaming. The data, in form of dictionary, has a field "timestamp". After parsing json and getting individual columns for every key, I noticed the timestamp field is not in the sequence in which it was pushed to kafka cluster i.e.

```<code>+----------+
| Timestamp|
+----------+
|     1    |
|     2    |
|     6    |  <--
|     4    |
|     5    |
|     7    |  <--
+----------+
</code>```

Is there any way to make sure that the data remains in sequence? One thing I can think of is using orderby on timestamp with output_mode="complete". Are there any other efficient alternatives?
Thanks.

答:
Kafka guarantee messages order within partition only. If you want strict order within Kafka - keep one partition per topic and guarantee ordering when delivering there. You might want to implement "ordering service" which reads from the incoming queue and writes messages to another queue with only one partition. Good explanation and examples may be found in various blog posts: here or here and more.

Ordering messages in Spark is the easiest option. You should consider saving or caching ordered results to storage for reuse.

Body:
So I am pushing some json data from kafka to Spark using structured streaming. The data, in form of dictionary, has a field "timestamp". After parsing json and getting individual columns for every key, I noticed the timestamp field is not in the sequence in which it was pushed to kafka cluster i.e.

+----------+
| Timestamp|
+----------+
|     1    |
|     2    |
|     6    |  <--
|     4    |
|     5    |
|     7    |  <--
+----------+

Is there any way to make sure that the data remains in sequence? One thing I can think of is using orderby on timestamp with output_mode="complete". Are there any other efficient alternatives?
Thanks.


问:
photo shoot not working with camera connected to the computer
I am trying to take photos while the camera is connected to the computer. As soon as the camera is connected to to PC the camera changes it's mode to busy. I would like trigger the camera to take picture while it is connected to the computer.</p>

答: You can use the EdsSendStatusCommand function with kEdsCameraStatusCommand _UIUnLock to use the camera manually while plugged in. Note that some commands issued with the Canon SDK may lock the camera UI again.


问:
What are some good rigid body dynamics references?
I'm not a math guy in the least but I'm interested in learning about rigid body physics (for the purpose of implementing a basic 3d physics engine).  In school I only took Maths through Algebra II, but I've done 3d dev for years so I have a fairly decent understanding of vectors, quaternions, matrices, etc.  My real problem is reading complex formulas and such, so I'm looking for some decent rigid body dynamics references that will make some sense.

Anyone have any good references?

答:
I guess what you are looking for is Classical Mechanics, which describes motion in one, two, and three dimensions in a generalized manner.

I found a good introductory course on Classical Mechanics from the University of Texas.

I do not guarantee that you will be able to understand all the concepts there, but it will at least give you a basis for your plan. I advise you to consult a Physics professor to help you understand the math.

Good luck!

OwnerDisplayName: Cody Brocious

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cody Brocious

OwnerDisplayName: Jon Limjap


问:
Batch renaming files with Bash
How can Bash rename a series of packages to remove their version numbers? I've been toying around with both expr and %%, to no avail.

Examples:

Xft2-2.1.13.pkg becomes Xft2.pkg

jasper-1.900.1.pkg becomes jasper.pkg

xorg-libXrandr-1.2.3.pkg becomes xorg-libXrandr.pkg

答:
You could use bash's parameter expansion feature

```<code>for i in ./*.pkg ; do mv "$i" "${i/-[0-9.]*.pkg/.pkg}" ; done
</code>```

Quotes are needed for filenames with spaces.

OwnerDisplayName: Nerdling

Title: Batch renaming files with Bash

Body:
You could use bash's parameter expansion feature

for i in ./*.pkg ; do mv "$i" "${i/-[0-9.]*.pkg/.pkg}" ; done

Quotes are needed for filenames with spaces.

OwnerDisplayName: rq


问:
error at javascript that connect to sql, asp.net c#
I have javascript timer countdown with the code:

```<code><script language="JavaScript">
TargetDate = "<% = TargetDate %>";
/*this is a property in code behind*/BackColor = "palegreen";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "the auction end"
</script>
<script language="JavaScript" src="countdown.js"></script>
</script>
</code>```

the code behind:

```<code>public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}
</code>```

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)

答: You also have a spelling error in your connection string: Trusted_Connectopn should be Trusted_Connection

Body:
I have javascript timer countdown with the code:

</script>

the code behind:

public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)


问:
How can I save this data to a txt using pyTelegramBotAPI
up here has a nested structure where it starts with

```<code>@bot.message_handler(content_types=["text"])
def handle_text (message, user_markup=None):
</code>```

right after that comes the nested structure and this function would be inside it

```<code>def wallet(message):
    if message.text == 'Wallet NST':
       sent=bot.send_message(message.chat.id, """Crypto currency is an Ethereum token.
    NST Smart Contract Token Address is as follows:
    (0xD89040Ac9823B72F64d71f66Fa2DeAE7C8520671).
    Please make sure you are using the right smart contract or your funds may be irretrievably lost. \n
    INFORM YOUR WALLET NST(NEW SOLUTION ) :""")
      bot.register_next_step_handler(sent, salva)

def guard(message):
    archive=open('oriondb.txt', 'w')
    archive.write(int(messagefrom_user.id)  + message.from_user.username + message.chat.text )
    bot.send_message(message.chat.id, 'CARTEIRA SALVA COM SUCESSO!')
    bot.register_next_step_handler( handle_text)
</code>```

I would like to save the answer to a txt file or a database how can i do this using pytelegramBotAPI?

答:
I think it should work:</p>

```<code>@bot.message_handler(content_types=["text"])
def wallet(m):
cid = m.chat.id

if m.text == 'Wallet NST':
   bot.register_next_step_handler(sent, salva)
   sent=bot.send_message(cid, """Crypto currency is an Ethereum token.
   NST Smart Contract Token Address is as follows:
   (0xD89040Ac9823B72F64d71f66Fa2DeAE7C8520671).
   Please make sure you are using the right smart contract or your funds may be
   irretrievably lost. \n
   INFORM YOUR WALLET NST(NEW SOLUTION ) :""")

archive=open('oriondb.txt', 'a')
archive.append(str(cid)  + m.chat.username + m.chat.text )
bot.send_message(cid, 'CARTEIRA SALVA COM SUCESSO!')
</code>```

Body:
up here has a nested structure where it starts with

@bot.message_handler(content_types=["text"])
def handle_text (message, user_markup=None):

right after that comes the nested structure and this function would be inside it

def wallet(message):
    if message.text == 'Wallet NST':
       sent=bot.send_message(message.chat.id, """Crypto currency is an Ethereum token.
    NST Smart Contract Token Address is as follows:
    (0xD89040Ac9823B72F64d71f66Fa2DeAE7C8520671).
    Please make sure you are using the right smart contract or your funds may be irretrievably lost. \n
    INFORM YOUR WALLET NST(NEW SOLUTION ) :""")
      bot.register_next_step_handler(sent, salva)

def guard(message):
    archive=open('oriondb.txt', 'w')
    archive.write(int(messagefrom_user.id)  + message.from_user.username + message.chat.text )
    bot.send_message(message.chat.id, 'CARTEIRA SALVA COM SUCESSO!')
    bot.register_next_step_handler( handle_text)

I would like to save the answer to a txt file or a database how can i do this using pytelegramBotAPI?

Body:
I think it should work:

@bot.message_handler(content_types=["text"])
def wallet(m):
cid = m.chat.id

if m.text == 'Wallet NST':
   bot.register_next_step_handler(sent, salva)
   sent=bot.send_message(cid, """Crypto currency is an Ethereum token.
   NST Smart Contract Token Address is as follows:
   (0xD89040Ac9823B72F64d71f66Fa2DeAE7C8520671).
   Please make sure you are using the right smart contract or your funds may be
   irretrievably lost. \n
   INFORM YOUR WALLET NST(NEW SOLUTION ) :""")

archive=open('oriondb.txt', 'a')
archive.append(str(cid)  + m.chat.username + m.chat.text )
bot.send_message(cid, 'CARTEIRA SALVA COM SUCESSO!')


问:
CachedNetworkImage only shows placeholder and doesn't load image in Flutter chat app
First of all, I am a complete beginner (not only in dart/flutter), but in programming in general. I am currently working on a chat app.

Goal: When I am picking an image within the ChatScreen - analog to e.g. WhatsApp - it should immediately appear as a message (placeholder with loading symbol, while it is uploaded to Firestore).

Problem: Everything is working fine, but here is one issue: When I am picking an image via the imagepicker, it get's uploaded but there's a delay until it is displayed as a message in the chat. imagepicker -> write to Firestore -> Streambuilder
 (listView.builder).

My attempt: I am using CachedNetworkImage, but unfortunately, it keep's showing the placeholder (CircularProgressIndicator), but not the actual image. If I am just displaying the image, everything works fine (besides the delay).

Moreover, I would highly appreciate some ideas to make the app run faster / improve the code ;-).

```<code>//Chat screen which lists all the chat messages, including _handleSubmitted and the _buildTextComposer

import 'dart:math';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:intl/intl.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:flutter_image/network.dart';
import 'package:flutter_native_image/flutter_native_image.dart';

final database = Firestore.instance
    .collection('nachrichten')
    .document('G5xlQHvb56ZqpWs7ojUV');
final reference = FirebaseDatabase.instance.reference().child('messages');

class ChatScreen extends StatefulWidget {
  @override
  State createState() => new ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> with TickerProviderStateMixin {
  final TextEditingController _textController = new TextEditingController();
  final ScrollController _scrollController = new ScrollController();

  bool _isComposing = false;
  bool isLoading;
  String imageUrl;
  File imageFile;

  //optional from other code
  @override
  void initState() {
    super.initState();
    imageUrl = '';
  }

  Future getImage() async {
    imageFile = await ImagePicker.pickImage(source: ImageSource.camera);

    if (imageFile != null) {
      setState(() {
        isLoading = true;
      });
      uploadFile();
    }
  }

  Future uploadFile() async {
    //file compression
    File compressedFile = await FlutterNativeImage.compressImage(imageFile.path,
        quality: 100, percentage: 100);
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = reference.putFile(compressedFile);
    StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
    storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
      imageUrl = downloadUrl;
      setState(() {
        isLoading = false;
        _handleSubmitted(imageUrl: imageUrl);
      });
    }, onError: (err) {
      setState(() {
        isLoading = false;
      });
      Fluttertoast.showToast(msg: 'This file is not an image');
    });
  }

  //Builds the button text composer, including camera icon, text input and send button
  Widget _buildTextComposer() {
    return new IconTheme(
      data: new IconThemeData(color: Theme.of(context).accentColor),
      child: new Container(
          margin: const EdgeInsets.symmetric(horizontal: 0.80),
          child: new Row(children: <Widget>[
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 0.4),
              child: new IconButton(
                icon: new Icon(Icons.photo_camera),
                onPressed: getImage,
              ),
            ),
            new Flexible(
              child: Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                padding: EdgeInsets.all(10.0),
                decoration: new BoxDecoration(
                  border: Border.all(color: Colors.grey.shade200),
                  borderRadius: new BorderRadius.circular(20.0),
                ),

                //container with constraint limits the maximum height of the text input field
                child: new Container(
                  constraints: BoxConstraints.loose(Size.fromHeight(100.0)),
                  child: new TextField(
                    maxLines: null,
                    keyboardType: TextInputType.multiline,
                    controller: _textController,
                    onChanged: (String text) {
                      setState(() {
                        _isComposing = text.length > 0;
                      });
                    },
//                    onSubmitted: _handleSubmitted,
                    decoration: new InputDecoration.collapsed(
                        hintText: "Nachricht schreiben..."),
                  ),
                ),
              ),
            ),
            new Container(
                margin: new EdgeInsets.symmetric(horizontal: 0.4),
                child: Theme.of(context).platform == TargetPlatform.iOS
                    ? new CupertinoButton(
                        child: new Text("Send"),
                        onPressed: _isComposing
                            ? () => _handleSubmitted(text: _textController.text)
                            : null,
                      )
                    : new IconButton(
                        icon: new Icon(Icons.send),
                        onPressed: _isComposing
                            ? () => _handleSubmitted(text: _textController.text)
                            : null,
                      )),
          ]),
          decoration: Theme.of(context).platform == TargetPlatform.iOS
              ? new BoxDecoration(
                  border:
                      new Border(top: new BorderSide(color: Colors.grey[200])))
              : null),
    );
  }

  //Builds the actual chat screen with Scaffold
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new Text("Chat.here Gruppenchat"),
          centerTitle: true,
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0),
      body: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance
              .collection('nachrichten')
              .orderBy('timestamp', descending: true)
              .limit(20)
              .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (!snapshot.hasData) return Text('Loading data');
            final int documentsLength = snapshot.data.documents.length;
            return Container(
                child: Column(
                  children: <Widget>[
                    new Flexible(
                        child: new ListView.builder(
                      controller: _scrollController,
                      reverse: true,
                      itemCount: documentsLength,
                      itemBuilder: (context, int index) {
                        final DocumentSnapshot document =
                            snapshot.data.documents[index];
                        return new Container(
                          margin: const EdgeInsets.symmetric(
                              horizontal: 10.0, vertical: 10.0),
                          child: new Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              new Container(
                                margin: const EdgeInsets.only(right: 16.0),
                                child: new CircleAvatar(
                                    child: new Text(
                                        document['author'].substring(0, 1))),
                              ),
                              new Expanded(
                                child: new Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    new Row(
                                      children: <Widget>[
                                        new Text(document['author'],
                                            style: TextStyle(
                                                fontSize: 12.0,
                                                color: Colors.black45,
                                                fontWeight: FontWeight.bold)),
                                        new Text(
                                            ' ' +
                                                DateFormat("MMM. d. '|' HH:mm")
                                                    .format(
                                                        document['timestamp']),
                                            style: TextStyle(
                                                fontSize: 12.0,
                                                color: Colors.black45))
                                      ],
                                    ),

                                    //can be deleted. just to test the picture.
                                    (document['text'] == null)
                                        ? new Container(
                                            child: new ClipRRect(
                                              borderRadius:
                                                  new BorderRadius.circular(
                                                      7.0),
                                              child: CachedNetworkImage(
                                                placeholder: Container(
                                                  child:
                                                      CircularProgressIndicator(
                                                    valueColor:
                                                        AlwaysStoppedAnimation<
                                                                Color>(
                                                            Colors.orange),
                                                  ),
                                                  width: 200.0,
                                                  height: 200.0,
                                                  padding: EdgeInsets.all(70.0),
                                                  decoration: BoxDecoration(
                                                    color: Colors.blue,
                                                    borderRadius:
                                                        BorderRadius.all(
                                                      Radius.circular(8.0),
                                                    ),
                                                  ),
                                                ),
                                                imageUrl:
                                                    'https://wuppertal-total.de/wp-content/uploads/2019/01/stamp_schmidt_fdp.jpg',
                                                width: 200.0,
                                                height: 200.0,
                                                fit: BoxFit.cover,
                                              ),

                                            ),
                                            margin:
                                                EdgeInsets.only(right: 50.0),
                                          )

                                        : new Card(
                                            margin:
                                                EdgeInsets.only(right: 50.0),
                                            //green color for messages of yourself
                                            color:
                                                document['author'] == "Matthias"
                                                    ? Color.fromRGBO(
                                                        220, 255, 202, 1.0)
                                                    : null,
                                            child: new Container(
                                                padding: EdgeInsets.all(6.0),
                                                child: new Text(
                                                  document['text'],
                                                  style:
                                                      TextStyle(fontSize: 15.0),
                                                )),
                                            shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(7.0)),
                                          ),

                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    )),
                    new Divider(height: 1.0),
                    new Container(
                      decoration:
                          new BoxDecoration(color: Theme.of(context).cardColor),
                      child: _buildTextComposer(),
                    ),
                  ],
                ),
                decoration: Theme.of(context).platform == TargetPlatform.iOS
                    ? new BoxDecoration(
                        border: new Border(
                            top: new BorderSide(color: Colors.grey[200])))
                    : null);
          }),
    );
  }

  void _handleSubmitted({String text, String imageUrl}) {
    _textController.clear();
    setState(() {
      _isComposing = false;
    });

    //creation of an own document in Firestore
    Firestore.instance.runTransaction((Transaction transaction) async {
      CollectionReference reference =
          Firestore.instance.collection('nachrichten');

      await reference.add({
        "text": text,
        "author": "Matthias",
        "imageUrl": imageUrl,
        "timestamp": DateTime.now(),

        //"timestamp": FieldValue.serverTimestamp()
      });
    });

//Let the chat list jump to the newest chat message at the bottom
    _scrollController.animateTo(
      0.0,
      curve: Curves.easeOut,
      duration: const Duration(milliseconds: 300),
    );
  }

}
</code>```

答:
it worked for my case. I used cached_network_image: ^2.0.0

```<code>flutter clean
</code>```

Quit app on emulator, re-run the app.

Body:
First of all, I am a complete beginner (not only in dart/flutter), but in programming in general. I am currently working on a chat app.

Goal: When I am picking an image within the ChatScreen - analog to e.g. WhatsApp - it should immediately appear as a message (placeholder with loading symbol, while it is uploaded to Firestore).

Problem: Everything is working fine, but here is one issue: When I am picking an image via the imagepicker, it get's uploaded but there's a delay until it is displayed as a message in the chat. imagepicker -> write to Firestore -> Streambuilder
 (listView.builder).

My attempt: I am using CachedNetworkImage, but unfortunately, it keep's showing the placeholder (CircularProgressIndicator), but not the actual image. If I am just displaying the image, everything works fine (besides the delay).

Moreover, I would highly appreciate some ideas to make the app run faster / improve the code ;-).

//Chat screen which lists all the chat messages, including _handleSubmitted and the _buildTextComposer

import 'dart:math';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:intl/intl.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:flutter_image/network.dart';
import 'package:flutter_native_image/flutter_native_image.dart';

final database = Firestore.instance
    .collection('nachrichten')
    .document('G5xlQHvb56ZqpWs7ojUV');
final reference = FirebaseDatabase.instance.reference().child('messages');

class ChatScreen extends StatefulWidget {
  @override
  State createState() => new ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> with TickerProviderStateMixin {
  final TextEditingController _textController = new TextEditingController();
  final ScrollController _scrollController = new ScrollController();

  bool _isComposing = false;
  bool isLoading;
  String imageUrl;
  File imageFile;

  //optional from other code
  @override
  void initState() {
    super.initState();
    imageUrl = '';
  }

  Future getImage() async {
    imageFile = await ImagePicker.pickImage(source: ImageSource.camera);

    if (imageFile != null) {
      setState(() {
        isLoading = true;
      });
      uploadFile();
    }
  }

  Future uploadFile() async {
    //file compression
    File compressedFile = await FlutterNativeImage.compressImage(imageFile.path,
        quality: 100, percentage: 100);
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = reference.putFile(compressedFile);
    StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
    storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
      imageUrl = downloadUrl;
      setState(() {
        isLoading = false;
        _handleSubmitted(imageUrl: imageUrl);
      });
    }, onError: (err) {
      setState(() {
        isLoading = false;
      });
      Fluttertoast.showToast(msg: 'This file is not an image');
    });
  }

  //Builds the button text composer, including camera icon, text input and send button
  Widget _buildTextComposer() {
    return new IconTheme(
      data: new IconThemeData(color: Theme.of(context).accentColor),
      child: new Container(
          margin: const EdgeInsets.symmetric(horizontal: 0.80),
          child: new Row(children: <Widget>[
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 0.4),
              child: new IconButton(
                icon: new Icon(Icons.photo_camera),
                onPressed: getImage,
              ),
            ),
            new Flexible(
              child: Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                padding: EdgeInsets.all(10.0),
                decoration: new BoxDecoration(
                  border: Border.all(color: Colors.grey.shade200),
                  borderRadius: new BorderRadius.circular(20.0),
                ),

                //container with constraint limits the maximum height of the text input field
                child: new Container(
                  constraints: BoxConstraints.loose(Size.fromHeight(100.0)),
                  child: new TextField(
                    maxLines: null,
                    keyboardType: TextInputType.multiline,
                    controller: _textController,
                    onChanged: (String text) {
                      setState(() {
                        _isComposing = text.length > 0;
                      });
                    },
//                    onSubmitted: _handleSubmitted,
                    decoration: new InputDecoration.collapsed(
                        hintText: "Nachricht schreiben..."),
                  ),
                ),
              ),
            ),
            new Container(
                margin: new EdgeInsets.symmetric(horizontal: 0.4),
                child: Theme.of(context).platform == TargetPlatform.iOS
                    ? new CupertinoButton(
                        child: new Text("Send"),
                        onPressed: _isComposing
                            ? () => _handleSubmitted(text: _textController.text)
                            : null,
                      )
                    : new IconButton(
                        icon: new Icon(Icons.send),
                        onPressed: _isComposing
                            ? () => _handleSubmitted(text: _textController.text)
                            : null,
                      )),
          ]),
          decoration: Theme.of(context).platform == TargetPlatform.iOS
              ? new BoxDecoration(
                  border:
                      new Border(top: new BorderSide(color: Colors.grey[200])))
              : null),
    );
  }

  //Builds the actual chat screen with Scaffold
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new Text("Chat.here Gruppenchat"),
          centerTitle: true,
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0),
      body: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance
              .collection('nachrichten')
              .orderBy('timestamp', descending: true)
              .limit(20)
              .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (!snapshot.hasData) return Text('Loading data');
            final int documentsLength = snapshot.data.documents.length;
            return Container(
                child: Column(
                  children: <Widget>[
                    new Flexible(
                        child: new ListView.builder(
                      controller: _scrollController,
                      reverse: true,
                      itemCount: documentsLength,
                      itemBuilder: (context, int index) {
                        final DocumentSnapshot document =
                            snapshot.data.documents[index];
                        return new Container(
                          margin: const EdgeInsets.symmetric(
                              horizontal: 10.0, vertical: 10.0),
                          child: new Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              new Container(
                                margin: const EdgeInsets.only(right: 16.0),
                                child: new CircleAvatar(
                                    child: new Text(
                                        document['author'].substring(0, 1))),
                              ),
                              new Expanded(
                                child: new Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    new Row(
                                      children: <Widget>[
                                        new Text(document['author'],
                                            style: TextStyle(
                                                fontSize: 12.0,
                                                color: Colors.black45,
                                                fontWeight: FontWeight.bold)),
                                        new Text(
                                            ' ' +
                                                DateFormat("MMM. d. '|' HH:mm")
                                                    .format(
                                                        document['timestamp']),
                                            style: TextStyle(
                                                fontSize: 12.0,
                                                color: Colors.black45))
                                      ],
                                    ),

                                    //can be deleted. just to test the picture.
                                    (document['text'] == null)
                                        ? new Container(
                                            child: new ClipRRect(
                                              borderRadius:
                                                  new BorderRadius.circular(
                                                      7.0),
                                              child: CachedNetworkImage(
                                                placeholder: Container(
                                                  child:
                                                      CircularProgressIndicator(
                                                    valueColor:
                                                        AlwaysStoppedAnimation<
                                                                Color>(
                                                            Colors.orange),
                                                  ),
                                                  width: 200.0,
                                                  height: 200.0,
                                                  padding: EdgeInsets.all(70.0),
                                                  decoration: BoxDecoration(
                                                    color: Colors.blue,
                                                    borderRadius:
                                                        BorderRadius.all(
                                                      Radius.circular(8.0),
                                                    ),
                                                  ),
                                                ),
                                                imageUrl:
                                                    'https://wuppertal-total.de/wp-content/uploads/2019/01/stamp_schmidt_fdp.jpg',
                                                width: 200.0,
                                                height: 200.0,
                                                fit: BoxFit.cover,
                                              ),

                                            ),
                                            margin:
                                                EdgeInsets.only(right: 50.0),
                                          )

                                        : new Card(
                                            margin:
                                                EdgeInsets.only(right: 50.0),
                                            //green color for messages of yourself
                                            color:
                                                document['author'] == "Matthias"
                                                    ? Color.fromRGBO(
                                                        220, 255, 202, 1.0)
                                                    : null,
                                            child: new Container(
                                                padding: EdgeInsets.all(6.0),
                                                child: new Text(
                                                  document['text'],
                                                  style:
                                                      TextStyle(fontSize: 15.0),
                                                )),
                                            shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(7.0)),
                                          ),

                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    )),
                    new Divider(height: 1.0),
                    new Container(
                      decoration:
                          new BoxDecoration(color: Theme.of(context).cardColor),
                      child: _buildTextComposer(),
                    ),
                  ],
                ),
                decoration: Theme.of(context).platform == TargetPlatform.iOS
                    ? new BoxDecoration(
                        border: new Border(
                            top: new BorderSide(color: Colors.grey[200])))
                    : null);
          }),
    );
  }

  void _handleSubmitted({String text, String imageUrl}) {
    _textController.clear();
    setState(() {
      _isComposing = false;
    });

    //creation of an own document in Firestore
    Firestore.instance.runTransaction((Transaction transaction) async {
      CollectionReference reference =
          Firestore.instance.collection('nachrichten');

      await reference.add({
        "text": text,
        "author": "Matthias",
        "imageUrl": imageUrl,
        "timestamp": DateTime.now(),

        //"timestamp": FieldValue.serverTimestamp()
      });
    });

//Let the chat list jump to the newest chat message at the bottom
    _scrollController.animateTo(
      0.0,
      curve: Curves.easeOut,
      duration: const Duration(milliseconds: 300),
    );
  }

}

Body:
it worked for my case. I used cached_network_image: ^2.0.0

flutter clean

Quit app on emulator, re-run the app.