问:
Error: Missing class properties transform
Error: Missing class properties transform

Test.js:

```<code>export class Test extends Component {
  constructor (props) {
    super(props)
  }

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }
</code>```

.babelrc:

```<code>{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["transform-class-properties"]
}
</code>```

package.json:

```<code>"babel-core": "^6.5.1",
"babel-eslint": "^4.1.8",
"babel-loader": "^6.2.2",
"babel-plugin-react-transform": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.5.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"babel-register": "^6.5.2",
</code>```

I have scoured the web and all fixes revolve around: Upgrading to babel6, switching the order of "stage-0" to be after "es2015". All of which I have done.

答: I had this error because I was using stage-3 instead of stage-0.

Body:
Error: Missing class properties transform

Test.js:

export class Test extends Component {
  constructor (props) {
    super(props)
  }

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

.babelrc:

{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["transform-class-properties"]
}

package.json:

"babel-core": "^6.5.1",
"babel-eslint": "^4.1.8",
"babel-loader": "^6.2.2",
"babel-plugin-react-transform": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.5.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"babel-register": "^6.5.2",

I have scoured the web and all fixes revolve around: Upgrading to babel6, switching the order of "stage-0" to be after "es2015". All of which I have done.


来源: stackexchange

问:
Show / Hide specific color ranges with PixelBender
What is the best way to hide specific (interpolated) color ranges? For example, I have a gradient that goes from blue > cyan > yellow > red. What I need is to hide blue > cyan, yellow > red but leave the cyan > yellow.

```<code>var rangeA:Object = {min:0x0000FF, max:0x00FFFF}  //hide
var rangeB:Object = {min:0x00FFFF, max:0xFFFF00}; //show
var rangeC:Object = {min:0xFFFF00, max:0xFF0000}; //hide
</code>```

It is ok to apply different filter for each range.

Any ideas?

答:
This is the simplest solution i've found:</p>

```<code>void
evaluatePixel()
{
    float4 color = sampleNearest(src,outCoord());

    float maxR = max(minColor.r, maxColor.r);
    float maxG = max(minColor.g, maxColor.g);
    float maxB = max(minColor.b, maxColor.b);

    float minR = min(minColor.r, maxColor.r);
    float minG = min(minColor.g, maxColor.g);
    float minB = min(minColor.b, maxColor.b);

     dst = color;

    // Check whether a color is within the range
    if(color.r >= minR && color.g >= minG && color.b >= minB)
    {
        if(color.r <= maxR && color.g <= maxG && color.b <= maxB)
        {
            dst = float4(0.0,0.0,0.0,0.0);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What is the best way to hide specific (interpolated) color ranges? For example, I have a gradient that goes from blue > cyan > yellow > red. What I need is to hide blue > cyan, yellow > red but leave the cyan > yellow.

var rangeA:Object = {min:0x0000FF, max:0x00FFFF}  //hide
var rangeB:Object = {min:0x00FFFF, max:0xFFFF00}; //show
var rangeC:Object = {min:0xFFFF00, max:0xFF0000}; //hide

It is ok to apply different filter for each range.

Any ideas?

Body:
This is the simplest solution i've found:

void
evaluatePixel()
{
    float4 color = sampleNearest(src,outCoord());

    float maxR = max(minColor.r, maxColor.r);
    float maxG = max(minColor.g, maxColor.g);
    float maxB = max(minColor.b, maxColor.b);

    float minR = min(minColor.r, maxColor.r);
    float minG = min(minColor.g, maxColor.g);
    float minB = min(minColor.b, maxColor.b);

     dst = color;

    // Check whether a color is within the range
    if(color.r >= minR && color.g >= minG && color.b >= minB)
    {
        if(color.r <= maxR && color.g <= maxG && color.b <= maxB)
        {
            dst = float4(0.0,0.0,0.0,0.0);
        }
    }
}


问:
ASP.NET MVC - Compound Model
I have a trivial web app with the following model:

```<code>public class SillyModel
{
    public SillyModel()
    { Id = Guid.NewGuid();  Children = new List<SillyModel>(); }
    [Key]
    public virtual Guid Id { get; set; }
    public virtual string Value { get; set; }
    public virtual List<SillyModel> Children { get; set; }
}
</code>```

}

I have an Edit View of:

```<code>@model WebApplication1.Models.SillyModel
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{

@Html.AntiForgeryToken()

@Html.Partial("EditPartial", Model)

<div class="form-horizontal">
    <h4>SillyModel</h4>
    <hr />
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}
</code>```

With the Partial:

```<code>@model WebApplication1.Models.SillyModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)

<div class="form-group">
    @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
    </div>
    @foreach (var item in Model.Children)
    {
        @Html.Partial("EditPartial", item)
    }
</div>
</code>```

The rendering is Fine!  But for the life of me (well at least 3 days of struggle) I can not get it so that the returned model is properly bound!  [No children are returned]

I am at my wits end.

答:
You have to re-structure the way you are coding a little

In the Views/YourController, add a folder called EditorTemplates if not yet exists and add a view named SillyModel and copy the code from EditPartial to this new view

You change the foreach to for loop to decorate the controls with index

The code

~/Views/YourController/EditorTemplates/SillyModel.cshtml

```<code>@model WebApplication1.Models.SillyModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)

<div class="form-group">
    @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
    </div>
    @for (var index=0; index<Model.Children.Count;index++)
    {
        @Html.EditorFor(model=>Model.Children[index])
    }
</div>
</code>```

~/Views/YourController/Edit

instead of @Html.Partial("EditPartial", Model), use @Html.EditorFor(m=>m)

Explanation

By adding the EditorTemplates/SillyModel , now you can call @Html.EditorFor(model=>Model.Children[index]) and your custom editor will be rendered

You need to use indexed controls in order Binding to the Model succeeded

Hope this will help you

ContentLicense: CC BY-SA 3.0

Title: ASP.NET MVC - Compound Model

Body:
I have a trivial web app with the following model:

public class SillyModel
{
    public SillyModel()
    { Id = Guid.NewGuid();  Children = new List<SillyModel>(); }
    [Key]
    public virtual Guid Id { get; set; }
    public virtual string Value { get; set; }
    public virtual List<SillyModel> Children { get; set; }
}

}

I have an Edit View of:

@model WebApplication1.Models.SillyModel
@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{

@Html.AntiForgeryToken()

@Html.Partial("EditPartial", Model)

SillyModel

            <input type="submit" value="Save" class="btn btn-default" />

}

With the Partial:

@model WebApplication1.Models.SillyModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)

    @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })

    @foreach (var item in Model.Children)
    {
        @Html.Partial("EditPartial", item)
    }

The rendering is Fine!  But for the life of me (well at least 3 days of struggle) I can not get it so that the returned model is properly bound!  [No children are returned]

I am at my wits end.

Body:
You have to re-structure the way you are coding a little

In the Views/YourController, add a folder called EditorTemplates if not yet exists and add a view named SillyModel and copy the code from EditPartial to this new view

You change the foreach to for loop to decorate the controls with index

The code

~/Views/YourController/EditorTemplates/SillyModel.cshtml

@model WebApplication1.Models.SillyModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)

<div class="form-group">
    @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
    </div>
    @for (var index=0; index<Model.Children.Count;index++)
    {
        @Html.EditorFor(model=>Model.Children[index])
    }
</div>

~/Views/YourController/Edit

instead of @Html.Partial("EditPartial", Model), use @Html.EditorFor(m=>m)

Explanation

By adding the EditorTemplates/SillyModel , now you can call @Html.EditorFor(model=>Model.Children[index]) and your custom editor will be rendered

You need to use indexed controls in order Binding to the Model succeeded

Hope this will help you


问:
IBM Notes: Eclipse Plugin deployment to framework directory
I am not totally sure, if this question is in the right forum here, but as it is about a development environment and deploying developments I think it is save to ask.

I have a plugin for the IBM Notes client that I need to install silently in the background.

I used "CustomizeAddon.exe" to create a package and created an install.addon.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>

<ibm-portal-composite>
    <domain-object name="com.ibm.rcp.installmanifest">
        <object-data>
            <install>
                <installfeature id="Jabber4Notes" required="true">
                    <requirements>
                        <feature id="com.endava.jabber4notes.feature"
                            version="2.11.8.298" match="compatible"
                            shared="true" mergeaction="add"
                            url="jar:${installer.root}/updateSite.zip!/" />
                        <feature id="com.endava.jabber4notes.IMPFragmentFeature"
                            version="2.11.8.298" match="compatible"
                            shared="true" mergeaction="add"
                            url="jar:${installer.root}/updateSite.zip!/" />
                    </requirements>
                </installfeature>
            </install>
        </object-data>
    </domain-object>
</ibm-portal-composite>
```

But although I use the parameter shared="true" the plugin always installs to the workspace directory instead of the feature- directory.

How can I change this behaviour?

答:
Make sure to have write permissions on the shared site.

If that's not the problem try to use colocation affinity to specify that the deployment site should be the same of another plugin; com.ibm.rcp.site.anchor.shared.feature is always installed on the shared site so you could add this:

```<code>colocation-affinity="com.ibm.rcp.site.anchor.shared.feature"
</code>```

Here you can find more information regarding this topic: LINK

Body:
I am not totally sure, if this question is in the right forum here, but as it is about a development environment and deploying developments I think it is save to ask.

I have a plugin for the IBM Notes client that I need to install silently in the background.

I used "CustomizeAddon.exe" to create a package and created an install.addon.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>

<ibm-portal-composite>
    <domain-object name="com.ibm.rcp.installmanifest">
        <object-data>
            <install>
                <installfeature id="Jabber4Notes" required="true">
                    <requirements>
                        <feature id="com.endava.jabber4notes.feature"
                            version="2.11.8.298" match="compatible"
                            shared="true" mergeaction="add"
                            url="jar:${installer.root}/updateSite.zip!/" />
                        <feature id="com.endava.jabber4notes.IMPFragmentFeature"
                            version="2.11.8.298" match="compatible"
                            shared="true" mergeaction="add"
                            url="jar:${installer.root}/updateSite.zip!/" />
                    </requirements>
                </installfeature>
            </install>
        </object-data>
    </domain-object>
</ibm-portal-composite>

