问:
io.fabric8.kubernetes.client.KubernetesClientException: not ready after 70000 MILLISECONDS
Getting this Error from AKS Jenkins Agent pods. Any idea whats will be reason for this Error?
Troubleshooting steps i did.

revert Jenkins to old version => results in same Error
upgrade Jenkins to all new Version including plugins in use => Results in same Error.
Downgraded Jenkins K8s and K8s API plugins to stable version as per some suggestion in github. => same Error
Created Brand new cluster and install Jenkins and Job pod starting giving same Error. => same Error

How to fix this?

```<code>18:23:33  [Pipeline] // podTemplate
18:23:33  [Pipeline] End of Pipeline
18:23:33  io.fabric8.kubernetes.client.KubernetesClientException: not ready after 5000 MILLISECONDS
18:23:33    at io.fabric8.kubernetes.client.utils.Utils.waitUntilReadyOrFail(Utils.java:176)
18:23:33    at io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl.exec(PodOperationsImpl.java:322)
18:23:33    at io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl.exec(PodOperationsImpl.java:84)
18:23:33    at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.doLaunch(ContainerExecDecorator.java:413)
18:23:33    at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.launch(ContainerExecDecorator.java:330)
18:23:33    at hudson.Launcher$ProcStarter.start(Launcher.java:507)
18:23:33    at org.jenkinsci.plugins.durabletask.BourneShellScript.launchWithCookie(BourneShellScript.java:176)
18:23:33    at org.jenkinsci.plugins.durabletask.FileMonitoringTask.launch(FileMonitoringTask.java:132)
18:23:33    at org.jenkinsci.plugins.workflow.steps.durable_task.DurableTaskStep$Execution.start(DurableTaskStep.java:324)
18:23:33    at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:319)
18:23:33    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:193)
18:23:33    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
18:23:33    at jdk.internal.reflect.GeneratedMethodAccessor6588.invoke(Unknown Source)
18:23:33    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
18:23:33    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
18:23:33    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
18:23:33    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
18:23:33    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
18:23:33    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
18:23:33    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
18:23:33    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
18:23:33    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:163)
18:23:33    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
18:23:33    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:158)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
18:23:33    at WorkflowScript.run(WorkflowScript:114)
18:23:33    at ___cps.transform___(Native Method)
18:23:33    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
18:23:33    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
18:23:33    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
18:23:33    at jdk.internal.reflect.GeneratedMethodAccessor210.invoke(Unknown Source)
18:23:33    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
18:23:33    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
18:23:33    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
18:23:33    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
18:23:33    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
18:23:33    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
18:23:33    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
18:23:33    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
18:23:33    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
18:23:33    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
18:23:33    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
18:23:33    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
18:23:33    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)

</code>```

答:
EDIT: Doesn't seem to make any difference. Still getting 5000 ms timeouts, so not sure this method works (with Environment variables at least). It might work if you are actually able to change timeout, but I haven't got that figured out.

Started seeing the same issue after updating Jenkins (and plugins) only - not the K8S cluster.

Except I'm getting 5000 instead of 7000 milliseconds.

```<code>io.fabric8.kubernetes.client.KubernetesClientException: not ready after 5000 MILLISECONDS
</code>```

Digging into the stacktrace and source on Github leads back to this default timeout (which haven't changed in 6 years), so somehow you seem to have a non-default.

```<code>public static final Long DEFAULT_WEBSOCKET_TIMEOUT = 5 * 1000L;
</code>```

It seems it can be overriden with environment variable KUBERNETES_WEBSOCKET_TIMEOUT_SYSTEM_PROPERTY on the pod. I just tried to raise mine to 10sec seeing if it makes a difference.

Might be worth a try. If so, it could indicate that the cluster API-server is somehow slower than excepted to respond. I'm not aware of anything that should affect cluster performance around the time of the upgrade in my case, and since the default timeout haven't changed changed for years, it seems odd. Maybe some of the code was refactored somehow no longer ignoring timeouts/retrying etc - Only guessing.

EDIT: I'm on running on bare metal cluster

Body:
Getting this Error from AKS Jenkins Agent pods. Any idea whats will be reason for this Error?
Troubleshooting steps i did.

revert Jenkins to old version => results in same Error
upgrade Jenkins to all new Version including plugins in use => Results in same Error.
Downgraded Jenkins K8s and K8s API plugins to stable version as per some suggestion in github. => same Error
Created Brand new cluster and install Jenkins and Job pod starting giving same Error. => same Error

How to fix this?

18:23:33  [Pipeline] // podTemplate
18:23:33  [Pipeline] End of Pipeline
18:23:33  io.fabric8.kubernetes.client.KubernetesClientException: not ready after 5000 MILLISECONDS
18:23:33    at io.fabric8.kubernetes.client.utils.Utils.waitUntilReadyOrFail(Utils.java:176)
18:23:33    at io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl.exec(PodOperationsImpl.java:322)
18:23:33    at io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl.exec(PodOperationsImpl.java:84)
18:23:33    at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.doLaunch(ContainerExecDecorator.java:413)
18:23:33    at org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.launch(ContainerExecDecorator.java:330)
18:23:33    at hudson.Launcher$ProcStarter.start(Launcher.java:507)
18:23:33    at org.jenkinsci.plugins.durabletask.BourneShellScript.launchWithCookie(BourneShellScript.java:176)
18:23:33    at org.jenkinsci.plugins.durabletask.FileMonitoringTask.launch(FileMonitoringTask.java:132)
18:23:33    at org.jenkinsci.plugins.workflow.steps.durable_task.DurableTaskStep$Execution.start(DurableTaskStep.java:324)
18:23:33    at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:319)
18:23:33    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:193)
18:23:33    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
18:23:33    at jdk.internal.reflect.GeneratedMethodAccessor6588.invoke(Unknown Source)
18:23:33    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
18:23:33    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
18:23:33    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
18:23:33    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
18:23:33    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
18:23:33    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
18:23:33    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
18:23:33    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
18:23:33    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:163)
18:23:33    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
18:23:33    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:158)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:135)
18:23:33    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
18:23:33    at WorkflowScript.run(WorkflowScript:114)
18:23:33    at ___cps.transform___(Native Method)
18:23:33    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
18:23:33    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
18:23:33    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
18:23:33    at jdk.internal.reflect.GeneratedMethodAccessor210.invoke(Unknown Source)
18:23:33    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
18:23:33    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
18:23:33    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
18:23:33    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
18:23:33    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
18:23:33    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
18:23:33    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
18:23:33    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
18:23:33    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
18:23:33    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
18:23:33    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
18:23:33    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
18:23:33    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)

Body:
EDIT: Doesn't seem to make any difference. Still getting 5000 ms timeouts, so not sure this method works (with Environment variables at least). It might work if you are actually able to change timeout, but I haven't got that figured out.

Started seeing the same issue after updating Jenkins (and plugins) only - not the K8S cluster.

Except I'm getting 5000 instead of 7000 milliseconds.

io.fabric8.kubernetes.client.KubernetesClientException: not ready after 5000 MILLISECONDS

Digging into the stacktrace and source on Github leads back to this default timeout (which haven't changed in 6 years), so somehow you seem to have a non-default.

public static final Long DEFAULT_WEBSOCKET_TIMEOUT = 5 * 1000L;

It seems it can be overriden with environment variable KUBERNETES_WEBSOCKET_TIMEOUT_SYSTEM_PROPERTY on the pod. I just tried to raise mine to 10sec seeing if it makes a difference.

Might be worth a try. If so, it could indicate that the cluster API-server is somehow slower than excepted to respond. I'm not aware of anything that should affect cluster performance around the time of the upgrade in my case, and since the default timeout haven't changed changed for years, it seems odd. Maybe some of the code was refactored somehow no longer ignoring timeouts/retrying etc - Only guessing.

EDIT: I'm on running on bare metal cluster


来源: stackexchange

问:
Input wont reset after form submission?
I am using email.js to send emails client side, and validator to validate the email and phone number. Everything works fine, except... I am trying to empty the input fields after a successful submission.

Here is what I have so far:

State management:

```<code>    const formRef = useRef()
    const [emailError, setEmailError] = useState('')
    const [phoneError, setPhoneError] = useState('')

    const [inputValues, setInputValues] = useState({email: "", phone: ""})
    const handleOnChange = event => {
        const { name, value } = event.target;
        setInputValues({ ...inputValues, [name]: value });
        validateEmail(inputValues.email)
        validatePhone(inputValues.phone)
    };
</code>```

Validation and Submit handler:

```<code>    const validateEmail = (email) => {
        if (validator.isEmail(email)) {
            setEmailError('Valid Email :)')
            return true
        } else {
            setEmailError('Enter valid Email!')
             return false
        }

    }
    const validatePhone = (phone) => {
        if (validator.isMobilePhone(phone)) {
            setPhoneError('Valid Phone :)')
            return true
        } else {
            setPhoneError('Enter valid Phone!')
            return false
        }
    }

    const handleSubmit = (e) => {
        e.preventDefault()

        const isValidEmail = validateEmail(e.target.email.value)
        const isValidPhone = validatePhone(e.target.phone.value)

        if(isValidEmail && isValidPhone){
            console.log("if both inputs are true, on to submit")

            setSentMessage(false)

            //shouldnt this line empty out the current fields?
            setInputValues({email: "", phone: ""})
        } else {
            console.log("one of the inputs is false, wont submit")
        }
    }
</code>```

Form:

```<code><form ref={formRef} onSubmit={handleSubmit} className={classes.contactPageInputs}>

                <input placeholder='email' type="text" id="userEmail" name="email" onChange={(e) => handleOnChange(e)}></input>
                    <span style={{fontWeight: 'bold', color: 'red' }}>{emailError}</span>
                <input placeholder='phone' id="userPhone" name="phone" onChange={(e) => handleOnChange(e)}></input> <br />
                    <span style={{fontWeight: 'bold', color: 'red' }}>{phoneError}</span>
                <button className={classes.submitButton}>submit</button>
</form>
</code>```

QUESTION:
How can I reset the input fields after submission?

答:
Setting the form refs value to null worked.
Here is what I added to the handleSubmit function, after sending the email:

```<code>formRef.current[0].value = null
formRef.current[1].value = null
</code>```

UPDATE
This si the better way. I added value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message}   to each respective input field.

