问:
Basically, I want to edit a html file in the Jenkins workspace which is generated after built. Tried few Jenkins Plugins, but no use
Basically, I want to edit a html file in the Jenkins workspace which is generated after built.

Tried few Jenkins Plugins, but no use.

Basically, I want to edit a html file in the Jenkins workspace which is generated after built.

Tried few Jenkins Plugins, but no use.

答:
Basically i have used sed command in Jenkins using Shell Execute. I could be able to replace any string.
Thanks</p>


来源: stackexchange

问:
In Silverlight, is it possible to bind buttons to a command from a different class?
In Silverlight, if  the datacontext of the userControl inn Xaml is Class A, can a button in the  bind to a command in a different class (lets say class B)?

Thanks.

答:
In a word, yes.  However, your Class A (datacontext) will need access to an instance of Class B and expose it publicly (or expose whatever it is you want to bind to--like a delegate).

In general, anything you bind to in XAML requires that the binding path is reachable through your DataContext.

ContentLicense: CC BY-SA 3.0


问:
How to slice np array's certain dimention with different start point?
The sample code is as below.

I want to get dataNew(h, w, length) according to data(h, w, c) and ind(h, w). Here length < c, it means dataNew is sliced from data.

Here, length and ind[i, j] is made sure to suit the c value.

I have realize it through for loops, but I wnat the python way. Please help, thanks!

import numpy as np

h, w, c = 3, 4, 5

data = np.arange(60).reshape((h, w, c))
print(data)

length = 3
ind = np.random.randint(0, 3, 12).reshape(h, w)
print(ind)

dataNew = np.empty((h, w, length), np.int16)
for i in range(h):
    for j in range(w):
        st = ind[i, j]
        dataNew[i, j] = data[i, j][st : st + length]

print(dataNew)
```

答:
One way would be creating an indexing array using broadcasting and use np.take_along_axis to index the array:

```<code>ix = ind[...,None] + np.arange(length)
np.take_along_axis(data, ix, -1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
One way would be creating an indexing array using broadcasting and use np.take_along_axis to index the array:

ix = ind[...,None] + np.arange(length)
np.take_along_axis(data, ix, -1)


问:
How to prevent a UIViewController from being popped out?
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

```<code>override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}
</code>```

答: Actually, there is a very simple solution: navigationItem.hidesBackButton = true - this will hide "BACK" button and disable swipe-to-back feature.

Body:
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}


问:
HardFault when running code from RAM in CortexM0
I'm currently developing firmware for an Arm Cortex-M0+ microcontroller and I'm facing a rather interesting issue. I'm not looking for any answers but rather would like to share the problem with other developers so I can (hopefully) shed some light on the issue I'm facing. I will describe it below:

I have a program that dynamically loads (properly compiled and linked) code from an external Flash Chip, to be executed straight out of the MCU RAM. The interesting is that I can perfectly execute the RAM-loaded code when running in step-by-step (via debugger), but it will always crash [formally HardFault] when freely running. I've tried to disable all interrupts, I've double checked the instructions, memory addresses, byte alignments, everything, but I still cannot pinpoint a reason for the exception.

Have some of you any hint of what could be happening? I'm very interested to know more about your experiences! Thanks,

Update 1 (30/05)

Free run in this case, means not setting a breakpoint right before the branch to RAM. Whenever I step into the branch and execute the instructions in RAM it will run correctly and return. Wherever the breakpoint is not there (and thus the MCU goes zooming thought the branch) the HardFault is observed. Notice that it will crash even when booting up with the debugger engaged but not having the breakpoint set.

Update 2 (30/05)

I'm using a Cypress S6E1C3 Series Arm Cortex M0+ FM0+ Microcontroller.

Update 3 (30/05)

After digging around and playing with the code, I could get it to work properly! It however brought up more questions than answers for me. Reading the official ARM documentation about the BLX instruction (BLX) I found out that the LSBit of the branch address determines the CPU instruction mode (1 causes it to run in Thumb mode). By explicitly setting this bit, I get the code to always work, even in free-run mode. The thing is, the code in RAM has not been compiled in Thumb mode, and there is not apparent reason why running the code step-by-step with the debugger would cause the instruction mode to change... Any ideas?

K.

答:
The issue was in the branch address (as correctly pointed out by @PeterCordes). The branch to RAM was performed by the following code (slightly adjusted for this audience):

```<code>// Prepare address and Function Pointer
uint32_t codeBufferAddress = reinterpret_cast<uint32_t>(&buffer) + offset;
void(*methodFromRAM)(void*) = reinterpret_cast<void(*)(void*)>(codeBufferAddress | 0x01);

// Branch to RAM
// thisPointer holds an object byte-stream...
(*methodFromRAM)(reinterpret_cast<void*>(thisPointer));
</code>```

Note that in line 3 codeBufferAddress is or'ed with 0x01 (codeBufferAddress | 0x01), which ensures that the branch will be taken in Thumb Mode. By the moment I posted this question, the value held by codeBufferAddress was 0x20003E40, which clearly does not set the LSBit and thus would force the MCU to run in ARM Mode.

I think the compiler would not be able to infer and adjust the branch mode, because the address is dynamically generated  (even though I think it could be a bit smarter and force all branches to run in Thumb Mode, since my MCU can only decode Thumb).

Anyways, when running in step-by-step mode, I could not observe any changes in the target address, and for now I can only guess it forces the MCU to run in Thumb Mode... but this is only a guess. Any ideas?

K.

Body:
The issue was in the branch address (as correctly pointed out by @PeterCordes). The branch to RAM was performed by the following code (slightly adjusted for this audience):

// Prepare address and Function Pointer
uint32_t codeBufferAddress = reinterpret_cast<uint32_t>(&buffer) + offset;
void(*methodFromRAM)(void*) = reinterpret_cast<void(*)(void*)>(codeBufferAddress | 0x01);

// Branch to RAM
// thisPointer holds an object byte-stream...
(*methodFromRAM)(reinterpret_cast<void*>(thisPointer));

Note that in line 3 codeBufferAddress is or'ed with 0x01 (codeBufferAddress | 0x01), which ensures that the branch will be taken in Thumb Mode. By the moment I posted this question, the value held by codeBufferAddress was 0x20003E40, which clearly does not set the LSBit and thus would force the MCU to run in ARM Mode.

I think the compiler would not be able to infer and adjust the branch mode, because the address is dynamically generated  (even though I think it could be a bit smarter and force all branches to run in Thumb Mode, since my MCU can only decode Thumb).

Anyways, when running in step-by-step mode, I could not observe any changes in the target address, and for now I can only guess it forces the MCU to run in Thumb Mode... but this is only a guess. Any ideas?

K.


问:
XSLT chaining or combining xsl:copy-of and xsl:copy
I've got the following two XSL transforms that I would like to chain together in one XSL file.

The first transform:

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="/">
  <xsl:copy-of select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>
</code>```

And the second transform (using the output of the first as input):

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/xs:schema/xs:element[@name='ServiceAuth']"/>
<xsl:template match="/xs:schema/xs:import[@namespace='http://www.somecompany.com/serviceAuth/ ']"/>
</xsl:stylesheet>
</code>```

What I'm aiming to accomplish with this, is to copy only the xs:schema node (and all it's children) from a WSDL whilst at the same time removing two nodes from inside the xs:schema node.

How do I chain these two together in one XSL or is there an even better way to accomplish the above objective?

Below is the WSDL input file that should serve as input to the first transform:

```<code><s0:definitions name="CBS_GetUpgradeEligibility" targetNamespace="http://www.somecompany.com/" xmlns:s0="http://schemas.xmlsoap.org/wsdl/" xmlns:s1="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:s2="http://www.somecompany.com/" xmlns:s3="http://schemas.xmlsoap.org/wsdl/soap/">
   <s0:types>
      <xs:schema targetNamespace="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:auth="http://www.somecompany.com/serviceAuth/" xmlns:cbs="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:esb="http://www.somecompany.com/esbTypes/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.somecompany.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
         <xs:import namespace="http://www.somecompany.com/esbTypes/" schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ESBTypes"/>
         <xs:import namespace="http://www.somecompany.com/serviceAuth/ " schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ServiceAuth"/>
         <xs:simpleType name="DESTINATION_MSISDN">
            <xs:restriction base="xs:string">
               <xs:maxLength value="11"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_13">
            <xs:restriction base="xs:string">
               <xs:maxLength value="13"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_20">
            <xs:restriction base="xs:string">
               <xs:maxLength value="20"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:complexType name="UPGRADE_TYPE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isber" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="isreward" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="code" type="cbs:STRING_20"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="QUALIFIES_FOR_UPGRADE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isaveragespentmet" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="is7daypremature" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradepossible" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradeduedate" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="0" name="UpgradeType" type="cbs:UPGRADE_TYPE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
         <xs:element name="ServiceAuth">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="Username" type="auth:Username"/>
                  <xs:element name="Password" type="auth:Password"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityRequest">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="TSORequest" type="cbs:getUpgradeEligibilityRequestElement"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityResponse">
            <xs:complexType>
               <xs:sequence>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOID" type="esb:TSOID"/>
                  <xs:element name="TSOResponse" type="cbs:getUpgradeEligibilityResponseElement"/>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOResult" type="esb:TSOResult"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:complexType name="getUpgradeEligibilityRequestElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getUpgradeEligibilityResponseElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
               <xs:element maxOccurs="1" minOccurs="1" name="QualifiesForUpgrade" type="cbs:QUALIFIES_FOR_UPGRADE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
      </xs:schema>
   </s0:types>
   <s0:message name="GetUpgradeEligibilityRequestMessage">
      <s0:part element="s1:ServiceAuth" name="ServiceAuth"/>
      <s0:part element="s1:GetUpgradeEligibilityRequest" name="GetUpgradeEligibilityRequest"/>
   </s0:message>
   <s0:message name="GetUpgradeEligibilityResponseMessage">
      <s0:part element="s1:GetUpgradeEligibilityResponse" name="GetUpgradeEligibilityResponse"/>
   </s0:message>
   <s0:portType name="esbTransactionPort">
      <s0:operation name="getUpgradeEligibility">
         <s0:input message="s2:GetUpgradeEligibilityRequestMessage"/>
         <s0:output message="s2:GetUpgradeEligibilityResponseMessage"/>
      </s0:operation>
   </s0:portType>
   <s0:binding name="getUpgradeEligibilityEsbTransactionBinding" type="s2:esbTransactionPort">
      <s3:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <s0:operation name="getUpgradeEligibility">
         <s3:operation soapAction="" style="document"/>
         <s0:input>
            <s3:header message="s2:GetUpgradeEligibilityRequestMessage" part="ServiceAuth" use="literal"/>
            <s3:body parts="GetUpgradeEligibilityRequest" use="literal"/>
         </s0:input>
         <s0:output>
            <s3:body parts="GetUpgradeEligibilityResponse" use="literal"/>
         </s0:output>
      </s0:operation>
   </s0:binding>
   <s0:service name="getUpgradeEligibilityEsbTransactionBindingQSService">
      <s0:port binding="s2:getUpgradeEligibilityEsbTransactionBinding" name="getUpgradeEligibilityEsbTransactionBindingQSPort">
         <s3:address location="http://VESB14-PRD:7701/CBS_GetUpgradeEligibility"/>
      </s0:port>
   </s0:service>
</s0:definitions>
</code>```

答:
I haven't touched XSLT for quite some time - but I think you can do it iterativly instead of by applying templates.

Start by selecting /s0:definitions/s0:types/xs:schema - then go over all of it's children (<xsl:for-each ... If i recall correctly) and for each of them test if it is the node you want to omit. if not - use copy-of, otherwise just drop it

Also, if you run the XSLT using some java code, or ANY utility you can just pass the output of the 1st XSLT as the input of the 2nd XSLT.

Hope this helps.

Body:
I've got the following two XSL transforms that I would like to chain together in one XSL file.

The first transform:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="/">
  <xsl:copy-of select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>

And the second transform (using the output of the first as input):

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/xs:schema/xs:element[@name='ServiceAuth']"/>
<xsl:template match="/xs:schema/xs:import[@namespace='http://www.somecompany.com/serviceAuth/ ']"/>
</xsl:stylesheet>

What I'm aiming to accomplish with this, is to copy only the xs:schema node (and all it's children) from a WSDL whilst at the same time removing two nodes from inside the xs:schema node.

How do I chain these two together in one XSL or is there an even better way to accomplish the above objective?

Below is the WSDL input file that should serve as input to the first transform:

<s0:definitions name="CBS_GetUpgradeEligibility" targetNamespace="http://www.somecompany.com/" xmlns:s0="http://schemas.xmlsoap.org/wsdl/" xmlns:s1="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:s2="http://www.somecompany.com/" xmlns:s3="http://schemas.xmlsoap.org/wsdl/soap/">
   <s0:types>
      <xs:schema targetNamespace="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:auth="http://www.somecompany.com/serviceAuth/" xmlns:cbs="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:esb="http://www.somecompany.com/esbTypes/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.somecompany.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
         <xs:import namespace="http://www.somecompany.com/esbTypes/" schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ESBTypes"/>
         <xs:import namespace="http://www.somecompany.com/serviceAuth/ " schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ServiceAuth"/>
         <xs:simpleType name="DESTINATION_MSISDN">
            <xs:restriction base="xs:string">
               <xs:maxLength value="11"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_13">
            <xs:restriction base="xs:string">
               <xs:maxLength value="13"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_20">
            <xs:restriction base="xs:string">
               <xs:maxLength value="20"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:complexType name="UPGRADE_TYPE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isber" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="isreward" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="code" type="cbs:STRING_20"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="QUALIFIES_FOR_UPGRADE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isaveragespentmet" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="is7daypremature" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradepossible" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradeduedate" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="0" name="UpgradeType" type="cbs:UPGRADE_TYPE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
         <xs:element name="ServiceAuth">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="Username" type="auth:Username"/>
                  <xs:element name="Password" type="auth:Password"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityRequest">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="TSORequest" type="cbs:getUpgradeEligibilityRequestElement"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityResponse">
            <xs:complexType>
               <xs:sequence>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOID" type="esb:TSOID"/>
                  <xs:element name="TSOResponse" type="cbs:getUpgradeEligibilityResponseElement"/>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOResult" type="esb:TSOResult"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:complexType name="getUpgradeEligibilityRequestElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getUpgradeEligibilityResponseElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
               <xs:element maxOccurs="1" minOccurs="1" name="QualifiesForUpgrade" type="cbs:QUALIFIES_FOR_UPGRADE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
      </xs:schema>
   </s0:types>
   <s0:message name="GetUpgradeEligibilityRequestMessage">
      <s0:part element="s1:ServiceAuth" name="ServiceAuth"/>
      <s0:part element="s1:GetUpgradeEligibilityRequest" name="GetUpgradeEligibilityRequest"/>
   </s0:message>
   <s0:message name="GetUpgradeEligibilityResponseMessage">
      <s0:part element="s1:GetUpgradeEligibilityResponse" name="GetUpgradeEligibilityResponse"/>
   </s0:message>
   <s0:portType name="esbTransactionPort">
      <s0:operation name="getUpgradeEligibility">
         <s0:input message="s2:GetUpgradeEligibilityRequestMessage"/>
         <s0:output message="s2:GetUpgradeEligibilityResponseMessage"/>
      </s0:operation>
   </s0:portType>
   <s0:binding name="getUpgradeEligibilityEsbTransactionBinding" type="s2:esbTransactionPort">
      <s3:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <s0:operation name="getUpgradeEligibility">
         <s3:operation soapAction="" style="document"/>
         <s0:input>
            <s3:header message="s2:GetUpgradeEligibilityRequestMessage" part="ServiceAuth" use="literal"/>
            <s3:body parts="GetUpgradeEligibilityRequest" use="literal"/>
         </s0:input>
         <s0:output>
            <s3:body parts="GetUpgradeEligibilityResponse" use="literal"/>
         </s0:output>
      </s0:operation>
   </s0:binding>
   <s0:service name="getUpgradeEligibilityEsbTransactionBindingQSService">
      <s0:port binding="s2:getUpgradeEligibilityEsbTransactionBinding" name="getUpgradeEligibilityEsbTransactionBindingQSPort">
         <s3:address location="http://VESB14-PRD:7701/CBS_GetUpgradeEligibility"/>
      </s0:port>
   </s0:service>
</s0:definitions>


问:
How to get message body from RoutingContext?
I created a vert.x HTTP server and I want to receive messages from clients in json format.
This is my code:

```<code>public class HttpServerVerticle extends AbstractVerticle {
    @Override
    public void start(Future<Void> future) {
        Router router = Router.router(vertx)
            .exceptionHandler(ex -> log.error("Error: " + ex));
        router.route().handler(BodyHandler.create());
        router.route("/getData").handler(this::getRequestHandler);

        HttpServerOptions serverOptions = new HttpServerOptions();
        vertx.createHttpServer(serverOptions)
                .requestHandler(router::accept)
                .listen(9539, result -> {
                    if (result.succeeded()) {
                        future.complete();
                    } else {
                        future.fail(result.cause());
                    }
                });
    }

    private void getRequestHandler(RoutingContext request) {
        JsonObject data = request.getBodyAsJson();  // In this place I had exception
        ...
        request.response().end("{\"reply\":\"ok\"}");
    }
}
</code>```

When my handler was fire and I get some message from the client I get this exception:

```<code>io.vertx.core.json.DecodeException: Failed to decode:Unexpected end-of-input: expected close marker for Object (start marker at [Source: (String)"{"ClientRequest":["ok"],"Type":"Test"[truncated 678 chars]; line: 1, column: 1])
</code>```

How can I avoid this exception and all time get the full message?

答:
You should specify the HTTP method

```<code>router.route("/getData").handler(this::getRequestHandler);
</code>```

is expecting an HTTP GET, but what you need is an HTTP POST:

```<code>router.post("/getData")
  .consumes("application/json")
  .handler(this::getRequestHandler);
</code>```

will accept json in the body. The consumes is optional and enforces the client to only send json.