But although I use the parameter shared="true" the plugin always installs to the workspace directory instead of the feature- directory.

How can I change this behaviour?

Body:
Make sure to have write permissions on the shared site.

If that's not the problem try to use colocation affinity to specify that the deployment site should be the same of another plugin; com.ibm.rcp.site.anchor.shared.feature is always installed on the shared site so you could add this:

colocation-affinity="com.ibm.rcp.site.anchor.shared.feature"

Here you can find more information regarding this topic: LINK


问:
Unable to resolve Private Hosted Zone in VPC
I’m having some trouble with Private Hosted Zones on AWS Route 53. I have two VPCs (staging and production) and I'd like to set up a private zone for each one under *.local.

What I have done is from the Route 53 console added a Private Hosted Zone for local. and added, as an example, a CNAME entry for docker.local to my hosted docker registry.

At this point, I would expect to be able to ssh into any ec2 instance inside that VPC and successfully dig docker.local. However, that's not the case and I continue to receive NXDOMAIN responses even a few hours after creating the zone. I’ve made sure to set the DNS options on the VPC as is instructed in a lot of places, but no luck. I feel like I’m possibly misunderstanding how this works as it seems too simple to mess up, but I'm out of ideas.

答: Problem is caused by a custom DHCP Options Set I didn't know we had. Using the default option set with AWS nameservers fixes the problem (as you would expect). </p>


问:
SKLabelNode Hit Test
When conducting a hit test on an ARSCNView containing SCNNodes with SCNText geometry, it appears that the hit test will only be successful if the point tested lies inside a letter in the SCNText. </p>

<p>This is not optimal, as it makes the nodes harder to tap. Is there a way to change the "hit box" so that the hit test will be successful if the tested point lies anywhere inside the bounds of the SCNNode? I am trying to avoid the case where the hit test is unsuccessful if the user's tap lies in-between two letters in the SCNText.  </p>

答:
I resolved my problem by setting the SCNHitTestOption.boundingBoxOnly option to true. This will conduct the hit test ignoring the node's geometry. </p>

```<code>let hitTestResults = sceneView.hitTest(tapPoint, options: [.boundingBoxOnly: true])
</code>```

Title: SKLabelNode Hit Test

Body:
When conducting a hit test on an ARSCNView containing SCNNodes with SCNText geometry, it appears that the hit test will only be successful if the point tested lies inside a letter in the SCNText.

This is not optimal, as it makes the nodes harder to tap. Is there a way to change the "hit box" so that the hit test will be successful if the tested point lies anywhere inside the bounds of the SCNNode? I am trying to avoid the case where the hit test is unsuccessful if the user's tap lies in-between two letters in the SCNText.

Body:
I resolved my problem by setting the SCNHitTestOption.boundingBoxOnly option to true. This will conduct the hit test ignoring the node's geometry.

let hitTestResults = sceneView.hitTest(tapPoint, options: [.boundingBoxOnly: true])


问:
Can I insert HTML script tag on consumer course with LTI (Learning Tools Interoperability)?
I would like to develop a plugin that would allow an instructor/course developer on the LMS side to insert a script tag on a course and/or quiz. This script tag has code that allows for identity verification and session proctoring.

The script tag looks like this:

```<code><script src="//integrityadvocate.com/Integrity/Embed?appid=APP_ID&participantidentifier=PARTICIPANT_IDENTIFIER&participantfirstname=PARTICIPANT_FIRST_NAME&participantlastname=PARTICIPANT_LAST_NAME" async></script>
</code>```

Is it possible to do this with LTI?

Also, would it be possible to build an LTI based plugin that would then return the resulting verification data back to the LMS in a way that it could be viewed with the participant results of the course/quiz?

答:
Despite LTI being a standard the exact workflow is very LMS specific, but it sounds like a use case for LTI Deep Linking.
https://www.imsglobal.org/specs/lticiv1p0

LTI Deep Linking allows the LMS (aka Tool Consumer) to send a launch to Your Plugin (aka Tool Provider) with information about the launching user i.e. Name, ID, Launching Context and a call back url.

Your plugin would then build the script tag with the provided information and then send it back to the LMS with the call back url.

Unfortunately its up to the specific LMS workflow to define where the launch point is and therefore where the script gets inserted (Quiz or Course Content or both). Most LMS's will allow you to launch from the WYSIWYG editor or Course Content editor which should meet your needs.

There are a number of ways to return results to the LMS, simplest would be an LTI Grade Book Item. A Gradebook item is  specific record per user, per resource and can only be a numeric grade. But you could return 1 or 0 for verified/not verified.
https://www.imsglobal.org/specs/ltiv1p1/implementation-guide#toc-6

The LTI apps.net tester is an easy way to test these workflows to see if they provide the information you need.
http://ltiapps.net/test/tc.php

There are things such as SCORM statistics and Learning Record stores. Which would allow more granularity in returning results. But these are normally extra integration's, not LMS specific features.

Body:
I would like to develop a plugin that would allow an instructor/course developer on the LMS side to insert a script tag on a course and/or quiz. This script tag has code that allows for identity verification and session proctoring.

The script tag looks like this:

Is it possible to do this with LTI?

Also, would it be possible to build an LTI based plugin that would then return the resulting verification data back to the LMS in a way that it could be viewed with the participant results of the course/quiz?


问:
Creating an Array with multiple arrays within the array
I was wondering how you create an array with multiple arrays inside as I already have the created arrays which you can see bellow in the code. But I want to put those array in side of an array called "Patients". while more so all the index of 1 in the following array Name, age, Etc can be seen under index 1 of Patients. Thank you

Public Class DataEntry

```<code>Dim Patients()

Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)
</code>```

答:
You'd be best making a patient class similar to the following

```<code>Public Class Patient
    Private _surName As String
    Private _firstName As String
    Private _age As Integer

    Property SurName() As String
        Get
            Return _surName
        End Get
        Set(ByVal Value As String)
            _surName = Value
        End Set
    End Property

    Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal Value As String)
            _firstName = Value
        End Set
    End Property

    Property Age() As String
        Get
            Return _age
        End Get
        Set(ByVal Value As Integer)
            If Value >= 0 Then
                _age = Value
            End If
        End Set
    End Property
End Class
</code>```

Then creating instances of that class

```<code>Dim p As Patient = New Patient()
p.FirstName = "john"
p.LastName = "Smith"
p.Age = 50

Dim p1 As Patient = New Patient()
p.FirstName = "james"
p.LastName = "bond"
p.Age = 47

'etc
</code>```

and then adding the patients to a list or array:

```<code>Dim patients As List(Of Patient) = New List(Of Patient)
patients.Add(p)
patients.Add(p1)
</code>```

Body:
I was wondering how you create an array with multiple arrays inside as I already have the created arrays which you can see bellow in the code. But I want to put those array in side of an array called "Patients". while more so all the index of 1 in the following array Name, age, Etc can be seen under index 1 of Patients. Thank you

Public Class DataEntry

Dim Patients()

Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)

Body:
You'd be best making a patient class similar to the following

Public Class Patient
    Private _surName As String
    Private _firstName As String
    Private _age As Integer

    Property SurName() As String
        Get
            Return _surName
        End Get
        Set(ByVal Value As String)
            _surName = Value
        End Set
    End Property

    Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal Value As String)
            _firstName = Value
        End Set
    End Property

    Property Age() As String
        Get
            Return _age
        End Get
        Set(ByVal Value As Integer)
            If Value >= 0 Then
                _age = Value
            End If
        End Set
    End Property
End Class

Then creating instances of that class

Dim p As Patient = New Patient()
p.FirstName = "john"
p.LastName = "Smith"
p.Age = 50

Dim p1 As Patient = New Patient()
p.FirstName = "james"
p.LastName = "bond"
p.Age = 47

'etc

and then adding the patients to a list or array:

Dim patients As List(Of Patient) = New List(Of Patient)
patients.Add(p)
patients.Add(p1)


问:
Elegant solution to remove trailing 0's with precision set
Is there any elegant solution using the std C++ or Boost libraries to output a double to std::cout in a way that the following conditions are met:

scientific notation is disabled

the precision for the decimal part is 6

however, trailing 0's (for the decimal part) are not printed out

For example:

```<code>double d = 200000779998;
std::cout << `[something]` << d;
</code>```

should print out exactly 200000779998. [something] should possibly be a noexcept combination of some existing manipulators.

This is not a solution to the problem:

```<code>std::cout << std::setprecision(6) << std::fixed << d;
</code>```

because it prints out 200000779998.000000 with trailing 0's

答:
Instead of using the fixed manipulator, you can try to use (abuse?) defaultfloat. As far as I understand, it chooses either fixed or scientific based on the ability to put the number within the specified precision. As a result you can set the precision to the number of digits of the integral part + the requested fractional precision (6 in your case).

