问:
Specified path for unstripped native libs is not a directory - generateCrashlyticsSymbolFileRelease
How I can define androidNdkOut and androidNdkLibsOut paths with new Firebase Crashlytics SDK?

When I try to run:
./gradlew clean assembleRelease uploadCrashlyticsSymbolFileRelease

I get next error:

```<code>Execution failed for task ':app:generateCrashlyticsSymbolFileRelease'.
> java.io.IOException: Specified path for unstripped native libs is not a directory: /Users/martin/repos/example-app-android/app/obj
</code>```

If I manually move all my NDK libs to ./app folder I get the same error with different path:

```<code>Execution failed for task ':app:generateCrashlyticsSymbolFileRelease'.
> java.io.IOException: Specified path for stripped native libs is not a directory: /Users/martin/repos/example-app-android/app/build/intermediates/transforms/stripDebugSymbol/release
</code>```

In this second case the build command sometimes fails, sometimes not.

This issue started to appear after I moved from Fabric Crashlytics plugin to Firebase Crashlytics plugin.
In the Fabric case, I had the option to define: androidNdkOut and androidNdkLibsOut paths.
Is that missing in the new Firebase plugin?

Relevant Code:

Old code example:

```<code>    crashlytics {
        enableNdk true
        androidNdkOut "$buildDir/ndklibs/obj"
        androidNdkLibsOut "$buildDir/ndklibs/libs"
    }
</code>```

New Code example:

```<code>            firebaseCrashlytics {
                nativeSymbolUploadEnabled true

            }
</code>```

答:
I got answer on this link in a meantime:
https://github.com/firebase/firebase-android-sdk/issues/1199#issuecomment-584680918

In the new Firebase Crashlytics plugin, the androidNdkOut and androidNdkLibsOut properties have been changed to strippedNativeLibsDir and unstrippedNativeLibsDir, and should be declared in firebaseCrashlytics within the variant block, where you declared nativeSymbolUploadEnabled true.

There is still the issue with the paths itself, you need to set relative paths for the strippedNativeLibsDir and unstrippedNativeLibsDir to your /app directory.
Example:
https://github.com/firebase/firebase-android-sdk/issues/1199#issuecomment-585262965

Body:
How I can define androidNdkOut and androidNdkLibsOut paths with new Firebase Crashlytics SDK?

When I try to run:
./gradlew clean assembleRelease uploadCrashlyticsSymbolFileRelease

I get next error:

Execution failed for task ':app:generateCrashlyticsSymbolFileRelease'.
> java.io.IOException: Specified path for unstripped native libs is not a directory: /Users/martin/repos/example-app-android/app/obj

If I manually move all my NDK libs to ./app folder I get the same error with different path:

Execution failed for task ':app:generateCrashlyticsSymbolFileRelease'.
> java.io.IOException: Specified path for stripped native libs is not a directory: /Users/martin/repos/example-app-android/app/build/intermediates/transforms/stripDebugSymbol/release

In this second case the build command sometimes fails, sometimes not.

This issue started to appear after I moved from Fabric Crashlytics plugin to Firebase Crashlytics plugin.
In the Fabric case, I had the option to define: androidNdkOut and androidNdkLibsOut paths.
Is that missing in the new Firebase plugin?

Relevant Code:

Old code example:

    crashlytics {
        enableNdk true
        androidNdkOut "$buildDir/ndklibs/obj"
        androidNdkLibsOut "$buildDir/ndklibs/libs"
    }

New Code example:

            firebaseCrashlytics {
                nativeSymbolUploadEnabled true

            }


来源: stackexchange

问:
Commonly used alias for sqlalchemy module when using import module_name as module_alias
For some libraries such as numpy and pandas we usually import them with the np and pd aliases.
I am asking whether there is a widely known alias for the sqlalchemy module in python as in

```<code>import module_name as module_alias
</code>```

I have already searched in google without great success:

```<code>site:docs.sqlalchemy.org "import sqlalchemy as"
</code>```

So far, I have seen some people are using these two:

```<code>import sqlalchemy as sa
import sqlalchemy as db
</code>```

答:
Despite in sqlalchemy they do not use it, in the alembic documentation it's often used import sqlalchemy as sa for importing sqlalchemy.

Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python.

ContentLicense: CC BY-SA 4.0

Body:
For some libraries such as numpy and pandas we usually import them with the np and pd aliases.
I am asking whether there is a widely known alias for the sqlalchemy module in python as in

import module_name as module_alias

I have already searched in google without great success:

site:docs.sqlalchemy.org "import sqlalchemy as"

So far, I have seen some people are using these two:

import sqlalchemy as sa
import sqlalchemy as db


问:
Making an image carousel using an Image Slider
I am making an image carousel using Android Image Slider with Glide and I'm trying to test if I can implement ArrayList when adding URLs to the adapter but when I add the URLs to the ArrayList, the other data doesn't show, only the last on the Array. It seems that I can't store the URLs to the SliderItem's value. Why is the other image not displaying on the Slider?

I used the default adapter of Android Image Slider: SliderAdapterExample.java.

Home.java

```<code>SliderItem sliderItem = new SliderItem();

    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));
    }

    adapter.addItem(sliderItem);
</code>```

SliderItem.java

```<code>public class SliderItem {
private String description;
private String imageUrl;

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}}
</code>```

Here is what I got for now. Only the last link works. See image below:

https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg

答:
You need to move adapter.addItem(sliderItem); within for loop.

```<code>    SliderItem sliderItem = new SliderItem();

    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));

        // here
        adapter.addItem(sliderItem);
    }
</code>```

or

```<code>    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        SliderItem sliderItem = new SliderItem();
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));

        // here
        adapter.addItem(sliderItem);
    }
</code>```

According to your code, you have three url, so you need three SliderItem.But if you put adapter.addItem(sliderItem); outside for loop, you can get last SliderItem only.

Additionally, everytime you add an item to adapter, you need to set adapter.notifyDataSetChanged() to addItem().

If my solution has any problem, please let me free to know.

Body:
I am making an image carousel using Android Image Slider with Glide and I'm trying to test if I can implement ArrayList when adding URLs to the adapter but when I add the URLs to the ArrayList, the other data doesn't show, only the last on the Array. It seems that I can't store the URLs to the SliderItem's value. Why is the other image not displaying on the Slider?

I used the default adapter of Android Image Slider: SliderAdapterExample.java.

Home.java

SliderItem sliderItem = new SliderItem();

    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));
    }

    adapter.addItem(sliderItem);

SliderItem.java

public class SliderItem {
private String description;
private String imageUrl;

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}}

Here is what I got for now. Only the last link works. See image below:

https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg

Body:
You need to move adapter.addItem(sliderItem); within for loop.

    SliderItem sliderItem = new SliderItem();

    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));

        // here
        adapter.addItem(sliderItem);
    }

or

    ArrayList<String> urls = new ArrayList<>();
    urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
    urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
    urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");

    for(int i = 0; i < urls.size(); i++){
        SliderItem sliderItem = new SliderItem();
        sliderItem.setDescription("Slider Item Added Manually");
        sliderItem.setImageUrl(urls.get(i));

        // here
        adapter.addItem(sliderItem);
    }

According to your code, you have three url, so you need three SliderItem.But if you put adapter.addItem(sliderItem); outside for loop, you can get last SliderItem only.

Additionally, everytime you add an item to adapter, you need to set adapter.notifyDataSetChanged() to addItem().

If my solution has any problem, please let me free to know.


问:
Kibana deployed to kubernetes cluster returns 404
I have kibana deployed to kubernetes cluster as StatefulSet. However, when pointing my browser to the kibana, it returns {"statusCode":404,"error":"Not Found","message":"Not Found"}. Any advice and insight is appreciated. Here is the log that I see in the pod when accessing the application at the browser using http://app.domain.io/kibana

```<code>{"type":"response","@timestamp":"2019-01-29T04:18:50Z","tags":[],"pid":1,"method":"get","statusCode":404,"req":{"url":"/kibana","method":"get","headers":{"x-forwarded-for":"[IP]","x-forwarded-proto":"https","x-forwarded-port":"443","host":"[host]","x-amzn-trace-id":"Root=1-5c4fd42a-1261c1e0474144902a2d6840","cache-control":"max-age=0","upgrade-insecure-requests":"1","user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","accept-encoding":"gzip, deflate, br","accept-language":"en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ko;q=0.5"},"remoteAddress":"[IP]","userAgent":"10.0.2.185"},"res":{"statusCode":404,"responseTime":19,"contentLength":9},"message":"GET /kibana 404 19ms - 9.0B"}
</code>```

