问:
How to configure multi-user chat (mod_muc) for Ejabberd?
I've found this: https://docs.ejabberd.im/admin/configuration/modules/#mod-muc

And this: https://docs.ejabberd.im/admin/ejabberdctl/muc-admin/#prerequisite

What are the steps I need to do to setup MUC from a fresh install? mod_muc is already in the ejabberd.yml file, and so is mod_muc_admin. I've also added myself as an admin.

Here is my ejabberd.yml file:

```<code>ubuntu@ip-10-0-1-208:/opt/ejabberd/conf$ cat ejabberd.yml
###
###'           ejabberd configuration file
###
### The parameters used in this configuration file are explained at
###
###       https://docs.ejabberd.im/admin/configuration
###
### The configuration file is written in YAML.
### *******************************************************
### *******           !!! WARNING !!!               *******
### *******     YAML IS INDENTATION SENSITIVE       *******
### ******* MAKE SURE YOU INDENT SECTIONS CORRECTLY *******
### *******************************************************
### Refer to http://en.wikipedia.org/wiki/YAML for the brief description.
###

hosts:
  - ip-10-0-1-208.us-west-1.compute.internal
  - xmpp.ughstudios.com

loglevel: info

certfiles:
  - "/opt/ejabberd/conf/server.pem"
##  - "/etc/letsencrypt/live/localhost/fullchain.pem"
##  - "/etc/letsencrypt/live/localhost/privkey.pem"

ca_file: "/opt/ejabberd/conf/cacert.pem"

listen:
  -
    port: 5222
    ip: "::"
    module: ejabberd_c2s
    max_stanza_size: 262144
    shaper: c2s_shaper
    access: c2s
    starttls_required: true
  -
    port: 5269
    ip: "::"
    module: ejabberd_s2s_in
    max_stanza_size: 524288
  -
    port: 5443
    ip: "::"
    module: ejabberd_http
    tls: true
    request_handlers:
      "/admin": ejabberd_web_admin
      "/api": mod_http_api
      "/bosh": mod_bosh
      "/captcha": ejabberd_captcha
      "/upload": mod_http_upload
      "/ws": ejabberd_http_ws
      "/oauth": ejabberd_oauth
  -
    port: 5280
    ip: "::"
    module: ejabberd_http
    request_handlers:
      "/admin": ejabberd_web_admin
  -
    port: 1883
    ip: "::"
    module: mod_mqtt
    backlog: 1000

s2s_use_starttls: optional

acl:
  local:
    user_regexp: ""
  loopback:
    ip:
      - 127.0.0.0/8
      - ::1/128
      - ::FFFF:127.0.0.1/128
  admin:
    user:
      - daniel@xmpp.ughstudios.com

auth_method: [external]
extauth_program: /opt/ejabberd_auth_bridge.py
extauth_instances: 3
auth_use_cache: true

access_rules:
  local:
    allow: local
  c2s:
    deny: blocked
    allow: all
  announce:
    allow: admin
  configure:
    allow: admin
  muc_create:
    allow: local
  pubsub_createnode:
    allow: local
  trusted_network:
    allow: loopback

api_permissions:
  "console commands":
    from:
      - ejabberd_ctl
    who: all
    what: "*"
  "admin access":
    who:
      access:
        allow:
          acl: loopback
          acl: admin
      oauth:
        scope: "ejabberd:admin"
        access:
          allow:
            acl: loopback
            acl: admin
    what:
      - "*"
      - "!stop"
      - "!start"
  "public commands":
    who:
      ip: 127.0.0.1/8
    what:
      - status
      - connected_users_number

shaper:
  normal: 1000
  fast: 50000

shaper_rules:
  max_user_sessions: 10
  max_user_offline_messages:
    5000: admin
    100: all
  c2s_shaper:
    none: admin
    normal: all
  s2s_shaper: fast

max_fsm_queue: 10000

acme:
   contact: "mailto:admin@ip-10-0-1-208.us-west-1.compute.internal"
   ca_url: "https://acme-v02.api.letsencrypt.org"

modules:
  mod_adhoc: {}
  mod_admin_extra: {}
  mod_announce:
    access: announce
  mod_avatar: {}
  mod_blocking: {}
  mod_bosh: {}
  mod_caps: {}
  mod_carboncopy: {}
  mod_client_state: {}
  mod_configure: {}
  mod_disco: {}
  mod_fail2ban: {}
  mod_http_api: {}
  mod_http_upload:
    put_url: https://@HOST@:5443/upload
  mod_last: {}
  mod_mam:
    ## Mnesia is limited to 2GB, better to use an SQL backend
    ## For small servers SQLite is a good fit and is very easy
    ## to configure. Uncomment this when you have SQL configured:
    ## db_type: sql
    assume_mam_usage: true
    default: never
  mod_mqtt: {}
  mod_muc:
    access:
      - allow
    access_admin:
      - allow: admin
      - allow: daniel
      - allow: david
        #access_create: all
    #access_persistent: all
    access_mam:
      - allow
    default_room_options:
      allow_subscription: true  # enable MucSub
      mam: false
  mod_muc_admin: {}
  mod_offline:
    access_max_user_messages: max_user_offline_messages
  mod_ping: {}
  mod_privacy: {}
  mod_private: {}
  mod_proxy65:
    access: local
    max_connections: 5
  mod_pubsub:
    access_createnode: pubsub_createnode
    plugins:
      - flat
      - pep
    force_node_config:
      ## Avoid buggy clients to make their bookmarks public
      storage:bookmarks:
        access_model: whitelist
  mod_push: {}
  mod_push_keepalive: {}
  mod_register:
    ## Only accept registration requests from the "trusted"
    ## network (see access_rules section above).
    ## Think twice before enabling registration from any
    ## address. See the Jabber SPAM Manifesto for details:
    ## https://github.com/ge0rg/jabber-spam-fighting-manifesto
    ip_access: trusted_network
  mod_roster:
    versioning: true
  mod_s2s_dialback: {}
  mod_shared_roster: {}
  mod_stream_mgmt:
    resend_on_timeout: if_offline
  mod_vcard: {}
  mod_vcard_xupdate: {}
  mod_version:
    show_os: false

### Local Variables:
### mode: yaml
### End:
### vim: set filetype=yaml tabstop=8
</code>```

答:
What are the steps I need to do to setup MUC from a fresh install?

Usually mod_muc is already configured and enabled by default. Of course, if ejabberd is installed in a remote server, you will need to setup DNS for the MUC service, similar to what you may want to do for any other services that have their specific domain, like pubsub.example.org

Body:
I've found this: https://docs.ejabberd.im/admin/configuration/modules/#mod-muc

And this: https://docs.ejabberd.im/admin/ejabberdctl/muc-admin/#prerequisite

What are the steps I need to do to setup MUC from a fresh install? mod_muc is already in the ejabberd.yml file, and so is mod_muc_admin. I've also added myself as an admin.

Here is my ejabberd.yml file:

ubuntu@ip-10-0-1-208:/opt/ejabberd/conf$ cat ejabberd.yml
###
###'           ejabberd configuration file
###
### The parameters used in this configuration file are explained at
###
###       https://docs.ejabberd.im/admin/configuration
###
### The configuration file is written in YAML.
### *******************************************************
### *******           !!! WARNING !!!               *******
### *******     YAML IS INDENTATION SENSITIVE       *******
### ******* MAKE SURE YOU INDENT SECTIONS CORRECTLY *******
### *******************************************************
### Refer to http://en.wikipedia.org/wiki/YAML for the brief description.
###

hosts:
  - ip-10-0-1-208.us-west-1.compute.internal
  - xmpp.ughstudios.com

loglevel: info

certfiles:
  - "/opt/ejabberd/conf/server.pem"
##  - "/etc/letsencrypt/live/localhost/fullchain.pem"
##  - "/etc/letsencrypt/live/localhost/privkey.pem"

ca_file: "/opt/ejabberd/conf/cacert.pem"

listen:
  -
    port: 5222
    ip: "::"
    module: ejabberd_c2s
    max_stanza_size: 262144
    shaper: c2s_shaper
    access: c2s
    starttls_required: true
  -
    port: 5269
    ip: "::"
    module: ejabberd_s2s_in
    max_stanza_size: 524288
  -
    port: 5443
    ip: "::"
    module: ejabberd_http
    tls: true
    request_handlers:
      "/admin": ejabberd_web_admin
      "/api": mod_http_api
      "/bosh": mod_bosh
      "/captcha": ejabberd_captcha
      "/upload": mod_http_upload
      "/ws": ejabberd_http_ws
      "/oauth": ejabberd_oauth
  -
    port: 5280
    ip: "::"
    module: ejabberd_http
    request_handlers:
      "/admin": ejabberd_web_admin
  -
    port: 1883
    ip: "::"
    module: mod_mqtt
    backlog: 1000

s2s_use_starttls: optional

acl:
  local:
    user_regexp: ""
  loopback:
    ip:
      - 127.0.0.0/8
      - ::1/128
      - ::FFFF:127.0.0.1/128
  admin:
    user:
      - daniel@xmpp.ughstudios.com