double d = 200000779998;
std::cout << std::setprecision(integralDigits(d) + 6) << d << std::endl;
```

You can try it here.

Body:
Is there any elegant solution using the std C++ or Boost libraries to output a double to std::cout in a way that the following conditions are met:

scientific notation is disabled

the precision for the decimal part is 6

however, trailing 0's (for the decimal part) are not printed out

For example:

double d = 200000779998;
std::cout << `[something]` << d;

should print out exactly 200000779998. [something] should possibly be a noexcept combination of some existing manipulators.

This is not a solution to the problem:

std::cout << std::setprecision(6) << std::fixed << d;

because it prints out 200000779998.000000 with trailing 0's

Body:
Instead of using the fixed manipulator, you can try to use (abuse?) defaultfloat. As far as I understand, it chooses either fixed or scientific based on the ability to put the number within the specified precision. As a result you can set the precision to the number of digits of the integral part + the requested fractional precision (6 in your case).

double d = 200000779998;
std::cout << std::setprecision(integralDigits(d) + 6) << d << std::endl;

You can try it here.


问:
Benefit of using Node JS in existing application
I'm new in Node JS and I got a question for you.

What benefit is it to use node JS when you have a existing application?

The existing application is asp.net mvc with bootstrap and jquery in frontend.

Thank you!

答:
Node.js is a programming environment on its own.  If you already have a working app in another programming environment, you would generally not use node.js for that project unless you needed to run some third party code that only runs in node.js and you needed to somehow incorporate that into your existing app.

To do that, you'd probably create a separate app using node.js that used the desired node.js library and then communicate between that new app and your main app using TCP networking of some form (e.g. http, webSockets, etc...).  As an example, let's say you needed to do some image recognition in some photos and the image recognition library you wanted to use only ran in node.js (and, for whatever reason, you weren't going to use a different library that ran in your existing asp.net).  Then, you'd create a new app that could do the image recognition portion and you'd figure out how to communicate between the node.js app and the main asp.net application.

Otherwise, if you already have an existing app and aren't contemplating throwing  it away and switching to another programming environment, then you probably wouldn't use node.js for that project.

When starting a brand new project, you could more thoroughly consider the needs of the new project and evaluate that against several different programming environments (including node.js) to see which might be the best match for you to use.

For lots of general reasons to use node.js for a new project see this:

How to decide when to use Node.js?

FYI, your question about when to use node.js in an existing asp.net project is probably fairly similar to when to incorporate Python or Ruby or Perl or PHP into an ASP.NET project.  The answer is when you find you have some already done code that runs only in some other environment and you want to use that existing code without rewriting it to fit your current environment.


问:
Display: inline-block for a list
I want to create a list that should look like this

```<code>Few Clouds
Humidity: 33%
Wind: 5.1 mph
</code>```

However, because I'm using JS to insert
 elements , I have to pre-write some parts of the list like this (excluding the [JS] part):

```<code>[JS]
Humidity: [JS]%
Wind: [JS] mph
</code>```

Here's my code to solve this:

```<code><ul class="list-unstyled">
    <li class="clouds text-capitalize inline"> </li>
    <span class="inline">Humidity: </span><li class="wind inline"> </li><span class="inline">%</span>
    <span class="inline">Wind: </span><li class="humidity inline"> </li><span class="inline">mph</span>
 </ul>
</code>```

and

```<code>.inline{
   display: inline-block;
}
</code>```

but this results in (after the javascript plugs in data)

```<code>Few Clouds Humidity: 5.82 % Wind: 100mph
</code>```

which is expected, but I dont know how to fix it so it looks like how I wanted in the first snippet. Ignore the other classes, they're bootstrap classes and classes for me to access them in javascript. Thank you for any help.

答:
You don't need the inline class with the html span tags. Just add an additional li element for every line.

.list-unstyled {
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="list-unstyled">
 <li class="clouds text-capitalize">Few Clouds</li>
 <li>Humidity: <span class="wind">5.82</span>%</li>
 <li>Wind: <span class="humidity">100 </span>mph</li>
 </ul></code>```

View On Plunker

Title: Display: inline-block for a list

Body:
I want to create a list that should look like this

Few Clouds
Humidity: 33%
Wind: 5.1 mph

However, because I'm using JS to insert
 elements , I have to pre-write some parts of the list like this (excluding the [JS] part):

[JS]
Humidity: [JS]%
Wind: [JS] mph

Here's my code to solve this:

    Humidity:

%
    Wind:

mph

and

.inline{
   display: inline-block;
}

but this results in (after the javascript plugs in data)

Few Clouds Humidity: 5.82 % Wind: 100mph

which is expected, but I dont know how to fix it so it looks like how I wanted in the first snippet. Ignore the other classes, they're bootstrap classes and classes for me to access them in javascript. Thank you for any help.

Body:
You don't need the inline class with the html span tags. Just add an additional li element for every line.

.list-unstyled {
  list-style: none;
}

<ul class="list-unstyled">
 <li class="clouds text-capitalize">Few Clouds</li>
 <li>Humidity: <span class="wind">5.82</span>%</li>
 <li>Wind: <span class="humidity">100 </span>mph</li>
 </ul>

View On Plunker


问:
how to customize an element-wise function on tensor in tensorflow?
Say, I have a tensor, it might contain positive and negative values:

```<code>[ 1, -1, 2, -2 ]
</code>```

Now, I want to apply log(x) for positive values, and a constant -10 for negative values:

```<code>[ log(1), -10, log(2), -10 ]
</code>```

In another word, I want to have a function like numpy.vectorize. Is this possible in tensorflow?

One possible way is to use a non-learnable variable, but I don't know if it can properly do back propagation.

答: I found it, the tf.where does exactly this kind of job: https://www.tensorflow.org/api_docs/python/tf/where

Body:
Say, I have a tensor, it might contain positive and negative values:

[ 1, -1, 2, -2 ]

Now, I want to apply log(x) for positive values, and a constant -10 for negative values:

[ log(1), -10, log(2), -10 ]

In another word, I want to have a function like numpy.vectorize. Is this possible in tensorflow?

One possible way is to use a non-learnable variable, but I don't know if it can properly do back propagation.