```<code>apiVersion: v1
kind: Service
metadata:
  name: svc-kibana
  labels:
    app: app-kibana
spec:
  selector:
    app: app-kibana
#    tier: database
  ports:
  - name: kibana
    protocol: TCP
    port: 8080
    targetPort: 5601
  clusterIP: None # Headless
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: kibana
spec:
  serviceName: "svc-kibana"
  podManagementPolicy: "Parallel" # Default is OrderedReady
  replicas: 1 # Default is 1
  selector:
    matchLabels:
      app: app-kibana # Has to match .spec.template.metadata.labels
  template:
    metadata:
      labels:
        app: app-kibana # Has to match .spec.selector.matchLabels
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: kibana
        securityContext:
          capabilities:
            add:
              - IPC_LOCK
              - SYS_RESOURCE
        image: kibana:6.5.4
        imagePullPolicy: Always
        env:
        - name: ELASTICSEARCH_URL
          value: http://svc-elasticsearch:9200
        - name: SERVER_BASEPATH
          value: /api/v1/namespaces/default/services/svc-kibana/proxy
        ports:
        - containerPort: 5601
          name: kibana
          protocol: TCP
</code>```

Here is the healthcheck from AWS ALB:

```<code>{"type":"response","@timestamp":"2019-01-29T06:30:53Z","tags":[],"pid":1,"method":"get","statusCode":200,"req":{"url":"/app/kibana","method":"get","headers":{"host":"[IP]:5601","connection":"close","user-agent":"ELB-HealthChecker/2.0","accept-encoding":"gzip, compressed"},"remoteAddress":"[IP]","userAgent":"[IP]"},"res":{"statusCode":200,"responseTime":27,"contentLength":9},"message":"GET /app/kibana 200 27ms - 9.0B"}
</code>```

I tried to remove the ENV values and use ConfigMap mounted on /etc/kibana/kibana.yml with the following config but to no avail:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: "2019-01-29T02:12:55Z"
  name: kibana-config
  namespace: default
  resourceVersion: "4178388"
  selfLink: /api/v1/namespaces/default/configmaps/kibana-config
  uid: 63b10866-236b-11e9-a14d-482ae31e6a94
data:
  kibana.yml: |+
    server.port: 5601
    server.host: "0.0.0.0"
    elasticsearch.url: "http://svc-elasticsearch:9200"
    kibana.index: ".kibana"
    logging.silent: false
    logging.quiet: false
    logging.verbose: true
</code>```

答:
I was facing the same issue in the kubernetes cluster where the kibana was running behind the nginx proxy.

```<code>DNS: https://my-url/dashboard

Nginx conf:

     location /dashboard/ {
          rewrite ^/dashboard/(.*) /$1 break;
          proxy_pass http://kibana:5601/;
</code>```

After adding the above suggested parameters by Kok How teh in the kibana.yml

```<code>kibana.yml:
 server.name: kibana
 server.host: "0"
 elasticsearch.url: http://elasticsearch:9200
 server.basePath: "/dashboard"   #this line
</code>```

was able to resolve the redirection issue.

Body:
I have kibana deployed to kubernetes cluster as StatefulSet. However, when pointing my browser to the kibana, it returns {"statusCode":404,"error":"Not Found","message":"Not Found"}. Any advice and insight is appreciated. Here is the log that I see in the pod when accessing the application at the browser using http://app.domain.io/kibana

{"type":"response","@timestamp":"2019-01-29T04:18:50Z","tags":[],"pid":1,"method":"get","statusCode":404,"req":{"url":"/kibana","method":"get","headers":{"x-forwarded-for":"[IP]","x-forwarded-proto":"https","x-forwarded-port":"443","host":"[host]","x-amzn-trace-id":"Root=1-5c4fd42a-1261c1e0474144902a2d6840","cache-control":"max-age=0","upgrade-insecure-requests":"1","user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","accept-encoding":"gzip, deflate, br","accept-language":"en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ko;q=0.5"},"remoteAddress":"[IP]","userAgent":"10.0.2.185"},"res":{"statusCode":404,"responseTime":19,"contentLength":9},"message":"GET /kibana 404 19ms - 9.0B"}

apiVersion: v1
kind: Service
metadata:
  name: svc-kibana
  labels:
    app: app-kibana
spec:
  selector:
    app: app-kibana
#    tier: database
  ports:
  - name: kibana
    protocol: TCP
    port: 8080
    targetPort: 5601
  clusterIP: None # Headless
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: kibana
spec:
  serviceName: "svc-kibana"
  podManagementPolicy: "Parallel" # Default is OrderedReady
  replicas: 1 # Default is 1
  selector:
    matchLabels:
      app: app-kibana # Has to match .spec.template.metadata.labels
  template:
    metadata:
      labels:
        app: app-kibana # Has to match .spec.selector.matchLabels
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: kibana
        securityContext:
          capabilities:
            add:
              - IPC_LOCK
              - SYS_RESOURCE
        image: kibana:6.5.4
        imagePullPolicy: Always
        env:
        - name: ELASTICSEARCH_URL
          value: http://svc-elasticsearch:9200
        - name: SERVER_BASEPATH
          value: /api/v1/namespaces/default/services/svc-kibana/proxy
        ports:
        - containerPort: 5601
          name: kibana
          protocol: TCP

Here is the healthcheck from AWS ALB:

{"type":"response","@timestamp":"2019-01-29T06:30:53Z","tags":[],"pid":1,"method":"get","statusCode":200,"req":{"url":"/app/kibana","method":"get","headers":{"host":"[IP]:5601","connection":"close","user-agent":"ELB-HealthChecker/2.0","accept-encoding":"gzip, compressed"},"remoteAddress":"[IP]","userAgent":"[IP]"},"res":{"statusCode":200,"responseTime":27,"contentLength":9},"message":"GET /app/kibana 200 27ms - 9.0B"}

I tried to remove the ENV values and use ConfigMap mounted on /etc/kibana/kibana.yml with the following config but to no avail:

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: "2019-01-29T02:12:55Z"
  name: kibana-config
  namespace: default
  resourceVersion: "4178388"
  selfLink: /api/v1/namespaces/default/configmaps/kibana-config
  uid: 63b10866-236b-11e9-a14d-482ae31e6a94
data:
  kibana.yml: |+
    server.port: 5601
    server.host: "0.0.0.0"
    elasticsearch.url: "http://svc-elasticsearch:9200"
    kibana.index: ".kibana"
    logging.silent: false
    logging.quiet: false
    logging.verbose: true

Body:
I was facing the same issue in the kubernetes cluster where the kibana was running behind the nginx proxy.

DNS: https://my-url/dashboard

Nginx conf:

     location /dashboard/ {
          rewrite ^/dashboard/(.*) /$1 break;
          proxy_pass http://kibana:5601/;

After adding the above suggested parameters by Kok How teh in the kibana.yml

kibana.yml:
 server.name: kibana
 server.host: "0"
 elasticsearch.url: http://elasticsearch:9200
 server.basePath: "/dashboard"   #this line

was able to resolve the redirection issue.


问:
app.yaml cannot locate entry point after changing main.py into __init__.py
I followed this Large Flask Applications tutorial and changed my main.py into __init__.py. Now, running the app locally uses flask run instead of python main.py.

The problem: when I deploy the app, I get a 502 Bad Gateway error obviously. I know that, by default, App Engine will look for the main.py file as an entry point.

But now that the entry point has changed, what can I do?

Can Google App Engine work with large Flask apps?

答:
As per the documentation The Python Runtime, you can change the entrypoint value in the app.yaml file, so it would redirect your __init__.py file.

Besides that, I would recommend you to take a look at the following links, where there is more information, regarding building and developing an application with Python and Flask.

Building a Python 3.7 App on App Engine

Python App Engine 2017: Building a simple Flask app

These links should provide a good overview of development with these two applications, which should cover how to avoid such errors that you are facing.

Let me know if the information helped you!


问:
template with specified mode does not match problem
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

```<code><xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>
</code>```

But the template for this mode does not match:

```<code><xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...
</code>```

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

```<code><xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>
</code>```

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

```<code><?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">
            <body>
                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">
                        <section label="menuetto_A" xml:id="section_A_m1-5">
                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>
                        </section>
                    </score>
                </mdiv>
            </body>
        </music>
    </mei>
</code>```

I am expecting a sequence of @xml:id-values which I derive from my calculations.

答: As far as I can tell from the code fragments supplied, you have not defined any "fallback" template for the mode checkAccidentalsVisibility, therefore when you apply-templates to a document node in this mode, the built-in template rules kick in, and the default rule for elements uses apply-templates to process the children of the element but not its attributes. So attributes don't get processed.

Body:
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

<xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>

But the template for this mode does not match:

<xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

<xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

<?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">

                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">

                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>

                    </score>
                </mdiv>

        </music>
    </mei>

I am expecting a sequence of @xml:id-values which I derive from my calculations.


问:
Remove specific cookie from session python requests
Remove specific cookie from session python requests.

Only found

```<code>s.cookies.clear()
</code>```

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']

答:
From view of how cookie works on web, we should remove specific cookie in response, not from  request. Every time browser get a response from a server, it updates his cookie with cookie header in response.
So the answer is :</p>

```<code>response.delete_cookie(cookie_name)
</code>```

Body:
Remove specific cookie from session python requests.

Only found

s.cookies.clear()

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']

Body:
From view of how cookie works on web, we should remove specific cookie in response, not from  request. Every time browser get a response from a server, it updates his cookie with cookie header in response.
So the answer is :

response.delete_cookie(cookie_name)


问:
"Cannot find module" when importing .csv file in Create React App
I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.

I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.

The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).

I am using TypeScript but I don't think this has anything to do with the problem.

```<code>import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';

const BarChart: React.FC = () => {
  d3.csv(CSVData).then(res => {
    console.log(res);
  });
  return <div>Test</div>;
};

export default BarChart;
</code>```

答:
Thanks to Nick Ribal for his answer, I found a similar solution by moving my data file into the public folder and then referencing this via the PUBLIC_URL environment variable.

I used the D3 CSV method which will get data from a URL if passed one rather than using fetch and parsing this as text.

With D3 CSV method:

```<code>import React, { useState } from 'react';
import { DSVRowArray } from 'd3';
import * as d3 from 'd3';

type CSVData = DSVRowArray | null;

const BarChart: React.FC = () => {
  const initialState: CSVData = null;
  const [fetchedCSVData, setFetchedCSVdata] = useState<CSVData>(initialState);

  if (!fetchedCSVData) {
    d3.csv(`${process.env.PUBLIC_URL}/data/data.csv`).then(res => {
      setFetchedCSVdata(res);
    });
  }
  return <div>Test</div>;
};

export default BarChart;
</code>```

Without D3 CSV method:

```<code>import React, { useState } from 'react';

type CSVData = string | null;

const BarChart: React.FC = () => {
  const initialState: CSVData = null;
  const [fetchedCSVData, setFetchedCSVData] = useState<CSVData>(initialState);

  if (!fetchedCSVData) {
    fetch(`${process.env.PUBLIC_URL}/data/data.csv`)
      .then(res => res.text())
      .then(stringData => {
        console.log(stringData);
        setFetchedCSVData(stringData);
      });
  }

  return <div>Test</div>;
};

export default BarChart;
</code>```

Body:
I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.

I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.

The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).

I am using TypeScript but I don't think this has anything to do with the problem.

import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';

const BarChart: React.FC = () => {
  d3.csv(CSVData).then(res => {
    console.log(res);
  });
  return
Test
;
};

export default BarChart;

Body:
Thanks to Nick Ribal for his answer, I found a similar solution by moving my data file into the public folder and then referencing this via the PUBLIC_URL environment variable.

I used the D3 CSV method which will get data from a URL if passed one rather than using fetch and parsing this as text.

With D3 CSV method:

import React, { useState } from 'react';
import { DSVRowArray } from 'd3';
import * as d3 from 'd3';

type CSVData = DSVRowArray | null;

const BarChart: React.FC = () => {
  const initialState: CSVData = null;
  const [fetchedCSVData, setFetchedCSVdata] = useState<CSVData>(initialState);

  if (!fetchedCSVData) {
    d3.csv(`${process.env.PUBLIC_URL}/data/data.csv`).then(res => {
      setFetchedCSVdata(res);
    });
  }
  return <div>Test</div>;
};

export default BarChart;

Without D3 CSV method:

import React, { useState } from 'react';

type CSVData = string | null;

const BarChart: React.FC = () => {
  const initialState: CSVData = null;
  const [fetchedCSVData, setFetchedCSVData] = useState<CSVData>(initialState);

  if (!fetchedCSVData) {
    fetch(`${process.env.PUBLIC_URL}/data/data.csv`)
      .then(res => res.text())
      .then(stringData => {
        console.log(stringData);
        setFetchedCSVData(stringData);
      });
  }

  return <div>Test</div>;
};

export default BarChart;


问:
Update inner object element in Json using Gson
I have below json and need to update elements, below code works for elements in top level, How can I extend this to work it inside another inner level (object).

Json:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  }
}
</code>```

In below code I am passing below

eg.
keyPath = "headerId"
updateText = "123456"
jsonText = above json

Code :

```<code>public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for(String key : keys)
    {
        if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject())
        {
            jsonObject = (JsonObject)jsonObject.get(key);
        }
    }
    jsonObject.remove(finalKey);
    jsonObject.add(finalKey, jp);
    return returnVal.toString();
}
</code>```

Code

Expected out put json:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "123456",
    "queue": "draft",
  }
}
</code>```

Actual reult:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  },
  "headerId": "123456",
}
</code>```