auth_method: [external]
extauth_program: /opt/ejabberd_auth_bridge.py
extauth_instances: 3
auth_use_cache: true

access_rules:
  local:
    allow: local
  c2s:
    deny: blocked
    allow: all
  announce:
    allow: admin
  configure:
    allow: admin
  muc_create:
    allow: local
  pubsub_createnode:
    allow: local
  trusted_network:
    allow: loopback

api_permissions:
  "console commands":
    from:
      - ejabberd_ctl
    who: all
    what: "*"
  "admin access":
    who:
      access:
        allow:
          acl: loopback
          acl: admin
      oauth:
        scope: "ejabberd:admin"
        access:
          allow:
            acl: loopback
            acl: admin
    what:
      - "*"
      - "!stop"
      - "!start"
  "public commands":
    who:
      ip: 127.0.0.1/8
    what:
      - status
      - connected_users_number

shaper:
  normal: 1000
  fast: 50000

shaper_rules:
  max_user_sessions: 10
  max_user_offline_messages:
    5000: admin
    100: all
  c2s_shaper:
    none: admin
    normal: all
  s2s_shaper: fast

max_fsm_queue: 10000

acme:
   contact: "mailto:admin@ip-10-0-1-208.us-west-1.compute.internal"
   ca_url: "https://acme-v02.api.letsencrypt.org"

modules:
  mod_adhoc: {}
  mod_admin_extra: {}
  mod_announce:
    access: announce
  mod_avatar: {}
  mod_blocking: {}
  mod_bosh: {}
  mod_caps: {}
  mod_carboncopy: {}
  mod_client_state: {}
  mod_configure: {}
  mod_disco: {}
  mod_fail2ban: {}
  mod_http_api: {}
  mod_http_upload:
    put_url: https://@HOST@:5443/upload
  mod_last: {}
  mod_mam:
    ## Mnesia is limited to 2GB, better to use an SQL backend
    ## For small servers SQLite is a good fit and is very easy
    ## to configure. Uncomment this when you have SQL configured:
    ## db_type: sql
    assume_mam_usage: true
    default: never
  mod_mqtt: {}
  mod_muc:
    access:
      - allow
    access_admin:
      - allow: admin
      - allow: daniel
      - allow: david
        #access_create: all
    #access_persistent: all
    access_mam:
      - allow
    default_room_options:
      allow_subscription: true  # enable MucSub
      mam: false
  mod_muc_admin: {}
  mod_offline:
    access_max_user_messages: max_user_offline_messages
  mod_ping: {}
  mod_privacy: {}
  mod_private: {}
  mod_proxy65:
    access: local
    max_connections: 5
  mod_pubsub:
    access_createnode: pubsub_createnode
    plugins:
      - flat
      - pep
    force_node_config:
      ## Avoid buggy clients to make their bookmarks public
      storage:bookmarks:
        access_model: whitelist
  mod_push: {}
  mod_push_keepalive: {}
  mod_register:
    ## Only accept registration requests from the "trusted"
    ## network (see access_rules section above).
    ## Think twice before enabling registration from any
    ## address. See the Jabber SPAM Manifesto for details:
    ## https://github.com/ge0rg/jabber-spam-fighting-manifesto
    ip_access: trusted_network
  mod_roster:
    versioning: true
  mod_s2s_dialback: {}
  mod_shared_roster: {}
  mod_stream_mgmt:
    resend_on_timeout: if_offline
  mod_vcard: {}
  mod_vcard_xupdate: {}
  mod_version:
    show_os: false

### Local Variables:
### mode: yaml
### End:
### vim: set filetype=yaml tabstop=8


来源: stackexchange

问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答:
Create an anonymous shared memory region before forking and then all children can use it after the fork:

```<code>char *shared = mmap(0,size,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);
</code>```

Be aware that you'll need some synchronization mechanism when sharing memory. One way to accomplish this is to put a mutex or semaphore inside the shared memory region.

ContentLicense: CC BY-SA 3.0

Title: Sharing data across processes on linux

Body:
Create an anonymous shared memory region before forking and then all children can use it after the fork:

char *shared = mmap(0,size,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);

Be aware that you'll need some synchronization mechanism when sharing memory. One way to accomplish this is to put a mutex or semaphore inside the shared memory region.


问:
Python in VSCode: Set working directory to python file's path everytime
So I want to migrate from Spyder to VSCode, and I come across this problem where I cannot access a dataset as my working directory is not the same as the dataset's path.

launch.json is not auto-generated for me as I'm not debugging anything (I tried this).

How do I set the working directory to always be the dir of the Python file I want to run, in VSCode? (and if it's bad practice, could you show me a config that is easy to work with?) I'd like to set this up for VSCode's IPython terminal.

答:
Mind you the solutions on this page don't work unless you open the dir as a workspace in Code. If you just open the script, none of these answers work.

MSFT doesn't see this as an issue worth fixing. Because everyone on their island works in workspaces not with scripts, even with scripting languages.

ContentLicense: CC BY-SA 4.0


问:
Mounting Kubernetes config map as single file returns error: "caused: mount through procfd: not a directory: unknown"
This is my pod:

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main
```
<p>This is my config map:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ConfigMap
metadata:
  name: config-main
data:
  config.tmpl: |
        # here goes my config content

</code>```

This produces the following error:

Error: failed to create containerd task: failed to create shim: OCI
runtime create failed: container_linux.go:380: starting container
process caused: process_linux.go:545: container init caused:
rootfs_linux.go:76: mounting
"/var/lib/kubelet/pods/dc66ebd1-90ef-4c25-bb69-4b3329f61a5a/volume-subpaths/config-main/podname/1"
to rootfs at "/etc/configs/config.tmpl" caused: mount through procfd:
not a directory: unknown

The container has pre-existing /etc/configs/config.tmpl file that I want to override

答:
To mount as file instead of directory try:</p>
```<code>spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      items:
      - key: config.tmpl
        path: config.tmpl
      name: config-main
    name: config-main
</code>```

Body:
This is my pod:

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main

This is my config map:

apiVersion: v1
kind: ConfigMap
metadata:
  name: config-main
data:
  config.tmpl: |
        # here goes my config content

This produces the following error:

Error: failed to create containerd task: failed to create shim: OCI
runtime create failed: container_linux.go:380: starting container
process caused: process_linux.go:545: container init caused:
rootfs_linux.go:76: mounting
"/var/lib/kubelet/pods/dc66ebd1-90ef-4c25-bb69-4b3329f61a5a/volume-subpaths/config-main/podname/1"
to rootfs at "/etc/configs/config.tmpl" caused: mount through procfd:
not a directory: unknown

The container has pre-existing /etc/configs/config.tmpl file that I want to override

Body:
To mount as file instead of directory try:

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      items:
      - key: config.tmpl
        path: config.tmpl
      name: config-main
    name: config-main


问:
Detect left or right swipe through MouseArea Qt QML
I've the problem, how to detect swipe through MouseArea in qml ?

This code, from documentation:

```<code>    Rectangle {
    id: container
    width: 600; height: 200

    Rectangle {
        id: rect
        width: 500; height: 500

        MouseArea {
            anchors.fill: parent
            drag.target: rect
            drag.axis: Drag.XAxis
            drag.minimumX: 0
            drag.maximumX: container.width - rect.width

            //event slide here ?
        }
    }
}
</code>```

but i didn't understood how to get left or right swipe, i get this use in the mobile application (ios & android).

Somebody can help me ? Thanks.
How to detect left or right swipe with finger? Thanks.

答:
Here my five cents:</p>
```<code>MouseArea {

signal sgSwipeLeft();
signal sgSwipeRight();
signal sgSwipeDown();
signal sgSwipeUp();

QtObject {

    property bool pTracing: false;
    property real pXVelocity: 0.0;
    property real pYVelocity: 0.0;
    property int pXPrev: 0;
    property int pYPrev: 0;

    id: oPrivate;
}

id: oRoot;
preventStealing: true;

onPressed: {

    oPrivate.pTracing = true;
    oPrivate.pXVelocity = 0;
    oPrivate.pYVelocity = 0;
    oPrivate.pXPrev = mouse.x;
    oPrivate.pYPrev = mouse.y;
}

onPositionChanged: {

    if (!oPrivate.pTracing) return;

    var oCurrentXVelocity = (mouse.x - oPrivate.pXPrev);
    oPrivate.pXVelocity = (oPrivate.pXVelocity + oCurrentXVelocity) / 2.0;
    oPrivate.pXPrev = mouse.x;

    var oCurrentYVelocity = (mouse.y - oPrivate.pYPrev);
    oPrivate.pYVelocity = (oPrivate.pXVelocity + oCurrentYVelocity) / 2.0;
    oPrivate.pYPrev = mouse.y;

    if (oPrivate.pXVelocity > 15 && mouse.x > parent.width * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeRight();
    } else if (oPrivate.pXVelocity < -15 && mouse.x > parent.width * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeLeft();
    } else if (oPrivate.pYVelocity > 15 && mouse.y > parent.height * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeDown();
    } else if (oPrivate.pYVelocity < -15 && mouse.y < parent.height * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeUp();
    }
}

onClicked: console.log("onClicked");
onPressAndHold: console.log("onPressAndHold");
onSgSwipeLeft: console.log("onSgSwipeLeft");
onSgSwipeDown: console.log("onSgSwipeDown");
onSgSwipeRight: console.log("onSgSwipeRight");
onSgSwipeUp: console.log("onSgSwipeUp");
onReleased: console.log("onReleased");
}
</code>```

Body:
I've the problem, how to detect swipe through MouseArea in qml ?

This code, from documentation:

    Rectangle {
    id: container
    width: 600; height: 200

    Rectangle {
        id: rect
        width: 500; height: 500

        MouseArea {
            anchors.fill: parent
            drag.target: rect
            drag.axis: Drag.XAxis
            drag.minimumX: 0
            drag.maximumX: container.width - rect.width

            //event slide here ?
        }
    }
}

but i didn't understood how to get left or right swipe, i get this use in the mobile application (ios & android).

Somebody can help me ? Thanks.
How to detect left or right swipe with finger? Thanks.

Body:
Here my five cents:

MouseArea {

signal sgSwipeLeft();
signal sgSwipeRight();
signal sgSwipeDown();
signal sgSwipeUp();

QtObject {

    property bool pTracing: false;
    property real pXVelocity: 0.0;
    property real pYVelocity: 0.0;
    property int pXPrev: 0;
    property int pYPrev: 0;

    id: oPrivate;
}

id: oRoot;
preventStealing: true;

onPressed: {

    oPrivate.pTracing = true;
    oPrivate.pXVelocity = 0;
    oPrivate.pYVelocity = 0;
    oPrivate.pXPrev = mouse.x;
    oPrivate.pYPrev = mouse.y;
}

onPositionChanged: {

    if (!oPrivate.pTracing) return;

    var oCurrentXVelocity = (mouse.x - oPrivate.pXPrev);
    oPrivate.pXVelocity = (oPrivate.pXVelocity + oCurrentXVelocity) / 2.0;
    oPrivate.pXPrev = mouse.x;

    var oCurrentYVelocity = (mouse.y - oPrivate.pYPrev);
    oPrivate.pYVelocity = (oPrivate.pXVelocity + oCurrentYVelocity) / 2.0;
    oPrivate.pYPrev = mouse.y;

    if (oPrivate.pXVelocity > 15 && mouse.x > parent.width * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeRight();
    } else if (oPrivate.pXVelocity < -15 && mouse.x > parent.width * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeLeft();
    } else if (oPrivate.pYVelocity > 15 && mouse.y > parent.height * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeDown();
    } else if (oPrivate.pYVelocity < -15 && mouse.y < parent.height * 0.2) {
        oPrivate.pTracing = false;
        oRoot.sgSwipeUp();
    }
}

onClicked: console.log("onClicked");
onPressAndHold: console.log("onPressAndHold");
onSgSwipeLeft: console.log("onSgSwipeLeft");
onSgSwipeDown: console.log("onSgSwipeDown");
onSgSwipeRight: console.log("onSgSwipeRight");
onSgSwipeUp: console.log("onSgSwipeUp");
onReleased: console.log("onReleased");
}


问:
How to access the latest state value in the functional component in React
```<code>import React, { useState } from "react";
import Child from "./Child";
import "./styles.css";

export default function App() {
  let [state, setState] = useState({
    value: ""
  });

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
    console.log(state.value);
  };
  return (
    <div className="App">
      <h1>{state.value}</h1>

      <Child handleChange={handleChange} value={state.value} />
    </div>
  );
}
import React from "react";

function Child(props) {
  return (
    <input
      type="text"
      placeholder="type..."
      onChange={e => {
        let newValue = e.target.value;
        props.handleChange(newValue);
      }}
      value={props.value}
    />
  );
}

export default Child;
</code>```

Here I am passing the data from the input field to the parent component. However, while displaying it on the page with the h1 tag, I am able to see the latest state. But while using console.log() the output is the previous state. How do I solve this in the functional React component?

答:
```<code>Maybe it is helpful for others I found this way...
</code>```

I want all updated projects in my state as soon as I added them
so that I use use effect hook like this.

```<code>useEffect(() => {
    [temp_variable] = projects //projects get from useSelector
    let newFormValues = {...data}; //data from useState
    newFormValues.Projects = pro; //update my data object
    setData(newFormValues); //set data using useState
},[projects])
</code>```

Body:
import React, { useState } from "react";
import Child from "./Child";
import "./styles.css";

export default function App() {
  let [state, setState] = useState({
    value: ""
  });

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
    console.log(state.value);
  };
  return (

{state.value}

      <Child handleChange={handleChange} value={state.value} />

  );
}
import React from "react";