I would also suggest to name the route "/data" instead of "/getData" to conform with the concept of RESTful APIs.

Body:
I created a vert.x HTTP server and I want to receive messages from clients in json format.
This is my code:

public class HttpServerVerticle extends AbstractVerticle {
    @Override
    public void start(Future<Void> future) {
        Router router = Router.router(vertx)
            .exceptionHandler(ex -> log.error("Error: " + ex));
        router.route().handler(BodyHandler.create());
        router.route("/getData").handler(this::getRequestHandler);

        HttpServerOptions serverOptions = new HttpServerOptions();
        vertx.createHttpServer(serverOptions)
                .requestHandler(router::accept)
                .listen(9539, result -> {
                    if (result.succeeded()) {
                        future.complete();
                    } else {
                        future.fail(result.cause());
                    }
                });
    }

    private void getRequestHandler(RoutingContext request) {
        JsonObject data = request.getBodyAsJson();  // In this place I had exception
        ...
        request.response().end("{\"reply\":\"ok\"}");
    }
}

When my handler was fire and I get some message from the client I get this exception:

io.vertx.core.json.DecodeException: Failed to decode:Unexpected end-of-input: expected close marker for Object (start marker at [Source: (String)"{"ClientRequest":["ok"],"Type":"Test"[truncated 678 chars]; line: 1, column: 1])

How can I avoid this exception and all time get the full message?

Body:
You should specify the HTTP method

router.route("/getData").handler(this::getRequestHandler);

is expecting an HTTP GET, but what you need is an HTTP POST:

router.post("/getData")
  .consumes("application/json")
  .handler(this::getRequestHandler);

will accept json in the body. The consumes is optional and enforces the client to only send json.

I would also suggest to name the route "/data" instead of "/getData" to conform with the concept of RESTful APIs.


问:
Error 1004 application defined or object defined error
Here the code:

```<code>Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub
</code>```

What s wrong with that?

答:
Please see below corrected code... instead of starting n at 0, start with a at 0. Plus, avoid using .Select everything... and you should try to declare your ranges fully:

Sub deleterow222()

Dim lastRow As Long, R As Long
Dim ws As Worksheet: Set ws = ActiveWorkbook.ActiveSheet
Dim idColumn as Long: idColumn = 6
Dim diffColumn as Long: diffColumn = 19

    lastRow = ws.Range("F" & ws.Rows.Count).End(xlUp).Row
    For R = lastRow To 2 Step -1
        With ws
            If .Cells(R, idColumn) = .Cells(R - 1, idColumn) And .Cells(R, diffColumn) > 30 Then
                .Cells(R, idColumn).EntireRow.Delete
            End If
        End With
    Next R

End Sub
```

Body:
Here the code:

Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub

What s wrong with that?


问:
Adding executable code to my wxpython gui text boxes
I currently have a working script that lets me create a copy of a backup file, take that copy and rename it to Filename_New, and rename the original file to Filename_Bad.

I am new to creating GUI's, and python code in general, but currently have a gui and would like to tie in the 3 specific pieces of code to the different boxes in the gui so that when you enter the filename in step 1 in the gui it runs that section of my python code.

Not really sure how to integrate these two things together, so any advice would be greatly appreciated. Thanks in advance, hopefully the code below is formatted correctly.

Here is a piece of my python code to execute the copy process.

I have two other variations of the process above that adds _NEW, and _BAD to the other files.

I would like to tie this code to that GUI in a text box where you enter the file name and the code executes when you hit Okay.

```<code>
### Do all your imports as needed

import wx, wx.lib.newevent

import os, sys, copy, shutil

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)

        self.InitUI()
        self.Centre()

    def InitUI(self):

        panel = wx.Panel(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        #### As already mentioned you defined a wx.BoxSizer but later were using
        #### a wx.GridBagSizer. By the way I also changed a little bit the span
        #### and flags of the widgets when added to the wx.GridBagSizer
        sizer = wx.GridBagSizer(1, 1)

        text = wx.StaticText(panel, label="Enter the VR File That Crashed: ")
        sizer.Add(text, pos=(0, 0), span=(1, 2), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)

        #### tc will be used by other methods so it is better to use self.tc
        self.tc = wx.TextCtrl(panel)
        sizer.Add(self.tc, pos=(1, 0), span=(1, 2),
            flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)

        #### Changed the label of the buttons
        buttonOk = wx.Button(panel, label="Search File", size=(90, 28))
        buttonClose = wx.Button(panel, label="Do Stuffs", size=(90, 28))
        sizer.Add(buttonOk, pos=(2, 0), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)
        sizer.Add(buttonClose, pos=(2, 1), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)

        panel.SetSizer(sizer)

        #### This is how you Bind the button to a method so everytime the button
        #### is clicked the method is executed
        buttonOk.Bind(wx.EVT_BUTTON, self.SearchFile)
        buttonClose.Bind(wx.EVT_BUTTON, self.DoStuffs)

    def SearchFile(self, event):
        #### This is how you use the wx.FileDialog and put the selected path in
        #### the wx.TextCtrl
        dlg = wx.FileDialog(None, message="Select File", style=wx.FD_OPEN|wx.FD_CHANGE_DIR|wx.FD_FILE_MUST_EXIST|wx.FD_PREVIEW)
        if dlg.ShowModal() == wx.ID_OK:
            self.tc.SetValue(dlg.GetPath())
        else:
            pass

    def DoStuffs(self, event):
        #### This is how you get the path to the selected/typed file and then
        #### do your stuffs
        def copy_vrb(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_COPY"
            shutil.copy(oldvr, newvrb + ".vrb")

        def file_rename(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_BAD"
            shutil.copy(oldvr, newvrb + ".vr")

        def rename_copy(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_NEW"
            shutil.copy(oldvr, newvrb + ".vr")

        oldvrb = self.tc.GetValue()
        copy_vrb(oldvr)
        file_rename(oldvr)
        rename_copy(oldvr)

        print(oldvr)

if __name__ == '__main__':
    app = wx.App()
    ex = Example(None, title='Rename')
    ex.Show()
    app.MainLoop()
else:
    pass

</code>```

Type in a filename into the gui and have the code execute on that filename.

答:
Welcome to StackOverflow.

The short answer to your question is that you need to Bind the buttons in your GUI to some method. You can see in the code below how this is done.

I changed your code a little bit because you were defining a wx.BoxSixer but then you were addidng widgets to a wx.GridBagSizer. Also, I changed the buttons to show you how to search for a file with a wx.FileDialog, just in case you do not want to type the path to the file and because I assumed (perhaps incorrectly) that the Close button is to close the app. No need for this, just click the X and the app closes.

Code with comments

```<code>### Do all your imports as needed

import wx, wx.lib.newevent

import os, sys, copy, shutil

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)

        self.InitUI()
        self.Centre()

    def InitUI(self):

        panel = wx.Panel(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        #### As already mentioned you defined a wx.BoxSizer but later were using
        #### a wx.GridBagSizer. By the way I also changed a little bit the span
        #### and flags of the widgets when added to the wx.GridBagSizer
        sizer = wx.GridBagSizer(1, 1)

        text = wx.StaticText(panel, label="Enter the VR File That Crashed: ")
        sizer.Add(text, pos=(0, 0), span=(0, 2), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)

        #### tc will be used by other methods so it is better to use self.tc
        self.tc = wx.TextCtrl(panel)
        sizer.Add(self.tc, pos=(1, 0), span=(0, 2),
            flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)

        #### Changed the label of the buttons
        buttonOk = wx.Button(panel, label="Search File", size=(90, 28))
        buttonClose = wx.Button(panel, label="Do Stuffs", size=(90, 28))
        sizer.Add(buttonOk, pos=(2, 0), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)
        sizer.Add(buttonClose, pos=(2, 1), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)

        panel.SetSizer(sizer)

        #### This is how you Bind the button to a method so everytime the button
        #### is clicked the method is executed
        buttonOk.Bind(wx.EVT_BUTTON, self.SearchFile)
        buttonClose.Bind(wx.EVT_BUTTON, self.DoStuffs)

    def SearchFile(self, event):
        #### This is how you use the wx.FileDialog and put the selected path in
        #### the wx.TextCtrl
        dlg = wx.FileDialog(None, message="Select File", style=wx.FD_OPEN|wx.FD_CHANGE_DIR|wx.FD_FILE_MUST_EXIST|wx.FD_PREVIEW)
        if dlg.ShowModal() == wx.ID_OK:
            self.tc.SetValue(dlg.GetPath())
        else:
            pass

    def DoStuffs(self, event):
        #### This is how you get the path to the selected/typed file and then
        #### do your stuffs
        oldvrb = self.tc.GetValue()
        print(oldvrb)

if __name__ == '__main__':
    app = wx.App()
    ex = Example(None, title='Rename')
    ex.Show()
    app.MainLoop()
else:
    pass
</code>```

Body:
I currently have a working script that lets me create a copy of a backup file, take that copy and rename it to Filename_New, and rename the original file to Filename_Bad.

I am new to creating GUI's, and python code in general, but currently have a gui and would like to tie in the 3 specific pieces of code to the different boxes in the gui so that when you enter the filename in step 1 in the gui it runs that section of my python code.

Not really sure how to integrate these two things together, so any advice would be greatly appreciated. Thanks in advance, hopefully the code below is formatted correctly.

Here is a piece of my python code to execute the copy process.

I have two other variations of the process above that adds _NEW, and _BAD to the other files.

I would like to tie this code to that GUI in a text box where you enter the file name and the code executes when you hit Okay.

### Do all your imports as needed

import wx, wx.lib.newevent

import os, sys, copy, shutil

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)

        self.InitUI()
        self.Centre()

    def InitUI(self):

        panel = wx.Panel(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        #### As already mentioned you defined a wx.BoxSizer but later were using
        #### a wx.GridBagSizer. By the way I also changed a little bit the span
        #### and flags of the widgets when added to the wx.GridBagSizer
        sizer = wx.GridBagSizer(1, 1)

        text = wx.StaticText(panel, label="Enter the VR File That Crashed: ")
        sizer.Add(text, pos=(0, 0), span=(1, 2), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)

        #### tc will be used by other methods so it is better to use self.tc
        self.tc = wx.TextCtrl(panel)
        sizer.Add(self.tc, pos=(1, 0), span=(1, 2),
            flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)

        #### Changed the label of the buttons
        buttonOk = wx.Button(panel, label="Search File", size=(90, 28))
        buttonClose = wx.Button(panel, label="Do Stuffs", size=(90, 28))
        sizer.Add(buttonOk, pos=(2, 0), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)
        sizer.Add(buttonClose, pos=(2, 1), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)

        panel.SetSizer(sizer)

        #### This is how you Bind the button to a method so everytime the button
        #### is clicked the method is executed
        buttonOk.Bind(wx.EVT_BUTTON, self.SearchFile)
        buttonClose.Bind(wx.EVT_BUTTON, self.DoStuffs)

    def SearchFile(self, event):
        #### This is how you use the wx.FileDialog and put the selected path in
        #### the wx.TextCtrl
        dlg = wx.FileDialog(None, message="Select File", style=wx.FD_OPEN|wx.FD_CHANGE_DIR|wx.FD_FILE_MUST_EXIST|wx.FD_PREVIEW)
        if dlg.ShowModal() == wx.ID_OK:
            self.tc.SetValue(dlg.GetPath())
        else:
            pass

    def DoStuffs(self, event):
        #### This is how you get the path to the selected/typed file and then
        #### do your stuffs
        def copy_vrb(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_COPY"
            shutil.copy(oldvr, newvrb + ".vrb")

        def file_rename(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_BAD"
            shutil.copy(oldvr, newvrb + ".vr")

        def rename_copy(oldvr):
            newvrb = os.path.splitext(oldvr)[0] + "_NEW"
            shutil.copy(oldvr, newvrb + ".vr")

        oldvrb = self.tc.GetValue()
        copy_vrb(oldvr)
        file_rename(oldvr)
        rename_copy(oldvr)

        print(oldvr)

if __name__ == '__main__':
    app = wx.App()
    ex = Example(None, title='Rename')
    ex.Show()
    app.MainLoop()
else:
    pass

Type in a filename into the gui and have the code execute on that filename.

Body:
Welcome to StackOverflow.

The short answer to your question is that you need to Bind the buttons in your GUI to some method. You can see in the code below how this is done.

I changed your code a little bit because you were defining a wx.BoxSixer but then you were addidng widgets to a wx.GridBagSizer. Also, I changed the buttons to show you how to search for a file with a wx.FileDialog, just in case you do not want to type the path to the file and because I assumed (perhaps incorrectly) that the Close button is to close the app. No need for this, just click the X and the app closes.

Code with comments

### Do all your imports as needed

import wx, wx.lib.newevent

import os, sys, copy, shutil

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)

        self.InitUI()
        self.Centre()

    def InitUI(self):

        panel = wx.Panel(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        #### As already mentioned you defined a wx.BoxSizer but later were using
        #### a wx.GridBagSizer. By the way I also changed a little bit the span
        #### and flags of the widgets when added to the wx.GridBagSizer
        sizer = wx.GridBagSizer(1, 1)

        text = wx.StaticText(panel, label="Enter the VR File That Crashed: ")
        sizer.Add(text, pos=(0, 0), span=(0, 2), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)

        #### tc will be used by other methods so it is better to use self.tc
        self.tc = wx.TextCtrl(panel)
        sizer.Add(self.tc, pos=(1, 0), span=(0, 2),
            flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)

        #### Changed the label of the buttons
        buttonOk = wx.Button(panel, label="Search File", size=(90, 28))
        buttonClose = wx.Button(panel, label="Do Stuffs", size=(90, 28))
        sizer.Add(buttonOk, pos=(2, 0), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)
        sizer.Add(buttonClose, pos=(2, 1), flag=wx.ALIGN_CENTER|wx.RIGHT|wx.BOTTOM, border=10)

        panel.SetSizer(sizer)

        #### This is how you Bind the button to a method so everytime the button
        #### is clicked the method is executed
        buttonOk.Bind(wx.EVT_BUTTON, self.SearchFile)
        buttonClose.Bind(wx.EVT_BUTTON, self.DoStuffs)

    def SearchFile(self, event):
        #### This is how you use the wx.FileDialog and put the selected path in
        #### the wx.TextCtrl
        dlg = wx.FileDialog(None, message="Select File", style=wx.FD_OPEN|wx.FD_CHANGE_DIR|wx.FD_FILE_MUST_EXIST|wx.FD_PREVIEW)
        if dlg.ShowModal() == wx.ID_OK:
            self.tc.SetValue(dlg.GetPath())
        else:
            pass

    def DoStuffs(self, event):
        #### This is how you get the path to the selected/typed file and then
        #### do your stuffs
        oldvrb = self.tc.GetValue()
        print(oldvrb)

if __name__ == '__main__':
    app = wx.App()
    ex = Example(None, title='Rename')
    ex.Show()
    app.MainLoop()
else:
    pass


问:
How do I install GDB on MacOS 10.13.3 (High Sierra)
There are tons and tons of post and blogs discussing this topic, but nothing seems to work...

From across the internet, here is the common consensus regarding the procedure required to install and run gdb.

Install gdb

```<code>brew install gdb
</code>```

Homebrew "successfully" installs gdb v8.1

Codesign gdb

Codesign gdb by following the codesigning procedure (as detailed in a separate SO post).

Update ~/.gdbinit

```<code>echo "set startup-with-shell off" >> ~/.gdbinit
</code>```

After completing all the steps, when I attempt to debug a simple "hello world" program, I get the following startup error resulting from SIGTRAP being throw.

```<code>(gdb) start
Temporary breakpoint 1 at 0x100000e66: file test.cpp, line 5.
Starting program: /Users/zfields/Documents/Development/test/a.out
[New Thread 0x1703 of process 67971]
[New Thread 0x1903 of process 67971]
During startup program terminated with signal SIGTRAP, Trace/breakpoint trap.
</code>```

What am I missing?

答:
Maybe a bit of unrelated:

Mac OS Sierra 10.13.6
gdb 8.0.1

had the same error as topic-starter.

https://gist.github.com/gravitylow/fb595186ce6068537a6e9da6d8b5b96d

I discovered that I already had gdbcert1 in my System.
Followed everything from 7.
Works!

Body:
There are tons and tons of post and blogs discussing this topic, but nothing seems to work...

From across the internet, here is the common consensus regarding the procedure required to install and run gdb.

Install gdb

brew install gdb

Homebrew "successfully" installs gdb v8.1

Codesign gdb

Codesign gdb by following the codesigning procedure (as detailed in a separate SO post).

Update ~/.gdbinit

echo "set startup-with-shell off" >> ~/.gdbinit

After completing all the steps, when I attempt to debug a simple "hello world" program, I get the following startup error resulting from SIGTRAP being throw.

(gdb) start
Temporary breakpoint 1 at 0x100000e66: file test.cpp, line 5.
Starting program: /Users/zfields/Documents/Development/test/a.out
[New Thread 0x1703 of process 67971]
[New Thread 0x1903 of process 67971]
During startup program terminated with signal SIGTRAP, Trace/breakpoint trap.

What am I missing?


问:
Parse an HTML template as you require it in JavaScript
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

```<code>   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]
</code>```

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

答:
Well, transforming a string to html is easy. So if you get a string reposonse back for your template you can transform it to a DOM structure like below.

/** Create a NON attached DOM element. This floats in nothing. Hello Dave */
var dave = document.createElement("div");

/** Give dave a body with the HTML string we received from "somewhere" */
dave.innerHTML = "
<input type='text'>
";

/**
  * dave is now

<input type='text'>

  */
dave.querySelector('input').value = "I'm sorry Dave, I'm afraid I can't do that";

/** ======================================================================
 * Now render we render Dave, this isn't really needed, but will do anyways.
 * We don't need the "wrapping" floating div we created so we get all of Dave's children
 * And let Dave be forgotten about in the abyss of eternity.
 */
var content = dave.children;

var main = document.getElementById('main');
for(var i = 0; i < content.length; i++) {
  main.appendChild(content[i]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
   background-color: red;
}
.foo input {
   background-color: black;
   color: white;
}</code>```

```

You can then do transformation on the 'children' as well, just as you would with a normal DOM tree object.

Body:
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

Body:
Well, transforming a string to html is easy. So if you get a string reposonse back for your template you can transform it to a DOM structure like below.

/** Create a NON attached DOM element. This floats in nothing. Hello Dave */
var dave = document.createElement("div");

/** Give dave a body with the HTML string we received from "somewhere" */
dave.innerHTML = "<div class='foo'><input type='text'></div>";

/**
  * dave is now <div><div class='foo'><input type='text'></div></div>
  */
dave.querySelector('input').value = "I'm sorry Dave, I'm afraid I can't do that";

/** ======================================================================
 * Now render we render Dave, this isn't really needed, but will do anyways.
 * We don't need the "wrapping" floating div we created so we get all of Dave's children
 * And let Dave be forgotten about in the abyss of eternity.
 */
var content = dave.children;

var main = document.getElementById('main');
for(var i = 0; i < content.length; i++) {
  main.appendChild(content[i]);
}

.foo {
   background-color: red;
}
.foo input {
   background-color: black;
   color: white;
}

<body id="main">
</body>

You can then do transformation on the 'children' as well, just as you would with a normal DOM tree object.


问:
How to make the clearTimeout fire
I have an SVG with <uses> not and when you touch one of them a touchstart events fires. If they move a touchmove event fires that has a timer. On touchend the timer is cleared before the value is supposed to change. However, it changes anyway.

The results of this are that the IsDraggingUnit is set to true even after the touchend is fired. I tested with an alert and it is firing successfully when ending your touch on the element.

var IsDraggingUnit = false;
var timeOutClear;

$('#Selected_Items use').on("touchstart", function(event) {
  IsDraggingUnit = false;
  $('#test > p').text(IsDraggingUnit);

  $(this).on("touchmove", function(event) {
    timeOutClear = setTimeout(function() {
      IsDraggingUnit = true;
      $('#test > p').text(IsDraggingUnit);
    }, 500);
  });

  $(this).on("touchend", function(event) {
    clearTimeout(timeOutClear);
    if (IsDraggingUnit == false) {
      fnPlotShow($(this), bookingRental, bookingExists)
    }
  });
});
```

答:
The issue is because you are nesting the touchmove and touchend events within the touchstart event. Therefore on subsequent touchstart occurrences each event fires multiple times and the reference to the original timeout gets lost and clearTimeout() does not clear them all.

To fix this, do not make the event handlers nested, and don't forget to set isDraggingUnit back to false on touchend

var isDraggingUnit = false, timeOutReference;

$('#Selected_Items use').on({
  touchstart: function(event) {
    isDraggingUnit = false;
    $('#test > p').text(isDraggingUnit);
  },
  touchmove: function(event) {
    timeOutReference = setTimeout(function() {
      isDraggingUnit = true;
      $('#test > p').text(isDraggingUnit);
    }, 500);
  },
  touchend: function(event) {
    clearTimeout(timeOutReference);
    if (!isDraggingUnit) {
      fnPlotShow($(this), bookingRental, bookingExists)
    }
    isDraggingUnit = false;
  }
});
```

Also note that your question states the SVG holds <uses> nodes, yet you select use. I assume this is just a typo in the question, though, as it wouldn't work at all if there was a mismatch there.

Title: How to make the clearTimeout fire

Body:
The issue is because you are nesting the touchmove and touchend events within the touchstart event. Therefore on subsequent touchstart occurrences each event fires multiple times and the reference to the original timeout gets lost and clearTimeout() does not clear them all.

To fix this, do not make the event handlers nested, and don't forget to set isDraggingUnit back to false on touchend

var isDraggingUnit = false, timeOutReference;

$('#Selected_Items use').on({
  touchstart: function(event) {
    isDraggingUnit = false;
    $('#test > p').text(isDraggingUnit);
  },
  touchmove: function(event) {
    timeOutReference = setTimeout(function() {
      isDraggingUnit = true;
      $('#test > p').text(isDraggingUnit);
    }, 500);
  },
  touchend: function(event) {
    clearTimeout(timeOutReference);
    if (!isDraggingUnit) {
      fnPlotShow($(this), bookingRental, bookingExists)
    }
    isDraggingUnit = false;
  }
});

Also note that your question states the SVG holds <uses> nodes, yet you select use. I assume this is just a typo in the question, though, as it wouldn't work at all if there was a mismatch there.


问:
Emulating SQL LIKE in JavaScript
How can I emulate the SQL keyword LIKE in JavaScript?

For those of you who don't know what LIKE is, it's a very simple regex which only supports the wildcards %, which matches 0 or more characters, and _ which matches exactly one character.

However, it's not just possible to do something like:

```<code>var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null;
</code>```

...because the pattern might contain dots, stars and any other special regex characters.

答:
I wanted something that also handles escaping the wildcards % and _ using \% and \_.

Here is my solution using negative lookbehind:

// escapes RegExp special characters
const escapePattern = s => s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

// converts ILIKE pattern to a RegExp object
const ilikeToRegExp = pattern =>
  new RegExp(
    `^${escapePattern(pattern)}$`
      // convert ILIKE wildcards, don't match escaped
      .replace(/(?<![\\])%/g, '.*')
      .replace(/(?<![\\])_/g, '.')
      // replace ILIKE escapes
      .replace(/\\%/g, '%')
      .replace(/\\_/g, '_'),
    'i'
  );
```

<p>Usage:</p>

<pre class="lang-js prettyprint-override"><code>ilikeToRegExp('%eLlo WoR%').test('hello world')
// true

ilikeToRegExp('ello wor').test('hello world')
// false

ilikeToRegExp('%90\%%').test('...90%...')
// true
</code>```

Title: Emulating SQL LIKE in JavaScript

Body:
How can I emulate the SQL keyword LIKE in JavaScript?

For those of you who don't know what LIKE is, it's a very simple regex which only supports the wildcards %, which matches 0 or more characters, and _ which matches exactly one character.

However, it's not just possible to do something like:

var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null;

...because the pattern might contain dots, stars and any other special regex characters.

Body:
I wanted something that also handles escaping the wildcards % and _ using \% and \_.

Here is my solution using negative lookbehind:

// escapes RegExp special characters
const escapePattern = s => s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

// converts ILIKE pattern to a RegExp object
const ilikeToRegExp = pattern =>
  new RegExp(
    `^${escapePattern(pattern)}$`
      // convert ILIKE wildcards, don't match escaped
      .replace(/(?<![\\])%/g, '.*')
      .replace(/(?<![\\])_/g, '.')
      // replace ILIKE escapes
      .replace(/\\%/g, '%')
      .replace(/\\_/g, '_'),
    'i'
  );

Usage:

ilikeToRegExp('%eLlo WoR%').test('hello world')
// true

ilikeToRegExp('ello wor').test('hello world')
// false

ilikeToRegExp('%90\%%').test('...90%...')
// true


问:
How to retrieve substring which is outside of brackets in JS?
I want the text which is outside of brackets, for eg.

Text is - Outside (inside)

and what I expect is - Outside

Can someone please help me to achieve this.

答:
If you wanted to remove all bracketed text from the string you could use

let str = 'Outside (inside)test(d 342 dd3d)dd(t423t t)dd()fasf(fsdfds32dfs)';
console.log(str.replace(/(\([\w\d ]*\))+/g, ''))```


问:
rails works locally, but server statut 304 on heroku
I render a partial via ajax in rails. Works great locally, but on heroku I get a 304 and nothing happens on the webpage : http://www.cremers.fr/articles/histoire

I first render all articles like so:

all_finance.html.erb:

```<code><%= render 'articles' %>
</code>```

then in the partial _articles.html.erb:

<% @articles.each do |a| %>
    <% if a.categorie == "histoire" %>
        <%= link_to "lire la suite", article_histoire_url(a.id), remote: true %>
    <% elsif a.categorie == "finance"  %>
        <%= link_to "lire la suite", article_finance_url(a.id), remote: true %>
    <% end %>
<% end %>
```

<p>article_finance_url processes the action <code>article#finance</code>.
<code>finance.js.erb</code>contains:</p>

```document.getElementById('trunc_article_<%= @article.id %>').remove();
document.getElementById('add_article_<%= @article.id %>').innerHTML = '<%= render("contenu") %>';
document.getElementById('add_link_<%= @article.id %>').innerHTML = '<%= link_to image_tag("partage.png", size: "20x20", class: "marge_ht"), article_finance_url(@article.id) %>';
```

<p><code>finance.html.erb</code>contains:</p>

```<%= render 'article' %>
```

Running this locally works fine. On heroku, the server responds the right content, i.e. finance.js.erb correctly rendered with the inbedded templates, but also give a 304 response.

答: For the sake of posterity: In my case I have omitted closing paranthesis in on of the js files. </p>

Body:
I render a partial via ajax in rails. Works great locally, but on heroku I get a 304 and nothing happens on the webpage : http://www.cremers.fr/articles/histoire

I first render all articles like so:

all_finance.html.erb:

<%= render 'articles' %>

then in the partial _articles.html.erb:

<% @articles.each do |a| %>
    <% if a.categorie == "histoire" %>
        <%= link_to "lire la suite", article_histoire_url(a.id), remote: true %>
    <% elsif a.categorie == "finance"  %>
        <%= link_to "lire la suite", article_finance_url(a.id), remote: true %>
    <% end %>
<% end %>

article_finance_url processes the action article#finance.
finance.js.erbcontains:

document.getElementById('trunc_article_<%= @article.id %>').remove();
document.getElementById('add_article_<%= @article.id %>').innerHTML = '<%= render("contenu") %>';
document.getElementById('add_link_<%= @article.id %>').innerHTML = '<%= link_to image_tag("partage.png", size: "20x20", class: "marge_ht"), article_finance_url(@article.id) %>';

finance.html.erbcontains:

<%= render 'article' %>

Running this locally works fine. On heroku, the server responds the right content, i.e. finance.js.erb correctly rendered with the inbedded templates, but also give a 304 response.


问:
Print multiple row outputs in csv file
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

</code>```

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

```<code>Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum
</code>```

Expected Output:

答:
You should be following this procedure:

First make a list of all columns, like this:

```<code>A = ['First', 'Random', 'Degree', 'Largest']
B = ['Second', 'Odd', 'Inclined', 'Maximum']
C = ['Third', 'Even', 'Steep', 'Smallest']
D = ['Fourth', 'Prime', 'Gradient', 'Minimum']
</code>```

And then

```<code>c = ['Group', 'Number', 'Angle', 'Max value']
df = pd.DataFrame([A, B, C, D], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)
</code>```

Output:

```<code>    Group  Number     Angle Max value
0   First  Random    Degree   Largest
1  Second     Odd  Inclined   Maximum
2   Third    Even     Steep  Smallest
3  Fourth   Prime  Gradient   Minimum
</code>```

Title: Print multiple row outputs in csv file

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum

Expected Output:

Body:
You should be following this procedure:

First make a list of all columns, like this:

A = ['First', 'Random', 'Degree', 'Largest']
B = ['Second', 'Odd', 'Inclined', 'Maximum']
C = ['Third', 'Even', 'Steep', 'Smallest']
D = ['Fourth', 'Prime', 'Gradient', 'Minimum']

And then

c = ['Group', 'Number', 'Angle', 'Max value']
df = pd.DataFrame([A, B, C, D], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Output:

    Group  Number     Angle Max value
0   First  Random    Degree   Largest
1  Second     Odd  Inclined   Maximum
2   Third    Even     Steep  Smallest
3  Fourth   Prime  Gradient   Minimum


问:
How to set $jQval.unobtrusive.options ErrorPlacement function correclty
What is the proper way to override the ErrorPlacement function in jquery.validate.unobtrusive?

Looking at the jquery.validate.unobtrusive.js script it appears that the developers intention would allow you to apply your own ErrorPlacement function by setting $jQval.unobtrusive.options.

In the validationInfo(form) function that defines the errorPlacement function we see a call to execInContext("errorPlacement", arguments).

It would seem that if we create a errorPlacement function under $.validator.unobtrusive.options then this will be called.

```<code>   $.validator.unobtrusive.options = {
        errorPlacement: function () {
            console.log("hello");
        }
    };
</code>```

The issue is that this must configured after jquery.validate.js and before jquery.validate.unobtrusive.js is referenced. Otherwise $jQval.unobtrusive.options is null and $form.data(data_validation, result) will not be set again.

```<code>    function validationInfo(form) {
    var $form = $(form),
        result = $form.data(data_validation),
        onResetProxy = $.proxy(onReset, form),
        defaultOptions = $jQval.unobtrusive.options || {},
        execInContext = function (name, args) {
            var func = defaultOptions[name];
            func && $.isFunction(func) && func.apply(form, args);
        }

    if (!result) {
        result = {
            options: {  // options structure passed to jQuery Validate's validate() method
                errorClass: defaultOptions.errorClass || "input-validation-error",
                errorElement: defaultOptions.errorElement || "span",
                errorPlacement: function () {
                    onError.apply(form, arguments);
                    execInContext("errorPlacement", arguments);
                },
                invalidHandler: function () {
                    onErrors.apply(form, arguments);
                    execInContext("invalidHandler", arguments);
                },
                messages: {},
                rules: {},
                success: function () {
                    onSuccess.apply(form, arguments);
                    execInContext("success", arguments);
                }
            },
            attachValidation: function () {
                $form
                    .off("reset." + data_validation, onResetProxy)
                    .on("reset." + data_validation, onResetProxy)
                    .validate(this.options);
            },
            validate: function () {  // a validation function that is called by unobtrusive Ajax
                $form.validate();
                return $form.valid();
            }
        };
        $form.data(data_validation, result);
    }

    return result;
}
</code>```

The other way to get deal with this is to

set the $.validator.unobtrusive.options error Placement Function

remove the Unobtrusive Validation

re apply the unobtrusive validation

```<code>$.validator.unobtrusive.options = {
    errorPlacement: function () {
        console.log("errorPlacement");
    }
};

$("#form_selector").removeData("unobtrusiveValidation");

// reapply the form's validator
$.validator.unobtrusive.parse(document);
</code>```

Or the other option would be to override the function call.

```<code>var validator = $("#form_selector").data('validator');
var originalFunction = validator.settings.errorPlacement;
validator.settings.errorPlacement = function(error,element) {
    console.log("errorPlacement");
    originalFunction(error, element);
};
</code>```

Which is the proper way of implementing your own errorPlacement method?

答:
Using Object.assign

After some experimentation i was able to get it working with the code below (loaded after everything). I Am using a bootstrap based theme so it wants has-error on the form-group container

```<code>Object.assign($.validator.unobtrusive,
    {
        options: {
            errorPlacement: function(error, element) {
                const container = $(element).closest(".form-group, .form-group-custom");
                if (container.length) {
                    container.addClass("has-error");
                }
            },
            success: function(error, element) {
                const container = $(element).closest(".form-group, .form-group-custom");
                if (container.length) {
                    container.removeClass("has-error");
                }
            }
        }
    });
</code>```

Body:
What is the proper way to override the ErrorPlacement function in jquery.validate.unobtrusive?

Looking at the jquery.validate.unobtrusive.js script it appears that the developers intention would allow you to apply your own ErrorPlacement function by setting $jQval.unobtrusive.options.

In the validationInfo(form) function that defines the errorPlacement function we see a call to execInContext("errorPlacement", arguments).

It would seem that if we create a errorPlacement function under $.validator.unobtrusive.options then this will be called.

   $.validator.unobtrusive.options = {
        errorPlacement: function () {
            console.log("hello");
        }
    };

The issue is that this must configured after jquery.validate.js and before jquery.validate.unobtrusive.js is referenced. Otherwise $jQval.unobtrusive.options is null and $form.data(data_validation, result) will not be set again.

    function validationInfo(form) {
    var $form = $(form),
        result = $form.data(data_validation),
        onResetProxy = $.proxy(onReset, form),
        defaultOptions = $jQval.unobtrusive.options || {},
        execInContext = function (name, args) {
            var func = defaultOptions[name];
            func && $.isFunction(func) && func.apply(form, args);
        }

    if (!result) {
        result = {
            options: {  // options structure passed to jQuery Validate's validate() method
                errorClass: defaultOptions.errorClass || "input-validation-error",
                errorElement: defaultOptions.errorElement || "span",
                errorPlacement: function () {
                    onError.apply(form, arguments);
                    execInContext("errorPlacement", arguments);
                },
                invalidHandler: function () {
                    onErrors.apply(form, arguments);
                    execInContext("invalidHandler", arguments);
                },
                messages: {},
                rules: {},
                success: function () {
                    onSuccess.apply(form, arguments);
                    execInContext("success", arguments);
                }
            },
            attachValidation: function () {
                $form
                    .off("reset." + data_validation, onResetProxy)
                    .on("reset." + data_validation, onResetProxy)
                    .validate(this.options);
            },
            validate: function () {  // a validation function that is called by unobtrusive Ajax
                $form.validate();
                return $form.valid();
            }
        };
        $form.data(data_validation, result);
    }

    return result;
}

The other way to get deal with this is to

set the $.validator.unobtrusive.options error Placement Function

remove the Unobtrusive Validation

re apply the unobtrusive validation

$.validator.unobtrusive.options = {
    errorPlacement: function () {
        console.log("errorPlacement");
    }
};

$("#form_selector").removeData("unobtrusiveValidation");

// reapply the form's validator
$.validator.unobtrusive.parse(document);

Or the other option would be to override the function call.

var validator = $("#form_selector").data('validator');
var originalFunction = validator.settings.errorPlacement;
validator.settings.errorPlacement = function(error,element) {
    console.log("errorPlacement");
    originalFunction(error, element);
};

Which is the proper way of implementing your own errorPlacement method?

Body:
Using Object.assign

After some experimentation i was able to get it working with the code below (loaded after everything). I Am using a bootstrap based theme so it wants has-error on the form-group container

Object.assign($.validator.unobtrusive,
    {
        options: {
            errorPlacement: function(error, element) {
                const container = $(element).closest(".form-group, .form-group-custom");
                if (container.length) {
                    container.addClass("has-error");
                }
            },
            success: function(error, element) {
                const container = $(element).closest(".form-group, .form-group-custom");
                if (container.length) {
                    container.removeClass("has-error");
                }
            }
        }
    });


问:
500 Error when setting up Swagger in asp .net CORE / MVC 6 app
I'm trying to setup a basic swagger API doc in a new asp .net CORE / MVC 6 project and receiving a 500 error from the swagger UI:
500 : http://localhost:4405/swagger/v1/swagger.json

My startup class has the following code in it:

```<code>using Swashbuckle.SwaggerGen;
using Swashbuckle.SwaggerGen.XmlComments;
using Swashbuckle.Application;
....
public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddSwaggerGen();
  services.ConfigureSwaggerDocument(options =>
  {
    options.SingleApiVersion(new Info
    {
        Version = "v1",
        Title = "Blog Test Api",
        Description = "A test API for this blogpost"
    });
  });
}
</code>```

and then under Configure:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
....
  app.UseSwaggerGen();
  app.UseSwaggerUi();
....
}
</code>```

When i build and run the project, the UI will come up when i go to swagger/UI/index.html, but the 500 error above is displayed. When i go to the swagger/v1/swagger.json link, console gives the following 500 error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Is there any way i can figure out the root cause of the 500 or enable any additional debug in swagger to figure out why it's throwing this error? Based on some of the tutorials i've looked at, only what i have in startup is required for a base implementation. Please let me know if i can provide any additional information.

EDIT: this is for rc1, and may not be relevant to the new netcore 1.0 currently out (6/29/2016)

答: For me the problem was due to OData. If I just commented out my services.AddOData(); I didn't get any error.just comment out the services.AddOData();</p>

Body:
I'm trying to setup a basic swagger API doc in a new asp .net CORE / MVC 6 project and receiving a 500 error from the swagger UI:
500 : http://localhost:4405/swagger/v1/swagger.json

My startup class has the following code in it:

using Swashbuckle.SwaggerGen;
using Swashbuckle.SwaggerGen.XmlComments;
using Swashbuckle.Application;
....
public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddSwaggerGen();
  services.ConfigureSwaggerDocument(options =>
  {
    options.SingleApiVersion(new Info
    {
        Version = "v1",
        Title = "Blog Test Api",
        Description = "A test API for this blogpost"
    });
  });
}

and then under Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
....
  app.UseSwaggerGen();
  app.UseSwaggerUi();
....
}

When i build and run the project, the UI will come up when i go to swagger/UI/index.html, but the 500 error above is displayed. When i go to the swagger/v1/swagger.json link, console gives the following 500 error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Is there any way i can figure out the root cause of the 500 or enable any additional debug in swagger to figure out why it's throwing this error? Based on some of the tutorials i've looked at, only what i have in startup is required for a base implementation. Please let me know if i can provide any additional information.

EDIT: this is for rc1, and may not be relevant to the new netcore 1.0 currently out (6/29/2016)


问:
Feature stops working when custom javascript is added
I am a JavaScript beginner and I am hoping someone here could help me solve this:

I've added this JavaScript to header using header and footers plugin:

```<code><script src="https://ajax.googleapis.com/…/li…/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".flip").click(function(){
    $(".panel").slideToggle("slow");
  });
});
</script>