答:
Updated code slightly and pass parameters as suggested by @Smile answer

```<code>keyPath : reqParams/headerId
          someId (if exist in root level)
</code>```

Code :

```<code>public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for (String key : keys) {

    if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject()) {
        jsonObject = (JsonObject) jsonObject.get(key);
        jsonObject.remove(finalKey);
        jsonObject.add(finalKey, jp);
        return returnVal.toString();
    } else if (jsonObject.get(finalKey) == null) {
        return returnVal.toString();
    }
}

jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
</code>```

}

Body:
I have below json and need to update elements, below code works for elements in top level, How can I extend this to work it inside another inner level (object).

Json:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  }
}

In below code I am passing below

eg.
keyPath = "headerId"
updateText = "123456"
jsonText = above json

Code :

public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for(String key : keys)
    {
        if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject())
        {
            jsonObject = (JsonObject)jsonObject.get(key);
        }
    }
    jsonObject.remove(finalKey);
    jsonObject.add(finalKey, jp);
    return returnVal.toString();
}

Code

Expected out put json:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "123456",
    "queue": "draft",
  }
}

Actual reult:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  },
  "headerId": "123456",
}

Body:
Updated code slightly and pass parameters as suggested by @Smile answer

keyPath : reqParams/headerId
          someId (if exist in root level)

Code :

public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for (String key : keys) {

    if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject()) {
        jsonObject = (JsonObject) jsonObject.get(key);
        jsonObject.remove(finalKey);
        jsonObject.add(finalKey, jp);
        return returnVal.toString();
    } else if (jsonObject.get(finalKey) == null) {
        return returnVal.toString();
    }
}

jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();

}


问:
How to import css file from assets folder in nuxt.js
```<code><template>
  <div class="container">
    <head>
      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />
    </head>
  </div>
</template>
</code>```

Importing css like above results in this error

```<code>vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)
</code>```

Is there really no other way loading css other than putting the whole css in the template?

答:
try to impot your css files in script like this :

```<code><script>
import "@/assets/css/style-light.css";
import "@/assets/css/login-light.css";

///

</script>
</code>```

EDIT: changed ~ to @

Body:
<template>

      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />

</template>

Importing css like above results in this error

vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)

Is there really no other way loading css other than putting the whole css in the template?

Body:
try to impot your css files in script like this :

<script>
import "@/assets/css/style-light.css";
import "@/assets/css/login-light.css";

///

</script>

EDIT: changed ~ to @


问:
Retrieving a video's play-time that is embedded in an R Shiny app
I am trying to embed a video in a Shiny app and have an action button that, when pressed, records the play-time of the video. For the purposes of this questions I really just want to paste/renderText the play-time on the screen. I am using the code below to get the video in and I have seen ways to accomplish this entirely in HTML but can't seem to get it to work in Shiny.</p>

```<code>library(shiny)
library(tidyverse)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),

  tags$video(src = "my_video.mp4", type = "viedo/mp4", width = "500px", height = "300px", controls = "controls"),
  actionButton(inputId = "get_time", label = "Get Time"),
  textOutput("currentTime")
)

server <- function(input, output, session) {

}

shinyApp(ui, server)
</code>```

答:
Here is a way.</p>