ContentLicense: CC BY-SA 4.0

Title: Input wont reset after form submission?

Body:
I am using email.js to send emails client side, and validator to validate the email and phone number. Everything works fine, except... I am trying to empty the input fields after a successful submission.

Here is what I have so far:

State management:

    const formRef = useRef()
    const [emailError, setEmailError] = useState('')
    const [phoneError, setPhoneError] = useState('')

    const [inputValues, setInputValues] = useState({email: "", phone: ""})
    const handleOnChange = event => {
        const { name, value } = event.target;
        setInputValues({ ...inputValues, [name]: value });
        validateEmail(inputValues.email)
        validatePhone(inputValues.phone)
    };

Validation and Submit handler:

    const validateEmail = (email) => {
        if (validator.isEmail(email)) {
            setEmailError('Valid Email :)')
            return true
        } else {
            setEmailError('Enter valid Email!')
             return false
        }

    }
    const validatePhone = (phone) => {
        if (validator.isMobilePhone(phone)) {
            setPhoneError('Valid Phone :)')
            return true
        } else {
            setPhoneError('Enter valid Phone!')
            return false
        }
    }

    const handleSubmit = (e) => {
        e.preventDefault()

        const isValidEmail = validateEmail(e.target.email.value)
        const isValidPhone = validatePhone(e.target.phone.value)

        if(isValidEmail && isValidPhone){
            console.log("if both inputs are true, on to submit")

            setSentMessage(false)

            //shouldnt this line empty out the current fields?
            setInputValues({email: "", phone: ""})
        } else {
            console.log("one of the inputs is false, wont submit")
        }
    }

Form:

<form ref={formRef} onSubmit={handleSubmit} className={classes.contactPageInputs}>

                <input placeholder='email' type="text" id="userEmail" name="email" onChange={(e) => handleOnChange(e)}></input>
                    {emailError}
                <input placeholder='phone' id="userPhone" name="phone" onChange={(e) => handleOnChange(e)}></input>

                    {phoneError}
                <button className={classes.submitButton}>submit</button>
</form>

QUESTION:
How can I reset the input fields after submission?

Body:
Setting the form refs value to null worked.
Here is what I added to the handleSubmit function, after sending the email:

formRef.current[0].value = null
formRef.current[1].value = null

UPDATE
This si the better way. I added value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message}   to each respective input field.


问:
Global variable is undefined if assign variable in the TargetConnected method in stimulus.js
This is the location controller file that is going to access by the html code.

```<code>export default class extends Controller {
    static targets = [ "visible", "map" ]

    mapTargetConnected(element) {
      this.name = "aaa"
    }

    add(event) {
      console.log(this.name) // this line is logged that variable is undefined.
    }
}
</code>```

here is the HTML code

```<code><%= form_with(model: @location, local: false, url: location_path(), data: {controller: 'location', action: 'ajax:beforeSend->location#add'}) do |form| %>
....
<% end %>
</code>```

This is the code regarding form submit via ajax request. if i access the this.name variable inside the add method or click event its says the variable is undefined… but if i same name variable assign it in connect() method than it’s working…

but i want to assign variable at targetConnected method and use it in the add action method.Please suggest any solution or let me know if i'm doing wrong.

答:
Most likely the add event is being triggered before the mapTargetConnected  has run.

Stimulus will go through the DOM and match elements and their targets and then trigger the relevant someTargetConnected  and connect lifecycle methods once the controller is set up.

However, this is not instant and there may be some nuance to how the timing works when you are working with other events.

You will need to work out when the actual map target is being added to the DOM and possibly do some logging to check that timing compared to when the ajax:beforeSend event triggers.

Sometimes, adding a setTimeout can assist as it will ensure that the code provided to it runs 'last' (there is some nuance to this, technically it is the next event cycle).

For example

    add(event) {
      // here the mapTargetConnected may not have run
      setTimeout(() => {
        // by this point, mapTargetConnected has hopefully now run
        console.log(this.name);
     });
    }
```

It is hard to offer more help without a bit more specifics on what ajax:beforeSend is and when it triggers, along with what actually adds the map target to the DOM. It may be more helpful to write this question with the initially rendered HTML output (with the minimum parts to help guide the question).

In general, it is good to remember that in the browser, things do not happen instantly, while they may be fast there can be timing issues to be aware of.

Body:
This is the location controller file that is going to access by the html code.

export default class extends Controller {
    static targets = [ "visible", "map" ]

    mapTargetConnected(element) {
      this.name = "aaa"
    }

    add(event) {
      console.log(this.name) // this line is logged that variable is undefined.
    }
}

here is the HTML code

<%= form_with(model: @location, local: false, url: location_path(), data: {controller: 'location', action: 'ajax:beforeSend->location#add'}) do |form| %>
....
<% end %>

This is the code regarding form submit via ajax request. if i access the this.name variable inside the add method or click event its says the variable is undefined… but if i same name variable assign it in connect() method than it’s working…

but i want to assign variable at targetConnected method and use it in the add action method.Please suggest any solution or let me know if i'm doing wrong.

Body:
Most likely the add event is being triggered before the mapTargetConnected  has run.

Stimulus will go through the DOM and match elements and their targets and then trigger the relevant someTargetConnected  and connect lifecycle methods once the controller is set up.

However, this is not instant and there may be some nuance to how the timing works when you are working with other events.

You will need to work out when the actual map target is being added to the DOM and possibly do some logging to check that timing compared to when the ajax:beforeSend event triggers.

Sometimes, adding a setTimeout can assist as it will ensure that the code provided to it runs 'last' (there is some nuance to this, technically it is the next event cycle).

For example

    add(event) {
      // here the mapTargetConnected may not have run
      setTimeout(() => {
        // by this point, mapTargetConnected has hopefully now run
        console.log(this.name);
     });
    }

It is hard to offer more help without a bit more specifics on what ajax:beforeSend is and when it triggers, along with what actually adds the map target to the DOM. It may be more helpful to write this question with the initially rendered HTML output (with the minimum parts to help guide the question).

In general, it is good to remember that in the browser, things do not happen instantly, while they may be fast there can be timing issues to be aware of.


问:
Bamboo build failing after intalling Clover plugin for Grails
After installing clover plugin my builds have started failing with the following error message:

“Failed to install plugin [clover-3.0.2]. Plugin has missing JAR dependencies.”

Any Ideas? As far as I can tell its missing hibernate core 3.1.1 GA but i am pretty sure i got that since grails runs fine.

答:
Sometimes I have this kind of mess up. For me it helps to wipe out my .grails home directory for the specific project. I think that the download was not completed somehow.

Try to delete .grails\1.3.7\projects\<PROJECTNAME>\plugins\clover-3.0.2 from your home directory. If this does not help, try to wipe out this plugins folder completely. I guess it will help. Good luck :-)

ContentLicense: CC BY-SA 3.0


问:
Inserting a degree symbol into python plot
This is a really simple problem but its escaping me. I'm just trying to insert a degree symbol into the titles and legends of my python plot. Code is below. Thanks.</p>

```<code>from numpy import *
import numpy as np
import matplotlib.pyplot as plt

theta1 = linspace(0,60,610)
theta2 = linspace(0,45,460)
theta3 = linspace(45,90,460)

CTS = 1/cos(radians(theta1))
CTS0 = 1/cos(radians(60-theta2))
CTS45 = 1/cos(radians(105-theta3))

plt.plot(theta1,CTS,label=u'CTS Head at 0',linewidth=2)
plt.plot(theta2,CTS0,label='CTS Head at 60',linewidth=2)
plt.plot(theta3,CTS45,label='CTS Head at 105',linewidth=2)

plt.xlabel('Manufactured Ply Angle (degrees)')
plt.ylabel('Thickness')

plt.legend( loc='lower right', numpoints = 1 )
plt.ylim([0,2.5])

plt.grid(b=None, which='major', axis='both')
plt.grid(color='k', linestyle='--', linewidth=0.5)
plt.axhline(y=1.035, xmin=0, xmax=90,color='k', linestyle='-', linewidth=1)

plt.show()
</code>```

答:
Similar to the answer given by dadaist, this also works for me to generate a degree symbol:

```<code>\N{degree sign}
</code>```

so, in your example it would be

```<code>plt.xlabel('Manufactured Ply Angle (\N{degree sign})')
</code>```

Body:
This is a really simple problem but its escaping me. I'm just trying to insert a degree symbol into the titles and legends of my python plot. Code is below. Thanks.

from numpy import *
import numpy as np
import matplotlib.pyplot as plt

theta1 = linspace(0,60,610)
theta2 = linspace(0,45,460)
theta3 = linspace(45,90,460)

CTS = 1/cos(radians(theta1))
CTS0 = 1/cos(radians(60-theta2))
CTS45 = 1/cos(radians(105-theta3))

plt.plot(theta1,CTS,label=u'CTS Head at 0',linewidth=2)
plt.plot(theta2,CTS0,label='CTS Head at 60',linewidth=2)
plt.plot(theta3,CTS45,label='CTS Head at 105',linewidth=2)

plt.xlabel('Manufactured Ply Angle (degrees)')
plt.ylabel('Thickness')

plt.legend( loc='lower right', numpoints = 1 )
plt.ylim([0,2.5])

plt.grid(b=None, which='major', axis='both')
plt.grid(color='k', linestyle='--', linewidth=0.5)
plt.axhline(y=1.035, xmin=0, xmax=90,color='k', linestyle='-', linewidth=1)

plt.show()

Body:
Similar to the answer given by dadaist, this also works for me to generate a degree symbol:

\N{degree sign}

so, in your example it would be

plt.xlabel('Manufactured Ply Angle (\N{degree sign})')


问:
Visual Studio Code Shortcut to "jump" a parentheses
Is there any shortcut or extension to "jump" a parentheses?

Like pressing tab in PyCharm.

答: When you write a pair of parenthesis and if you don't want to press the right arrow, you can press the right paranthesis key and it will do the same thing. If you navigate inside the paranthesesis again, a closed paranthesis will be typed instead</p>


问:
Are two identical sequential reads in a Postgres transaction guaranteed return the same records?
I was wondering if transactions in Postgres freeze the state of a table, similar to the way a  point-in-time does in Elasticsearch.

If have a query with a where clause, and I inside a transaction I run it, first as a count(*), then with a select, and finally, with an update, do I need to be worried about a different process inserting a record into the db and throwing off the results?

答:
In the default transaction isolation level READ COMMITTED, each statement in a transaction sees a different state (snapshot) of the database.

If you want all statements in a transaction to see the same snapshot, you will have to use the REPEATABLE READ isolation level. However, there is the possibility that concurrent data manipulations cause the UPDATE to fail with a serialization error, forcing you to repeat the transaction.


问:
Kotlin Flow "there is more than one label with such a name in this scope" on collect
I have a flow collection that I want to do a condition where if the list if empty to just return as there's no further work to be done.

my issue is that Android studio is tossing a nagging message at me

there is more than one label with such a name in this scope

I'm assuming it's upset because I'm doing a collect within a collect (see code below, it'll hopefully make sense why I'm doing that).

is there a way to relabel the collect so it knows which one I'm talking about, I didn't see anything on it.

Also I'm new to flow so if I'm doing this wrong, let me know the proper way as this seems valid as I need one flow for the other one.

viewModelScope.launch {
    companyDataStore.getFromDataStore()
        .catch { e ->
            _snackBar.value = e.message
        }.collect { company ->
            companyFeatures = company.features

            userClient.getGroupsByFeatures(companyFeatures)
                .catch { e ->
                    _snackBar.value = e.message
                }
            .collect { groupList ->
                if (groupList.data?.size == 0)
                {
                    return@collect
                }

                groups = groupList.data!!
                feedFilter.group = groups.firstOrNull()?.guid
            }
        }
}
```

答:
You can add labels to the collect blocks and use them with return statement:

```<code>.collect collectLabel2@ {
            // ...
            return@collectLabel2

            // ...
}
</code>```

Here label collectLabel2 is added.

To eliminate multiple collect blocks you can try to use flatMapMerge or flatMapLatest function:

```<code>viewModelScope.launch {
    companyDataStore.getFromDataStore()
        .catch { e ->
            _snackBar.value = e.message
        }
        .flatMapMerge { company ->
            companyFeatures = company.features

            userClient.getGroupsByFeatures(companyFeatures)
                .catch { e ->
                    _snackBar.value = e.message
                }
        }
        .collect { groupList ->
            if (groupList.data?.size != 0) {
                    groups = groupList.data!!
                    feedFilter.group = groups.firstOrNull()?.guid
            }
        }
}
</code>```

Body:
You can add labels to the collect blocks and use them with return statement:

.collect collectLabel2@ {
            // ...
            return@collectLabel2

            // ...
}

Here label collectLabel2 is added.

To eliminate multiple collect blocks you can try to use flatMapMerge or flatMapLatest function:

viewModelScope.launch {
    companyDataStore.getFromDataStore()
        .catch { e ->
            _snackBar.value = e.message
        }
        .flatMapMerge { company ->
            companyFeatures = company.features

            userClient.getGroupsByFeatures(companyFeatures)
                .catch { e ->
                    _snackBar.value = e.message
                }
        }
        .collect { groupList ->
            if (groupList.data?.size != 0) {
                    groups = groupList.data!!
                    feedFilter.group = groups.firstOrNull()?.guid
            }
        }
}


问:
How to filter table by two columns
I have the following table:

ID
TEST_ID
Component
ComponentInfo

1
5
Test 1
Info

2
5
Test 1
AB 2

3
5
Test 1
XY

4
5
Test X
Info 2

5
5
Test X
Info 1

6
5
Test Y
Info 2

7
6
Test 1
Info 2

8
7
ABC
Info 1

9
8
XYZ
Info 2

9
9
XYZ
Info 2

I like to get the following output:

TEST_ID
Component

5
Test 1

5
Test X

5
Test Y

6
Test 1

7
ABC

8
XYZ

9
XYZ

I think it would be nice to realize it in the data transformation part. How can I do that?

答:
Press strg select TEST_ID and Component, right click then remove duplicates

= Table.Distinct(#"changed type", {"TEST_ID", "Component"})

Thats what I need! :-)

Title: How to filter table by two columns


问:
How to convert a database data in predefined format and generate output in text format
I am having a SQL database having the attributes:

First_Name

Last_Name

Sex

Address

For reporting to the authority I have a fixed format like

For the First name:
FN(no of characters in the first name)First_Name

For example the first name Daniel should be like: FN05Daniel

For Bose, it should be: LN04Bose

Is there any way using SSIS the same can be accomplished and the output can be generated in text format?

If not SSIS please suggest any probable mechanism to get the result. I am just learning to code so please don't mind if it's a silly question.

答:
Using SQL:

You can simply use the following SQL command to format your data:

SELECT
    'FN' + CAST(LEN([First_Name] as varchar(3)) + [First_name] as [First_Name],
    'LN' + CAST(LEN([Last_Name] as varchar(3)) + [Last_name] as [First_Name],
FROM
    [MyTable]
```
<p>To export data to a text file, you can refer to the following answer:</p>
<ul>
<li>How to populate csv file from SQL Server stored procedure?</li>
</ul>
<p><strong>Using SSIS:</strong></p>
<p>You should create an SSIS package with one Data Flow task. The Data Flow task should contain:</p>
<ol>
<li>OLE DB Source reading from the SQL table</li>
<li>Derived Column to add the <code>FN</code> and <code>LN</code> prefixes:</li>
</ol>
```"FN" + RIGHT("0" + (DT_WSTR,10)LEN([First_Name]),2) + [First_Name]
"LN" + RIGHT("0" + (DT_WSTR,10)LEN([Last_Name]),2) + [Last_Name]
```

Flat File Destination to export data to a text file.

Body:
Using SQL:

You can simply use the following SQL command to format your data:

SELECT
    'FN' + CAST(LEN([First_Name] as varchar(3)) + [First_name] as [First_Name],
    'LN' + CAST(LEN([Last_Name] as varchar(3)) + [Last_name] as [First_Name],
FROM
    [MyTable]

To export data to a text file, you can refer to the following answer:

How to populate csv file from SQL Server stored procedure?

Using SSIS:

You should create an SSIS package with one Data Flow task. The Data Flow task should contain:

OLE DB Source reading from the SQL table

Derived Column to add the FN and LN prefixes:

"FN" + RIGHT("0" + (DT_WSTR,10)LEN([First_Name]),2) + [First_Name]
"LN" + RIGHT("0" + (DT_WSTR,10)LEN([Last_Name]),2) + [Last_Name]

Flat File Destination to export data to a text file.


问:
Should I dispose a Mutex?
I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex.

Now I'm wondering whether it's ok to just call WaitOne() and ReleaseMutex() in a try-finally block or should I also dispose the Mutex (e.g. in a using block). If so I guess I should always catch the AbandonedMutexException on the WaitOne() method or am I wrong here?

答:
A mutex is a Windows kernel object (here wrapped in a .NET object).

As such, it is an unmanaged resource that should be disposed.

More accurately, the .NET object contains a HANDLE to the mutex, which must be released/disposed of somehow.

I don't trust that code sample in the Mutex class docs where the mutex object is not disposed. Although Henzi has a good point in comment: The Mutex object is static and would be either disposed by the finalizer or destroyed by the Windows kernel when the process exits.

Also, note that Close() disposes the object as well.

Of course, there's nothing wrong with keeping an existing Mutex object in your app even while you don't use it. They are light resources.

Title: Should I dispose a Mutex?


问:
Why about the function enumerate am I not understanding?
I guess am not really sure what or why example number two doesn't sort like example 1.

```<code>numList = [4,5,7,2,3,100,43,543,34]

for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if numList[i1] < numList[i2]:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)

for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if x1 < x2:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)

</code>```

Example 1 result: [2, 3, 4, 5, 7, 34, 43, 100, 543]

Example 2 result: [2, 3, 4, 5, 34, 43, 100, 7, 543]

答:
The swap changes the value of numList[i1] in the body of the inner loop; it does not change the value of x1 (which won't change until the next iteration of the outer loop).

(That is, x1 is a reference to the int value that was at numList[i1] at the time of the assignment, not a reference to the i1th slot of numList.)

Body:
I guess am not really sure what or why example number two doesn't sort like example 1.

numList = [4,5,7,2,3,100,43,543,34]

for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if numList[i1] < numList[i2]:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)

for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if x1 < x2:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)

Example 1 result: [2, 3, 4, 5, 7, 34, 43, 100, 543]

Example 2 result: [2, 3, 4, 5, 34, 43, 100, 7, 543]


问:
Group by the dataframe with specific id and then plot with another columns
I have a dataframe as follow, I have grouped them the columns with "specific_id". However, I need to plot the data frame based on the column "time" ( if the time is sorted, it will be great also).

Here is the dataframe I have,

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame()
df['time'] = ['2019-01-07 09:38:30', '2020-01-08 09:38:30', '2021-01-07 09:38:30',
'2020-01-07 09:38:30']
df['specific_id'] = ['d', 'd', 'f', 'f']
df['c1'] = [2, 3,7, 5]
df['c2'] = [0, 5, 10, 3]

df
</code>```

I have group the dataframe with the following code,

```<code>df_sticked = df.filter(regex='c\d+', axis=1) \
.groupby(df['specific_id']).apply(np.ravel).apply(pd.Series) \
.rename(lambda x: f"c{x + 2}", axis=1).reset_index().fillna(0)
df_sticked
</code>```

However, when I want to plot the data, I can not show the time in the x axis.

```<code>import matplotlib.pyplot as plt
%matplotlib inline
dfforplot = df_sticked.iloc[:, 1:-1]
dfforplot.T.plot(figsize=(20,11), legend=False)
plt.show()
</code>```

Could you please help me?
Thanks

答:
I simplified the steps in order to plot time by value:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame()
df['time'] = ['2019-01-07 09:38:30', '2020-01-08 09:38:30', '2021-01-07 09:38:30',
'2020-01-07 09:38:30']
df['specific_id'] = ['d', 'd', 'f', 'f']
df['c1'] = [2, 3,7, 5]
df['c2'] = [0, 5, 10, 3]

df['c'] = df.filter(regex='c\d+', axis=1).values.tolist()
df = df[['specific_id', 'time', 'c']]
df = df.explode('c')
items = [x for _, x in df.groupby('specific_id')]

for item in items:
    plt.plot(item['time'].values,
             item['c'].values,
             label=item['specific_id'].iloc[0])
plt.legend(loc="upper left")
plt.show()
```

Body:
I have a dataframe as follow, I have grouped them the columns with "specific_id". However, I need to plot the data frame based on the column "time" ( if the time is sorted, it will be great also).

Here is the dataframe I have,

import pandas as pd
import numpy as np
df = pd.DataFrame()
df['time'] = ['2019-01-07 09:38:30', '2020-01-08 09:38:30', '2021-01-07 09:38:30',
'2020-01-07 09:38:30']
df['specific_id'] = ['d', 'd', 'f', 'f']
df['c1'] = [2, 3,7, 5]
df['c2'] = [0, 5, 10, 3]

df

I have group the dataframe with the following code,

df_sticked = df.filter(regex='c\d+', axis=1) \
.groupby(df['specific_id']).apply(np.ravel).apply(pd.Series) \
.rename(lambda x: f"c{x + 2}", axis=1).reset_index().fillna(0)
df_sticked

However, when I want to plot the data, I can not show the time in the x axis.

import matplotlib.pyplot as plt
%matplotlib inline
dfforplot = df_sticked.iloc[:, 1:-1]
dfforplot.T.plot(figsize=(20,11), legend=False)
plt.show()

Could you please help me?
Thanks


问:
How to send environment variables to Jest CLI?
I have a script that runs a Jest test for me, and I want to set an environment variable before running it, something like this:

my_test_script.sh

```<code>IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js
</code>```

However, inside "my.test.js" the IMPORTANT_ENV_VAR is not set when I run my test like this.

How do I pass the environment variable into the Jest CLI ?

答:
Going off of @Andrea Bisello's answer, you can load the environment variables from a plain JavaScript file. This is the key take-away.

So, in my environment, I already had a jest.config.ts. Since I was already using a .env file for defining my environment variables (located at the root of my project), I just needed a way to load them when running jest from a CLI at the root of my project.

Doing that is very simple; just add this to the jest.config.ts or jest.config.js:

// jest.config.{ts,js}
const { config } = require('dotenv');

config();
```
<p>Then, from the root of your repo, you can do something like:</p>
<pre class="lang-sh prettyprint-override"><code>npx jest
</code>```

Body:
I have a script that runs a Jest test for me, and I want to set an environment variable before running it, something like this:

my_test_script.sh

IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js

However, inside "my.test.js" the IMPORTANT_ENV_VAR is not set when I run my test like this.

How do I pass the environment variable into the Jest CLI ?

Body:
Going off of @Andrea Bisello's answer, you can load the environment variables from a plain JavaScript file. This is the key take-away.

So, in my environment, I already had a jest.config.ts. Since I was already using a .env file for defining my environment variables (located at the root of my project), I just needed a way to load them when running jest from a CLI at the root of my project.

Doing that is very simple; just add this to the jest.config.ts or jest.config.js:

// jest.config.{ts,js}
const { config } = require('dotenv');

config();

Then, from the root of your repo, you can do something like:

npx jest


问:
How to use geom_tile to plot factorial variable (photoperiod) behind continuous numeric data (x = time, y = variable)
I am working with time-series data, where at every timepoint, I have many measurements for each of  up to 16 subjects, spanning multiple days. I currently have the data organized as tidily as I can - here is a snippet.

```<code>> df
# A tibble: 23,844 x 40
   DateTime             Time exp_day Photoperiod    ZT Sex   Group Treatment Cohort Animal
   <dttm>              <dbl>   <dbl>       <dbl> <dbl> <chr> <chr> <chr>      <dbl>  <dbl>
 1 2021-10-18 12:47:00  0          1           1     6 M     mHFD  chABC          1    264
 2 2021-10-18 12:50:00  0.05       1           1     6 M     mHFD  chABC          1    264
 3 2021-10-18 12:53:00  0.1        1           1     6 M     mHFD  chABC          1    264
 4 2021-10-18 12:56:00  0.15       1           1     6 M     mHFD  chABC          1    264
 5 2021-10-18 12:59:00  0.2        1           1     6 M     mHFD  chABC          1    264
 6 2021-10-18 13:02:00  0.25       1           1     7 M     mHFD  chABC          1    264
 7 2021-10-18 13:05:00  0.3        1           1     7 M     mHFD  chABC          1    264
 8 2021-10-18 13:08:00  0.35       1           1     7 M     mHFD  chABC          1    264
 9 2021-10-18 13:11:00  0.4        1           1     7 M     mHFD  chABC          1    264
10 2021-10-18 13:14:00  0.45       1           1     7 M     mHFD  chABC          1    264
... with 23,834 more rows, and 30 more variables
</code>```

The DateTimes are duplicated for each animal - so while I have 23,844 total observations, there are 1987 for each subject:

```<code>> n_distinct(df$DateTime)
[1] 1987
> n_distinct(df$Animal)
[1] 12
</code>```

What I would like to do is plot time on the x axis, and variables on the y axis, but have the light cycle (light vs. dark) plotted as shaded or light bars behind the data, as shown below.

I found this StackExchange discussion which almost solves my problem, however, because I have the exact same date-time values for many subjects, what ends up happening is that Photoperiod value for each timepoint gets duplicated by as many animals as I have, resulting in shading being much darker instead of transparent:

```<code>ggplot(data = df) +
  aes(x = Time, y = RER) +
  geom_tile(mapping = aes(
    fill = as.factor(Photoperiod),
    y = mean(RER)),
    size = max(df$RER+1),
    alpha = 0.05,
    height = max(df$RER+1)
    ) +
  theme_classic()
</code>```

I'm very new to ggplot and R in general, so would really appreciate suggestions on cleaning this up (and also, recoloring the tiles?! I'm still baffled by the grammar with ggplot). Thank you, kind internet strangers!

EDIT: I was asked to provide toy data - sorry this is so humongous, but I wanted to include enough data points to demo the issue fully, so duplicate times for 2 animals were needed:

```<code>> dput(toy_data)
structure(list(Time = c(0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35,
0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95,
1, 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5, 1.55,
1.6, 1.65, 1.7, 1.75, 1.8, 1.85, 1.9, 1.95, 2, 2.05, 2.1, 2.15,
2.2, 2.25, 2.3, 2.35, 2.4, 2.45, 2.5, 2.55, 2.6, 2.65, 2.7, 2.75,
2.8, 2.85, 2.9, 2.95, 3, 3.05, 3.1, 3.15, 3.2, 3.25, 3.3, 3.35,
3.4, 3.45, 3.5, 3.55, 3.6, 3.65, 3.7, 3.75, 3.8, 3.85, 3.9, 3.95,
4, 4.05, 4.1, 4.15, 4.2, 4.25, 4.3, 4.35, 4.4, 4.45, 4.5, 4.55,
4.6, 4.65, 4.7, 4.75, 4.8, 4.85, 4.9, 4.95, 5, 5.05, 5.1, 5.15,
5.2, 5.25, 5.3, 5.35, 5.4, 5.45, 5.5, 5.55, 5.6, 5.65, 5.7, 5.75,
5.8, 5.85, 5.9, 5.95, 6, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3,
0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85,
0.9, 0.95, 1, 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45,
1.5, 1.55, 1.6, 1.65, 1.7, 1.75, 1.8, 1.85, 1.9, 1.95, 2, 2.05,
2.1, 2.15, 2.2, 2.25, 2.3, 2.35, 2.4, 2.45, 2.5, 2.55, 2.6, 2.65,
2.7, 2.75, 2.8, 2.85, 2.9, 2.95, 3, 3.05, 3.1, 3.15, 3.2, 3.25,
3.3, 3.35, 3.4, 3.45, 3.5, 3.55, 3.6, 3.65, 3.7, 3.75, 3.8, 3.85,
3.9, 3.95, 4, 4.05, 4.1, 4.15, 4.2, 4.25, 4.3, 4.35, 4.4, 4.45,
4.5, 4.55, 4.6, 4.65, 4.7, 4.75, 4.8, 4.85, 4.9, 4.95, 5, 5.05,
5.1, 5.15, 5.2, 5.25, 5.3, 5.35, 5.4, 5.45, 5.5, 5.55, 5.6, 5.65,
5.7, 5.75, 5.8, 5.85, 5.9, 5.95, 6), Photoperiod = c(1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0), Animal = c(264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265), RER = c(0.8160802, 0.8414883, 0.8616111, 0.8799883,
0.8853653, 0.8618485, 0.8510329, 0.767729, 0.8031961, 0.8323785,
0.746919, 0.735468, 0.7643967, 0.7355957, 0.7695087, 0.7857639,
0.7985682, 0.8040746, 0.7941816, 0.7780811, 0.7847954, 0.7520697,
0.771462, 0.8457935, 0.792997, 0.800769, 0.8275111, 0.8667183,
0.9003724, 0.9300525, 0.9354021, 0.950434, 0.9377719, 0.9537385,
0.957497, 0.8965999, 0.9208428, 0.9974157, 0.9558442, 0.9601937,
0.9428826, 0.9235089, 0.954285, 0.9506574, 0.9658971, 0.943697,
0.8846716, 0.9046962, 0.8838141, 0.880153, 0.893438, 0.8523828,
0.8407152, 0.8374369, 0.8187368, 0.8196678, 0.818763, 0.798008,
0.7942439, 0.7859463, 0.8233737, 0.8148571, 0.7615421, 0.7648527,
0.8054302, 0.7941433, 0.8022749, 0.7896502, 0.7637175, 0.7835857,
0.7571101, 0.7631419, 0.757715, 0.7518733, 0.7706109, 0.7968383,
0.7996781, 0.7944622, 0.771527, 0.7670471, 0.7703733, 0.7666674,
0.7745026, 0.7769082, 0.8292344, 0.8614953, 0.8414221, 0.8535554,
0.8817732, 0.9425337, 0.9397846, 0.944727, 0.934262, 0.9363095,
0.9287465, 0.9235471, 1.016768, 1.032561, 0.9664637, 0.9525408,
0.9237975, 0.9090067, 0.9142333, 0.8927826, 0.9324146, 0.8827952,
0.8865094, 0.8999404, 0.9107332, 0.9153765, 0.8917224, 0.85414,
0.8840183, 0.8951464, 0.8506548, 0.8448542, 0.9129671, 0.9588402,
0.9359728, 0.92337, 0.9468017, 0.7427233, 0.7401292, 0.731786,
0.7219006, 0.8070412, 0.801992, 0.9282705, 0.7020188, 0.7323134,
0.8721051, 0.7774209, 0.7546358, 0.7937038, 0.7963611, 0.8187793,
0.8353969, 0.8687972, 0.8970048, 0.9179802, 0.8970544, 0.934752,
0.9264608, 0.8939873, 0.8947772, 0.9109767, 0.9517013, 0.9122902,
0.89452, 0.8663988, 0.8703817, 0.9046032, 0.9098795, 0.9236861,
0.9013131, 0.9125994, 0.8989074, 0.8592472, 0.9292116, 0.8844017,
0.9101141, 0.9072555, 0.9100726, 0.9335378, 0.938631, 0.9414188,
0.9116636, 0.8453088, 0.8754182, 0.8618876, 0.8399428, 0.8514538,
0.875167, 0.8847721, 0.8606132, 0.8260812, 0.8763582, 0.8457979,
0.8227465, 0.8381892, 0.8416376, 0.8579757, 0.8317919, 0.7697672,
0.8201662, 0.8380933, 0.8529457, 0.8165758, 0.83944, 0.7748498,
0.8073791, 0.8753202, 0.8358103, 0.8230301, 0.825459, 0.8067374,
0.8479258, 0.9074212, 0.8845561, 0.904029, 0.9196977, 0.8838978,
0.8963885, 0.894173, 0.8619009, 0.8742555, 0.8846812, 0.8626546,
0.7966505, 0.7857755, 0.8116125, 0.8324698, 0.818864, 0.7777231,
0.7958539, 0.7686762, 0.7712164, 0.8568692, 0.7960808, 0.7915141,
0.7687887, 0.7816828, 0.8098081, 0.7885166, 0.7697541, 0.7951097,
0.8199027, 0.8549485, 0.8789132, 0.9114284, 0.8974345, 0.8821911,
0.8926013, 0.9105431, 0.9270198, 0.8770642, 0.8436169, 0.9331129,
0.9502046, 0.923188, 0.9427496, 0.9521099)), row.names = c(NA,
-242L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
I would create a separate de-duplicated data frame for the photoperiod plotting layer. Something like this:

```<code>library(dplyr)

pp_data = toy_data %>% distinct(Time, Photoperiod)

ggplot(data = toy_data) +
  aes(x = Time, y = RER) +
  geom_line(aes(color = factor(Animal))) +
  geom_tile(
    data = pp_data,
    mapping = aes(
      fill = factor(Photoperiod),
      y = 1 ## since we're using Inf height, this doesn't matter
    ),
    alpha = 0.2,
    height = Inf ## tiles will go all the way up and down
  ) +
  ## colors for photoperiod tiles, and no legend/guide
  scale_fill_manual(values = c("0" = "darkblue", "1" = "yellow"), guide = "none") +
  ## colors for the animals
  scale_color_manual(values = c("black", "darkorange3")) +
  ## no padding on the x-axis
  scale_x_continuous(expand = expansion(0, 0)) +
  theme_classic()
</code>```

Body:
I am working with time-series data, where at every timepoint, I have many measurements for each of  up to 16 subjects, spanning multiple days. I currently have the data organized as tidily as I can - here is a snippet.

> df
# A tibble: 23,844 x 40
   DateTime             Time exp_day Photoperiod    ZT Sex   Group Treatment Cohort Animal
   <dttm>              <dbl>   <dbl>       <dbl> <dbl> <chr> <chr> <chr>      <dbl>  <dbl>
 1 2021-10-18 12:47:00  0          1           1     6 M     mHFD  chABC          1    264
 2 2021-10-18 12:50:00  0.05       1           1     6 M     mHFD  chABC          1    264
 3 2021-10-18 12:53:00  0.1        1           1     6 M     mHFD  chABC          1    264
 4 2021-10-18 12:56:00  0.15       1           1     6 M     mHFD  chABC          1    264
 5 2021-10-18 12:59:00  0.2        1           1     6 M     mHFD  chABC          1    264
 6 2021-10-18 13:02:00  0.25       1           1     7 M     mHFD  chABC          1    264
 7 2021-10-18 13:05:00  0.3        1           1     7 M     mHFD  chABC          1    264
 8 2021-10-18 13:08:00  0.35       1           1     7 M     mHFD  chABC          1    264
 9 2021-10-18 13:11:00  0.4        1           1     7 M     mHFD  chABC          1    264
10 2021-10-18 13:14:00  0.45       1           1     7 M     mHFD  chABC          1    264
... with 23,834 more rows, and 30 more variables

The DateTimes are duplicated for each animal - so while I have 23,844 total observations, there are 1987 for each subject:

> n_distinct(df$DateTime)
[1] 1987
> n_distinct(df$Animal)
[1] 12

What I would like to do is plot time on the x axis, and variables on the y axis, but have the light cycle (light vs. dark) plotted as shaded or light bars behind the data, as shown below.

I found this StackExchange discussion which almost solves my problem, however, because I have the exact same date-time values for many subjects, what ends up happening is that Photoperiod value for each timepoint gets duplicated by as many animals as I have, resulting in shading being much darker instead of transparent:

ggplot(data = df) +
  aes(x = Time, y = RER) +
  geom_tile(mapping = aes(
    fill = as.factor(Photoperiod),
    y = mean(RER)),
    size = max(df$RER+1),
    alpha = 0.05,
    height = max(df$RER+1)
    ) +
  theme_classic()

I'm very new to ggplot and R in general, so would really appreciate suggestions on cleaning this up (and also, recoloring the tiles?! I'm still baffled by the grammar with ggplot). Thank you, kind internet strangers!

EDIT: I was asked to provide toy data - sorry this is so humongous, but I wanted to include enough data points to demo the issue fully, so duplicate times for 2 animals were needed:

> dput(toy_data)
structure(list(Time = c(0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35,
0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95,
1, 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5, 1.55,
1.6, 1.65, 1.7, 1.75, 1.8, 1.85, 1.9, 1.95, 2, 2.05, 2.1, 2.15,
2.2, 2.25, 2.3, 2.35, 2.4, 2.45, 2.5, 2.55, 2.6, 2.65, 2.7, 2.75,
2.8, 2.85, 2.9, 2.95, 3, 3.05, 3.1, 3.15, 3.2, 3.25, 3.3, 3.35,
3.4, 3.45, 3.5, 3.55, 3.6, 3.65, 3.7, 3.75, 3.8, 3.85, 3.9, 3.95,
4, 4.05, 4.1, 4.15, 4.2, 4.25, 4.3, 4.35, 4.4, 4.45, 4.5, 4.55,
4.6, 4.65, 4.7, 4.75, 4.8, 4.85, 4.9, 4.95, 5, 5.05, 5.1, 5.15,
5.2, 5.25, 5.3, 5.35, 5.4, 5.45, 5.5, 5.55, 5.6, 5.65, 5.7, 5.75,
5.8, 5.85, 5.9, 5.95, 6, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3,
0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85,
0.9, 0.95, 1, 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45,
1.5, 1.55, 1.6, 1.65, 1.7, 1.75, 1.8, 1.85, 1.9, 1.95, 2, 2.05,
2.1, 2.15, 2.2, 2.25, 2.3, 2.35, 2.4, 2.45, 2.5, 2.55, 2.6, 2.65,
2.7, 2.75, 2.8, 2.85, 2.9, 2.95, 3, 3.05, 3.1, 3.15, 3.2, 3.25,
3.3, 3.35, 3.4, 3.45, 3.5, 3.55, 3.6, 3.65, 3.7, 3.75, 3.8, 3.85,
3.9, 3.95, 4, 4.05, 4.1, 4.15, 4.2, 4.25, 4.3, 4.35, 4.4, 4.45,
4.5, 4.55, 4.6, 4.65, 4.7, 4.75, 4.8, 4.85, 4.9, 4.95, 5, 5.05,
5.1, 5.15, 5.2, 5.25, 5.3, 5.35, 5.4, 5.45, 5.5, 5.55, 5.6, 5.65,
5.7, 5.75, 5.8, 5.85, 5.9, 5.95, 6), Photoperiod = c(1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0), Animal = c(264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 264, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265), RER = c(0.8160802, 0.8414883, 0.8616111, 0.8799883,
0.8853653, 0.8618485, 0.8510329, 0.767729, 0.8031961, 0.8323785,
0.746919, 0.735468, 0.7643967, 0.7355957, 0.7695087, 0.7857639,
0.7985682, 0.8040746, 0.7941816, 0.7780811, 0.7847954, 0.7520697,
0.771462, 0.8457935, 0.792997, 0.800769, 0.8275111, 0.8667183,
0.9003724, 0.9300525, 0.9354021, 0.950434, 0.9377719, 0.9537385,
0.957497, 0.8965999, 0.9208428, 0.9974157, 0.9558442, 0.9601937,
0.9428826, 0.9235089, 0.954285, 0.9506574, 0.9658971, 0.943697,
0.8846716, 0.9046962, 0.8838141, 0.880153, 0.893438, 0.8523828,
0.8407152, 0.8374369, 0.8187368, 0.8196678, 0.818763, 0.798008,
0.7942439, 0.7859463, 0.8233737, 0.8148571, 0.7615421, 0.7648527,
0.8054302, 0.7941433, 0.8022749, 0.7896502, 0.7637175, 0.7835857,
0.7571101, 0.7631419, 0.757715, 0.7518733, 0.7706109, 0.7968383,
0.7996781, 0.7944622, 0.771527, 0.7670471, 0.7703733, 0.7666674,
0.7745026, 0.7769082, 0.8292344, 0.8614953, 0.8414221, 0.8535554,
0.8817732, 0.9425337, 0.9397846, 0.944727, 0.934262, 0.9363095,
0.9287465, 0.9235471, 1.016768, 1.032561, 0.9664637, 0.9525408,
0.9237975, 0.9090067, 0.9142333, 0.8927826, 0.9324146, 0.8827952,
0.8865094, 0.8999404, 0.9107332, 0.9153765, 0.8917224, 0.85414,
0.8840183, 0.8951464, 0.8506548, 0.8448542, 0.9129671, 0.9588402,
0.9359728, 0.92337, 0.9468017, 0.7427233, 0.7401292, 0.731786,
0.7219006, 0.8070412, 0.801992, 0.9282705, 0.7020188, 0.7323134,
0.8721051, 0.7774209, 0.7546358, 0.7937038, 0.7963611, 0.8187793,
0.8353969, 0.8687972, 0.8970048, 0.9179802, 0.8970544, 0.934752,
0.9264608, 0.8939873, 0.8947772, 0.9109767, 0.9517013, 0.9122902,
0.89452, 0.8663988, 0.8703817, 0.9046032, 0.9098795, 0.9236861,
0.9013131, 0.9125994, 0.8989074, 0.8592472, 0.9292116, 0.8844017,
0.9101141, 0.9072555, 0.9100726, 0.9335378, 0.938631, 0.9414188,
0.9116636, 0.8453088, 0.8754182, 0.8618876, 0.8399428, 0.8514538,
0.875167, 0.8847721, 0.8606132, 0.8260812, 0.8763582, 0.8457979,
0.8227465, 0.8381892, 0.8416376, 0.8579757, 0.8317919, 0.7697672,
0.8201662, 0.8380933, 0.8529457, 0.8165758, 0.83944, 0.7748498,
0.8073791, 0.8753202, 0.8358103, 0.8230301, 0.825459, 0.8067374,
0.8479258, 0.9074212, 0.8845561, 0.904029, 0.9196977, 0.8838978,
0.8963885, 0.894173, 0.8619009, 0.8742555, 0.8846812, 0.8626546,
0.7966505, 0.7857755, 0.8116125, 0.8324698, 0.818864, 0.7777231,
0.7958539, 0.7686762, 0.7712164, 0.8568692, 0.7960808, 0.7915141,
0.7687887, 0.7816828, 0.8098081, 0.7885166, 0.7697541, 0.7951097,
0.8199027, 0.8549485, 0.8789132, 0.9114284, 0.8974345, 0.8821911,
0.8926013, 0.9105431, 0.9270198, 0.8770642, 0.8436169, 0.9331129,
0.9502046, 0.923188, 0.9427496, 0.9521099)), row.names = c(NA,
-242L), class = c("tbl_df", "tbl", "data.frame"))

Body:
I would create a separate de-duplicated data frame for the photoperiod plotting layer. Something like this:

library(dplyr)

pp_data = toy_data %>% distinct(Time, Photoperiod)

ggplot(data = toy_data) +
  aes(x = Time, y = RER) +
  geom_line(aes(color = factor(Animal))) +
  geom_tile(
    data = pp_data,
    mapping = aes(
      fill = factor(Photoperiod),
      y = 1 ## since we're using Inf height, this doesn't matter
    ),
    alpha = 0.2,
    height = Inf ## tiles will go all the way up and down
  ) +
  ## colors for photoperiod tiles, and no legend/guide
  scale_fill_manual(values = c("0" = "darkblue", "1" = "yellow"), guide = "none") +
  ## colors for the animals
  scale_color_manual(values = c("black", "darkorange3")) +
  ## no padding on the x-axis
  scale_x_continuous(expand = expansion(0, 0)) +
  theme_classic()


答:
Here is a pdf of shortcuts for VS Code

This other SO question may also have the answer you're looking for

I am assuming you are referring to autocompletion in VS code for C++

The shortcut you are looking for looks to be as shown in the PDF linked:

Mac: CMD + SHIFT + \

Windows: CTRL + SHIFT + \

Title: Visual Studio Code Shortcut to "jump" a parentheses

Body:
Is there any shortcut or extension to "jump" a parentheses?

Like pressing tab in PyCharm.


问:
Firebase .web App Showing ( Site Not Found )
here is .web link: https://al-realtor.web.app
here is my .firebaseapp link: https://al-realtor.firebaseapp.com

The Web showing me Site not found!
But the FirebaseApp showing everything is all Right

I am Using in my code:

React

Tailwind

FontAwesome

React Router

and there is no error on my code. It running on netlify and .firebaseapp but not only .web app

答: Might be late to this but for anyone having this problem. The solution is just to wait. Most likely the google servers near you don't have the latest information about your site. You can usually access the site anyway by using USA VPN.</p>


问:
How to create multiple sub-folders in cookiecutter template using a sub-folder template
I want to create a template for our internal projects.

The layout of the project contains a variable amount of sub-folders.

I would like to specify the sub-folders to create, inside some configuration file.
For example, I have the following folder structure:

```<code>my_project
|
|___ Tables
|  |
|  |__ Table1    <--- The folders I would like to create
|  |__ Table2    <---|
|  |__ Table3    <---|
|
|___ Other_folders
</code>```

The configuration file should have something like this:

```<code>{
  "prj_name": "my_project",
  "tables": ["Table1", "Table2", "Table3"]
}
</code>```

I  have tried to create the following structure:

```<code>{{cookiecutter.prj_name}}
|
|___ Tables
|  |
|  |__ {% for table in cookiecutter.tables %}{{table}}{% endfor %}
|
|___ Other_folders
</code>```

and added to cookiecutter.json the mentioned configuration.

I ran cookiecutter using --no-input. And the result was only a single sub-folder (Table1).

Also tried to use the following folder name: {% for table in cookiecutter.tables.keys() %}{{table}}{% endfor %}
With the following configuration:

```<code>{
  "prj_name": "my_project",
  "tables": {
    "table1": "table1",
    "table2": "table2",
    "table3": "table3"
  }
}
</code>```

The output was still a single sub-folder (Table2Table1Table3)

Any idea how I can achieve the desired structure?

答:
I went with a low-tech solution here. My use case was pretty simple and there's a finite amount of folders I needed to create so my solution is manageable to me. YMMV, but I thought I'd offer it here in case it works for someone else.

I basically prepopulated the number of directories I figure I would ever need. I just used Python's format in a range loop to prepopulate however many folders I needed.

```<code>cookiecutter/mycookiecutter/
├── cookiecutter.json
└── {{cookiecutter.project_name}}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 0\ %}{{cookiecutter.account_info["accounts"][0]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 1\ %}{{cookiecutter.account_info["accounts"][1]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 10\ %}{{cookiecutter.account_info["accounts"][10]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 11\ %}{{cookiecutter.account_info["accounts"][11]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 12\ %}{{cookiecutter.account_info["accounts"][12]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 13\ %}{{cookiecutter.account_info["accounts"][13]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 14\ %}{{cookiecutter.account_info["accounts"][14]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 15\ %}{{cookiecutter.account_info["accounts"][15]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 16\ %}{{cookiecutter.account_info["accounts"][16]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 17\ %}{{cookiecutter.account_info["accounts"][17]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 18\ %}{{cookiecutter.account_info["accounts"][18]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 19\ %}{{cookiecutter.account_info["accounts"][19]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 2\ %}{{cookiecutter.account_info["accounts"][2]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 3\ %}{{cookiecutter.account_info["accounts"][3]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 4\ %}{{cookiecutter.account_info["accounts"][4]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 5\ %}{{cookiecutter.account_info["accounts"][5]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 6\ %}{{cookiecutter.account_info["accounts"][6]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 7\ %}{{cookiecutter.account_info["accounts"][7]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 8\ %}{{cookiecutter.account_info["accounts"][8]}}{%\ endif\ %}
    └── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 9\ %}{{cookiecutter.account_info["accounts"][9]}}{%\ endif\ %}
</code>```

cookiecutter.json

```<code>{
    "project_name": "test",
    "account_info": {
        "accounts": [
            "root",
            "corp",
            "dns",
            "dev",
            "prod"
        ]
    }
}
</code>```

Body:
I want to create a template for our internal projects.

The layout of the project contains a variable amount of sub-folders.

I would like to specify the sub-folders to create, inside some configuration file.
For example, I have the following folder structure:

my_project
|
|___ Tables
|  |
|  |__ Table1    <--- The folders I would like to create
|  |__ Table2    <---|
|  |__ Table3    <---|
|
|___ Other_folders

The configuration file should have something like this:

{
  "prj_name": "my_project",
  "tables": ["Table1", "Table2", "Table3"]
}

I  have tried to create the following structure:

{{cookiecutter.prj_name}}
|
|___ Tables
|  |
|  |__ {% for table in cookiecutter.tables %}{{table}}{% endfor %}
|
|___ Other_folders

and added to cookiecutter.json the mentioned configuration.

I ran cookiecutter using --no-input. And the result was only a single sub-folder (Table1).

Also tried to use the following folder name: {% for table in cookiecutter.tables.keys() %}{{table}}{% endfor %}
With the following configuration:

{
  "prj_name": "my_project",
  "tables": {
    "table1": "table1",
    "table2": "table2",
    "table3": "table3"
  }
}

The output was still a single sub-folder (Table2Table1Table3)

Any idea how I can achieve the desired structure?

Body:
I went with a low-tech solution here. My use case was pretty simple and there's a finite amount of folders I needed to create so my solution is manageable to me. YMMV, but I thought I'd offer it here in case it works for someone else.

I basically prepopulated the number of directories I figure I would ever need. I just used Python's format in a range loop to prepopulate however many folders I needed.

cookiecutter/mycookiecutter/
├── cookiecutter.json
└── {{cookiecutter.project_name}}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 0\ %}{{cookiecutter.account_info["accounts"][0]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 1\ %}{{cookiecutter.account_info["accounts"][1]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 10\ %}{{cookiecutter.account_info["accounts"][10]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 11\ %}{{cookiecutter.account_info["accounts"][11]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 12\ %}{{cookiecutter.account_info["accounts"][12]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 13\ %}{{cookiecutter.account_info["accounts"][13]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 14\ %}{{cookiecutter.account_info["accounts"][14]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 15\ %}{{cookiecutter.account_info["accounts"][15]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 16\ %}{{cookiecutter.account_info["accounts"][16]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 17\ %}{{cookiecutter.account_info["accounts"][17]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 18\ %}{{cookiecutter.account_info["accounts"][18]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 19\ %}{{cookiecutter.account_info["accounts"][19]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 2\ %}{{cookiecutter.account_info["accounts"][2]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 3\ %}{{cookiecutter.account_info["accounts"][3]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 4\ %}{{cookiecutter.account_info["accounts"][4]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 5\ %}{{cookiecutter.account_info["accounts"][5]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 6\ %}{{cookiecutter.account_info["accounts"][6]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 7\ %}{{cookiecutter.account_info["accounts"][7]}}{%\ endif\ %}
    ├── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 8\ %}{{cookiecutter.account_info["accounts"][8]}}{%\ endif\ %}
    └── {%\ if\ cookiecutter.account_info["accounts"]|length\ >\ 9\ %}{{cookiecutter.account_info["accounts"][9]}}{%\ endif\ %}

cookiecutter.json

{
    "project_name": "test",
    "account_info": {
        "accounts": [
            "root",
            "corp",
            "dns",
            "dev",
            "prod"
        ]
    }
}


问:
Can't find class of postgresql driver
I'm trying to use HikariCP library for PostgreSQL connection pools in Java. I am using Maven, and I'm getting this error: java.lang.ClassNotFoundException: org.postgresql.Driver.

I have tried using different versions of the PostgreSQL driver, but none have worked to my advantage. (I have done more, but I've been faced with this problem, that I have not taken note of)

org.postgresql.ds.PGSimpleDataSource, org.postgresql.Driver and com.impossibl.postgres.jdbc.PGDataSource still produce this error, even though it is said in the HikariCP guide to use either the first or third. The second I found from research.

My maven:

(...)
    <build>
        <defaultGoal>clean package</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <minimizeJar>true</minimizeJar>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

    <repositories>
        <repository>
            <id>spigotmc-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.12.2-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.3.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
    </dependencies>
</project>
```

<h2>What I'm using to produce this error:</h2>

<pre class="lang-java prettyprint-override"><code>        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("Failed to load.");
        }

        HikariConfig config = new HikariConfig("database.properties");
        ds = new HikariDataSource(config);
</code>```

(The constructor HikariDataSource(config); produces this error aswell)

I believe the reason why this is happening is that the driver is not being made into the classpath - however, all efforts I have tried can't seem to do this. This problem of the driver not being in the final jar (to my belief):
.

Actual error:

```<code>[20:16:35 WARN]: java.lang.ClassNotFoundException: org.postgresql.Driver
[20:16:35 WARN]:        at java.net.URLClassLoader.findClass(Unknown Source)
[20:16:35 WARN]:        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:152)
[20:16:35 WARN]:        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:100)
[20:16:35 WARN]:        at java.lang.ClassLoader.loadClass(Unknown Source)
[20:16:35 WARN]:        at java.lang.ClassLoader.loadClass(Unknown Source)
[20:16:35 WARN]:        at java.lang.Class.forName0(Native Method)
[20:16:35 WARN]:        at java.lang.Class.forName(Unknown Source)
[20:16:35 WARN]:        at me.test.kitpvp.Kitpvp.onEnable(Kitpvp.java:43)
[20:16:35 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264)
[20:16:35 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
(...)
[20:16:35 INFO]: Failed to load.
[20:16:35 WARN]: 74 [Server thread] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
</code>```

Edits

Adding <scope>compile</scope> produced same results - did not work.

答:
You can specify a filter to include the driver artifact in the shaded JAR:

```<code><configuration>
   <minimizeJar>true</minimizeJar>
   <filters>
       <filter>
           <artifact>org.postgresql:postgresql</artifact>
           <includes>
               <include>**</include>
           </includes>
       </filter>
   </filters>
</code>```

For more details: Selecting Contents for Uber JAR.

The issue occurs due to the (unfiltered) <minimizeJar>true</minimizeJar> configuration in your POM, and the fact that the driver class is not used at compile time.

maven-shade-plugin on minimizeJar:

When true, dependencies will be stripped down on the class level to only the transitive hull required for the artifact.

Title: Can't find class of postgresql driver

Body:
I'm trying to use HikariCP library for PostgreSQL connection pools in Java. I am using Maven, and I'm getting this error: java.lang.ClassNotFoundException: org.postgresql.Driver.

I have tried using different versions of the PostgreSQL driver, but none have worked to my advantage. (I have done more, but I've been faced with this problem, that I have not taken note of)

org.postgresql.ds.PGSimpleDataSource, org.postgresql.Driver and com.impossibl.postgres.jdbc.PGDataSource still produce this error, even though it is said in the HikariCP guide to use either the first or third. The second I found from research.

My maven:

(...)
    <build>
        <defaultGoal>clean package</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <minimizeJar>true</minimizeJar>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

    <repositories>
        <repository>
            <id>spigotmc-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.12.2-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.3.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
    </dependencies>
</project>

What I'm using to produce this error:

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("Failed to load.");
        }

        HikariConfig config = new HikariConfig("database.properties");
        ds = new HikariDataSource(config);

(The constructor HikariDataSource(config); produces this error aswell)

I believe the reason why this is happening is that the driver is not being made into the classpath - however, all efforts I have tried can't seem to do this. This problem of the driver not being in the final jar (to my belief):
.

Actual error:

[20:16:35 WARN]: java.lang.ClassNotFoundException: org.postgresql.Driver
[20:16:35 WARN]:        at java.net.URLClassLoader.findClass(Unknown Source)
[20:16:35 WARN]:        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:152)
[20:16:35 WARN]:        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:100)
[20:16:35 WARN]:        at java.lang.ClassLoader.loadClass(Unknown Source)
[20:16:35 WARN]:        at java.lang.ClassLoader.loadClass(Unknown Source)
[20:16:35 WARN]:        at java.lang.Class.forName0(Native Method)
[20:16:35 WARN]:        at java.lang.Class.forName(Unknown Source)
[20:16:35 WARN]:        at me.test.kitpvp.Kitpvp.onEnable(Kitpvp.java:43)
[20:16:35 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264)
[20:16:35 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
(...)
[20:16:35 INFO]: Failed to load.
[20:16:35 WARN]: 74 [Server thread] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...

Edits

Adding <scope>compile</scope> produced same results - did not work.

Body:
You can specify a filter to include the driver artifact in the shaded JAR:

<configuration>
   <minimizeJar>true</minimizeJar>
   <filters>
       <filter>
           <artifact>org.postgresql:postgresql</artifact>
           <includes>
               <include>**</include>
           </includes>
       </filter>
   </filters>

For more details: Selecting Contents for Uber JAR.

The issue occurs due to the (unfiltered) <minimizeJar>true</minimizeJar> configuration in your POM, and the fact that the driver class is not used at compile time.

maven-shade-plugin on minimizeJar:

When true, dependencies will be stripped down on the class level to only the transitive hull required for the artifact.


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
From 2 years of building highly optimized Java code (and that needed to be optimized that way) I would say that there is a time-spent rule that governs optimization:

optimizing on the spot: 5%-10% of your development time, because you have to do it countless times (every single time you have to amend your design)

optimizing just when you have had it working: 2% of your development time (you do it only once)

going back to it and optimizing when it's too slow: 30% of your development time, because you have to plunge yourself back into the system

SO I would come to the conclusion that there is a right time and a right way to optimize: do it entity by entity (class by class, if you have classes that have a single, well defined job to do, and can be tested and optimized), test well, make sure the logic is working, optimize just afterward, and forget about that entity's implementation details forever.

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: Varkhan


问:
Change javac path from ant
Can I specify the javac path from within ant, when using fork ? I'm asking this because I need to run a script from an automation framwork(cruisecontrol) , however when I use fork, it uses jdk of a lower version bundled with the framework. Hence is there any way I can specify a different path for javac?</p>

答:
Use the build.compiler system property, or set the compiler property on the javac task:

The compiler implementation to use. If this attribute is not set, the value of the build.compiler property, if set, will be used. Otherwise, the default compiler for the current VM will be used.

http://ant.apache.org/manual/Tasks/javac.html

Title: Change javac path from ant


问:
Is there a way to get all combinations of overlap between values in dictionary, or from within a list
I have a few lists

```<code>A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']
</code>```

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

```<code>my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}
</code>```

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

```<code>   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))
</code>```

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

```<code>   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC
</code>```

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

答:
Thanks for all solutions. Each solution was helpful. However, none of them was the exact answer I was looking for. Nonetheless, all of them partly helped me to come up with the right solution. Posting for everyone might be helpful.

I first needed to create 26 combinations for 5 lists.
The initial lists

```<code>A =['D','KIT','SAP']
B= ['F','G','LUFT','SAP']
C= ['I','SAP']
D= ['SAP','LUF','KIT']
E= ['SAP','LUF','KIT','HASS']
</code>```

Made a list of lists

```<code>lists = [A, B, C, D, E]
</code>```

Defined empty list called combination as @marco's solution. And added all possible combinations based on the length of lists, plus one. The combinations are the values from our final dictionary.

```<code> combinations =[]
    for l in range(2, len(lists) + 1):
        combinations += itertools.combinations(lists, l)
</code>```

After that define a dictionary with keys and values from the list of the list. From here I adopted partly @butterflyknife's solution.

```<code>master_dict = dict(A=A, B=B, C=C, D=D, F=F)
</code>```

For the keys of our final dictionary, we defined an empty list first. Then populated the combinations by using join.

```<code>key_list    = []
for i in range(2,len(master_dict) +1):
    for combo in it.combinations(master_dict.keys(), i):
        new_key = "".join(combo)
        if (len(combo)>1):
            key_list.append(new_key)
</code>```

Now, with both keys and values. We populate our final dictionary.

```<code>final_dict = dict()
for key, elem in zip(key_list, combinations):
    final_dict[key] = list(elem)

</code>```

This part is to find the overlaps and convert them to a data frame.

```<code>overlap_list  = []
dfs = []
for k,v in final_dict.items():
    overlap = list(set.intersection(*[set(x) for x in v]))
    overlap_list.append(overlap)
     #print(overlap, sep=", ")
    dct  ={ 'overlap':overlap,'number of overlapps':len(overlap),
              'overlap models':k}
    dfs.append(dct)
df          = pd.DataFrame.from_dict(dfs)
</code>```

Body:
I have a few lists

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

Body:
Thanks for all solutions. Each solution was helpful. However, none of them was the exact answer I was looking for. Nonetheless, all of them partly helped me to come up with the right solution. Posting for everyone might be helpful.

I first needed to create 26 combinations for 5 lists.
The initial lists

A =['D','KIT','SAP']
B= ['F','G','LUFT','SAP']
C= ['I','SAP']
D= ['SAP','LUF','KIT']
E= ['SAP','LUF','KIT','HASS']

Made a list of lists

lists = [A, B, C, D, E]

Defined empty list called combination as @marco's solution. And added all possible combinations based on the length of lists, plus one. The combinations are the values from our final dictionary.

 combinations =[]
    for l in range(2, len(lists) + 1):
        combinations += itertools.combinations(lists, l)

After that define a dictionary with keys and values from the list of the list. From here I adopted partly @butterflyknife's solution.

master_dict = dict(A=A, B=B, C=C, D=D, F=F)

For the keys of our final dictionary, we defined an empty list first. Then populated the combinations by using join.

key_list    = []
for i in range(2,len(master_dict) +1):
    for combo in it.combinations(master_dict.keys(), i):
        new_key = "".join(combo)
        if (len(combo)>1):
            key_list.append(new_key)

Now, with both keys and values. We populate our final dictionary.

final_dict = dict()
for key, elem in zip(key_list, combinations):
    final_dict[key] = list(elem)

This part is to find the overlaps and convert them to a data frame.

overlap_list  = []
dfs = []
for k,v in final_dict.items():
    overlap = list(set.intersection(*[set(x) for x in v]))
    overlap_list.append(overlap)
     #print(overlap, sep=", ")
    dct  ={ 'overlap':overlap,'number of overlapps':len(overlap),
              'overlap models':k}
    dfs.append(dct)
df          = pd.DataFrame.from_dict(dfs)


问:
Exclude observations below a certain threshold in a stacked bar chart in ggplot2
I need to exclude some observations below a certain threshold in   stacked bar chart done with ggplot2.

An example of my dataframe:

My code:

```<code>  ggplot(df, aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  geom_bar(stat="identity") +
  theme_bw()+
  theme(legend.key.size = unit(0.5,"line"), legend.position = c(0.8,0.7)) +
  labs(x = "UserName") +
  ylim(0, 95000) +
  scale_y_continuous(breaks = seq(0, 95000, 10000)) +
  scale_fill_brewer(palette = "Blues") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
</code>```

The problem is that I have many observations (UserName) with low values on the Y axes (Nb_Interrogations). So I'd like to exclude all the UserName below a certain threshold from the barplot, let's say 100.

I tried with the which function changing my code:

```<code>ggplot(df[which(df$Nb_Interrogations>100),]aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  geom_bar(stat="identity") +
  theme_bw()+
  theme(legend.key.size = unit(0.5,"line"), legend.position = c(0.8,0.7)) +
  labs(x = "UserName") +
  ylim(0, 95000) +
  scale_y_continuous(breaks = seq(0, 95000, 10000)) +
  scale_fill_brewer(palette = "Blues") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
</code>```

But it doesn't fit my case since it excludes all the observations below the threshold = 100 that are present in my DF from the general computation changing also the Y axes values. How can I solve this problem? thanks

答:
It looks like the simplest solution for you will involve subsetting your data first, and then plotting. Without workable data to test, this is just a theoretical answer, so you may have to adapt for your needs. You can pipe the subsetting and plotting together for ease. Something like this might do the trick for you:</p>
```<code>df %>%
  group_by(UserName) %>%
  filter(sum(Nb_Interrogations > 100)) %>%
  ggplot(., aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  ## the rest of your plotting code here ##
</code>```

Body:
I need to exclude some observations below a certain threshold in   stacked bar chart done with ggplot2.

An example of my dataframe:

My code:

  ggplot(df, aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  geom_bar(stat="identity") +
  theme_bw()+
  theme(legend.key.size = unit(0.5,"line"), legend.position = c(0.8,0.7)) +
  labs(x = "UserName") +
  ylim(0, 95000) +
  scale_y_continuous(breaks = seq(0, 95000, 10000)) +
  scale_fill_brewer(palette = "Blues") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

The problem is that I have many observations (UserName) with low values on the Y axes (Nb_Interrogations). So I'd like to exclude all the UserName below a certain threshold from the barplot, let's say 100.

I tried with the which function changing my code:

ggplot(df[which(df$Nb_Interrogations>100),]aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  geom_bar(stat="identity") +
  theme_bw()+
  theme(legend.key.size = unit(0.5,"line"), legend.position = c(0.8,0.7)) +
  labs(x = "UserName") +
  ylim(0, 95000) +
  scale_y_continuous(breaks = seq(0, 95000, 10000)) +
  scale_fill_brewer(palette = "Blues") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

But it doesn't fit my case since it excludes all the observations below the threshold = 100 that are present in my DF from the general computation changing also the Y axes values. How can I solve this problem? thanks

Body:
It looks like the simplest solution for you will involve subsetting your data first, and then plotting. Without workable data to test, this is just a theoretical answer, so you may have to adapt for your needs. You can pipe the subsetting and plotting together for ease. Something like this might do the trick for you:

df %>%
  group_by(UserName) %>%
  filter(sum(Nb_Interrogations > 100)) %>%
  ggplot(., aes(x=reorder(UserName,-Nb_Interrogations, sum), y=Nb_Interrogations, fill=Folder)) +
  ## the rest of your plotting code here ##