function Child(props) {
  return (
    <input
      type="text"
      placeholder="type..."
      onChange={e => {
        let newValue = e.target.value;
        props.handleChange(newValue);
      }}
      value={props.value}
    />
  );
}

export default Child;

Here I am passing the data from the input field to the parent component. However, while displaying it on the page with the h1 tag, I am able to see the latest state. But while using console.log() the output is the previous state. How do I solve this in the functional React component?

Body:
Maybe it is helpful for others I found this way...

I want all updated projects in my state as soon as I added them
so that I use use effect hook like this.

useEffect(() => {
    [temp_variable] = projects //projects get from useSelector
    let newFormValues = {...data}; //data from useState
    newFormValues.Projects = pro; //update my data object
    setData(newFormValues); //set data using useState
},[projects])


问:
`%_` and detecting unwanted named arguments to a method
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

```<code>die "Extra args passed" if %_;
</code>```

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?

答:
Or I miss and %_ is actually a very useful thing in object oriented
Raku programming?

I think, it is useful for something like following:

class F {
    has $.x;
    has $.y;
    multi method w-sum (:$x,:$y) { $x*$!x + $y*$!y };
}

class F3 is F {
        has $.z;
        method w-sum (:$z) { $z*$!z + callsame }
        # vs method w-sum (:$x, :$y, :$z) { $z*$!z + callwith( :$x, :$y ) }
}

my F3 $point3D .= new: :2x, :3y, :4z, ;

$point3D.w-sum: :1x, :2y, :3z, ;
```
<h1>Explanation:</h1>
<p>I use <code>%_</code> twice:</p>
<ol>
<li>I call method <code>w-sum</code> from <code>F3</code> with <code>x y z</code>, so
<code>%_={x => 1, y => 2}</code></li>
<li>I call method <code>w-sum</code> from <code>F</code> by <code>callsame</code> with <code>x y z</code>, so
<code>%_={z => 3}</code></li>
</ol>
<p>try <em>debug version</em>:</p>
<pre class="lang-raku prettyprint-override"><code>class F {
    has $.x;
    has $.y;
    multi method w-sum(:$x,:$y) { say 'from F: ', %_; $x*$!x + $y*$!y }
}

class F3 is F {
        has $.z;
        method w-sum (:$z) { say 'from F3: ', %_; $z*$!z + callsame }
        # vs method w-sum (:$x, :$y, :$z) { $z*$!z + callwith( :$x, :$y) }
}

my F3 $point3D .= new: :2x, :3y, :4z, ;

say $point3D.w-sum: :1x, :2y, :3z, ;
</code>```
```<code>from F3: {x => 1, y => 2}
from F: {z => 3}
20
</code>```

Body:
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

die "Extra args passed" if %_;

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?

Body:
Or I miss and %_ is actually a very useful thing in object oriented
Raku programming?

I think, it is useful for something like following:

class F {
    has $.x;
    has $.y;
    multi method w-sum (:$x,:$y) { $x*$!x + $y*$!y };
}

class F3 is F {
        has $.z;
        method w-sum (:$z) { $z*$!z + callsame }
        # vs method w-sum (:$x, :$y, :$z) { $z*$!z + callwith( :$x, :$y ) }
}

my F3 $point3D .= new: :2x, :3y, :4z, ;

$point3D.w-sum: :1x, :2y, :3z, ;

Explanation:

I use %_ twice:

I call method w-sum from F3 with x y z, so
%_={x => 1, y => 2}

I call method w-sum from F by callsame with x y z, so
%_={z => 3}

try debug version:

class F {
    has $.x;
    has $.y;
    multi method w-sum(:$x,:$y) { say 'from F: ', %_; $x*$!x + $y*$!y }
}

class F3 is F {
        has $.z;
        method w-sum (:$z) { say 'from F3: ', %_; $z*$!z + callsame }
        # vs method w-sum (:$x, :$y, :$z) { $z*$!z + callwith( :$x, :$y) }
}

my F3 $point3D .= new: :2x, :3y, :4z, ;

say $point3D.w-sum: :1x, :2y, :3z, ;

from F3: {x => 1, y => 2}
from F: {z => 3}
20


问:
How to Create/Use SVN without internet to done work in Same Project without getting Crashed in iPhone Project development
I am using MACOS for Developing the iPhone Application.

I have made the repository in to some Public Site that gives Functionality to build the Repository in their server and after that we can use the project to work simultaneously. But it uses internet connection that's why it becomes to slow to update and modification.
I have multiple Computers and I want to Use One PC as a Server and want to Create the Repository there and after from another multiple Computer, I want to use the Same Project to be done simultaneously.