```<code>library(shiny)

js <-
  "Shiny.setInputValue('time', document.getElementById('myVideo').currentTime);"

ui <- fluidPage(

  tags$video(id = "myVideo", src = "my_video.mp4", type = "video/mp4",
             width = "500px", height = "300px", controls = "controls"),
  actionButton(inputId = "get_time", label = "Get Time", onclick = js),
  textOutput("currentTime")
)

server <- function(input, output, session) {

  output[["currentTime"]] <- renderText({
    input[["time"]]
  })

}

shinyApp(ui, server)
</code>```

Body:
I am trying to embed a video in a Shiny app and have an action button that, when pressed, records the play-time of the video. For the purposes of this questions I really just want to paste/renderText the play-time on the screen. I am using the code below to get the video in and I have seen ways to accomplish this entirely in HTML but can't seem to get it to work in Shiny.

library(shiny)
library(tidyverse)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),

  tags$video(src = "my_video.mp4", type = "viedo/mp4", width = "500px", height = "300px", controls = "controls"),
  actionButton(inputId = "get_time", label = "Get Time"),
  textOutput("currentTime")
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

Body:
Here is a way.

library(shiny)

js <-
  "Shiny.setInputValue('time', document.getElementById('myVideo').currentTime);"

ui <- fluidPage(

  tags$video(id = "myVideo", src = "my_video.mp4", type = "video/mp4",
             width = "500px", height = "300px", controls = "controls"),
  actionButton(inputId = "get_time", label = "Get Time", onclick = js),
  textOutput("currentTime")
)

server <- function(input, output, session) {

  output[["currentTime"]] <- renderText({
    input[["time"]]
  })

}

shinyApp(ui, server)


问:
MySQL - conditionally add values from different tables?
Assume 3 tables:

Table 1 has information about a product's price (e.g. the base price)

Table 2 has information about a product's additional price factors (e.g. taxes, discounts, etc.)

Table 3 has flags indicating if Table 1 or Table 2 or both tables should be used in computing the product's total price

Is it possible in MySQL to compute the sum in this situation? If so, some guidance on the query would be appreciated.

答:
You could use MySQL's CASE or IF for your purpose, for example something like this:

```<code>SELECT IF(c.flag = ?, a.price + b.taxes - b.discount, a.price)
FROM <Table 1> AS a
JOIN <Table 2> AS b ON <what ever>
JOIN <Table 3> AS c ON <what ever>
</code>```

If I'd had the table definition, I'd be able to post a more concrete example. But, maybe, if you have a look at the documentation of CASE and IF, you could figure out your own solution.

ContentLicense: CC BY-SA 3.0

Body:
You could use MySQL's CASE or IF for your purpose, for example something like this:

SELECT IF(c.flag = ?, a.price + b.taxes - b.discount, a.price)
FROM <Table 1> AS a
JOIN <Table 2> AS b ON <what ever>
JOIN <Table 3> AS c ON <what ever>

If I'd had the table definition, I'd be able to post a more concrete example. But, maybe, if you have a look at the documentation of CASE and IF, you could figure out your own solution.


问:
Manipulating array of objects into new array
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]
```

<p>From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.</p>

<p>The first value would be a default value call <code>DATE</code> followed by each product name.</p>

```var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]
```

<p>I managed to create this by doing the following </p>

```var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});
```

<p>The second array should be in this format:</p>

```var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];
```

<p>As you can see, on <code>Feb 1</code> we have a value for all products sold but on <code>Feb 2</code> it's only <code>PROD1</code>. Likewise on <code>Feb 3</code> only <code>PROD2</code> and <code>PROD3</code>. </p>

<p>Each row col should match the first array like bellow</p>

<p><img src="https://i.stack.imgur.com/uegg3.png" alt="enter image description here"></p>

<p>desired output of two arrays as bellow</p>

```         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];
```

答:
You could get an object with the indices for the columns and reduce the given data by looking up the right row and update the value for a certain column.

var data = [{ DATE: "2020-02-01", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "845" }, { DATE: "2020-02-01", PRODUCT_NAME: "PROD2", PRODUCT_QUANTITY_MT: "1002" }, { DATE: "2020-02-01", PRODUCT_NAME: "PROD3", PRODUCT_QUANTITY_MT: "45" }, { DATE: "2020-02-02", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "20" }, { DATE: "2020-02-03", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "10" }, { DATE: "2020-02-03", PRODUCT_NAME: "PROD2", PRODUCT_QUANTITY_MT: "230" }],
    final = [{ title: "DATE" }, { title: "PROD1" }, { title: "PROD2" }, { title: "PROD3" }],
    cols = final.reduce((r, { title }, i) => (r[title] = i, r), {}),
    result = data.reduce((r, { DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT }) => {
        var row = r.find(q => q[0] === DATE);
        if (!row) r.push(row = Array.from({ length: final.length }, (_, i) => i ? '' : DATE));
        row[cols[PRODUCT_NAME]] = PRODUCT_QUANTITY_MT;
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.

The first value would be a default value call DATE followed by each product name.

var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]

I managed to create this by doing the following

var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});

The second array should be in this format:

var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];

As you can see, on Feb 1 we have a value for all products sold but on Feb 2 it's only PROD1. Likewise on Feb 3 only PROD2 and PROD3.

Each row col should match the first array like bellow

desired output of two arrays as bellow

         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];

Body:
You could get an object with the indices for the columns and reduce the given data by looking up the right row and update the value for a certain column.

var data = [{ DATE: "2020-02-01", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "845" }, { DATE: "2020-02-01", PRODUCT_NAME: "PROD2", PRODUCT_QUANTITY_MT: "1002" }, { DATE: "2020-02-01", PRODUCT_NAME: "PROD3", PRODUCT_QUANTITY_MT: "45" }, { DATE: "2020-02-02", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "20" }, { DATE: "2020-02-03", PRODUCT_NAME: "PROD1", PRODUCT_QUANTITY_MT: "10" }, { DATE: "2020-02-03", PRODUCT_NAME: "PROD2", PRODUCT_QUANTITY_MT: "230" }],
    final = [{ title: "DATE" }, { title: "PROD1" }, { title: "PROD2" }, { title: "PROD3" }],
    cols = final.reduce((r, { title }, i) => (r[title] = i, r), {}),
    result = data.reduce((r, { DATE, PRODUCT_NAME, PRODUCT_QUANTITY_MT }) => {
        var row = r.find(q => q[0] === DATE);
        if (!row) r.push(row = Array.from({ length: final.length }, (_, i) => i ? '' : DATE));
        row[cols[PRODUCT_NAME]] = PRODUCT_QUANTITY_MT;
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Is the rule of ReactJS re-rendering just: if the state of component changes, then the whole sub-tree is re-rendered?
First of all, by "re-render", here it means either

the render() method of any class component is called, OR

the function of the function component is called.

Let's called the element in the actual DOM changing a "refresh", to distinguish it from "re-render".

Is the rule of "re-render" as simple as:

When any state of a component is changed, then the component and all the subtree down from this component is re-rendered

and that's it?  For example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

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

Component A is so simple: it doesn't even take any props and is just outputting static text, yet it is still called every time (by looking at the console.log() output).

But even though it is "re-rendered", the actual DOM element is not "refreshed", as seen in Google Chrome's Inspect Element that the DOM element is not flashing for Component A, but is only flashing for the counter number.

So is this how it works?

Whenever any state of a component is changed, that component and the whole subtree will be "re-rendered".

But ReactJS will "reconcile" the content of the "Virtual DOM" that it built using those JSX with the content of the actual DOM, and if the content is different, "refresh the actual DOM".

But having said that, it seems ReactJS doesn't actually reconcile with the actual DOM, but reconcile with probably the "previous virtual DOM". Why?  Because if I use a setTimeout() to change the actual DOM of Component A to some other content after 3 seconds, and click the button, ReactJS doesn't change the content of Component A back to "Hello World". Example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

setTimeout(function() {
  document.querySelector("#foo").innerText = "hi"
}, 3000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

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

答:
This is to answer the WHY part of your question -

As explained in this link - https://gist.github.com/paulirish/5d52fb081b3570c81e3a, many things can trigger reflow of the DOM. Not just setting, even accessing the DOM element properties can cause reflow of DOM which is a very costly process.

So, if React starts comparing against the actual DOM, then it will bring down the performance of rendering rather than improving it. This is why react compares changes with previous copy and update the changes to the Actual DOM if required.

Body:
First of all, by "re-render", here it means either

the render() method of any class component is called, OR

the function of the function component is called.

Let's called the element in the actual DOM changing a "refresh", to distinguish it from "re-render".

Is the rule of "re-render" as simple as:

When any state of a component is changed, then the component and all the subtree down from this component is re-rendered

and that's it?  For example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

Component A is so simple: it doesn't even take any props and is just outputting static text, yet it is still called every time (by looking at the console.log() output).

But even though it is "re-rendered", the actual DOM element is not "refreshed", as seen in Google Chrome's Inspect Element that the DOM element is not flashing for Component A, but is only flashing for the counter number.

So is this how it works?

Whenever any state of a component is changed, that component and the whole subtree will be "re-rendered".

But ReactJS will "reconcile" the content of the "Virtual DOM" that it built using those JSX with the content of the actual DOM, and if the content is different, "refresh the actual DOM".

But having said that, it seems ReactJS doesn't actually reconcile with the actual DOM, but reconcile with probably the "previous virtual DOM". Why?  Because if I use a setTimeout() to change the actual DOM of Component A to some other content after 3 seconds, and click the button, ReactJS doesn't change the content of Component A back to "Hello World". Example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

setTimeout(function() {
  document.querySelector("#foo").innerText = "hi"
}, 3000);


问:
STRAPI is cutting the last 3 chars
I'm using the strapi 3.0.0-beta.15
DB - mongo 4.2.2

After updating one of model fields - which is type of 'text', it is cutting the last three chars and set it to '000'. Saw this only if there are numbers at field.

Writting text (before saving

After saving

Did anyone have stacked with such problems yet?

答:
This issue has been fixed in the last version of Strapi (at least beta.18)

I suggest you update your application using a migration guide if necessary, or, using the application update guide that is into the documentation.

Here is what I did in a short video - https://www.loom.com/share/23076126176546708f9dcaa7eac1924c

Title: STRAPI is cutting the last 3 chars


问:
How this c++ code runs without definition of function
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.</p>

```<code>#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}
</code>```

答:
Declaring using namespace std; means that you are using all the functions inside the namespace std. Now, in your code you have your own version of swapfunction which is void swap(int *a, int *b).

The program worked fine in coincidence, because the namespace std has pre-defined function of swap() that accepts integers. Without this, your program will not work as your function created takes a pointer. That means, you need to pass the address of the variable swap(&var1, &var2).

This is called Function Overloading. It finds the correct function that fits based on the parameters.

Hint: Avoid using using namespace std; as it will have problem(collisions) in bigger projects if you're not keen to your created functions.

Body:
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.

#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}


问:
Attach screenshot to cucumber-html-reporter using cucumber-tsflow and protractor
After every failed scenario, I would like to attach a screenshot to html report (generated by cucumber-html-reporter, using cucumber-tsflow and protractor. Is that possible?

As far as I understand, I don't have access to the world instance anymore when writing the steps using cucumber-tsflow. Otherwise something like this.attach(screenshot, 'image/png'); would have done the trick.

After googling for a while, I saw some people attaching the screenshot to the scenario like scenario.attach(screenshot);. However, the scenario I get in @after()(hook) is an instance of HookScenarioResult. That interface does not have any method to attach a file to.

I placed a simplified snippet code of the step.ts and conf.ts below. I tried to attach the screenshot in the afterAllScenarios() method with no succes. Hopefully someone can help me out with my problem.

samplestep-definition.ts

import { binding, given, then, when, before, after } from 'cucumber-tsflow';
import { browser } from 'protractor';
import { expect } from 'chai';
import { HookScenarioResult, Status } from 'cucumber';

import HomePage from './page-objects/home-page';

@binding()
export class HomePageSteps {
    private homePage = new HomePage();

    @before()
    public beforeAllScenarios(): void {
        browser.manage().window().maximize();
    }

    @given(/the user is at the home page/)
    public async givenUserAtHomePage(): Promise<void> {
        await this.homePage.get();
        const actual = await browser.getCurrentUrl();
        const expected = 'https://qaclickacademy.github.io/protocommerce/';
        expect(actual).to.equal(expected);
    }

    @when(/the user enters (.*) in the name field/)
    public async userEntersNameField(input: string): Promise<void> {
        await this.homePage.typeNameAndTab(input);
    }

    @then(/the user should see error message (.*)/)
    public async useShouldSeeErrorMessage(message: string) {
        const errorMessage = await this.homePage.getErrorMessage();
        expect(errorMessage).to.equal(message);
    }

    @after()
    public async afterAllScenarios(scenario: HookScenarioResult): Promise<void> {
        if (scenario.result.status === Status.PASSED) {
            const screenshot = await browser.takeScreenshot();
            // No access to World instance so the code below won't work
            this.attach(screenshot, "image/png");

            // HookScenario has no attach method, so the code below won't work
            scenario.attach(screenshot);
        }
    }
}
```

<p><strong>cucumber-config.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Config } from 'protractor';
import * as reporter from 'cucumber-html-reporter';

// An example configuration file
export let config: Config = {
  directConnect: true,
  framework: 'custom',
  frameworkPath: require.resolve('protractor-cucumber-framework'),
  capabilities: {
    browserName: 'chrome'
  },
  specs: ['../features/sample.feature'],

  cucumberOpts: {
    format: 'json:./report/cucumber_report.json',
    tags: [
      '@smoketesting'
    ]
  },

  onComplete: () => {
    console.log('on complete called');
    var options = {
      theme: 'bootstrap',
      jsonFile: './report/cucumber_report.json',
      output: './report/cucumber_report.html',
      reportSuiteAsScenarios: true,
      scenarioTimestamp: true,
      launchReport: true,
      metadata: {
        "App Version": "0.3.2"
      }
    };

    reporter.generate(options);
  }
};
</code>```

答:
If you have a custom World you need to make sure that the constructor utilize the attach property. I don't know how it's done with cucumber-tsflow, but cucumberjs which used internally by cucumber-tsflow need the attach parameter like this :

function World({ attach }) {
  this.attach = attach
}
```
<ol start="2">
<li>We use a custom world in typescript for our Angular E2E test app
Here's a cut of the file</li>
</ol>
<pre class="lang-js prettyprint-override"><code>// world.ts
const { setWorldConstructor } = require('cucumber');

export class World {
  private attach: (buffer: Buffer, mimeType: string) => void;
  constructor({ attach }) {
    this.attach = attach;
  }
}
</code>```

And then in the hook.ts

import { browser } from 'protractor';
import { HookScenarioResult } from 'cucumber';
const { Before, After } = require('cucumber');

// hook.ts
After(async function(scenario: HookScenarioResult) {
  const ss = await browser.takeScreenshot();
  const img = Buffer.alloc(ss.length, ss, 'base64');
  this.attach(img, 'image/png');
});
```

Also, apparently you have a way to use the world's constructor parameter: https://github.com/timjroberts/cucumber-js-tsflow/issues/16