问:
Access to a single pixel in C#
I'm working on a school project right now. It's meant to be a 3D editing software, (like a very minimized version of Maya). I have to write it in C#, using the 'Windows Application Project'.
I intend to implement all the 3D stuff myself, from projections to shading.
My question is, how can I get direct access to a single pixel in the C# windows application?
I know I'm going to have a main view port in the window. But I haven't decided yet how it will be made. Is there a built in object that I can use, that will let me define the boundaries of the view port, and then paint each pixel individually?
(I'm just shooting in the dark here, I don't know much about C#. I mostly program in C)

Thanks,
Malki.

答: If you have a need for pixel speed, high-speed-graphing-control-for-net-or-mfc, may provide some tips.</p>

OwnerDisplayName: Malki

Title: Access to a single pixel in C#

OwnerDisplayName: gimel


问:
which size of chunk will yield to best performance using master-worker with MPI?
Im using MPI to parrlel a program that is trying to solve the Metric TSP problem. I have P processors , and N cities to pass .

Each thread asks for work from the master, recieves a chunk - which is a range of permutation that he should check and calculates the minimal among them. I am optimizing this by pruning bad routes in advance.

There are total (N-1)! routes to calculate. each worker get a chunk with a number that represnt the first route he has to check and the also the last. In addition the master sends him the most recent best result known , so can easly prone bad routes in advance with some lower bound on thier remains.

Each time a worker is finding result that is better that the global , he asyncrounsly sends it to the all other workers and to the master.

Im not looking for better solution- I'm just trying to determine which chunk size is the best.

The best chunk size i've found so far is  (n!)/(n/2)!  , but it doesnt yield so good result .

please help me understand which chunk size is the best here. I'm trying to balance between the amount of computation and communication
thanks

答:
This depends heavily on factors beyond your control: MPI implementation, total load on the machine, etc. However, I'd hazard a guess that it also heavily depends on how many worker processes there are. On that note, understand that MPI spawns processes, not threads.

Ultimately, as is often the case with most optimization questions, the answer is simply "test a lot of different settings and see which one is best". You may want to do this manually, or write a tester app that implements some sort of heuristic (e.g. a genetic algorithm).


问:
TypeScript: remove key from type/subtraction type
I want to define a generic type ExcludeCart<T> that is essentially T but with a given key (in my case, cart) removed. So, for instance, ExcludeCart<{foo: number, bar: string, cart: number}> would be {foo: number, bar: string}. Is there a way to do this in TypeScript?

Here's why I want to do this, in case I'm barking up the wrong tree: I'm converting an existing JavaScript codebase to TypeScript, which contains a decorator function called cartify that takes a React component class Inner and returns another component class Wrapper.

Inner should take a cart prop, and zero or more other props. Wrapper accepts a cartClient prop (which is used to generate the cart prop to pass to Inner), and any prop that Inner accepts, except cart.

In other words, once I can figure out how to define ExcludeCart, I want to do this with it:

```<code>function cartify<P extends {cart: any}>(Inner: ComponentClass<P>) : ComponentClass<ExcludeCart<P> & {cartClient: any}>
</code>```

答:
While there isn't a built-in subtraction type, you can currently hack it in:

```<code>type Sub0<
    O extends string,
    D extends string,
> = {[K in O]: (Record<D, never> & Record<string, K>)[K]}

type Sub<
    O extends string,
    D extends string,
    // issue 16018
    Foo extends Sub0<O, D> = Sub0<O, D>
> = Foo[O]

type Omit<
    O,
    D extends string,
    // issue 16018
    Foo extends Sub0<keyof O, D> = Sub0<keyof O, D>
> = Pick<O, Foo[keyof O]>
</code>```

In the question's case, you would do:

```<code>type ExcludeCart<T> = Omit<T, 'cart'>
</code>```

With TypeScript >= 2.6, you can simplify it to:

```<code>/**
 * for literal unions
 * @example Sub<'Y' | 'X', 'X'> // === 'Y'
 */
export type Sub<
    O extends string,
    D extends string
    > = {[K in O]: (Record<D, never> & Record<string, K>)[K]}[O]

/**
 * Remove the keys represented by the string union type D from the object type O.
 *
 * @example Omit<{a: number, b: string}, 'a'> // === {b: string}
 * @example Omit<{a: number, b: string}, keyof {a: number}> // === {b: string}
 */
export type Omit<O, D extends string> = Pick<O, Sub<keyof O, D>>
</code>```

test it on the playground

Body:
I want to define a generic type ExcludeCart<T> that is essentially T but with a given key (in my case, cart) removed. So, for instance, ExcludeCart<{foo: number, bar: string, cart: number}> would be {foo: number, bar: string}. Is there a way to do this in TypeScript?

Here's why I want to do this, in case I'm barking up the wrong tree: I'm converting an existing JavaScript codebase to TypeScript, which contains a decorator function called cartify that takes a React component class Inner and returns another component class Wrapper.

Inner should take a cart prop, and zero or more other props. Wrapper accepts a cartClient prop (which is used to generate the cart prop to pass to Inner), and any prop that Inner accepts, except cart.

In other words, once I can figure out how to define ExcludeCart, I want to do this with it:

function cartify
(Inner: ComponentClass
) : ComponentClass<ExcludeCart
 & {cartClient: any}>

Body:
While there isn't a built-in subtraction type, you can currently hack it in:

type Sub0<
    O extends string,
    D extends string,
> = {[K in O]: (Record<D, never> & Record<string, K>)[K]}

type Sub<
    O extends string,
    D extends string,
    // issue 16018
    Foo extends Sub0<O, D> = Sub0<O, D>
> = Foo[O]

type Omit<
    O,
    D extends string,
    // issue 16018
    Foo extends Sub0<keyof O, D> = Sub0<keyof O, D>
> = Pick<O, Foo[keyof O]>

In the question's case, you would do:

type ExcludeCart<T> = Omit<T, 'cart'>

With TypeScript >= 2.6, you can simplify it to:

/**
 * for literal unions
 * @example Sub<'Y' | 'X', 'X'> // === 'Y'
 */
export type Sub<
    O extends string,
    D extends string
    > = {[K in O]: (Record<D, never> & Record<string, K>)[K]}[O]

/**
 * Remove the keys represented by the string union type D from the object type O.
 *
 * @example Omit<{a: number, b: string}, 'a'> // === {b: string}
 * @example Omit<{a: number, b: string}, keyof {a: number}> // === {b: string}
 */
export type Omit<O, D extends string> = Pick<O, Sub<keyof O, D>>

<a href="https://www.typescriptlang.org/play/#src=%2F**%0D%0A%20*%20for%20literal%20unions%0D%0A%20*%20%40example%20Sub%3C'Y'%20%7C%20'X'%2C%20'X'%3E%20%2F%2F%20%3D%3D%3D%20'Y'%0D%0A%20*%2F%0D%0Aexport%20type%20Sub%3C%0D%0A%20%20%20%20O%20extends%20string%2C%0D%0A%20%20%20%20D%20extends%20string%0D%0A%20%20%20%20%3E%20%3D%20%7B%5BK%20in%20O%5D%3A%20(Record%3CD%2C%20never%3E%20%26%20Record%3Cstring%2C%20K%3E)%5BK%5D%7D%5BO%5D%0D%0A%0D%0Atype%20A%20%3D%20Sub%3C'Y'%20%7C%20'X'%2C%20'X'%3E%0D%0A%0D%0A%2F**%0D%0A%20*%20Remove%20the%20keys%20represented%20by%20the%20string%20union%20type%20D%20from%20the%20object%20type%20O.%0D%0A%20*%0D%0A%20*%20%40example%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20'a'%3E%20%2F%2F%20%3D%3D%3D%20%7Bb%3A%20string%7D%0D%0A%20*%20%40example%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20keyof%20%7Ba%3A%20number%7D%3E%20%2F%2F%20%3D%3D%3D%20%7Bb%3A%20string%7D%0D%0A%20*%2F%0D%0Aexport%20type%20Omit%3CO%2C%20D%20extends%20string%3E%20%3D%20Pick%3CO%2C%20Sub%3Ckeyof%20O%2C%20D%3E%3E%0D%0A%0D%0Atype%20X%20%3D%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20keyof%20%7Ba%3A%20number%7D%3E" rel="noreferrer">test it on the playground


问:
angular-cli server - how to proxy API requests to another server?
With the angular-cli ng serve local dev server, it's serving all the static files from my project directory.

How can I proxy my AJAX calls to a different server?

答:
I'll explain what you need to know on the example below:

```<code>{
  "/folder/sub-folder/*": {
    "target": "http://localhost:1100",
    "secure": false,
    "pathRewrite": {
      "^/folder/sub-folder/": "/new-folder/"
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
</code>```

/folder/sub-folder/*: path says: When I see this path inside my angular app (the path can be stored anywhere) I want to do something with it. The * character indicates that everything that follows the sub-folder will be included. For instance, if you have multiple fonts inside /folder/sub-folder/, the * will pick up all of them

"target": "http://localhost:1100" for the path above make target  URL the host/source, therefore in the background we will have http://localhost:1100/folder/sub-folder/

"pathRewrite": {
"^/folder/sub-folder/": "/new-folder/"
},
Now let's say that you want to test your app locally, the url http://localhost:1100/folder/sub-folder/ may contain an invalid path: /folder/sub-folder/. You want to change that path to a correct one which is http://localhost:1100/new-folder/, therefore the pathRewrite will become useful. It will exclude the path in the app(left side) and include the newly written one (right side)

"secure": represents wether we are using http or https. If https is used in the target attribute then set secure attribute to true otherwise set it to false

"changeOrigin": option is only necessary if your host target is not the current environment, for example: localhost. If you want to change the host to www.something.com which would be the target in the proxy then set the changeOrigin attribute to "true":

"logLevel": attribute specifies wether the developer wants to display proxying on his terminal/cmd, hence he would use the "debug" value as shown in the image

In general, the proxy helps in developing the application locally. You set your file paths for production purpose and if you have all these files locally inside your project you may just use proxy to access them without changing the path dynamically in your app.

If it works, you should see something like this in your cmd/terminal.

Body:
I'll explain what you need to know on the example below:

{
  "/folder/sub-folder/*": {
    "target": "http://localhost:1100",
    "secure": false,
    "pathRewrite": {
      "^/folder/sub-folder/": "/new-folder/"
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

/folder/sub-folder/*: path says: When I see this path inside my angular app (the path can be stored anywhere) I want to do something with it. The * character indicates that everything that follows the sub-folder will be included. For instance, if you have multiple fonts inside /folder/sub-folder/, the * will pick up all of them

"target": "http://localhost:1100" for the path above make target  URL the host/source, therefore in the background we will have http://localhost:1100/folder/sub-folder/

"pathRewrite": {
"^/folder/sub-folder/": "/new-folder/"
},
Now let's say that you want to test your app locally, the url http://localhost:1100/folder/sub-folder/ may contain an invalid path: /folder/sub-folder/. You want to change that path to a correct one which is http://localhost:1100/new-folder/, therefore the pathRewrite will become useful. It will exclude the path in the app(left side) and include the newly written one (right side)

"secure": represents wether we are using http or https. If https is used in the target attribute then set secure attribute to true otherwise set it to false

"changeOrigin": option is only necessary if your host target is not the current environment, for example: localhost. If you want to change the host to www.something.com which would be the target in the proxy then set the changeOrigin attribute to "true":

"logLevel": attribute specifies wether the developer wants to display proxying on his terminal/cmd, hence he would use the "debug" value as shown in the image

In general, the proxy helps in developing the application locally. You set your file paths for production purpose and if you have all these files locally inside your project you may just use proxy to access them without changing the path dynamically in your app.

If it works, you should see something like this in your cmd/terminal.

ContentLicense: CC BY-SA 4.0


问:
Master Worksheet Populate Rows on New Worksheet based on Picklist Field Value (Data Validation)
I currently have a 'Master' worksheet with the following columns (reduced for simplicity)

A - Data Type

B - Name

C - Object

The Data Type field has a Data Validation set so there can only be 10 associated values entered. There are 10 corresponding 'tabs' in my Excel workbook that are named according to these picklist values (so I have 11 total tabs, including the Master).

I want the workbook set up so that when a row is entered by a user in the Master worksheet, the information is also populated on one of the 10 worksheets, based on the corresponding Data Type value selected. For these non-master tabs, the data needs to fill the highest non-populated row on the sheet.  (E.g. If I have 50 rows on the Master, with 4 being Data Type'Custom Field', and I want to add a 51st row which has a Data Type of 'Custom Field', I want it to populate the 5th line on the 'Custom Field' tab, not the 51st line.)

Does anyone know if this is possible to setup? Thank you so much in advance for your help.

答:
Something along the lines of this would do it, (this would work well with a button):</p>

```<code>Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 'Check how many rows of data on Sheet1
For i = 1 To LastRow 'loop from first to last row of Sheet1
    SheetName = Sheet1.Cells(i, 1).Value 'Check the first cell for the name of the Sheet it ought to be copied to
    LastRow2 = Sheets(SheetName).Cells(Sheets(SheetName).Rows.Count, "A").End(xlUp).Row + 1 'Check the last row of data on the sheet to be copied into and add one for the next free row
    Sheets(SheetName).Cells(LastRow2, 1).Value = Sheet1.Cells(i, 1).Value ' copy values from Sheet1
    Sheets(SheetName).Cells(LastRow2, 2).Value = Sheet1.Cells(i, 2).Value
    Sheets(SheetName).Cells(LastRow2, 3).Value = Sheet1.Cells(i, 3).Value
Next i
End Sub
</code>```

Body:
Something along the lines of this would do it, (this would work well with a button):

Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 'Check how many rows of data on Sheet1
For i = 1 To LastRow 'loop from first to last row of Sheet1
    SheetName = Sheet1.Cells(i, 1).Value 'Check the first cell for the name of the Sheet it ought to be copied to
    LastRow2 = Sheets(SheetName).Cells(Sheets(SheetName).Rows.Count, "A").End(xlUp).Row + 1 'Check the last row of data on the sheet to be copied into and add one for the next free row
    Sheets(SheetName).Cells(LastRow2, 1).Value = Sheet1.Cells(i, 1).Value ' copy values from Sheet1
    Sheets(SheetName).Cells(LastRow2, 2).Value = Sheet1.Cells(i, 2).Value
    Sheets(SheetName).Cells(LastRow2, 3).Value = Sheet1.Cells(i, 3).Value
Next i
End Sub


问:
Django template can't loop defaultdict
```<code>import collections

data = [
  {'firstname': 'John', 'lastname': 'Smith'},
  {'firstname': 'Samantha', 'lastname': 'Smith'},
  {'firstname': 'shawn', 'lastname': 'Spencer'},
]

new_data = collections.defaultdict(list)

for d in data:
    new_data[d['lastname']].append(d['firstname'])

print new_data
</code>```

Here's the output:

```<code>defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})
</code>```

and here's the template:

```<code>{% for lastname, firstname in data.items %}
  <h1> {{ lastname }} </h1>
  <p> {{ firstname|join:", " }} </p>
{% endfor %}
</code>```

But the loop in my template doesn't work. Nothing shows up. It doesn't even give me an error. How can i fix this? It's supposed to show the lastname along with the firstname, something like this:

```<code><h1> Smith </h1>
<p> John, Samantha </p>

<h1> Spencer </h1>
<p> shawn </p>
</code>```

答:
try:

```<code>dict(new_data)
</code>```

and in Python 2 it is better to use iteritems instead of items :)

Title: Django template can't loop defaultdict

Body:
import collections

data = [
  {'firstname': 'John', 'lastname': 'Smith'},
  {'firstname': 'Samantha', 'lastname': 'Smith'},
  {'firstname': 'shawn', 'lastname': 'Spencer'},
]

new_data = collections.defaultdict(list)

for d in data:
    new_data[d['lastname']].append(d['firstname'])

print new_data

Here's the output:

defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})

and here's the template:

{% for lastname, firstname in data.items %}

 {{ lastname }}

 {{ firstname|join:", " }}

{% endfor %}

But the loop in my template doesn't work. Nothing shows up. It doesn't even give me an error. How can i fix this? It's supposed to show the lastname along with the firstname, something like this:

 Smith

 John, Samantha

 Spencer

 shawn

Body:
try:

dict(new_data)

and in Python 2 it is better to use iteritems instead of items :)


问:
WHERE inside CASE statement
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

```<code>Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....
</code>```

What I want to do is something like this.

```<code>-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END
</code>```

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

答:
You can try this:</p>

```<code>CASE WHEN (SELECT MAX(ID) FROM Status_table) = 3
    THEN 3
    ELSE (SELECT MAX(ID)+1 FROM Status_table) --Invalid value that will not exist
END <> Item_Table.Status
</code>```

Title: WHERE inside CASE statement

Body:
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....

What I want to do is something like this.

-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

Body:
You can try this:

CASE WHEN (SELECT MAX(ID) FROM Status_table) = 3
    THEN 3
    ELSE (SELECT MAX(ID)+1 FROM Status_table) --Invalid value that will not exist
END <> Item_Table.Status


问:
Go http redirection securely
I know that in a PHP web app if you redirect using header('Location: http://somewhere.com') but you don't die() / exit(), the code after the header function is always executed and displayed. I would like to know if when using http.Redirect(w, r, "/somewhere", 302) in Go happens the same. And if yes how could avoid it.</p>

答:
The http.Redirect function writes a complete response. The program continues to execute after the call to http.Redirect. If the call to http.Redirect is not the last line of the function, then it is typical for applications to return from the handler immediately after the call.</p>

```<code>func serveFoo(w http.ResponseWriter, r *http.Request) {
   ...
      http.Redirect(w, r, "/somewhere", 302)
      return
   ...

}
</code>```

Title: Go http redirection securely

Body:
The http.Redirect function writes a complete response. The program continues to execute after the call to http.Redirect. If the call to http.Redirect is not the last line of the function, then it is typical for applications to return from the handler immediately after the call.

func serveFoo(w http.ResponseWriter, r *http.Request) {
   ...
      http.Redirect(w, r, "/somewhere", 302)
      return
   ...

}


问:
how to correctly accommodate the values?
I would like how to put the second result of the second query. the value is shows under row and I want that value is in front of the first result query.

The result should be shown where it is marked in red

```<code>$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
    $bandera=0;
    echo "<tr style=''>";
    echo '<td>'.utf8_encode($fila["factura"]).'</td>';
    echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
    echo '<td></td>';
    echo '<td></td>';
    echo '</tr>';

    //
    $id_documento=$fila["id_documento"];
    $reporte->set('id_documento',$id_documento);
    $reporte->contador();
    $contador=$reporte->get('contador');

    $id_documento=$fila["id_documento"];
    $reporte2->set('id_documento',$id_documento);
    $resultadosmov = $reporte2->movimientos();
    while($fila2 = mysqli_fetch_array($resultadosmov))
    {

        echo'<tr>';
        echo '<td></td>';
        echo '<td></td>';
        echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
        echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
        echo '</tr>';
    }

}
echo '</table>';
echo "</td></tr></table>";
</code>```

答:
Echo all the columns when processing the second query.

```<code>$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
    $bandera=0;
    //
    $id_documento=$fila["id_documento"];
    $reporte->set('id_documento',$id_documento);
    $reporte->contador();
    $contador=$reporte->get('contador');

    $id_documento=$fila["id_documento"];
    $reporte2->set('id_documento',$id_documento);
    $resultadosmov = $reporte2->movimientos();
    if ($resultadosmov->num_rows > 0) {
        while($fila2 = mysqli_fetch_array($resultadosmov))
        {
            echo "<tr>";
            echo '<td>'.utf8_encode($fila["factura"]).'</td>';
            echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
            echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
            echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
            echo '</tr>';
            // Make 1st two columns blank in additional rows
            $fila["factura"] = "";
            $file["rfc_emisor"] = "";
        }
    } else {
        echo "<tr style=''>";
        echo '<td>'.utf8_encode($fila["factura"]).'</td>';
        echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
        echo '<td></td>';
        echo '<td></td>';
        echo '</tr>';
    }
}
</code>```

BTW, what is the $bandera variable for? It's set but never used.

It would probably be even better if you could join the two queries, instead of doing queries in a loop.

Body:
I would like how to put the second result of the second query. the value is shows under row and I want that value is in front of the first result query.

The result should be shown where it is marked in red

$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
    $bandera=0;
    echo "
";
    echo ''.utf8_encode($fila["factura"]).'	';
    echo ''.utf8_encode($fila["rfc_emisor"]).'	';
    echo '	';
    echo '	';
    echo '
';

    //
    $id_documento=$fila["id_documento"];
    $reporte->set('id_documento',$id_documento);
    $reporte->contador();
    $contador=$reporte->get('contador');

    $id_documento=$fila["id_documento"];
    $reporte2->set('id_documento',$id_documento);
    $resultadosmov = $reporte2->movimientos();
    while($fila2 = mysqli_fetch_array($resultadosmov))
    {

        echo'
';
        echo '	';
        echo '	';
        echo ''.utf8_encode($fila2["no_parcialidad"]).'	';
        echo ''.utf8_encode($fila2["importe_total"]).'	';
        echo '
';
    }

}
echo '
';
echo "

";

Body:
Echo all the columns when processing the second query.

$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
    $bandera=0;
    //
    $id_documento=$fila["id_documento"];
    $reporte->set('id_documento',$id_documento);
    $reporte->contador();
    $contador=$reporte->get('contador');

    $id_documento=$fila["id_documento"];
    $reporte2->set('id_documento',$id_documento);
    $resultadosmov = $reporte2->movimientos();
    if ($resultadosmov->num_rows > 0) {
        while($fila2 = mysqli_fetch_array($resultadosmov))
        {
            echo "<tr>";
            echo '<td>'.utf8_encode($fila["factura"]).'</td>';
            echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
            echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
            echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
            echo '</tr>';
            // Make 1st two columns blank in additional rows
            $fila["factura"] = "";
            $file["rfc_emisor"] = "";
        }
    } else {
        echo "<tr style=''>";
        echo '<td>'.utf8_encode($fila["factura"]).'</td>';
        echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
        echo '<td></td>';
        echo '<td></td>';
        echo '</tr>';
    }
}

BTW, what is the $bandera variable for? It's set but never used.

It would probably be even better if you could join the two queries, instead of doing queries in a loop.


问:
Install mxnet 0.12.1 on AWS cuda9 deep learning AMI
AWS deep learning AMIs come with mxnet 0.12.0 RC. Apparently this version has a bug that sets random initialization weights to 0. How to I remove the preinstalled mxnet and upgrade?

Logged in via SHH as ec2-user, I tried

```<code>cd src
sudo rm -rf mxnet
git clone --recursive github.com/apache/incubator-mxnet.git mxnet
</code>```

but the R-package build fails. Do I have to make/compile the program prior to R-package? Because that also fails. This package installation only works with a nightmare of inconsistent LD library configurations.

答: Yes, you need to compile the MXNet program before building R package. The detailed installation guide is here: http://mxnet.incubator.apache.org/install/index.html</p>

Body:
AWS deep learning AMIs come with mxnet 0.12.0 RC. Apparently this version has a bug that sets random initialization weights to 0. How to I remove the preinstalled mxnet and upgrade?

Logged in via SHH as ec2-user, I tried

cd src
sudo rm -rf mxnet
git clone --recursive github.com/apache/incubator-mxnet.git mxnet

but the R-package build fails. Do I have to make/compile the program prior to R-package? Because that also fails. This package installation only works with a nightmare of inconsistent LD library configurations.


问:
Azure Bot Framework - resizable FormFlow window
I am trying to build a simple dialog with the FormFlow but the options I want to display are quite long and are cut off. Any idea how I can make the dialog window resizable?

答:
Unless you are using WebChat, where you might be able to tweak the CSS by building a custom version of it, you can't resize the dialog window.

The best option here would be removing the "I Would Like" part of your button text.


问:
Object already exists in RSACryptoServiceProvider
I copied the source code from one application to another, both running on the same machine.  I am also using the same string for containerName below in both applications.

What is preventing my new application from reading the key that was saved in the other application?  All other things are equal, logged in user account etc.

```<code>     CspParameters cspParams = new CspParameters();
     cspParams.KeyContainerName = containerName;
     cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

     // Get error "object already exists" below.
     RSACryptoServiceProvider  rsaKey = new RSACryptoServiceProvider(cspParams);
</code>```

答:
Did you try to grant permissions to Everyone, for example, for files in "Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\Machine Keys", as it described there:

http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f7b9f928-a794-47f2-a5bd-9f64ca375040

Body:
I copied the source code from one application to another, both running on the same machine.  I am also using the same string for containerName below in both applications.

What is preventing my new application from reading the key that was saved in the other application?  All other things are equal, logged in user account etc.

     CspParameters cspParams = new CspParameters();
     cspParams.KeyContainerName = containerName;
     cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

     // Get error "object already exists" below.
     RSACryptoServiceProvider  rsaKey = new RSACryptoServiceProvider(cspParams);


问:
Compare the Euclidean distance of two lists of tuples with fewer comparisons python
I am trying to calculate the Euclidean distance of two list of tuples with the threshold of 4 . If the threshold is less than a particular value then increment the counter . Each tuple is the x,y,z coordinate of the point . Is there anyway i can lower of the comparison of list1 with list2 ..

```<code>  X = [ (1,2,3),(2,3,4), (4,5,6) ]
  Y = [ (1,2,2) , (3,4,5),(6,7,8) ]
  from math import sqrt
  dist_X = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in X]
  dist_Y = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in Y]
  for x in dist_X:
     print (x ,  [ i for i,y in enumerate(dist_Y) if abs(x-y) <= 4])
</code>```

I was thinking of first calculating the Euclidean distance of each point with the origin (0,0,0) so that both the lists now contain the points that are close to each other but it didnt work because its a scalar value .. Am i going in the right direction?

EDIT

```<code>   visited1 = [ (1,2,3),(2,3,4), (4,5,6) ]
   visited2   = [ (1,2,2) , (3,4,5),(6,7,8) ]
    def euclidean(a,b):
        return sqrt((a[0] - b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
   comparison = 0
   for i,j in enumerate(visited2):
     for k,l in enumerate(visited1):
         if euclidean(visited2[i],visited1[k]) < 4:
                 count += 1
         comparison += 1
</code>```

In this every element of the list1 is compared with every element in the list2 .. I want to know if there is a way i can minimise the comparisons given the points(x,y,z) that i have?

答:
One precomputatiion that can sometimes speed things up are kd-trees. I ran a quick test against brute force and found that they can be quite a bit faster for larger lists:

```<code># n = 10
# trees                 0.08512560 ms
# brute                 0.01425540 ms
# n = 100
# trees                 0.20338160 ms
# brute                 0.09876890 ms
# n = 1000
# trees                 6.40193820 ms
# brute                16.15429670 ms
# n = 10000
# trees               298.69653380 ms
# brute              1393.71134270 ms
</code>```

Code:

```<code>import numpy as np
from scipy.spatial import cKDTree

import types
from timeit import timeit

def setup_data(n, k):
    data = {'d1': np.random.randint(0, 10, (n, 3)),
            'd2': np.random.randint(0, 10, (n, 3)),
            'mx': k}
    return data

def f_trees(d1, d2, mx):
    t1 = cKDTree(d1)
    t2 = cKDTree(d2)
    return t1.count_neighbors(t2, mx)

def f_brute(d1, d2, mx):
    dist2 = np.add.outer(np.einsum('ij,ij->i', d1, d1), np.einsum('ij,ij->i', d2, d2)) - 2*np.einsum('ij, kj', d1, d2)
    return np.count_nonzero(dist2 <= mx*mx)

for n in (10, 100, 1000, 10000):
    data = setup_data(n, 4)
    ref = np.array(f_trees(**data))
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            assert np.allclose(ref, func(**data))
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(**data)', globals={'f':func, 'data':data}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))
</code>```

Body:
I am trying to calculate the Euclidean distance of two list of tuples with the threshold of 4 . If the threshold is less than a particular value then increment the counter . Each tuple is the x,y,z coordinate of the point . Is there anyway i can lower of the comparison of list1 with list2 ..

  X = [ (1,2,3),(2,3,4), (4,5,6) ]
  Y = [ (1,2,2) , (3,4,5),(6,7,8) ]
  from math import sqrt
  dist_X = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in X]
  dist_Y = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in Y]
  for x in dist_X:
     print (x ,  [ i for i,y in enumerate(dist_Y) if abs(x-y) <= 4])

I was thinking of first calculating the Euclidean distance of each point with the origin (0,0,0) so that both the lists now contain the points that are close to each other but it didnt work because its a scalar value .. Am i going in the right direction?

EDIT

   visited1 = [ (1,2,3),(2,3,4), (4,5,6) ]
   visited2   = [ (1,2,2) , (3,4,5),(6,7,8) ]
    def euclidean(a,b):
        return sqrt((a[0] - b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
   comparison = 0
   for i,j in enumerate(visited2):
     for k,l in enumerate(visited1):
         if euclidean(visited2[i],visited1[k]) < 4:
                 count += 1
         comparison += 1

In this every element of the list1 is compared with every element in the list2 .. I want to know if there is a way i can minimise the comparisons given the points(x,y,z) that i have?

Body:
One precomputatiion that can sometimes speed things up are kd-trees. I ran a quick test against brute force and found that they can be quite a bit faster for larger lists:

# n = 10
# trees                 0.08512560 ms
# brute                 0.01425540 ms
# n = 100
# trees                 0.20338160 ms
# brute                 0.09876890 ms
# n = 1000
# trees                 6.40193820 ms
# brute                16.15429670 ms
# n = 10000
# trees               298.69653380 ms
# brute              1393.71134270 ms

Code:

import numpy as np
from scipy.spatial import cKDTree

import types
from timeit import timeit

def setup_data(n, k):
    data = {'d1': np.random.randint(0, 10, (n, 3)),
            'd2': np.random.randint(0, 10, (n, 3)),
            'mx': k}
    return data

def f_trees(d1, d2, mx):
    t1 = cKDTree(d1)
    t2 = cKDTree(d2)
    return t1.count_neighbors(t2, mx)

def f_brute(d1, d2, mx):
    dist2 = np.add.outer(np.einsum('ij,ij->i', d1, d1), np.einsum('ij,ij->i', d2, d2)) - 2*np.einsum('ij, kj', d1, d2)
    return np.count_nonzero(dist2 <= mx*mx)

for n in (10, 100, 1000, 10000):
    data = setup_data(n, 4)
    ref = np.array(f_trees(**data))
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            assert np.allclose(ref, func(**data))
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(**data)', globals={'f':func, 'data':data}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))


问:
Subset an igraph object for the name of the edge
Consider a data frame that correlated each variable from with each other:

```<code>iris_cor <- structure(list(x = c("Sepal.Length", "Sepal.Length", "Sepal.Length",
"Sepal.Length", "Sepal.Width", "Sepal.Width", "Sepal.Width",
"Sepal.Width", "Petal.Length", "Petal.Length", "Petal.Length",
"Petal.Length", "Petal.Width", "Petal.Width", "Petal.Width",
"Petal.Width"), y = c("Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width"), r = c(NA, -0.117569784133002, 0.871753775886583,
0.817941126271576, -0.117569784133002, NA, -0.42844010433054,
-0.366125932536439, 0.871753775886583, -0.42844010433054, NA,
0.962865431402796, 0.817941126271576, -0.366125932536439, 0.962865431402796,
NA)), row.names = c(NA, -16L), class = c("tbl_df", "tbl", "data.frame"
), .Names = c("x", "y", "r"))
</code>```

If I wanted to make a network plot of this I would do the following:

```<code>library(igraph)
iris_igraph <- graph_from_data_frame(iris_cor)
</code>```

Now if I were only interested in the correlations that involved with Sepal.Length I am unclear on how to efficiently extract that information. Trying both of these approaches is not successful. The first because of the error and the second because I only get the first instance of Sepal.Length not all of them:

```<code>> subgraph.edges(iris_igraph, E(iris_igraph)[name == "Sepal.Length"])
Error in eval(x$expr, data, x$env) : object 'name' not found
>
> subgraph.edges(iris_igraph, V(iris_igraph)[name == "Sepal.Length"])
IGRAPH dc7408b DN-- 1 1 --
+ attr: name (v/c), r (e/n)
+ edge from dc7408b (vertex names):
[1] Sepal.Length->Sepal.Length
</code>```

This results in the desired output:

```<code>subgraph.edges(iris_igraph, E(iris_igraph)[1:4])
</code>```

However a numbered index is not practical when the desired subsets of the igraph object aren't in order or there are many nodes/edges.

Can anyone recommend a way to subset an igraph object for the name of the edge?

答:
According to indexing edge sequences, you can use the special function inc for edges subsetting, which:

takes a vertex sequence, and selects all edges that have at least one incident vertex in the vertex sequence.

```<code>E(iris_igraph)[inc('Sepal.Length')]
#+ 7/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width  Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[7] Petal.Width ->Sepal.Length
</code>```

Select edges from Sepal.Length:

```<code>E(iris_igraph)[from('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width
</code>```

Select edges to Sepal.Length:

```<code>E(iris_igraph)[to('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[4] Petal.Width ->Sepal.Length
</code>```

Body:
Consider a data frame that correlated each variable from with each other:

iris_cor <- structure(list(x = c("Sepal.Length", "Sepal.Length", "Sepal.Length",
"Sepal.Length", "Sepal.Width", "Sepal.Width", "Sepal.Width",
"Sepal.Width", "Petal.Length", "Petal.Length", "Petal.Length",
"Petal.Length", "Petal.Width", "Petal.Width", "Petal.Width",
"Petal.Width"), y = c("Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width"), r = c(NA, -0.117569784133002, 0.871753775886583,
0.817941126271576, -0.117569784133002, NA, -0.42844010433054,
-0.366125932536439, 0.871753775886583, -0.42844010433054, NA,
0.962865431402796, 0.817941126271576, -0.366125932536439, 0.962865431402796,
NA)), row.names = c(NA, -16L), class = c("tbl_df", "tbl", "data.frame"
), .Names = c("x", "y", "r"))

If I wanted to make a network plot of this I would do the following:

library(igraph)
iris_igraph <- graph_from_data_frame(iris_cor)

Now if I were only interested in the correlations that involved with Sepal.Length I am unclear on how to efficiently extract that information. Trying both of these approaches is not successful. The first because of the error and the second because I only get the first instance of Sepal.Length not all of them:

> subgraph.edges(iris_igraph, E(iris_igraph)[name == "Sepal.Length"])
Error in eval(x$expr, data, x$env) : object 'name' not found
>
> subgraph.edges(iris_igraph, V(iris_igraph)[name == "Sepal.Length"])
IGRAPH dc7408b DN-- 1 1 --
+ attr: name (v/c), r (e/n)
+ edge from dc7408b (vertex names):
[1] Sepal.Length->Sepal.Length

This results in the desired output:

subgraph.edges(iris_igraph, E(iris_igraph)[1:4])

However a numbered index is not practical when the desired subsets of the igraph object aren't in order or there are many nodes/edges.

Can anyone recommend a way to subset an igraph object for the name of the edge?

Body:
According to indexing edge sequences, you can use the special function inc for edges subsetting, which:

takes a vertex sequence, and selects all edges that have at least one incident vertex in the vertex sequence.

E(iris_igraph)[inc('Sepal.Length')]
#+ 7/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width  Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[7] Petal.Width ->Sepal.Length

Select edges from Sepal.Length:

E(iris_igraph)[from('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width

Select edges to Sepal.Length:

E(iris_igraph)[to('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[4] Petal.Width ->Sepal.Length


问:
Send sms to different numbers based on the recipient Twilio and Contact form 7 - Wordpress
I'm working on integrating Twilio with Wordpress and Contact form 7 plugin.

I made a hook for Contact form 7 to send sms with Twilio on form submission. It works.

My next step is to send to different numbers based on the recipient ( I have 3 different location in the contact form 7 and the recipient changes based on the chosen location).

I can't make it work.

Below is my code, any thoughts?

This hook works and sends to 1 number only

```<code>add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function() {
    $sid = 'xxx';
    $token = 'xxx';
    $client = new Client($sid, $token);
    $to = '+1111111111';

$client->messages->create(
// the number you'd like to send the message to
    $to,
    array(
   'from' =>'+1212121211',
   'body' => "form submitted"
   )
);
}
</code>```

This is the second part, I can't make it work.

```<code>global $to;
function wpcf7_do_something (&$WPCF7_ContactForm) {
    if ($WPCF7_ContactForm->mail['recipient'] = "bla@bla.com") {
        $to = '+1XXXXXXXXX';
    } else if($WPCF7_ContactForm->mail['recipient'] = "blabla@blabla.com") {
        $to = '+1x1x1x1x1x';
    } else {
        $to = "+1000000000"
    }
}
add_action('wpcf7_before_send_mail', 'wpcf7_do_something');

add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );

function your_wpcf7_mail_sent_function() {
    $sid = 'xxxxxxx';
    $token = 'xxxxxxx';
    $client = new Client($sid, $token);

    $client->messages->create(
    // the number you'd like to send the message to
       $to,
       array(
          'from' =>'+1XXXXXXXXX',
          'body' => "form submitted"
       )
    );
}
</code>```

答:
Twilio developer evangelist here.

From what I can tell from other Stack Overflow and Stack Exchange questions, you actually get passed the form to the wpcf7_mail_sent hook, so you don't need the two hooks like you have been trying. Something like the following should work:

```<code>add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function($cf7form) {
    if ($cf7form->mail['recipient'] = "bla@bla.com") {
        $to = '+1XXXXXXXXX';
    } else if($cf7form->mail['recipient'] = "blabla@blabla.com") {
        $to = '+1x1x1x1x1x';
    } else {
        $to = "+1000000000"
    }

    $sid = 'xxx';
    $token = 'xxx';
    $client = new Client($sid, $token);

    $client->messages->create(
    // the number you'd like to send the message to
        $to,
        array(
            'from' =>'+1212121211',
            'body' => "form submitted"
        )
    );
}
</code>```

Let me know if that helps at all.

Body:
I'm working on integrating Twilio with Wordpress and Contact form 7 plugin.

I made a hook for Contact form 7 to send sms with Twilio on form submission. It works.

My next step is to send to different numbers based on the recipient ( I have 3 different location in the contact form 7 and the recipient changes based on the chosen location).

I can't make it work.

Below is my code, any thoughts?

This hook works and sends to 1 number only

add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function() {
    $sid = 'xxx';
    $token = 'xxx';
    $client = new Client($sid, $token);
    $to = '+1111111111';

$client->messages->create(
// the number you'd like to send the message to
    $to,
    array(
   'from' =>'+1212121211',
   'body' => "form submitted"
   )
);
}

This is the second part, I can't make it work.

global $to;
function wpcf7_do_something (&$WPCF7_ContactForm) {
    if ($WPCF7_ContactForm->mail['recipient'] = "bla@bla.com") {
        $to = '+1XXXXXXXXX';
    } else if($WPCF7_ContactForm->mail['recipient'] = "blabla@blabla.com") {
        $to = '+1x1x1x1x1x';
    } else {
        $to = "+1000000000"
    }
}
add_action('wpcf7_before_send_mail', 'wpcf7_do_something');

add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );

function your_wpcf7_mail_sent_function() {
    $sid = 'xxxxxxx';
    $token = 'xxxxxxx';
    $client = new Client($sid, $token);

    $client->messages->create(
    // the number you'd like to send the message to
       $to,
       array(
          'from' =>'+1XXXXXXXXX',
          'body' => "form submitted"
       )
    );
}

Body:
Twilio developer evangelist here.

From what I can tell from other Stack Overflow and Stack Exchange questions, you actually get passed the form to the wpcf7_mail_sent hook, so you don't need the two hooks like you have been trying. Something like the following should work:

add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function($cf7form) {
    if ($cf7form->mail['recipient'] = "bla@bla.com") {
        $to = '+1XXXXXXXXX';
    } else if($cf7form->mail['recipient'] = "blabla@blabla.com") {
        $to = '+1x1x1x1x1x';
    } else {
        $to = "+1000000000"
    }

    $sid = 'xxx';
    $token = 'xxx';
    $client = new Client($sid, $token);

    $client->messages->create(
    // the number you'd like to send the message to
        $to,
        array(
            'from' =>'+1212121211',
            'body' => "form submitted"
        )
    );
}

Let me know if that helps at all.


问:
How to copy data to Azure Data Lake store using multiple threads from azure file share?
I have 2TB data in azure file share and I want that to be copied to azure data lake store. That should get copied with same directory structure. I tried with

```<code>az dls fs upload --account eanpdlstore2 --source-path "/root/mymountpoint/ShopperVisionDataRoot/" --destination-path "/pngcaseprocessing/ShopperVisionDataRoot"
</code>```

But it is taking forever to copy the data to azure data lake from azure file share. Can some shed some light on how to get this work or any other feasible way to do this?

The dir structure is like Main_dir/sub_dir/sub_dir/{multiple_data_folders} and should get copied same way. The point is I don't want to copy all the data folders under Main_dir/sub_dir/sub_dir/ but only two in each sub_dir. So I tried this to get those two to different location.

```<code>find DATA_PREP_INPUT2 -maxdepth 1 -mindepth 1 -type d | while IFS= read -r subdir; do
  mkdir -p DATA_PREP_INPUT_TEST/"$(basename $subdir)" &&
  cp -n -r "$subdir"/{IPD_130288,IPD_130284} DATA_PREP_INPUT_TEST/"$(basename $subdir)"/;
done
</code>```

and then I can use the above azure command to copy. But this is also taking too long to copy one data dir.

答:
As an alternative you may wish to consider Azure Data Factory, if you aren't hitting limits for azure file shares.

It does a great job at copying between data sources, it can run concurrently and the execution location is automatically closest to your data sink (in most cases - it can be overridden if needs be).

It has support for Azure File Shares:
https://learn.microsoft.com/en-us/azure/data-factory/connector-azure-file-storage

And data lake store:
https://learn.microsoft.com/en-us/azure/data-factory/connector-azure-data-lake-store

Here are some tips for performance tuning:
https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-performance

I don't believe at the time of writing the "copy wizard" (which makes it easier to experiment) is available in V2, but it's the version you need for for Azure File Shares.

Here's a getting stared guide:
https://learn.microsoft.com/en-us/azure/data-factory/

Body:
I have 2TB data in azure file share and I want that to be copied to azure data lake store. That should get copied with same directory structure. I tried with

az dls fs upload --account eanpdlstore2 --source-path "/root/mymountpoint/ShopperVisionDataRoot/" --destination-path "/pngcaseprocessing/ShopperVisionDataRoot"

But it is taking forever to copy the data to azure data lake from azure file share. Can some shed some light on how to get this work or any other feasible way to do this?

The dir structure is like Main_dir/sub_dir/sub_dir/{multiple_data_folders} and should get copied same way. The point is I don't want to copy all the data folders under Main_dir/sub_dir/sub_dir/ but only two in each sub_dir. So I tried this to get those two to different location.

find DATA_PREP_INPUT2 -maxdepth 1 -mindepth 1 -type d | while IFS= read -r subdir; do
  mkdir -p DATA_PREP_INPUT_TEST/"$(basename $subdir)" &&
  cp -n -r "$subdir"/{IPD_130288,IPD_130284} DATA_PREP_INPUT_TEST/"$(basename $subdir)"/;
done

and then I can use the above azure command to copy. But this is also taking too long to copy one data dir.


问:
Search highlighter in Java
boldHighlight method takes text string and highlights in it q keywords via  tags

colorHighlight method takes text string and highlights int q keywords via  with 12 alternating colors

```<code>String text = "The use of hello as a telephone greeting has been credited to Thomas
               Edison; according to one source, he expressed his surprise with a
               misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on
               ships) as a telephone greeting"

String keywords = "HELLO Surprise"
</code>```

boldHighlight(text, keywords); // will produce:

The use of hello as a telephone greeting has been credited to Thomas Edison; according     to one source, he expressed his surprise with a misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on ships) as a telephone greeting`

colorHighlight(text, keywords); // will produce:

The use of hello as a telephone greeting has been credited to Thomas Edison;>according     to one source, he expressed his surprise with a misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on ships) as a telephone greeting

The question:

is there something I could use like third party library that would do similar job as bellow methods? Or if you look at the code, is there something that can be improved, to make the performance better and/or make it more elegant?`

```<code>private static final String[] colors = new String[]{"ffff66", "a0ffff", "99ff99", "ff9999", "ff66ff", "880000", "00aa00", "886800", "004699", "990099", "ffff66", "a0ffff"};

public static String safeCharWithSpace(String input) {
    input = input.trim();
    return Normalizer.normalize(input.toLowerCase(), Normalizer.Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
            .replaceAll("[^\\p{Alnum}]+", " ");
}

private static String prepQuery(String q) {
    try {
        log.debug("qr encoded: " + q);
        q = URLDecoder.decode(q, "UTF-8");
    } catch (UnsupportedEncodingException ignore) {
    }
    log.debug("qr decoded: " + q);

    return removeIgnoreCase(q, stopWords);
}

public static String boldHighlight(String text, String q) {
    return highlight(text, q, false);
}

public static String colorHighlight(String text, String q) {
    return highlight(text, q, true);
}

private static String replaceWord(String text, String keyword, int colorNumber, boolean useColor) {
    String color = "";
    keyword = safeCharWithSpace(keyword);
    if (StringUtils.isNotEmpty(keyword) && !StringUtils.isWhitespace(keyword)) {
        if (useColor) color = " style='background-color: " + colors[colorNumber] + "'";
        return text.replaceAll("(?i)(" + keyword + ")(?!([^<]+)?>>)", "<b" + color + ">$1</b>");
    } else
        return text;
}

public static String highlight(String text, String q, boolean useColor) {
    String qr = prepQuery(q);
    String rtn = null;
    int i = 0;

    if (qr.startsWith("\"")) {
        String keywords = StringUtils.remove(qr, "\"");
        rtn = replaceWord(text, keywords, 0, useColor);
    } else {
        String[] keywords = qr.split("\\s");
        for (String keyword : keywords) {
            rtn = replaceWord(text, keyword, i, useColor);
            if (useColor) {
                if (i < 11) i++;
                else i = 0;
            }
        }
    }
    return rtn;
}
</code>```

for removal of stop words removeIgnoreCase()  in prepQuery() method refer to my other post: Removing strings from another string in java

答:
Wow, well you could go about it a few different ways.

You could call a static method.

i.e.

```<code>${statics["java.lang.System"].currentTimeMillis()}
</code>```

The MVC thing to do would be to do this processing before the template is processed, but I know your just maintaining the code.

It looks like it is just doing several replace all's, so a change to a Java method should work.  I have to suggesst you look at the escaping tools Freemarker has.

Freemarker really has great documentation, and built ins cover many situations.

Title: Search highlighter in Java

Body:
boldHighlight method takes text string and highlights in it q keywords via  tags

colorHighlight method takes text string and highlights int q keywords via  with 12 alternating colors

String text = "The use of hello as a telephone greeting has been credited to Thomas
               Edison; according to one source, he expressed his surprise with a
               misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on
               ships) as a telephone greeting"

String keywords = "HELLO Surprise"

boldHighlight(text, keywords); // will produce:

The use of hello as a telephone greeting has been credited to Thomas Edison; according     to one source, he expressed his surprise with a misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on ships) as a telephone greeting`

colorHighlight(text, keywords); // will produce:

The use of hello as a telephone greeting has been credited to Thomas Edison;>according     to one source, he expressed his surprise with a misheard Hullo. Alexander Graham Bell initially used Ahoy (as used on ships) as a telephone greeting

The question:

is there something I could use like third party library that would do similar job as bellow methods? Or if you look at the code, is there something that can be improved, to make the performance better and/or make it more elegant?`

private static final String[] colors = new String[]{"ffff66", "a0ffff", "99ff99", "ff9999", "ff66ff", "880000", "00aa00", "886800", "004699", "990099", "ffff66", "a0ffff"};

public static String safeCharWithSpace(String input) {
    input = input.trim();
    return Normalizer.normalize(input.toLowerCase(), Normalizer.Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
            .replaceAll("[^\\p{Alnum}]+", " ");
}

private static String prepQuery(String q) {
    try {
        log.debug("qr encoded: " + q);
        q = URLDecoder.decode(q, "UTF-8");
    } catch (UnsupportedEncodingException ignore) {
    }
    log.debug("qr decoded: " + q);

    return removeIgnoreCase(q, stopWords);
}

public static String boldHighlight(String text, String q) {
    return highlight(text, q, false);
}

public static String colorHighlight(String text, String q) {
    return highlight(text, q, true);
}

private static String replaceWord(String text, String keyword, int colorNumber, boolean useColor) {
    String color = "";
    keyword = safeCharWithSpace(keyword);
    if (StringUtils.isNotEmpty(keyword) && !StringUtils.isWhitespace(keyword)) {
        if (useColor) color = " style='background-color: " + colors[colorNumber] + "'";
        return text.replaceAll("(?i)(" + keyword + ")(?!([^<]+)?>>)", "$1");
    } else
        return text;
}

public static String highlight(String text, String q, boolean useColor) {
    String qr = prepQuery(q);
    String rtn = null;
    int i = 0;

    if (qr.startsWith("\"")) {
        String keywords = StringUtils.remove(qr, "\"");
        rtn = replaceWord(text, keywords, 0, useColor);
    } else {
        String[] keywords = qr.split("\\s");
        for (String keyword : keywords) {
            rtn = replaceWord(text, keyword, i, useColor);
            if (useColor) {
                if (i < 11) i++;
                else i = 0;
            }
        }
    }
    return rtn;
}

for removal of stop words removeIgnoreCase()  in prepQuery() method refer to my other post: Removing strings from another string in java

Body:
Wow, well you could go about it a few different ways.

You could call a static method.

i.e.

${statics["java.lang.System"].currentTimeMillis()}

The MVC thing to do would be to do this processing before the template is processed, but I know your just maintaining the code.

It looks like it is just doing several replace all's, so a change to a Java method should work.  I have to suggesst you look at the escaping tools Freemarker has.

Freemarker really has great documentation, and built ins cover many situations.


问:
How to load custom components in React from a different folder?
I'm thinking about moving my project to React but there is a road block.

Let me explain.

The project have components (now it's written in php).
If you need to customize on of them you just need to extend the original class of a component and load it from a custom folder.

Example:

The components are located under this directory:
/path/to/core/components/CustomerProfile

If you need to customize something you need to use this directory:
/path/to/custom/components/CustomerProfile

How can I use custom Components in React (and load them from a custom folder)?

Thanks.

答:
```<code>import {CustomComponent} from 'relative-path-to-customcomponent'
</code>```

and do not forget to export the default component.

How to export :
Inside your component file,

```<code>export default ComponentName
</code>```

Body:
import {CustomComponent} from 'relative-path-to-customcomponent'

and do not forget to export the default component.

How to export :
Inside your component file,

export default ComponentName


问:
Excel 2013 VBA Clear All Filters macro
It seems older macros are not working. I have proper securtiy set to run VBA macros but when I have tried a few methods for clearing ALL filters on a worksheet, I get a compile error.

Here is what I have tried:

Sub AutoFilter_Remove()
'This macro removes any filtering in order to display all of the data but it does not remove the filter arrows
ActiveSheet.ShowAllData
End Sub
```

I have buttons on the sheets to clear all filters for ease of use for users since the sheets has a lot of columns that have filters on them.

答:
This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:

We start with:

```<code>  Sub ResetWSFilters(ws as worksheet)
             If ws.FilterMode Then
     ws.ShowAllData
     Else
     End If
    'This gets rid of "normal" filters - but tables will remain filtered
    For Each listObj In ws.ListObjects
               If listObj.ShowHeaders Then
                    listObj.AutoFilter.ShowAllData
                    listObj.Sort.SortFields.Clear
               End If
       Next listObj
        'And this gets rid of table filters
        End Sub
</code>```

We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook

```<code>Sub ResetAllWBFilters(wb as workbook)
  Dim ws As Worksheet
  Dim wb As Workbook
  Dim listObj As ListObject

       For Each ws In wb.Worksheets
          If ws.FilterMode Then
          ws.ShowAllData
          Else
          End If
 'This removes "normal" filters in the workbook - however, it doesn't remove table filters
   For Each listObj In ws.ListObjects
        If listObj.ShowHeaders Then
             listObj.AutoFilter.ShowAllData
             listObj.Sort.SortFields.Clear
        End If
   Next listObj

        Next
'And this removes table filters. You need both aspects to make it work.
    End Sub
</code>```

You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:

```<code>Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub
</code>```

The one I use the most: Resetting all filters in the workbook that the module is stored in:

```<code>Sub ResetFilters()
      Dim ws As Worksheet
      Dim wb As Workbook
      Dim listObj As ListObject
       Set wb = ThisWorkbook
       'Set wb = ActiveWorkbook
       'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
           For Each ws In wb.Worksheets
              If ws.FilterMode Then
              ws.ShowAllData
              Else
              End If
     'This removes "normal" filters in the workbook - however, it doesn't remove table filters
       For Each listObj In ws.ListObjects
            If listObj.ShowHeaders Then
                 listObj.AutoFilter.ShowAllData
                 listObj.Sort.SortFields.Clear
            End If
       Next listObj

            Next
'And this removes table filters. You need both aspects to make it work.
    End Sub
</code>```

Title: Excel 2013 VBA Clear All Filters macro

Body:
It seems older macros are not working. I have proper securtiy set to run VBA macros but when I have tried a few methods for clearing ALL filters on a worksheet, I get a compile error.

Here is what I have tried:

Sub AutoFilter_Remove()
'This macro removes any filtering in order to display all of the data but it does not remove the filter arrows
ActiveSheet.ShowAllData
End Sub

I have buttons on the sheets to clear all filters for ease of use for users since the sheets has a lot of columns that have filters on them.

Body:
This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:

We start with:

  Sub ResetWSFilters(ws as worksheet)
             If ws.FilterMode Then
     ws.ShowAllData
     Else
     End If
    'This gets rid of "normal" filters - but tables will remain filtered
    For Each listObj In ws.ListObjects
               If listObj.ShowHeaders Then
                    listObj.AutoFilter.ShowAllData
                    listObj.Sort.SortFields.Clear
               End If
       Next listObj
        'And this gets rid of table filters
        End Sub

We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook

Sub ResetAllWBFilters(wb as workbook)
  Dim ws As Worksheet
  Dim wb As Workbook
  Dim listObj As ListObject

       For Each ws In wb.Worksheets
          If ws.FilterMode Then
          ws.ShowAllData
          Else
          End If
 'This removes "normal" filters in the workbook - however, it doesn't remove table filters
   For Each listObj In ws.ListObjects
        If listObj.ShowHeaders Then
             listObj.AutoFilter.ShowAllData
             listObj.Sort.SortFields.Clear
        End If
   Next listObj

        Next
'And this removes table filters. You need both aspects to make it work.
    End Sub

You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:

Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub

The one I use the most: Resetting all filters in the workbook that the module is stored in:

Sub ResetFilters()
      Dim ws As Worksheet
      Dim wb As Workbook
      Dim listObj As ListObject
       Set wb = ThisWorkbook
       'Set wb = ActiveWorkbook
       'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
           For Each ws In wb.Worksheets
              If ws.FilterMode Then
              ws.ShowAllData
              Else
              End If
     'This removes "normal" filters in the workbook - however, it doesn't remove table filters
       For Each listObj In ws.ListObjects
            If listObj.ShowHeaders Then
                 listObj.AutoFilter.ShowAllData
                 listObj.Sort.SortFields.Clear
            End If
       Next listObj

            Next
'And this removes table filters. You need both aspects to make it work.
    End Sub