How can i done that settings or that kind repository ?
Please help me regarding this.

答:
If you are using osx, chances are svn is already installed on the computer you want to use as a host. You can configure svn to work with apache and use your local machine as the svn host. The following link has the details for setting it up:

http://mark-kirby.co.uk/2008/how-to-set-up-and-use-subversion-svn-on-os-x-leopard/


问:
Redux Action is Dispatched but state not updating accordingly
When i click the delete button the action(removeBus) is dispatched and the correct payload value is sent however the store is not updating
here is my busSlice file

```<code>import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

</code>```

here is where  i created and export the store

```<code>import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

</code>```

the component that uses the state is created in the following code and App is wrapped inside a redux provider Component and the above store is provided as a props in index.js

```<code>import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (
    <div className="App">
      {busses.map((bus) => (
        <ul>
          <li key={bus.id}>
            <p>{bus.description}</p>
            <button onClick={() => handleRemove(bus.id)}>delete</button>
          </li>
        </ul>
      ))}
    </div>
  );
}

</code>```

using redux dev tools i can see an action busses\removeBus is dispatched with the appropriate payload value but nothing is happening to the state.

答:
You can change:

```<code>removeBus: (state, action) => {
      state.filter((bus) => bus.id != action.payload);
      console.log(action.payload);
    }
</code>```

can be the data types of bus.id and action.payload are different.

Body:
When i click the delete button the action(removeBus) is dispatched and the correct payload value is sent however the store is not updating
here is my busSlice file

import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

here is where  i created and export the store

import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

the component that uses the state is created in the following code and App is wrapped inside a redux provider Component and the above store is provided as a props in index.js

import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (

      {busses.map((bus) => (

{bus.description}

            <button onClick={() => handleRemove(bus.id)}>delete</button>

      ))}

  );
}

using redux dev tools i can see an action busses\removeBus is dispatched with the appropriate payload value but nothing is happening to the state.

Body:
You can change:

removeBus: (state, action) => {
      state.filter((bus) => bus.id != action.payload);
      console.log(action.payload);
    }

can be the data types of bus.id and action.payload are different.


问:
Switch from one git branch to another without loosing the newly added code
I have a repository having two branches master ( keeps final error free code ) and develop ( developing branch ).The default branch is master, I cloned and worked on the project, but unfortunately I forgot to checkout to the develop branch before I start coding.So all the changes that I made will be on the master branch. Is there any way to switch the branch after developing? so that I can commit and push the code only to the develop branch without loosing my code.</p>

答:
```<code>git fetch origin master
git checkout main
</code>```

this command will switch your branch

Body:
git fetch origin master
git checkout main

this command will switch your branch


答:
If you don't have any work saved on your develop branch, just delete it with git branch -d develop and rename master to develop with git branch -m master develop.

If you have something already on your develop, just merge the changes into develop with git checkout develop then git merge master.

Title: Switch from one git branch to another without loosing the newly added code

Body: I have a repository having two branches master ( keeps final error free code ) and develop ( developing branch ).The default branch is master, I cloned and worked on the project, but unfortunately I forgot to checkout to the develop branch before I start coding.So all the changes that I made will be on the master branch. Is there any way to switch the branch after developing? so that I can commit and push the code only to the develop branch without loosing my code.


问:
Auto remove container with docker-compose.yml
docker-compose run has a flag --rm that auto removes the container after run. I am wondering if theres an equivalent config with docker-compose.yml for a specific service, as one of which services i got in yml is a one off build process which should just output the compile file and disappear itself.

答:
It's been quite some time since this question was posted, but I thought it would be informative to share something that worked for my case, in 2022 :)
But keep in mind that this solution still does not remove old containers, as the original author intended to achieve.

```<code>docker-compose up --force-recreate -V
</code>```

In my case, I have a small Redis cluster where I want the data to be completely erased after I stop the servers.
Only using --force-recreate didn't do the trick, because the anonymous volume is still reused. That's where -V comes in.

Body:
It's been quite some time since this question was posted, but I thought it would be informative to share something that worked for my case, in 2022 :)
But keep in mind that this solution still does not remove old containers, as the original author intended to achieve.

docker-compose up --force-recreate -V

In my case, I have a small Redis cluster where I want the data to be completely erased after I stop the servers.
Only using --force-recreate didn't do the trick, because the anonymous volume is still reused. That's where -V comes in.


问:
Transfer doctrine query to native SQL without function
i'd like to ask if anybody can translate this PHP code (doctrine) to native SQL. I find out solution on one of my problem but only in doctrine and id like to see native SQL.

```<code>$repository->createQueryBuilder('r')
        ->where('r.order >= :order')
        ->setParameter('order', $nextItem ? $nextItem->getOrder() : 0)
        ->andWhere('r.order < :order2')
        ->setParameter('order2', $item->getOrder())
        ->getQuery()
        ->getResult();
</code>```

Thank u very much.

答:
After ->getQuery() you can call ->getSQL()

In the Query class:

```<code>    /**
     * Gets the SQL query/queries that correspond to this DQL query.
     *
     * @return mixed The built sql query or an array of all sql queries.
     *
     * @override
     */
    public function getSQL()
    {
        return $this->parse()->getSqlExecutor()->getSqlStatements();
    }
</code>```

update

For whatever rewason, his code isnt in the project, and he isn't even using doctrine. I guess what he is looking for is this:

SELECT * FROM  yourtable r WHERE r.order >= :order AND r.order < :order2

Body:
i'd like to ask if anybody can translate this PHP code (doctrine) to native SQL. I find out solution on one of my problem but only in doctrine and id like to see native SQL.

$repository->createQueryBuilder('r')
        ->where('r.order >= :order')
        ->setParameter('order', $nextItem ? $nextItem->getOrder() : 0)
        ->andWhere('r.order < :order2')
        ->setParameter('order2', $item->getOrder())
        ->getQuery()
        ->getResult();

Thank u very much.

Body:
After ->getQuery() you can call ->getSQL()

In the Query class:

    /**
     * Gets the SQL query/queries that correspond to this DQL query.
     *
     * @return mixed The built sql query or an array of all sql queries.
     *
     * @override
     */
    public function getSQL()
    {
        return $this->parse()->getSqlExecutor()->getSqlStatements();
    }

update

For whatever rewason, his code isnt in the project, and he isn't even using doctrine. I guess what he is looking for is this:

SELECT * FROM  yourtable r WHERE r.order >= :order AND r.order < :order2


问:
training stops after a while
i'm trying to solve classification problem(cat vs dog)
in the middle of the first epoch my training got interrupted
i'm using image_dataset_from_directory to read my images:

```<code>train_dataset = image_dataset_from_directory(data_set_path+'/train' , labels='inferred',label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)
val_dataset = image_dataset_from_directory(data_set_path+'/val' , labels='inferred', label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)
test_dataset = image_dataset_from_directory(data_set_path+'/test' , labels='inferred', label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)
</code>```

and my model is as follow:

```<code>inputs = keras.Input(shape=(180,180,3))
x = data_augmentation(inputs)
x = layers.Rescaling(1./255)(x)
x = layers.Conv2D(32,3,padding = 'same', use_bias = False)(x)
for filter_size in (32,64,128,256,512):
    residual = x
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.SeparableConv2D(filter_size,3,padding= 'same' ,use_bias=False)(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.SeparableConv2D(filter_size,3,padding= 'same', use_bias=False)(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.MaxPooling2D(3, strides = 2 , padding= 'same')(x)

    residual = layers.Conv2D(filter_size,1,strides = 2,padding= 'same', use_bias= False)
    (residual)
    x = layers.add([x, residual])
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dropout(0.5)(x)
output = layers.Dense(1, activation = 'sigmoid')(x)
model = keras.Model(inputs = inputs, outputs=output)
</code>```

in the middle of first epoch i get this error:

```<code>InvalidArgumentError: Graph execution error:

2 root error(s) found.
  (0) INVALID_ARGUMENT:  Input is empty.
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
     [[model_1/sequential/random_rotation/Shape/_4]]
  (1) INVALID_ARGUMENT:  Input is empty.
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_7730]
</code>```

i would be grateful if anyone can help me

答:
I am not sure if it is the case for your error but I had problems with dogs vs cats dataset before. A few of the images were corrupted and needed to be removed before training could proceed.

Try reading the images with opencv or skimage and remove the ones with exception.

Issue with dataset, https://discuss.pytorch.org/t/pil-unidentifiedimageerror-in-dataloader/73577.

Title: training stops after a while

Body:
i'm trying to solve classification problem(cat vs dog)
in the middle of the first epoch my training got interrupted
i'm using image_dataset_from_directory to read my images:

train_dataset = image_dataset_from_directory(data_set_path+'/train' , labels='inferred',label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)
val_dataset = image_dataset_from_directory(data_set_path+'/val' , labels='inferred', label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)
test_dataset = image_dataset_from_directory(data_set_path+'/test' , labels='inferred', label_mode='binary', batch_size=32, image_size=(180,180), seed= 348)

and my model is as follow:

inputs = keras.Input(shape=(180,180,3))
x = data_augmentation(inputs)
x = layers.Rescaling(1./255)(x)
x = layers.Conv2D(32,3,padding = 'same', use_bias = False)(x)
for filter_size in (32,64,128,256,512):
    residual = x
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.SeparableConv2D(filter_size,3,padding= 'same' ,use_bias=False)(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.SeparableConv2D(filter_size,3,padding= 'same', use_bias=False)(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)

    x = layers.MaxPooling2D(3, strides = 2 , padding= 'same')(x)

    residual = layers.Conv2D(filter_size,1,strides = 2,padding= 'same', use_bias= False)
    (residual)
    x = layers.add([x, residual])
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dropout(0.5)(x)
output = layers.Dense(1, activation = 'sigmoid')(x)
model = keras.Model(inputs = inputs, outputs=output)

in the middle of first epoch i get this error:

InvalidArgumentError: Graph execution error:

2 root error(s) found.
  (0) INVALID_ARGUMENT:  Input is empty.
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
     [[model_1/sequential/random_rotation/Shape/_4]]
  (1) INVALID_ARGUMENT:  Input is empty.
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_7730]

i would be grateful if anyone can help me


问:
Generating a tree in Excel
I have some data in an Excel sheet that represents a hierarchy. As the tree is large and reviewing the data is becoming quite a task, I am trying to generate a pictorial representation of the tree. Excel doesn't seem to have built-in support for tree generation. What would be the best way to generate the tree from within Excel? Are there add-ons available?

Suggestions related to tree generation using other tools would also be welcome. (I have already tried the org chart option in Visio. For some reason, it could not open my Excel file.)

答: I have used the ActiveX Treeview Control on Excel sheets, and it is fine. HOWEVER, depending on your version of Windows and which Security Updates you have, it may or may not work. I developed an application using one, for a major City bank, but we had to re-work entirely when certain upgrades were applied company-wide. After a very long and useless discussion with Microsoft in the US, we got nowhere at all. If you Google "excel treeview security upgrades" you'll find various discussions. I suggest using 3rd party, though I can't suggest one. </p>

Title: Generating a tree in Excel


问:
How to use DropDownButton for dynamic list in flutter?
I am trying to implement dynamic dropdownButton in my app where the items of dropdown is going to come from the names of columns in my excel sheet. I am able to show all the columns of excel but I couldn't able to trace the index of column which the user is selecting from the dropdown.

I tried to make a map of dropdownitems like this in which the key is the index and value is the DropdownMenuItem like this :

```<code>late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<int,DropdownMenuItem<String>>> dropdownItems = [];
</code>```

Then I added some values by iterating the columns of excel using a for loop :

```<code>excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      var newItem = DropdownMenuItem(
         child: Text(val),
              value: val,
          );
       dropdownItems.add({i:newItem});
   }

}
</code>```

But I could not able to map the values in items attribute of DropdownButton, I tried to implement like this but this is throwing error

```<code>DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((int i,DropdownMenuItem<String> p) => p).toList(),
 onChanged: (String? value){
      setState(() {
            initialDropDownVal = value!;
       });
})
</code>```

And I am not sure how to change set the selectedIndex in onChanged function. Please help me in this. Thanks

答:
```<code>late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<String,int>> dropdownItems = [];
</code>```
```<code>excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      dropdownItems.add({val:i});
   }

}
</code>```
```<code>DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((e) {
             return DropdownMenuItem(
                    child: Text(e.keys.first),
                    value: e.keys.first,
             );
       }).toList(),
onChanged: (String? value){
            setState(() {
            initialDropDownVal = value!;

            for(int i = 0; i< dropdownItems.length; ++i){
                if(dropdownItems[i].keys.first==value){
                     setState(() {
                           selectedIndex = dropdownItems[i].values.first;

                      });
                      break;
                            }
                          }
                        });
                      }),
)
</code>```

Body:
I am trying to implement dynamic dropdownButton in my app where the items of dropdown is going to come from the names of columns in my excel sheet. I am able to show all the columns of excel but I couldn't able to trace the index of column which the user is selecting from the dropdown.

I tried to make a map of dropdownitems like this in which the key is the index and value is the DropdownMenuItem like this :

late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<int,DropdownMenuItem<String>>> dropdownItems = [];

Then I added some values by iterating the columns of excel using a for loop :

excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      var newItem = DropdownMenuItem(
         child: Text(val),
              value: val,
          );
       dropdownItems.add({i:newItem});
   }

}

But I could not able to map the values in items attribute of DropdownButton, I tried to implement like this but this is throwing error

DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((int i,DropdownMenuItem<String> p) => p).toList(),
 onChanged: (String? value){
      setState(() {
            initialDropDownVal = value!;
       });
})

And I am not sure how to change set the selectedIndex in onChanged function. Please help me in this. Thanks

Body:
late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<String,int>> dropdownItems = [];

excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      dropdownItems.add({val:i});
   }

}

DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((e) {
             return DropdownMenuItem(
                    child: Text(e.keys.first),
                    value: e.keys.first,
             );
       }).toList(),
onChanged: (String? value){
            setState(() {
            initialDropDownVal = value!;

            for(int i = 0; i< dropdownItems.length; ++i){
                if(dropdownItems[i].keys.first==value){
                     setState(() {
                           selectedIndex = dropdownItems[i].values.first;

                      });
                      break;
                            }
                          }
                        });
                      }),
)


问:
Blazor server route prefix dynamic
I have an Blazor server Application and we need to set up an global route prefix that we can use to set specific data based on the prefix. Is there any solution for that?

Ex. We want this /company/{companyID}/
To be on Every route and have a Middleware or something similar to cath the companyID in.

```<code>endpoints.MapGet("/company/{companyID:regex(^[a-zA-Z]{{3,100}}(-[a-zA-Z+]{{3,100}})?$)}/{**rest}", async context =>
                {
                    var companyID = context.Request.RouteValues["companyID"]?.ToString()?.ToLower() ?? "default";
                    var restPath = context.Request.RouteValues["rest"]?.ToString()?.ToLower();

// Here i do stuff with the CompanyID

                    // This is for now, but will redirect to /index without company/companyID. Here i just want to go on with the Ondex component and keep the url.
                    context.Response.Redirect(restPath == null ? "/" : $"/{restPath}");
                });

                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
</code>```

答:
This may fit your requirements.  It uses LocalStorage to persist the company name instead of cookies.  I've set it up using the Blazor Server template.

Install Blazored.LocalStorage

First a Company Service

```<code>using Blazored.LocalStorage;

namespace Blazor.Company;

public class CompanyService
{
    private ILocalStorageService _localStorageService;

    public const string CompanyNameKey = "CompanyName";

    public string CompanyName { get; private set; } = string.Empty;

    public CompanyService(ILocalStorageService localStorageService)
        => _localStorageService = localStorageService;

    public async Task SetCompany(string company)
    {
        this.CompanyName = company;
        await _localStorageService.SetItemAsync<string>(CompanyNameKey, company);
    }

    public async Task<string> GetCompany()
    {
        this.CompanyName = await _localStorageService.GetItemAsync<string>(CompanyNameKey);
        return this.CompanyName;
    }
}
</code>```

Program looks like this:

```<code>builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<CompanyService>();
</code>```

Index looks like this:

```<code>page "/"
@page "/Company"
@page "/Company/{CompanyName}"

<PageTitle>Index</PageTitle>

@if (this.hasCompany && this.isSet)
{
    <div class="m-2 p-4 bg-success text-white">
        <h3>You work for : @CompanyService.CompanyName</h3>
    </div>
}
@if (this.isSet && !this.hasCompany)
{
    <div class="m-2 p-4 bg-danger text-white">
        You need to set up your company
    </div>
}

@code {
    [Parameter] public string CompanyName { get; set; } = string.Empty;

    private string companyName = string.Empty;

    private bool isSet = false;
    private bool hasCompany => !string.IsNullOrWhiteSpace(this.companyName);

    [Inject] private CompanyService? companyService { get; set; }
    private CompanyService CompanyService => companyService!;

    protected override void OnInitialized()
    {
        if (!string.IsNullOrWhiteSpace(this.CompanyName))
            companyName = this.CompanyName;
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            if (string.IsNullOrWhiteSpace(this.companyName))
                companyName = await CompanyService.GetCompany();
            else
                await CompanyService.SetCompany(companyName);

            this.isSet = true;
            StateHasChanged();
        }
    }
}
</code>```

Title: Blazor server route prefix dynamic

Body:
I have an Blazor server Application and we need to set up an global route prefix that we can use to set specific data based on the prefix. Is there any solution for that?

Ex. We want this /company/{companyID}/
To be on Every route and have a Middleware or something similar to cath the companyID in.

endpoints.MapGet("/company/{companyID:regex(^[a-zA-Z]{{3,100}}(-[a-zA-Z+]{{3,100}})?$)}/{**rest}", async context =>
                {
                    var companyID = context.Request.RouteValues["companyID"]?.ToString()?.ToLower() ?? "default";
                    var restPath = context.Request.RouteValues["rest"]?.ToString()?.ToLower();

// Here i do stuff with the CompanyID

                    // This is for now, but will redirect to /index without company/companyID. Here i just want to go on with the Ondex component and keep the url.
                    context.Response.Redirect(restPath == null ? "/" : $"/{restPath}");
                });

                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");

Body:
This may fit your requirements.  It uses LocalStorage to persist the company name instead of cookies.  I've set it up using the Blazor Server template.

Install Blazored.LocalStorage

First a Company Service

using Blazored.LocalStorage;

namespace Blazor.Company;

public class CompanyService
{
    private ILocalStorageService _localStorageService;

    public const string CompanyNameKey = "CompanyName";

    public string CompanyName { get; private set; } = string.Empty;

    public CompanyService(ILocalStorageService localStorageService)
        => _localStorageService = localStorageService;

    public async Task SetCompany(string company)
    {
        this.CompanyName = company;
        await _localStorageService.SetItemAsync<string>(CompanyNameKey, company);
    }

    public async Task<string> GetCompany()
    {
        this.CompanyName = await _localStorageService.GetItemAsync<string>(CompanyNameKey);
        return this.CompanyName;
    }
}

Program looks like this:

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<CompanyService>();

Index looks like this:

page "/"
@page "/Company"
@page "/Company/{CompanyName}"

<PageTitle>Index</PageTitle>

@if (this.hasCompany && this.isSet)
{
    <div class="m-2 p-4 bg-success text-white">
        <h3>You work for : @CompanyService.CompanyName</h3>
    </div>
}
@if (this.isSet && !this.hasCompany)
{
    <div class="m-2 p-4 bg-danger text-white">
        You need to set up your company
    </div>
}

@code {
    [Parameter] public string CompanyName { get; set; } = string.Empty;

    private string companyName = string.Empty;

    private bool isSet = false;
    private bool hasCompany => !string.IsNullOrWhiteSpace(this.companyName);

    [Inject] private CompanyService? companyService { get; set; }
    private CompanyService CompanyService => companyService!;

    protected override void OnInitialized()
    {
        if (!string.IsNullOrWhiteSpace(this.CompanyName))
            companyName = this.CompanyName;
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            if (string.IsNullOrWhiteSpace(this.companyName))
                companyName = await CompanyService.GetCompany();
            else
                await CompanyService.SetCompany(companyName);

            this.isSet = true;
            StateHasChanged();
        }
    }
}


问:
Google Sheets pivot data with multiple values
I'm trying to display sample data as follows. I'm able to do this using pivot tables and multiple values with no problem but would like to find a way using either Query or some other method. This problem was partly solved using the formula below but does not include the 'Other' column.

```<code>=Index({"",Transpose(Unique(Filter(B2:B,B2:B<>"")));Flatten({Sort(Unique(C2:C)),IFError(Unique(C2:C)/0)}),IFNA(VLookup(Transpose(Unique(Filter(B2:B,B2:B<>"")))&Flatten({Text(Sort(Unique(C2:C)),"hh:mm"),Text(Sort(Unique(C2:C)),"hh:mm")&".1"}),{Flatten({B2:B&Text(C2:C,"hh:mm"),B2:B&Text(C2:C,"hh:mm")&".1"}),Flatten({A2:A,D2:D})},2,0))})
</code>```

Sample data:

Desired result:

答:
use:

```<code>=ARRAYFORMULA({"", TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")));
 FLATTEN({SORT(UNIQUE(C2:C)), IFERROR(TEXT(UNIQUE(C2:C), {"@", "@"})/0)}),
 IFNA(VLOOKUP(TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")))&FLATTEN({TEXT(SORT(UNIQUE(C2:C)), "hh:mm"),
 TEXT(SORT(Unique(C2:C)), "hh:mm")&{".1", ".2"}}), {FLATTEN({B2:B&TEXT(C2:C, "hh:mm"),
 B2:B&TEXT(C2:C, "hh:mm")&{".1", ".2"}}), FLATTEN({A2:A, D2:D, E2:E})}, 2, ))})
</code>```

Body:
I'm trying to display sample data as follows. I'm able to do this using pivot tables and multiple values with no problem but would like to find a way using either Query or some other method. This problem was partly solved using the formula below but does not include the 'Other' column.

=Index({"",Transpose(Unique(Filter(B2:B,B2:B<>"")));Flatten({Sort(Unique(C2:C)),IFError(Unique(C2:C)/0)}),IFNA(VLookup(Transpose(Unique(Filter(B2:B,B2:B<>"")))&Flatten({Text(Sort(Unique(C2:C)),"hh:mm"),Text(Sort(Unique(C2:C)),"hh:mm")&".1"}),{Flatten({B2:B&Text(C2:C,"hh:mm"),B2:B&Text(C2:C,"hh:mm")&".1"}),Flatten({A2:A,D2:D})},2,0))})

Sample data:

Desired result:

Body:
use:

=ARRAYFORMULA({"", TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")));
 FLATTEN({SORT(UNIQUE(C2:C)), IFERROR(TEXT(UNIQUE(C2:C), {"@", "@"})/0)}),
 IFNA(VLOOKUP(TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")))&FLATTEN({TEXT(SORT(UNIQUE(C2:C)), "hh:mm"),
 TEXT(SORT(Unique(C2:C)), "hh:mm")&{".1", ".2"}}), {FLATTEN({B2:B&TEXT(C2:C, "hh:mm"),
 B2:B&TEXT(C2:C, "hh:mm")&{".1", ".2"}}), FLATTEN({A2:A, D2:D, E2:E})}, 2, ))})


问:
ASP.NET Core 2 - ReSharper "Create Razor View" adds new view to Pages folder
I've started trying out new ASP.NET Core 2 for building an MVC Web App, and it looks good so far...

Except that when I create Views from my controller actions, ReSharper creates them in a Pages folder, rather than the Views folder (where I generally like to keep my Views ;-) )

ReSharper doesn't behave this way for regular ASP.NET Web Apps (not core), it puts the views in the correct view folder, so this looks to be to do with Core / Core 2.

What is resharper using to decide where to create the view?

How can I change this behavior so that it creates the views in the traditional location?

答:
This still applies to the ASP.NET Core Web App (Model-View-Controller) .NET 6 template installed with VS 2022. R# generates views in \Pages by default, which is the wrong location anyway.

With the ResharperConfig.cs (as described above) now R# creates the views in the right place, assuming the View's parent folder exists.

My entity centered Clean Architecture configuration:

```<code>using JetBrains.Annotations;

[assembly: AspMvcMasterLocationFormat("~/Views/{1}/{0}.cshtml")]
[assembly: AspMvcViewLocationFormat("~/{1}/Views/{0}.cshtml")]
[assembly: AspMvcPartialViewLocationFormat("~/Views/Shared/{0}.cshtml")]
[assembly: AspMvcAreaMasterLocationFormat("~/Areas/{2}/Views/{1}/{0}.cshtml")]
[assembly: AspMvcAreaViewLocationFormat("~/Areas/{2}/Views/{1}/{0}.cshtml")]
[assembly: AspMvcAreaPartialViewLocationFormat("~/Areas/{2}/Views/Shared/{0}.cshtml")]
</code>```

This [assembly: AspMvcViewLocationFormat("~/{1}/Views/{0}.cshtml")] makes sure R# generates views in this location:
\<Controller>\Views\<Action>.cshtml

You should combine that with a IViewLocationExpander to instruct .NET to also look in the same location to find the views while rendering them:

```<code>using Microsoft.AspNetCore.Mvc.Razor;

public class CleanArchViewLocationExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context)
    {
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(l => l.Replace("/Views/{1}/", "/{1}/Views/"));
    }
}
</code>```

Which you then register in Program.cs like this:

```<code>builder.Services.Configure<RazorViewEngineOptions>(
    options =>
    {
        options.ViewLocationExpanders.Add(new CleanArchViewLocationExpander());
    });
</code>```

Happy coding!

Body:
This still applies to the ASP.NET Core Web App (Model-View-Controller) .NET 6 template installed with VS 2022. R# generates views in \Pages by default, which is the wrong location anyway.

With the ResharperConfig.cs (as described above) now R# creates the views in the right place, assuming the View's parent folder exists.

My entity centered Clean Architecture configuration:

using JetBrains.Annotations;

[assembly: AspMvcMasterLocationFormat("~/Views/{1}/{0}.cshtml")]
[assembly: AspMvcViewLocationFormat("~/{1}/Views/{0}.cshtml")]
[assembly: AspMvcPartialViewLocationFormat("~/Views/Shared/{0}.cshtml")]
[assembly: AspMvcAreaMasterLocationFormat("~/Areas/{2}/Views/{1}/{0}.cshtml")]
[assembly: AspMvcAreaViewLocationFormat("~/Areas/{2}/Views/{1}/{0}.cshtml")]
[assembly: AspMvcAreaPartialViewLocationFormat("~/Areas/{2}/Views/Shared/{0}.cshtml")]

This [assembly: AspMvcViewLocationFormat("~/{1}/Views/{0}.cshtml")] makes sure R# generates views in this location:
\<Controller>\Views\<Action>.cshtml

You should combine that with a IViewLocationExpander to instruct .NET to also look in the same location to find the views while rendering them:

using Microsoft.AspNetCore.Mvc.Razor;

public class CleanArchViewLocationExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context)
    {
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(l => l.Replace("/Views/{1}/", "/{1}/Views/"));
    }
}

Which you then register in Program.cs like this:

builder.Services.Configure<RazorViewEngineOptions>(
    options =>
    {
        options.ViewLocationExpanders.Add(new CleanArchViewLocationExpander());
    });

Happy coding!


问:
Show H1 somwhere else on the page again without typing it manually (as a kind of variable)?
I am searching for a way to display an H1 somwhere else on the page again with just HTML or JavaScript.

What I mean: I do have a H1-title which is typed in manually. And I want it automatically be displayed at the bottom on the page again, without having to type it in manually again. (The thing with the bottom on the page is just an example, my project is a bit more complex).

I'm searching kind of a variable, I think.

Thanks in advance for your help.

答:
 x = document.getElementById("title").innerHTML ;
document.getElementById("reap").innerHTML = x;```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <h1 id="title">Your manually written title</h1>

<h1 id="reap">Where You want to show it again</h1></code>```

you can do this with the help of the backend or just create an id for H1 eg...

```<code><h1 id="title">Your manually written title</h1>

<h1 id="reap">Where You want to show it again</h1>
</code>```

just select with

```<code>x = document.getElementById("title").innerHTML ;
document.getElementById("reap").innerHTML = x;
</code>```

Just create a variable with query selector

Body:
 x = document.getElementById("title").innerHTML ;
document.getElementById("reap").innerHTML = x;

 <h1 id="title">Your manually written title</h1>

<h1 id="reap">Where You want to show it again</h1>

you can do this with the help of the backend or just create an id for H1 eg...

<h1 id="title">Your manually written title</h1>

<h1 id="reap">Where You want to show it again</h1>

just select with

x = document.getElementById("title").innerHTML ;
document.getElementById("reap").innerHTML = x;

Just create a variable with query selector


问:
filter duplicate elements from an array using collection
I don't resolve the processList error.
I am using collection to filter duplicate elements from an array and print as a list.
Form a list of numbers from 0-9.
Insert a new set of numbers from 0-5.</p>
```<code>package programming;

    import java.awt.List;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Set;

    public class FillterDublicateElementFromArrayPrintList2 {
        public static void main(String[] args) {

            ArrayList<String> list = new ArrayList<String>();

            // Form a list of numbers from 0-9.
            for (int i = 0; i < 10; i++) {
                list.add(String.valueOf(i));
            }

            for (int i = 0; i < 5; i++) {
                list.add(String.valueOf(i));
            }

            System.out.println("Input list : " + list);
            System.out.println("\nFiltered duplicates : " + processList(list));
        }

        public static Set<String> processList(List<String> listContainingDuplicates) {

            final Set<String> resultSet = new HashSet<String>();
            final Set<String> tempSet = new HashSet<String>();

            for (String yourInt : listContainingDuplicates) {
                if (!tempSet.add(yourInt)) {
                    resultSet.add(yourInt);
                }
            }
            return resultSet;
        }
    }
</code>```

答:
you definitely have logical problems in realizing your processList function, you can follow the following steps:

put all the elements of the list in a set.

create a new list.

iterate the set, then put each element of the set into the new list.

return the new list.
done.

Body:
I don't resolve the processList error.
I am using collection to filter duplicate elements from an array and print as a list.
Form a list of numbers from 0-9.
Insert a new set of numbers from 0-5.

package programming;

    import java.awt.List;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Set;

    public class FillterDublicateElementFromArrayPrintList2 {
        public static void main(String[] args) {

            ArrayList<String> list = new ArrayList<String>();

            // Form a list of numbers from 0-9.
            for (int i = 0; i < 10; i++) {
                list.add(String.valueOf(i));
            }

            for (int i = 0; i < 5; i++) {
                list.add(String.valueOf(i));
            }

            System.out.println("Input list : " + list);
            System.out.println("\nFiltered duplicates : " + processList(list));
        }

        public static Set<String> processList(List<String> listContainingDuplicates) {

            final Set<String> resultSet = new HashSet<String>();
            final Set<String> tempSet = new HashSet<String>();

            for (String yourInt : listContainingDuplicates) {
                if (!tempSet.add(yourInt)) {
                    resultSet.add(yourInt);
                }
            }
            return resultSet;
        }
    }


问:
Database Errors while running dbt run
I am new to dbt and I am trying to run dbt from cli, which is connected to snowflake. I have successfully created a profile.yml, dbt_profile.yml and dbt debug shows everything is connected. but when I run dbt run to create the example models I get this error

```<code>  Running with dbt=1.0.1
  Found 2 models, 4 tests, 0 snapshots, 0 analyses, 179 macros, 0 operations, 0 seed files, 0 sources, 0 exposures, 0 metrics
Encountered an error:
Runtime Error
  Database error while listing schemas in database "LEE_Test"
  Database Error
    002043 (02000): SQL compilation error:
    Object does not exist, or operation cannot be performed.
</code>```

答:
okay there might be a  problems in your dbt profile in which u have given the snowflake detials there is some mistake there  probably in naming or either

here is an exmaple on how you can connect to snowflake

```<code>default:(profile name )
  outputs:

    dev: # User-Password config
      type: snowflake
      account: snowflake_account_link
      user: DBT_CLOUD_DEV
      password: *******
      role: your role of snowflake
      database: your data base name
      warehouse: name of your warehouse
      schema: <your schema name >
      threads: 2
      client_session_keep_alive: False

  target: dev

</code>```

let me know if this works or not

Title: Database Errors while running dbt run

Body:
I am new to dbt and I am trying to run dbt from cli, which is connected to snowflake. I have successfully created a profile.yml, dbt_profile.yml and dbt debug shows everything is connected. but when I run dbt run to create the example models I get this error

  Running with dbt=1.0.1
  Found 2 models, 4 tests, 0 snapshots, 0 analyses, 179 macros, 0 operations, 0 seed files, 0 sources, 0 exposures, 0 metrics
Encountered an error:
Runtime Error
  Database error while listing schemas in database "LEE_Test"
  Database Error
    002043 (02000): SQL compilation error:
    Object does not exist, or operation cannot be performed.

Body:
okay there might be a  problems in your dbt profile in which u have given the snowflake detials there is some mistake there  probably in naming or either

here is an exmaple on how you can connect to snowflake

default:(profile name )
  outputs:

    dev: # User-Password config
      type: snowflake
      account: snowflake_account_link
      user: DBT_CLOUD_DEV
      password: *******
      role: your role of snowflake
      database: your data base name
      warehouse: name of your warehouse
      schema: <your schema name >
      threads: 2
      client_session_keep_alive: False

  target: dev

let me know if this works or not


问:
composer.lock changes despite "Nothing to install or update"
I'm confused by Composer's behaviour when I try to update a single package.

Per the docs and Stack Overflow answers like this one, I should be able to update a single package with a command like

```<code>composer update somevendor/somepackage
</code>```

My expectation when I do this is that my vendor folder and composer.lock should be left unmodified with the exception of somevendor/somepackage and its dependencies. However, this is not the case. Instead, I see the hashes of some packages unrelated to the one I am updating change in composer.lock. Indeed, even if I try to update a nonexistent package by mashing the keyboard:

```<code>composer update adsfiodfsa/dsafiodsafio
</code>```

... then even though Composer tells me that there's nothing to update:

$ composer update adsfiodfsa/dsafiodsafio
Package "adsfiodfsa/dsafiodsafio" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
Generating optimized class loader```

<p>... I still see that <code>composer.lock</code> has changed! Stranger still, the <code>/vendor</code> folder (which I added to my Git repo for the purpose of testing this) <em>hasn't</em> been modified, even though the lock file seems to be claiming that I have different versions of some packages now:</p>

<pre class="lang-none prettyprint-override"><code>$ <b>git status</b>
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

    modified:   composer.lock

no changes added to commit (use "git add" and/or "git commit -a")</code>```

Is this intended behaviour, or a bug? If it's correct, can someone explain why my composer.lock file is changing despite nothing being updated? In case it helps, running a git diff on my composer.lock after the update (which doesn't modify the vendor folder) yields the following diff, which seems to clearly claim that some packages have changed:

diff --git a/composer.lock b/composer.lock
index e2f65b9..e6c9a95 100644
--- a/composer.lock
+++ b/composer.lock
@@ -1,7 +1,7 @@
 {
     "_readme": [
         "This file locks the dependencies of your project to a known state",
-        "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
         "This file is @generated automatically"
     ],
     "hash": "3d8098978270f73f9829e9d1138edef9",
@@ -583,7 +583,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/doctrine/dbal/zipball/9e7954694971a5fab6ebabb38f9ffeec49d0d2ad",
+                "url": "https://api.github.com/repos/doctrine/dbal/zipball/a0a43c0eb15ed66e71f8160b6bb25f4071ed22ca",
                 "reference": "9e7954694971a5fab6ebabb38f9ffeec49d0d2ad",
                 "shasum": ""
             },
@@ -879,7 +879,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/firebase/firebase-token-generator-php/zipball/61691f56372d32515350dd5522c78be64a0e8d60",
+                "url": "https://api.github.com/repos/firebase/firebase-token-generator-php/zipball/1044f9f5ec8b270dc6c073c7bf2fe67081dbfbb2",
                 "reference": "61691f56372d32515350dd5522c78be64a0e8d60",
                 "shasum": ""
             },
@@ -1076,7 +1076,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/RingPHP/zipball/dbbb91d7f6c191e5e405e900e3102ac7f261bc0b",
+                "url": "https://api.github.com/repos/guzzle/RingPHP/zipball/9465032ac5d6beaa55f10923403e6e1c36018d9c",
                 "reference": "dbbb91d7f6c191e5e405e900e3102ac7f261bc0b",
                 "shasum": ""
             },
@@ -1425,7 +1425,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/bf2bff61743f20a13dc46ff1e3bbd0f19c997d2b",
+                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/77aef55318035d37dbd4e87ea0c37a191f3e766e",
                 "reference": "bf2bff61743f20a13dc46ff1e3bbd0f19c997d2b",
                 "shasum": ""
             },
@@ -2027,7 +2027,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/php-fig/log/zipball/bf2c13de4300e227d7b2fd08027673a79c519987",
+                "url": "https://api.github.com/repos/php-fig/log/zipball/9e45edca52cc9c954680072c93e621f8b71fab26",
                 "reference": "bf2c13de4300e227d7b2fd08027673a79c519987",
                 "shasum": ""
             },
@@ -2211,7 +2211,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/ac8b475454c120bfb31f5bef475233dd4fb6b626",
+                "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/21b7eb31c51d98e9da0543527a0242875f3d92b9",
                 "reference": "ac8b475454c120bfb31f5bef475233dd4fb6b626",
                 "shasum": ""
             },
@@ -2744,7 +2744,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/HttpKernel/zipball/7b1632cf2bdbc69c59a44942b70d5aae91034304",
+                "url": "https://api.github.com/repos/symfony/HttpKernel/zipball/31652385d94eafc2103a98435d6d5bd7eea61736",
                 "reference": "7b1632cf2bdbc69c59a44942b70d5aae91034304",
                 "shasum": ""
             },
@@ -3405,7 +3405,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpspec/phpspec/zipball/73d0335bf8473be8bcfab5a9d66adce8d0db3857",
+                "url": "https://api.github.com/repos/phpspec/phpspec/zipball/147ff359413be67781d1dd1f3be5d7a4d4af769a",
                 "reference": "73d0335bf8473be8bcfab5a9d66adce8d0db3857",
                 "shasum": ""
             },
@@ -3483,7 +3483,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
+                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/5a355f91730c845301a9e28f91c8a5053353c496",
                 "reference": "3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
                 "shasum": ""
             },
@@ -3543,7 +3543,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/9ef4b8cbf3e839a44a9b375d8c59e109ac7aa020",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/688b6a58acb19c1899dc887b1efb6403dc6dc0bd",
                 "reference": "9ef4b8cbf3e839a44a9b375d8c59e109ac7aa020",
                 "shasum": ""
             },
@@ -3861,7 +3861,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/74ffb87f527f24616f72460e54b595f508dccb5c",
+                "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5034a3d9f2057a7b7d6ad03a984509dadfdda3cc",
                 "reference": "74ffb87f527f24616f72460e54b595f508dccb5c",
                 "shasum": ""
             },
```

答:
Leave looking to complicated solutions and start

```<code>composer init
</code>```

again.

Body:
I'm confused by Composer's behaviour when I try to update a single package.

Per the docs and Stack Overflow answers like this one, I should be able to update a single package with a command like

composer update somevendor/somepackage

My expectation when I do this is that my vendor folder and composer.lock should be left unmodified with the exception of somevendor/somepackage and its dependencies. However, this is not the case. Instead, I see the hashes of some packages unrelated to the one I am updating change in composer.lock. Indeed, even if I try to update a nonexistent package by mashing the keyboard:

composer update adsfiodfsa/dsafiodsafio

... then even though Composer tells me that there's nothing to update:

$ composer update adsfiodfsa/dsafiodsafio
Package "adsfiodfsa/dsafiodsafio" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
Generating optimized class loader

... I still see that composer.lock has changed! Stranger still, the /vendor folder (which I added to my Git repo for the purpose of testing this) hasn't been modified, even though the lock file seems to be claiming that I have different versions of some packages now:

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

    modified:   composer.lock

no changes added to commit (use "git add" and/or "git commit -a")

Is this intended behaviour, or a bug? If it's correct, can someone explain why my composer.lock file is changing despite nothing being updated? In case it helps, running a git diff on my composer.lock after the update (which doesn't modify the vendor folder) yields the following diff, which seems to clearly claim that some packages have changed:

diff --git a/composer.lock b/composer.lock
index e2f65b9..e6c9a95 100644
--- a/composer.lock
+++ b/composer.lock
@@ -1,7 +1,7 @@
 {
     "_readme": [
         "This file locks the dependencies of your project to a known state",
-        "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
         "This file is @generated automatically"
     ],
     "hash": "3d8098978270f73f9829e9d1138edef9",
@@ -583,7 +583,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/doctrine/dbal/zipball/9e7954694971a5fab6ebabb38f9ffeec49d0d2ad",
+                "url": "https://api.github.com/repos/doctrine/dbal/zipball/a0a43c0eb15ed66e71f8160b6bb25f4071ed22ca",
                 "reference": "9e7954694971a5fab6ebabb38f9ffeec49d0d2ad",
                 "shasum": ""
             },
@@ -879,7 +879,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/firebase/firebase-token-generator-php/zipball/61691f56372d32515350dd5522c78be64a0e8d60",
+                "url": "https://api.github.com/repos/firebase/firebase-token-generator-php/zipball/1044f9f5ec8b270dc6c073c7bf2fe67081dbfbb2",
                 "reference": "61691f56372d32515350dd5522c78be64a0e8d60",
                 "shasum": ""
             },
@@ -1076,7 +1076,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/RingPHP/zipball/dbbb91d7f6c191e5e405e900e3102ac7f261bc0b",
+                "url": "https://api.github.com/repos/guzzle/RingPHP/zipball/9465032ac5d6beaa55f10923403e6e1c36018d9c",
                 "reference": "dbbb91d7f6c191e5e405e900e3102ac7f261bc0b",
                 "shasum": ""
             },
@@ -1425,7 +1425,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/bf2bff61743f20a13dc46ff1e3bbd0f19c997d2b",
+                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/77aef55318035d37dbd4e87ea0c37a191f3e766e",
                 "reference": "bf2bff61743f20a13dc46ff1e3bbd0f19c997d2b",
                 "shasum": ""
             },
@@ -2027,7 +2027,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/php-fig/log/zipball/bf2c13de4300e227d7b2fd08027673a79c519987",
+                "url": "https://api.github.com/repos/php-fig/log/zipball/9e45edca52cc9c954680072c93e621f8b71fab26",
                 "reference": "bf2c13de4300e227d7b2fd08027673a79c519987",
                 "shasum": ""
             },
@@ -2211,7 +2211,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/ac8b475454c120bfb31f5bef475233dd4fb6b626",
+                "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/21b7eb31c51d98e9da0543527a0242875f3d92b9",
                 "reference": "ac8b475454c120bfb31f5bef475233dd4fb6b626",
                 "shasum": ""
             },
@@ -2744,7 +2744,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/HttpKernel/zipball/7b1632cf2bdbc69c59a44942b70d5aae91034304",
+                "url": "https://api.github.com/repos/symfony/HttpKernel/zipball/31652385d94eafc2103a98435d6d5bd7eea61736",
                 "reference": "7b1632cf2bdbc69c59a44942b70d5aae91034304",
                 "shasum": ""
             },
@@ -3405,7 +3405,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpspec/phpspec/zipball/73d0335bf8473be8bcfab5a9d66adce8d0db3857",
+                "url": "https://api.github.com/repos/phpspec/phpspec/zipball/147ff359413be67781d1dd1f3be5d7a4d4af769a",
                 "reference": "73d0335bf8473be8bcfab5a9d66adce8d0db3857",
                 "shasum": ""
             },
@@ -3483,7 +3483,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
+                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/5a355f91730c845301a9e28f91c8a5053353c496",
                 "reference": "3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
                 "shasum": ""
             },
@@ -3543,7 +3543,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/9ef4b8cbf3e839a44a9b375d8c59e109ac7aa020",
+                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/688b6a58acb19c1899dc887b1efb6403dc6dc0bd",
                 "reference": "9ef4b8cbf3e839a44a9b375d8c59e109ac7aa020",
                 "shasum": ""
             },
@@ -3861,7 +3861,7 @@
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/74ffb87f527f24616f72460e54b595f508dccb5c",
+                "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5034a3d9f2057a7b7d6ad03a984509dadfdda3cc",
                 "reference": "74ffb87f527f24616f72460e54b595f508dccb5c",
                 "shasum": ""
             },

Body:
Leave looking to complicated solutions and start

composer init

again.