Body:
After every failed scenario, I would like to attach a screenshot to html report (generated by cucumber-html-reporter, using cucumber-tsflow and protractor. Is that possible?

As far as I understand, I don't have access to the world instance anymore when writing the steps using cucumber-tsflow. Otherwise something like this.attach(screenshot, 'image/png'); would have done the trick.

After googling for a while, I saw some people attaching the screenshot to the scenario like scenario.attach(screenshot);. However, the scenario I get in @after()(hook) is an instance of HookScenarioResult. That interface does not have any method to attach a file to.

I placed a simplified snippet code of the step.ts and conf.ts below. I tried to attach the screenshot in the afterAllScenarios() method with no succes. Hopefully someone can help me out with my problem.

samplestep-definition.ts

import { binding, given, then, when, before, after } from 'cucumber-tsflow';
import { browser } from 'protractor';
import { expect } from 'chai';
import { HookScenarioResult, Status } from 'cucumber';

import HomePage from './page-objects/home-page';

@binding()
export class HomePageSteps {
    private homePage = new HomePage();

    @before()
    public beforeAllScenarios(): void {
        browser.manage().window().maximize();
    }

    @given(/the user is at the home page/)
    public async givenUserAtHomePage(): Promise<void> {
        await this.homePage.get();
        const actual = await browser.getCurrentUrl();
        const expected = 'https://qaclickacademy.github.io/protocommerce/';
        expect(actual).to.equal(expected);
    }

    @when(/the user enters (.*) in the name field/)
    public async userEntersNameField(input: string): Promise<void> {
        await this.homePage.typeNameAndTab(input);
    }

    @then(/the user should see error message (.*)/)
    public async useShouldSeeErrorMessage(message: string) {
        const errorMessage = await this.homePage.getErrorMessage();
        expect(errorMessage).to.equal(message);
    }

    @after()
    public async afterAllScenarios(scenario: HookScenarioResult): Promise<void> {
        if (scenario.result.status === Status.PASSED) {
            const screenshot = await browser.takeScreenshot();
            // No access to World instance so the code below won't work
            this.attach(screenshot, "image/png");

            // HookScenario has no attach method, so the code below won't work
            scenario.attach(screenshot);
        }
    }
}

cucumber-config.ts

import { Config } from 'protractor';
import * as reporter from 'cucumber-html-reporter';

// An example configuration file
export let config: Config = {
  directConnect: true,
  framework: 'custom',
  frameworkPath: require.resolve('protractor-cucumber-framework'),
  capabilities: {
    browserName: 'chrome'
  },
  specs: ['../features/sample.feature'],

  cucumberOpts: {
    format: 'json:./report/cucumber_report.json',
    tags: [
      '@smoketesting'
    ]
  },

  onComplete: () => {
    console.log('on complete called');
    var options = {
      theme: 'bootstrap',
      jsonFile: './report/cucumber_report.json',
      output: './report/cucumber_report.html',
      reportSuiteAsScenarios: true,
      scenarioTimestamp: true,
      launchReport: true,
      metadata: {
        "App Version": "0.3.2"
      }
    };

    reporter.generate(options);
  }
};

Body:
If you have a custom World you need to make sure that the constructor utilize the attach property. I don't know how it's done with cucumber-tsflow, but cucumberjs which used internally by cucumber-tsflow need the attach parameter like this :

function World({ attach }) {
  this.attach = attach
}

We use a custom world in typescript for our Angular E2E test app
Here's a cut of the file

// world.ts
const { setWorldConstructor } = require('cucumber');

export class World {
  private attach: (buffer: Buffer, mimeType: string) => void;
  constructor({ attach }) {
    this.attach = attach;
  }
}

And then in the hook.ts

import { browser } from 'protractor';
import { HookScenarioResult } from 'cucumber';
const { Before, After } = require('cucumber');

// hook.ts
After(async function(scenario: HookScenarioResult) {
  const ss = await browser.takeScreenshot();
  const img = Buffer.alloc(ss.length, ss, 'base64');
  this.attach(img, 'image/png');
});

Also, apparently you have a way to use the world's constructor parameter: https://github.com/timjroberts/cucumber-js-tsflow/issues/16


问:
Website authentication using smart cards' certificate and public key
So I have a credit card looking like smart card with a chip.  This card logins on a website after the card is inserted into the card reader.

Now I have to write a program in python which can read the card and login on that website. After research on internet I found out that I need to extract :

Certificate and

Public key (since private key cannot be extracted)

from the card and then use these 2 things to create a HTTPs connection (example here) . So far I am able to extract certificate in pem format. But i cant find a way to extract key in pem format till now. I used PyKCS11 to read the card. Below is my code:

```<code>from asn1crypto import pem, x509
from PyKCS11 import *
import binascii

pkcs11 = PyKCS11Lib()
pkcs11.load(r'C:\Windows\System32\XXXX.dll')
print(pkcs11.getSlotList(tokenPresent=False))

slot = pkcs11.getSlotList(tokenPresent=False)[0]
print(pkcs11.getTokenInfo(slot))

session = pkcs11.openSession(0, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('123456')
result = []
result_pem = []

# find public key and print modulus
pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0]
modulus = session.getAttributeValue(pubKey, [CKA_MODULUS])[0]
print("\nmodulus: {}".format(binascii.hexlify(bytearray(modulus))))

#find certificates
certs = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE)])
for cert in certs:
    cka_value, cka_id = session.getAttributeValue(cert, [CKA_VALUE, CKA_ID])
    cert_der = bytes(cka_value)
    cert = x509.Certificate.load(cert_der)
    # Write out a PEM encoded value
    cert_pem = pem.armor('CERTIFICATE', cert_der)
    result.append(cert)
    result_pem.append(cert_pem)
    with open('cert.pem','wb') as f:
         f.write(cert_pem)
print(result)
</code>```

So here are my questions:
1. Is my approach right?

If yes, then how to extract public key in pem format?

How this smart card authentication actually works on client side and server side?

答:
Public key extraxction

If you already have exported the certificate, it is probably easier to extract the public key from there, instead of from the smartcard. You can use openssl for that:

```<code>openssl x509 -in cert.pem -pubkey -out pubkey.pem -noout
</code>```

Authentication

What you are trying to achieve is to open a TLS connection with mutual authentication using a client certificate. If you do this, the private key of your client certificate signs parts of the handshake to authenticate itself towards the server.

Extracting the certificate and the public key from the smartcard won't help you here. You need to find a library, which allows you to use your private key straight from your PKCS#11 token.

Body:
So I have a credit card looking like smart card with a chip.  This card logins on a website after the card is inserted into the card reader.

Now I have to write a program in python which can read the card and login on that website. After research on internet I found out that I need to extract :

Certificate and

Public key (since private key cannot be extracted)

from the card and then use these 2 things to create a HTTPs connection (example here) . So far I am able to extract certificate in pem format. But i cant find a way to extract key in pem format till now. I used PyKCS11 to read the card. Below is my code:

from asn1crypto import pem, x509
from PyKCS11 import *
import binascii

pkcs11 = PyKCS11Lib()
pkcs11.load(r'C:\Windows\System32\XXXX.dll')
print(pkcs11.getSlotList(tokenPresent=False))

slot = pkcs11.getSlotList(tokenPresent=False)[0]
print(pkcs11.getTokenInfo(slot))

session = pkcs11.openSession(0, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('123456')
result = []
result_pem = []

# find public key and print modulus
pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0]
modulus = session.getAttributeValue(pubKey, [CKA_MODULUS])[0]
print("\nmodulus: {}".format(binascii.hexlify(bytearray(modulus))))

#find certificates
certs = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE)])
for cert in certs:
    cka_value, cka_id = session.getAttributeValue(cert, [CKA_VALUE, CKA_ID])
    cert_der = bytes(cka_value)
    cert = x509.Certificate.load(cert_der)
    # Write out a PEM encoded value
    cert_pem = pem.armor('CERTIFICATE', cert_der)
    result.append(cert)
    result_pem.append(cert_pem)
    with open('cert.pem','wb') as f:
         f.write(cert_pem)
print(result)

So here are my questions:
1. Is my approach right?

If yes, then how to extract public key in pem format?

How this smart card authentication actually works on client side and server side?

Body:
Public key extraxction

If you already have exported the certificate, it is probably easier to extract the public key from there, instead of from the smartcard. You can use openssl for that:

openssl x509 -in cert.pem -pubkey -out pubkey.pem -noout

Authentication

What you are trying to achieve is to open a TLS connection with mutual authentication using a client certificate. If you do this, the private key of your client certificate signs parts of the handshake to authenticate itself towards the server.

Extracting the certificate and the public key from the smartcard won't help you here. You need to find a library, which allows you to use your private key straight from your PKCS#11 token.


问:
FormulaArray Producing Runtime 1004 Error
I am trying to run the following procedure that entails placing an array formula in a range ("CA2010") on a sheet ("Slate Data").

I've tested the the array formula many times and it produces the desired results.

The sub below gets

run-time '1004' error: Unable to set the FormulaArray property of the Range class.

```<code>Sub countuniqueBINs()

Dim placementoutlook As Workbook
Set placementoutlook = Excel.Workbooks("Placement Outlook")
Dim sdws As Worksheet
Set sdws = placementoutlook.Sheets("Slate Data")

sdws.Range("CA2010").NumberFormat = "general"
sdws.Range("CA2010").FormulaArray = "=SUM(IF(FREQUENCY(IF(SUBTOTAL(3,OFFSET(E2:E2000,ROW(E2:E2000)-ROW(E2),0,1)),MATCH(""~""&E2:E2000,E2:E2000&"""",0)),ROW(E2:E2000)-ROW(E2)+1),1))"

End Sub
</code>```

I tried breaking the array formula into two parts based on some guidance out there, but it still did not resolve the issue.

答: The reason for the error is that the R1C1 format version of your formula exceeds 255 characters (even though the A1 style version is much shorter than that) due to the relative references. If you use absolute references, the formula is short enough to be entered using FormulaArray; if you can't do that, you'll need to use the workaround of splitting the formula into sections so that you can use the Range.Replace method after entering a shorter version.

Body:
I am trying to run the following procedure that entails placing an array formula in a range ("CA2010") on a sheet ("Slate Data").

I've tested the the array formula many times and it produces the desired results.

The sub below gets

run-time '1004' error: Unable to set the FormulaArray property of the Range class.

Sub countuniqueBINs()

Dim placementoutlook As Workbook
Set placementoutlook = Excel.Workbooks("Placement Outlook")
Dim sdws As Worksheet
Set sdws = placementoutlook.Sheets("Slate Data")

sdws.Range("CA2010").NumberFormat = "general"
sdws.Range("CA2010").FormulaArray = "=SUM(IF(FREQUENCY(IF(SUBTOTAL(3,OFFSET(E2:E2000,ROW(E2:E2000)-ROW(E2),0,1)),MATCH(""~""&E2:E2000,E2:E2000&"""",0)),ROW(E2:E2000)-ROW(E2)+1),1))"

End Sub

I tried breaking the array formula into two parts based on some guidance out there, but it still did not resolve the issue.


问:
How do I insert an uploaded image into an  tag/placeholder?
How do I insert an uploaded image into an html  tag?
Is it possible to create an  tag as placeholder for uploaded images?

I can select an image with "< input type="file" name="fileToUpload" id="fileToUpload" >" and after this i want to send that image to an img placeholder.

And is it possible to delete the uploaded image from the placeholder after the user closed the website?

Thanks a lot!

答:
first "src" called "attribute"

what you have to do

1-locate you image on server -> see where did you upload the file first

2-take the path of the file and put it inside the "src" "attribute"

ex:

1-you uploaded the image lets say project/images

2-your image path will be in  project/images/image.jpg

3-take this part and but it inside the src attribute

```<code> src="project/images/image.jpg"
</code>```

Title: How do I insert an uploaded image into an <IMG> tag/placeholder?

Body:
first "src" called "attribute"

what you have to do

1-locate you image on server -> see where did you upload the file first

2-take the path of the file and put it inside the "src" "attribute"

ex:

1-you uploaded the image lets say project/images

2-your image path will be in  project/images/image.jpg

3-take this part and but it inside the src attribute

 src="project/images/image.jpg"


问:
Multiple includes of the same source files through a project is correct?
I'm trying to call a method in my main, which is declared in another file.

When I try to call it with this line of code in the Main.c:

```<code>#include "SPI3.c"

void main(void) {

initSpi();

}
</code>```

it gives the following error:

```<code>SPI3.c:196:: error: (237) function "_initSpi" redefined
</code>```

The function is declared in the file SPI3.c

```<code>void initSpi()
{
     //CODE

}
</code>```

I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when
you include the same file more than once and it redefines the function.

I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.

What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?

Thanks, feel free to ask for more details.

答:
You should not include .c files, but .h files (except if you know exactly what you are doing).

I would rather do the following thing:
in your SPI3.h file, declare your function:

```<code>void initSpi(void);
</code>```

Don't forget Include guard in your .h file

and in your main.c file:

```<code>#include "SPI3.h"
</code>```

Thus your function is only defined once (in your SPI3.c file), and you will not get the redefined error.

Just for clarification

When you write the following code in your .c file:

```<code>void initSpi()
{
     //CODE

}
</code>```

Then you both declare and define your function.

When you write the following code in your .h file:

```<code>void initSpi(void);
</code>```

Then you just declare your function. It is your function prototype.

Your function can be declared multiple times, but can only be defined once (except if using the weak keyword).

That why it is recommended to declare (and only declare) your functions in .h files and to only include those files into your .c files.

Body:
I'm trying to call a method in my main, which is declared in another file.

When I try to call it with this line of code in the Main.c:

#include "SPI3.c"

void main(void) {

initSpi();

}

it gives the following error:

SPI3.c:196:: error: (237) function "_initSpi" redefined

The function is declared in the file SPI3.c

void initSpi()
{
     //CODE

}

I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when
you include the same file more than once and it redefines the function.

I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.

What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?

Thanks, feel free to ask for more details.

Body:
You should not include .c files, but .h files (except if you know exactly what you are doing).

I would rather do the following thing:
in your SPI3.h file, declare your function:

void initSpi(void);

Don't forget Include guard in your .h file

and in your main.c file:

#include "SPI3.h"

Thus your function is only defined once (in your SPI3.c file), and you will not get the redefined error.

Just for clarification

When you write the following code in your .c file:

void initSpi()
{
     //CODE

}

Then you both declare and define your function.

When you write the following code in your .h file:

void initSpi(void);

Then you just declare your function. It is your function prototype.

Your function can be declared multiple times, but can only be defined once (except if using the weak keyword).

That why it is recommended to declare (and only declare) your functions in .h files and to only include those files into your .c files.


问:
Quarkus IBM MQ integration
I'm looking for solution to integrate Quarkus (only CDI without EJB) with IBM MQ.
Anybody hat such problem? or have any idea.

Parameters which I'm using to connect:

host

port

channel

queue manager

queue name

I know I can create my own connection factory as bean like in stand alone app and then pool of consumers. Which is actually my alternative solution. But maybe there is better or "prettier" solution.
Maybe library like camel allow for such configuration? I couldn't find such configuration example

答:
Currently, the standard Java programming interface for MQ is JMS. You can pull in the MQ JMS client as a dependency to your project by addding the following to your maven pom.xml:

```<code>    <!-- JMS API interfaces -->
    <dependency>
        <groupId>javax.jms</groupId>
        <artifactId>javax.jms-api</artifactId>
        <version>2.0.1</version>
    </dependency>

    <!-- MQ JMS client packages -->
    <dependency>
        <groupId>com.ibm.mq</groupId>
        <artifactId>com.ibm.mq.allclient</artifactId>
        <version>${mq.version}</version>
    </dependency>
</dependencies>
</code>```

That will enable you to create a JMS ConnectionFactory programmatically within your app using the JMSFactoryFactory class, as described in:

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.0.0/com.ibm.mq.dev.doc/q032180_.htm

This doesn't allow you to use injection, you need to declare and create your ConnectionFactory within the application itself.

Within Quarkus, in order to be able to inject a ConnectionFactory object into your application, you could write your own extension.
There are more details about writing an extension at:

https://quarkus.io/guides/writing-extensions

The central requirement for that would be to write a Producer class in the runtime part of your extension that produces a JMSConnectionFactory object using properties defined in a config object (which also needs to be defined to contain the properties you want to set in the ConnectionFactory).
The producer would need a method similar to:

```<code>@Produces
@ApplicationScoped
@DefaultBean
public ConnectionFactory connectionFactory() throws JMSException {
    JmsFactoryFactory ff;
    JmsConnectionFactory factory;
    try {
        // Get a new JMSConnectionFactory
        ff = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER);
        factory = ff.createConnectionFactory();
        // Always work in TCP/IP client mode
        factory.setIntProperty(CommonConstants.WMQ_CONNECTION_MODE, CommonConstants.WMQ_CM_CLIENT);
        // Now set the properties in this ConnectionFactory from the config.
        if (config.hostname.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_HOST_NAME, config.hostname.get());
        if (config.port.isPresent())
            factory.setIntProperty(CommonConstants.WMQ_PORT, config.port.get());
        if (config.channel.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_CHANNEL, config.channel.get());
        if (config.queuemanager.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_QUEUE_MANAGER, config.queuemanager.get());
        }
    catch (JMSException je) {
        // Something went wrong. Either handle it here or throw it on.
        throw je;
    }
    return factory;
}
</code>```

Title: Quarkus IBM MQ integration

Body:
Currently, the standard Java programming interface for MQ is JMS. You can pull in the MQ JMS client as a dependency to your project by addding the following to your maven pom.xml:

    <!-- JMS API interfaces -->
    <dependency>
        <groupId>javax.jms</groupId>
        <artifactId>javax.jms-api</artifactId>
        <version>2.0.1</version>
    </dependency>

    <!-- MQ JMS client packages -->
    <dependency>
        <groupId>com.ibm.mq</groupId>
        <artifactId>com.ibm.mq.allclient</artifactId>
        <version>${mq.version}</version>
    </dependency>
</dependencies>

That will enable you to create a JMS ConnectionFactory programmatically within your app using the JMSFactoryFactory class, as described in:

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.0.0/com.ibm.mq.dev.doc/q032180_.htm

This doesn't allow you to use injection, you need to declare and create your ConnectionFactory within the application itself.

Within Quarkus, in order to be able to inject a ConnectionFactory object into your application, you could write your own extension.
There are more details about writing an extension at:

https://quarkus.io/guides/writing-extensions

The central requirement for that would be to write a Producer class in the runtime part of your extension that produces a JMSConnectionFactory object using properties defined in a config object (which also needs to be defined to contain the properties you want to set in the ConnectionFactory).
The producer would need a method similar to:

@Produces
@ApplicationScoped
@DefaultBean
public ConnectionFactory connectionFactory() throws JMSException {
    JmsFactoryFactory ff;
    JmsConnectionFactory factory;
    try {
        // Get a new JMSConnectionFactory
        ff = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER);
        factory = ff.createConnectionFactory();
        // Always work in TCP/IP client mode
        factory.setIntProperty(CommonConstants.WMQ_CONNECTION_MODE, CommonConstants.WMQ_CM_CLIENT);
        // Now set the properties in this ConnectionFactory from the config.
        if (config.hostname.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_HOST_NAME, config.hostname.get());
        if (config.port.isPresent())
            factory.setIntProperty(CommonConstants.WMQ_PORT, config.port.get());
        if (config.channel.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_CHANNEL, config.channel.get());
        if (config.queuemanager.isPresent())
            factory.setStringProperty(CommonConstants.WMQ_QUEUE_MANAGER, config.queuemanager.get());
        }
    catch (JMSException je) {
        // Something went wrong. Either handle it here or throw it on.
        throw je;
    }
    return factory;
}


问:
How to make a random 2D jagged array of varying length?
I have to create a 2D jagged array with a random number of rows (5-10) with each row having a random length (5-10). I filled the jagged array with random numbers. It should look something like this:

```<code>2 4 1 5 3 8 6 3

2 5 8 9 7 4 3 5 6

6 7 9 3 5

2 6 7 8 4 5 3 6 7

1 4 2 2 1
</code>```

This is my current createArray method

```<code> public static int [][] createArray(){
   int row = (int)(Math.random()*5)+5;
   int column = (int)(Math.random()*5)+5;

   int[][]array = new int[row][];

   for(int i = 0; i < array.length; i++){
      for(int j = 0; j < array[i].length; j++){
        //Fill the matrix with random numbers
        array[i][j] = (int)(Math.random()*10);
      }}

   return array;
  }//End createArray method
</code>```

However, this just randomizes the rows and columns and doesn't create a jagged array. Can anyone help lead me in the right direction? Thanks a lot!

答:
```<code>package JavaPrograms;
import java.util.Random;
public class jaggedarr
{
    public static void main(String[] args) {
        int a[][] = new int[3][];
        Random r = new Random();
        a[0] = new int[4];
        a[1] = new int[2];
        a[2] = new int[3];
        for (int[] a1 : a)
        {
            for (int j = 0; j < a1.length; j++)
            {
                a1[j] = r.nextInt(20);
            }
        }
        for(int i[] : a)
        {
            for(int j : i)
            {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    }
}
</code>```

Body:
I have to create a 2D jagged array with a random number of rows (5-10) with each row having a random length (5-10). I filled the jagged array with random numbers. It should look something like this:

2 4 1 5 3 8 6 3

2 5 8 9 7 4 3 5 6

6 7 9 3 5

2 6 7 8 4 5 3 6 7

1 4 2 2 1

This is my current createArray method

 public static int [][] createArray(){
   int row = (int)(Math.random()*5)+5;
   int column = (int)(Math.random()*5)+5;

   int[][]array = new int[row][];

   for(int i = 0; i < array.length; i++){
      for(int j = 0; j < array[i].length; j++){
        //Fill the matrix with random numbers
        array[i][j] = (int)(Math.random()*10);
      }}

   return array;
  }//End createArray method

However, this just randomizes the rows and columns and doesn't create a jagged array. Can anyone help lead me in the right direction? Thanks a lot!


问:
Uncaught Error: Call to undefined function stats_cdf_t()
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

```<code>F.DIST.RT(4, 2, 1)
</code>```

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php

答:
As stated from the reference page, you need to install the correct php extension to call stats_cdf_t function, as it is not included inside php standard library.

You can use pecl to install it on your server.

Body:
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

F.DIST.RT(4, 2, 1)

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php


问:
When receiving chinese string, I only get unusable characters
I am using an textreader from the internet to read Chinese text, but I'm receiving incorrect letters.

For example, I get back æ‚¨å¥½ ï¼ instead of 轉注字. Also, if I parse German strings, I receive Sie kÃ¶nnen instead of Sie können.

This is the original string from website:

```<code><string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Sie kÃ¶nnen einige Blumen auswÃ¤hlen</string>
</code>```

It is UTF-8 encoded. How do I resolve this encoding issue?

Regards

答:
Try to initialize your TextReader with the appropriate encoding:

```<code>using(var reader = new StreamReader(stream, Encoding.UTF8)
{
    // read the text
}
</code>```

Body:
I am using an textreader from the internet to read Chinese text, but I'm receiving incorrect letters.

For example, I get back æ‚¨å¥½ ï¼ instead of 轉注字. Also, if I parse German strings, I receive Sie kÃ¶nnen instead of Sie können.

This is the original string from website:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Sie kÃ¶nnen einige Blumen auswÃ¤hlen</string>

It is UTF-8 encoded. How do I resolve this encoding issue?

Regards

Body:
Try to initialize your TextReader with the appropriate encoding:

using(var reader = new StreamReader(stream, Encoding.UTF8)
{
    // read the text
}


问:
Find the Intersection of both lists and create new list that that contain elements according to frequency
If we have two lists:

```<code>list1 = [1,2,1,1,2,4,1];

list2 = [1,2,1,3,2,1];
</code>```

then the new list contain the common elements or the intersection of lists and then the elements are added using frequency count:

Result Expected:

```<code>list3 = [1,1,1,2,2];
</code>```

Solution I came with but it is not optimized

```<code>List<Integer> commonlist = new ArrayList<Integer>(list2);
    List<Integer> intersectionlist = new ArrayList<Integer>();
    commonlist.retainAll(list1);
    for (int i : commonlist) {
        int freq1 = Collections.frequency(list1, i);
        // System.out.println("list1: " + i + " -> " + freq1);
        int freq2 = Collections.frequency(list2, i);
        // System.out.println("list2: " + i + " -> " + freq2);
        if (freq1 < freq2) {
            for (int j = 1; j <= freq1; j++) {
                intersectionlist.add(i);
            }
        } else {
            for (int j = 1; j <= freq2; j++) {
                intersectionlist.add(i);
            }
        }
    }
    System.out.println(intersectionlist);
</code>```

答:
I have tried an approach, each time an common element is encountered we increment an Map that stores frequencies:

```<code>public List<Integer> getCommon(int[] a, int[] b) {
    Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
    List<Integer> sets = new ArrayList<Integer>();

    for (int i : a) {
        for (int j=0; j<b.length; ++j) {
            if (i == b[j]) {
                int frequency = (int) frequencies.getOrDefault((Integer) i, 0) + 1;
                frequencies.put((Integer) i, frequency);
                b[j] = -1;
                break;
            }
        }
    }

    for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
        int key = (int) entry.getKey();
        int value = (int) entry.getValue();
        for (int i = 0; i < value; ++i) {
            sets.add(key);
        }
    }

    return sets;
}
</code>```

The result will be [1, 1, 1, 2, 2]

Body:
If we have two lists:

list1 = [1,2,1,1,2,4,1];

list2 = [1,2,1,3,2,1];

then the new list contain the common elements or the intersection of lists and then the elements are added using frequency count:

Result Expected:

list3 = [1,1,1,2,2];

Solution I came with but it is not optimized

List<Integer> commonlist = new ArrayList<Integer>(list2);
    List<Integer> intersectionlist = new ArrayList<Integer>();
    commonlist.retainAll(list1);
    for (int i : commonlist) {
        int freq1 = Collections.frequency(list1, i);
        // System.out.println("list1: " + i + " -> " + freq1);
        int freq2 = Collections.frequency(list2, i);
        // System.out.println("list2: " + i + " -> " + freq2);
        if (freq1 < freq2) {
            for (int j = 1; j <= freq1; j++) {
                intersectionlist.add(i);
            }
        } else {
            for (int j = 1; j <= freq2; j++) {
                intersectionlist.add(i);
            }
        }
    }
    System.out.println(intersectionlist);

Body:
I have tried an approach, each time an common element is encountered we increment an Map that stores frequencies:

public List<Integer> getCommon(int[] a, int[] b) {
    Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
    List<Integer> sets = new ArrayList<Integer>();

    for (int i : a) {
        for (int j=0; j<b.length; ++j) {
            if (i == b[j]) {
                int frequency = (int) frequencies.getOrDefault((Integer) i, 0) + 1;
                frequencies.put((Integer) i, frequency);
                b[j] = -1;
                break;
            }
        }
    }

    for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
        int key = (int) entry.getKey();
        int value = (int) entry.getValue();
        for (int i = 0; i < value; ++i) {
            sets.add(key);
        }
    }

    return sets;
}

The result will be [1, 1, 1, 2, 2]