<script>
$(document).ready(function(){
  $(".zavrit").click(function(){
    $(".panel").slideUp("slow");
  });
});
</script>
</code>```

I am targeting it to the sections with contact forms all over the page because my client wanted to reveal them on click.
(I am using a text editor to add the sections with shortcodes to the divs with custom classes)

The function is working just fine, but the problem is, the image carousel lightbox feature stopped working properly, as when you click on an image and want to slide to another, the arrows don't work. Also, you cant close the lightbox by clicking somewhere on the overlay.

I am really a beginner in the custom code so its possible that I just made some stupid mistake, can you help?

PAGE URL: http://test.sbweb.cz

When I remove the script the carousel works fine, is there any other option for the script maybe to just execute when the buttons are clicked?

答: I´ve finally found a solution to make elementor features work with the jquery script, I just had to delete the "src" part of the script, now everything work fine. Probably there was the same source from elementor somewhere in the code..</p>

Body:
I am a JavaScript beginner and I am hoping someone here could help me solve this:

I've added this JavaScript to header using header and footers plugin:

I am targeting it to the sections with contact forms all over the page because my client wanted to reveal them on click.
(I am using a text editor to add the sections with shortcodes to the divs with custom classes)

The function is working just fine, but the problem is, the image carousel lightbox feature stopped working properly, as when you click on an image and want to slide to another, the arrows don't work. Also, you cant close the lightbox by clicking somewhere on the overlay.

I am really a beginner in the custom code so its possible that I just made some stupid mistake, can you help?

PAGE URL: http://test.sbweb.cz

When I remove the script the carousel works fine, is there any other option for the script maybe to just execute when the buttons are clicked?


问:
Am I missing some important fact about interning symbols in LISP?
To be brief. Here is my several tries to intern and use a symbol in clisp.

```<code> [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL
</code>```

Why???

```<code> [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T
</code>```

Probably must be upcase.

```<code> [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:
</code>```

ok

```<code> [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

Interesting. Should I set it before.

```<code> [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?

答:
Your problem has nothing to do with interning.

The first problem is indeed causes by the fact that the reader will always uppercase the symbols, so you need to call (intern "FOO") in order to get the same result as 'foo.

The problem with EVAL is caused by the fact that LET introduces a lexical binding which is not visible inside EVAL. If you really want this to work you'd have to declare abc to be special, like so:

```<code>(let ((abc 2))
    (declare (special abc))
    (eval '(1+ abc)))
</code>```

A special declaration will cause the variable to have dynamic binding, instead of lexical binding (the latter means that the binding is limited to the local lexical context, i.e. within the LET form. With the special declaration the variable is available to anything that is called by from that form).

Note that the use of both special declarations and eval is something you should be very careful about and you should probably rethink your use of EVAL in the first place. It is very rare that you actually need to use it. In most cases you're actually looking for the use of lambda functions instead.

Body:
To be brief. Here is my several tries to intern and use a symbol in clisp.

 [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL

Why???

 [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T

Probably must be upcase.

 [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:

ok

 [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:

Interesting. Should I set it before.

 [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?

Body:
Your problem has nothing to do with interning.

The first problem is indeed causes by the fact that the reader will always uppercase the symbols, so you need to call (intern "FOO") in order to get the same result as 'foo.

The problem with EVAL is caused by the fact that LET introduces a lexical binding which is not visible inside EVAL. If you really want this to work you'd have to declare abc to be special, like so:

(let ((abc 2))
    (declare (special abc))
    (eval '(1+ abc)))

A special declaration will cause the variable to have dynamic binding, instead of lexical binding (the latter means that the binding is limited to the local lexical context, i.e. within the LET form. With the special declaration the variable is available to anything that is called by from that form).

Note that the use of both special declarations and eval is something you should be very careful about and you should probably rethink your use of EVAL in the first place. It is very rare that you actually need to use it. In most cases you're actually looking for the use of lambda functions instead.


问:
Angular update object in object array
Say i have the following object array, lets name it itemArray;

```<code>{
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}
</code>```

And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?

What i would like is something like the example below;

```<code>updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }
</code>```

or even better, replacing the entire object;

```<code>  updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }
</code>```

This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?

Template requested in comment:

```<code><tr *ngFor="let u of itemsArray.items; let i = index">
  <td>{{ u.id }}</td>
  <td>{{ u.name }}</td>
  <td>
    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
    <label for="singleCheckbox-{{i}}"></label>
  </td>
</tr>
</code>```

答:
In angular/typescript we can avoid mutation of the objects in the array.

An example using your item arr as a BehaviorSubject:

```<code>// you can initialize the items$ with the default array
this.items$ = new BehaviorSubject<any>([user1, user2, ...])

updateUser(user){
   this.myservice.getUpdate(user.id).subscribe(newitem => {

     // remove old item
     const items = this.items$.value.filter((item) => item.id !== newitem.id);

     // add a the newItem and broadcast a new table
     this.items$.next([...items, newItem])
   });
}
</code>```

And in the template you can subscribe on the items$

```<code><tr *ngFor="let u of items$ | async; let i = index">
   <td>{{ u.id }}</td>
   <td>{{ u.name }}</td>
   <td>
        <input type="checkbox" checked="u.accepted" (click)="updateUser(u)">
        <label for="singleCheckbox-{{i}}"></label>
   </td>
</tr>
</code>```

Title: Angular update object in object array

Body:
Say i have the following object array, lets name it itemArray;

{
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}

And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?

What i would like is something like the example below;

updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }

or even better, replacing the entire object;

  updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }

This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?

Template requested in comment:

  {{ u.id }}
  {{ u.name }}

    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">

Body:
In angular/typescript we can avoid mutation of the objects in the array.

An example using your item arr as a BehaviorSubject:

// you can initialize the items$ with the default array
this.items$ = new BehaviorSubject<any>([user1, user2, ...])

updateUser(user){
   this.myservice.getUpdate(user.id).subscribe(newitem => {

     // remove old item
     const items = this.items$.value.filter((item) => item.id !== newitem.id);

     // add a the newItem and broadcast a new table
     this.items$.next([...items, newItem])
   });
}

And in the template you can subscribe on the items$

<tr *ngFor="let u of items$ | async; let i = index">
   <td>{{ u.id }}</td>
   <td>{{ u.name }}</td>
   <td>
        <input type="checkbox" checked="u.accepted" (click)="updateUser(u)">
        <label for="singleCheckbox-{{i}}"></label>
   </td>
</tr>


问:
am getting undefined while trying execute following code
TypeError: Cannot read property 'bind' of undefined

getting this error, please help me.

Am trying to check and uncheck the checkbox when onchange event occures

please find the code here
https://codesandbox.io/s/competent-mendeleev-cd881

答: In render you should make sure declare as a function updated code</p>


问:
Keeping nested anchor fixed while using width hover transition of div in CSS
I am currently trying to achieve something when on hover, the background colour will change and animate as a "push" when the width changes from 0% to 100%. However, with my solution, setting the div to be 0% causes the anchor tag to not stay in a single line (breaks). How do I fix this?

Fiddle: https://jsfiddle.net/9hd3v84r/

* {
  padding: 0;
  margin: 0;
}

.navrectangle {
  width: 20Vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
}

/* NAV */

a {
  color: #fff;
  text-decoration: none;
  font-weight: 700;
}

img {
  padding-top: 8vh;
  width: 70%;
  margin: auto;
  display: block;
}

.textnav {
  padding-top: 6vh;
  display: block;
  list-style-type: none;
  font-size: 1.3vw;
}

.textnav a {
  margin-left: 3vw;
  width: 100%;
}

.textnav li {
  padding: 2vh 0vh;
  width: 100%;
}

.recpush {
  width: 0%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.recpush:hover {
  overflow: visible;
  background: #50d986;
  width: 110%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.textnav li:hover a {
  color: #002067;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navrectangle">
  <nav>
    <img src="media/Asset 1.png" alt="">
    <div class="textnav">
      <div class="recpush">
        <li>NUMBER ONE</li>
      </div>
      <div class="recpush">
        <li>NUMBER TWO</li>
      </div>
      <div class="recpush">
        <li>NUMBER 3</li>
      </div>
      <div class="recpush">
        <li>NUMBER 4</li>
      </div>
    </div>

  </nav>
</div></code>```

Thanks guys

答:
Try this:

CSS:

```<code>li a{
  white-space: nowrap;
}
</code>```

Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line.

DEMO HERE

Body:
I am currently trying to achieve something when on hover, the background colour will change and animate as a "push" when the width changes from 0% to 100%. However, with my solution, setting the div to be 0% causes the anchor tag to not stay in a single line (breaks). How do I fix this?

Fiddle: https://jsfiddle.net/9hd3v84r/

* {
  padding: 0;
  margin: 0;
}

.navrectangle {
  width: 20Vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
}

/* NAV */

a {
  color: #fff;
  text-decoration: none;
  font-weight: 700;
}

img {
  padding-top: 8vh;
  width: 70%;
  margin: auto;
  display: block;
}

.textnav {
  padding-top: 6vh;
  display: block;
  list-style-type: none;
  font-size: 1.3vw;
}

.textnav a {
  margin-left: 3vw;
  width: 100%;
}

.textnav li {
  padding: 2vh 0vh;
  width: 100%;
}

.recpush {
  width: 0%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.recpush:hover {
  overflow: visible;
  background: #50d986;
  width: 110%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.textnav li:hover a {
  color: #002067;
}

NUMBER ONE

NUMBER TWO

NUMBER 3

NUMBER 4

Thanks guys

Body:
Try this:

CSS:

li a{
  white-space: nowrap;
}

Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line.

DEMO HERE


问:
Cast a protocol to another protocol Swift
I am trying to work with protocols across Pods.
I have then simplified by problem here so I can ask a question on StackOverflow.

In my problem TestClass does not know anything about SecondProtocol (as it is in a separate pod).

```<code>public protocol FirstProtocol {
    func get(data: String) -> String
}

public protocol SecondProtocol {
    func get(data: String) -> String
}

class TestClass {
    func get(data: String) -> String {
        return "Rest data"
    }

    public init() { }
}

extension TestClass : FirstProtocol {}

let myTest : FirstProtocol?

myTest = TestClass() as FirstProtocol

let secondTest: SecondProtocol?

secondTest = myTest as! SecondProtocol
</code>```

So the last line causes a crash in Swift. In a sense, I understand why. However secondTest is instantiated from the main program rather than the Pod secondTest, so SecondTest knows nothing about SecondProtocol. Yet a second pod expects an input of Second Protocol.

So how can I get secondTest to cast to SecondProtocol?

答:
All you're missing is to make TestClass conform to SecondProtocol, just like you did for FirstProtocol:

```<code>extension TestClass : SecondProtocol {}
</code>```

You can specify protocol conformances for classes, structs, and enums that are defined in other modules, such as in Foundation or UIKit as well as in third party dependencies.

Body:
I am trying to work with protocols across Pods.
I have then simplified by problem here so I can ask a question on StackOverflow.

In my problem TestClass does not know anything about SecondProtocol (as it is in a separate pod).

public protocol FirstProtocol {
    func get(data: String) -> String
}

public protocol SecondProtocol {
    func get(data: String) -> String
}

class TestClass {
    func get(data: String) -> String {
        return "Rest data"
    }

    public init() { }
}

extension TestClass : FirstProtocol {}

let myTest : FirstProtocol?

myTest = TestClass() as FirstProtocol

let secondTest: SecondProtocol?

secondTest = myTest as! SecondProtocol

So the last line causes a crash in Swift. In a sense, I understand why. However secondTest is instantiated from the main program rather than the Pod secondTest, so SecondTest knows nothing about SecondProtocol. Yet a second pod expects an input of Second Protocol.

So how can I get secondTest to cast to SecondProtocol?

Body:
All you're missing is to make TestClass conform to SecondProtocol, just like you did for FirstProtocol:

extension TestClass : SecondProtocol {}

You can specify protocol conformances for classes, structs, and enums that are defined in other modules, such as in Foundation or UIKit as well as in third party dependencies.


问:
How To Create Table Easily From A Join Result on Tables with Same Column/Field Names
I am trying to do a join on 2 tables that have the same schema:

```<code>SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

This works ok, until I decide to modify the query to save it:

```<code>CREATE TABLE `tableName` SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

This gives an error saying that there are duplicate columns.

I have a primary key in both tables.

I found a solution by aliasing each column from each table like this:

```<code>CREATE TABLE `tableName` SELECT tl1.id AS L_id1, tl1.filepath AS L_filepath1, tl1.urlid AS L_urlid1, tl1.fieldname AS L_fieldname1, tl1.fieldvalue AS L_fieldvalue1, tl2.id AS L_id2, tl2.filepath AS L_filepath2, tl2.urlid AS L_urlid2, tl2.fieldname AS L_fieldname2, tl2.fieldvalue AS L_fieldvalue2 FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

However, this is tedious. What if there were 100+ columns in each table? Is there a way to make this work without having to manually aliasing each column name? I am looking for something that will make MySQL create a table with column names of the format "X.Y" where X is the original table name and Y is the original field name, but any other solutions would do as well.

P.S.: If it's not clear, when I used "*", I needed columns from both tables, not just one. They are two different tables with different data but with the same column names. (I can't change the names, by the way.)

答:
You can do something like this (I don't understand why you want to create a 3rd table where it seems you already have twice the same data): </p>

```<code>CREATE TABLE `tableName` SELECT tl1.* FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

Body:
I am trying to do a join on 2 tables that have the same schema:

SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

This works ok, until I decide to modify the query to save it:

CREATE TABLE `tableName` SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

This gives an error saying that there are duplicate columns.

I have a primary key in both tables.

I found a solution by aliasing each column from each table like this:

CREATE TABLE `tableName` SELECT tl1.id AS L_id1, tl1.filepath AS L_filepath1, tl1.urlid AS L_urlid1, tl1.fieldname AS L_fieldname1, tl1.fieldvalue AS L_fieldvalue1, tl2.id AS L_id2, tl2.filepath AS L_filepath2, tl2.urlid AS L_urlid2, tl2.fieldname AS L_fieldname2, tl2.fieldvalue AS L_fieldvalue2 FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

However, this is tedious. What if there were 100+ columns in each table? Is there a way to make this work without having to manually aliasing each column name? I am looking for something that will make MySQL create a table with column names of the format "X.Y" where X is the original table name and Y is the original field name, but any other solutions would do as well.

P.S.: If it's not clear, when I used "*", I needed columns from both tables, not just one. They are two different tables with different data but with the same column names. (I can't change the names, by the way.)

Body:
You can do something like this (I don't understand why you want to create a 3rd table where it seems you already have twice the same data):

CREATE TABLE `tableName` SELECT tl1.* FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid