问:
Excel VBA event to calculate based on user input
To preface the situation, I am new to VBA programming so any help would be greatly appreciated.

I have two columns; one where the user can input a dollar value ("AL") and another where the user can input a percent value ("AK"). The object is to enable the user to input either value (% or $) and have the other value calculate. For instance, if the user inputs 10% in "AL", the applicable $ value will generate in "AK" and vice versa.

Below is the code I've come up with thus far but it isn't working. Any thoughts/suggestions would be greatly appreciated! Thank you!

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   'Application.EnableEvents = False Application.EnableEvents = True'

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value
        Exit Sub
    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value
        Exit Sub
    'Application.EnableEvents = False Application.EnableEvents = True'
    End If
  End If
End Sub
</code>```

答:
You can have a better use of your Worksheet_Change parameters, like Target.

1.Instead of:

```<code>Range("AL" & Target.Row).Value
</code>```

you can use:

```<code>Target.Offset(, 1).Value
</code>```

2.Instead of:

```<code>Range("AK" & Target.Row).Value
</code>```

you can use:

```<code>Target.Value
</code>```

3.Also Range(Target.Address) actually is Target

Code

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range
Set cell = Range("AK9:AL50")

Application.EnableEvents = False

If Not Application.Intersect(cell, Target) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Target.Offset(, 1).Value = Target.Value / Range("V" & Target.Row).Value
    ElseIf Target.Column = 38 Then ' value in second column changed
        Target.Offset(, 2).Value = Target.Value * Range("V" & Target.Row).Value
    End If
End If
Application.EnableEvents = True '<-- RESTORE SETTING OUTSIDE THE IF

End Sub
</code>```

Body:
To preface the situation, I am new to VBA programming so any help would be greatly appreciated.

I have two columns; one where the user can input a dollar value ("AL") and another where the user can input a percent value ("AK"). The object is to enable the user to input either value (% or $) and have the other value calculate. For instance, if the user inputs 10% in "AL", the applicable $ value will generate in "AK" and vice versa.

Below is the code I've come up with thus far but it isn't working. Any thoughts/suggestions would be greatly appreciated! Thank you!

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   'Application.EnableEvents = False Application.EnableEvents = True'

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value
        Exit Sub
    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value
        Exit Sub
    'Application.EnableEvents = False Application.EnableEvents = True'
    End If
  End If
End Sub

Body:
You can have a better use of your Worksheet_Change parameters, like Target.

1.Instead of:

Range("AL" & Target.Row).Value

you can use:

Target.Offset(, 1).Value

2.Instead of:

Range("AK" & Target.Row).Value

you can use:

Target.Value

3.Also Range(Target.Address) actually is Target

Code

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range
Set cell = Range("AK9:AL50")

Application.EnableEvents = False

If Not Application.Intersect(cell, Target) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Target.Offset(, 1).Value = Target.Value / Range("V" & Target.Row).Value
    ElseIf Target.Column = 38 Then ' value in second column changed
        Target.Offset(, 2).Value = Target.Value * Range("V" & Target.Row).Value
    End If
End If
Application.EnableEvents = True '<-- RESTORE SETTING OUTSIDE THE IF

End Sub


来源: stackexchange

问:
callrail api secondary request parameters
How do I add secondary request parameters using callrail api?

Independently the following two work.

```<code>curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?fields=first_time_callers,leads"
</code>```

gets back the fields I need.

```<code>curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?company_id={companyId123}"
</code>```

gets back specified company.

I need to combine the two. Here is what I've attempted:

```<code>curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?company_id={companyId123}&fields=first_time_callers,leads"
</code>```

I've looked through all their documentation . Without figuring out how to do it. Any help would be greatly appreciated.

答:
As of 3/31/2017 CallRail API does not currently accept secondary parameters in the HTTP request.

I received an e-mail from their support team telling me they are working on supporting that in the future.

ContentLicense: CC BY-SA 3.0

Body:
How do I add secondary request parameters using callrail api?

Independently the following two work.

curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?fields=first_time_callers,leads"

gets back the fields I need.

curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?company_id={companyId123}"

gets back specified company.

I need to combine the two. Here is what I've attempted:

curl -H "Authorization: Token token={faketoken123}" \
-X GET \
"https://api.callrail.com/v2/a/{accountId123}/calls.json?company_id={companyId123}&fields=first_time_callers,leads"

I've looked through all their documentation . Without figuring out how to do it. Any help would be greatly appreciated.


问:
Web Essentials 2017 and TypeScript definition generation
Just installed Web Essentials 2017 from the Visual Studio marketplace but the feature to create TypeScript definition from a C# class seems to be missing. In Web Essentials 2015, I would right mouse over the C# class file and there would be an option "Create TypeScript Intellisense file".

I checked the project change log and it shows that the TypeScript definition file generator was implemented in 1.2 and the installed version is 1.5.8.

https://github.com/madskristensen/WebEssentials2017/blob/master/CHANGELOG.md

What did I miss?

答: I found the following extension: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.TypeScriptDefinitionGenerator</p>


问:
How do I dinamically create and add view of MvxFrameControl in another layout
How can I dynamically create and add view to specific region of current view, for example create and add androids MvxFrameControl ?

I need some like on Android

```<code> var frameHelpControl = (MvxFrameControl)ViewFactory.CreateByModel(frameHelpControlModel);
 regionForHelpFrame.AddView(frameHelpControl, new ViewGroupParameters(.....));
</code>```

I need ability to create View by model via DI Factory and adding it to any region. I know that there exist such factory inside standart presenter but what if i need create controller for me without presenter?

For example, I have code in old iOS project

```<code> private void AddBubble(BubbleMC newBubbleModel)
 {
       var bubble = (BubbleVC)ViewContollerFactory.ViewControllerByModel(newBubbleModel, true);
       bubble.View.Frame = View.Bounds;
       AddChildViewController(bubble);
       Add(bubble.View);
       bubble.DidMoveToParentViewController(this);
 }
</code>```

How can I rewrite it on mvvmCross Android / iOS (i think it will the same) for BubbleVC that will inherits MvxFrameControl and will needed to be added in View.

答:
You can load a ViewModel like this:

```<code>var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var viewModelRequest = MvxViewModelRequest<MyViewModel>.GetDefaultRequest();
var viewModel = loaderService.LoadViewModel(viewModelRequest, null);
</code>```

Then you can just create a MvxFrameControl and assign the BindingContext the the newly created ViewModel.

However, instead of creating views and adding to a parent view, you should rely on the mechanic of something like RecyclerView on Android and TableView/CollectionView on iOS.

Body:
How can I dynamically create and add view to specific region of current view, for example create and add androids MvxFrameControl ?

I need some like on Android

 var frameHelpControl = (MvxFrameControl)ViewFactory.CreateByModel(frameHelpControlModel);
 regionForHelpFrame.AddView(frameHelpControl, new ViewGroupParameters(.....));

I need ability to create View by model via DI Factory and adding it to any region. I know that there exist such factory inside standart presenter but what if i need create controller for me without presenter?

For example, I have code in old iOS project

 private void AddBubble(BubbleMC newBubbleModel)
 {
       var bubble = (BubbleVC)ViewContollerFactory.ViewControllerByModel(newBubbleModel, true);
       bubble.View.Frame = View.Bounds;
       AddChildViewController(bubble);
       Add(bubble.View);
       bubble.DidMoveToParentViewController(this);
 }

How can I rewrite it on mvvmCross Android / iOS (i think it will the same) for BubbleVC that will inherits MvxFrameControl and will needed to be added in View.

Body:
You can load a ViewModel like this:

var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var viewModelRequest = MvxViewModelRequest<MyViewModel>.GetDefaultRequest();
var viewModel = loaderService.LoadViewModel(viewModelRequest, null);

Then you can just create a MvxFrameControl and assign the BindingContext the the newly created ViewModel.

However, instead of creating views and adding to a parent view, you should rely on the mechanic of something like RecyclerView on Android and TableView/CollectionView on iOS.


问:
WPF: message box with checkbox added
In WPF I am looking for a "do not show again" checkbox on my messagebox popup.

Does anyone know where I can get such a control or maybe how to copy the style of the regular WPF messagebox so I can create my own?

Thanks

答: You could just use a dialog box. An easy way to do it would be to keep a variable in the project settings that would be updated on the popup close() event. So then you would just have to verify the value in the project settings before showing the popup.</p>

ContentLicense: CC BY-SA 2.5

Title: WPF: message box with checkbox added


问:
Corner Radius of View in UITableViewCell Subclass
I am trying to create a round view in my tablevviewcell subclass

i set the cornerRadius to half the width, but the frame is returning 0. so corner radius is not setting correctly.

```<code>initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
    initialView.layer.cornerRadius = initialView.frame.size.width/2
</code>```

Thanks

```<code>override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}
</code>```

Frame is still printing -> (0.0, 0.0, 0.0, 0.0)

```<code>override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(initialView)
    contentView.addSubview(nameLabel)
    setupConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}
</code>```

答:
You are doing the interaction before the view is laid out. You need to subclass the UITableViewCell and override layoutSubviews like so:

```<code>class CustomCell: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        initialView.layer.cornerRadius = initialView.frame.size.width/2
    }
}
</code>```

Body:
I am trying to create a round view in my tablevviewcell subclass

i set the cornerRadius to half the width, but the frame is returning 0. so corner radius is not setting correctly.

initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
    initialView.layer.cornerRadius = initialView.frame.size.width/2

Thanks

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

Frame is still printing -> (0.0, 0.0, 0.0, 0.0)

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(initialView)
    contentView.addSubview(nameLabel)
    setupConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

Body:
You are doing the interaction before the view is laid out. You need to subclass the UITableViewCell and override layoutSubviews like so:

class CustomCell: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        initialView.layer.cornerRadius = initialView.frame.size.width/2
    }
}


问:
no matches in array in elasticsearch
I am using elasticsearch 5.2.2.

in my index I have data looking like this:

```<code>{
    "_index": "index",
    "_type": "273caf76-ec03-478c-b980-9743180bc863",
    "_id": "eee46e24-f383-4ae7-8930-dc3836e030a5",
    "_score": 3.41408,
    "_source": {
      "Father Name": [
        {
          "id": "some id",
          "value": "Some value test test"
        }
      ],
      "Mother Name": [
        {
          "id": "some id",
          "value": "Another value haha"
        }
      ],
      "Other values": [{ id: "", value: ""}]
    }
}
</code>```

When I am searching with _all, everything works fine and I can find all the results with reasonable scores

```<code>{"query":{"match":{"_all":"value"}},"from":0,"size":20}
</code>```

But that query is searching in all the fields. If I want for instance just to find results in Father Name or in Father Name and Mother Name, then I find nothing.

```<code>{"query":{"match":{"Father Name":"value"}},"from":0,"size":20}
</code>```

My goal is to find in have a search like with _all, but limited to a few fields.

答:
Your fields Father Name and Mother Name are arrays of inner objects.

To search within the value field within Father Name, for example, do

```<code>curl -XGET localhost:9200/myindex/_search?pretty -d '
{
  "query": {
    "match": {
      "Father Name.value": "first"
    }
  },
  "from": 0,
  "size": 20
}'
</code>```

I'm not sure, however, how to query for all fields within Father Name.

Reference Arrays of Inner Objects

Title: no matches in array in elasticsearch

Body:
I am using elasticsearch 5.2.2.

in my index I have data looking like this:

{
    "_index": "index",
    "_type": "273caf76-ec03-478c-b980-9743180bc863",
    "_id": "eee46e24-f383-4ae7-8930-dc3836e030a5",
    "_score": 3.41408,
    "_source": {
      "Father Name": [
        {
          "id": "some id",
          "value": "Some value test test"
        }
      ],
      "Mother Name": [
        {
          "id": "some id",
          "value": "Another value haha"
        }
      ],
      "Other values": [{ id: "", value: ""}]
    }
}

When I am searching with _all, everything works fine and I can find all the results with reasonable scores

{"query":{"match":{"_all":"value"}},"from":0,"size":20}

But that query is searching in all the fields. If I want for instance just to find results in Father Name or in Father Name and Mother Name, then I find nothing.

{"query":{"match":{"Father Name":"value"}},"from":0,"size":20}

My goal is to find in have a search like with _all, but limited to a few fields.

Body:
Your fields Father Name and Mother Name are arrays of inner objects.

To search within the value field within Father Name, for example, do

curl -XGET localhost:9200/myindex/_search?pretty -d '
{
  "query": {
    "match": {
      "Father Name.value": "first"
    }
  },
  "from": 0,
  "size": 20
}'

I'm not sure, however, how to query for all fields within Father Name.

Reference Arrays of Inner Objects


问:
Why doesn't this code for a navigation drawer work?
Following is some code to create a navigation drawer. The problem is that the drawer doesn't appear properly. The drawer is visible from the start of the activity but only partially, and it doesn't slide in and out from the side. It's just stationary in one place. What's wrong here?

NOTE: I've removed the Action Bar by writing NoActionBar in styles.xml

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<
android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.navigationexample3.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"></LinearLayout>

   <
   android.support.design.widget.NavigationView
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:id="@+id/nv"
   >

   <ListView
       android:layout_width="200dp"
       android:layout_height="match_parent"
       android:id="@+id/listView"></ListView>

   </android.support.design.widget.NavigationView>
</code>```

mainActivity.java

```<code>package com.example.nirvan.navigationexample3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView ls=(ListView)findViewById(R.id.listView);
    String[] values=
    {"one","two","three","four","five","six","seven","eight"};

    ArrayAdapter<String> adapter=new ArrayAdapter(this,
    R.layout.item,values);
    ls.setAdapter(adapter);
   }
 }
</code>```

item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

</TextView>
</code>```

答:
In addition to Luiz Fernando's reply, don't forget to put

```<code> </android.support.v4.widget.DrawerLayout>
</code>```

At the end of your XML file.

Body:
Following is some code to create a navigation drawer. The problem is that the drawer doesn't appear properly. The drawer is visible from the start of the activity but only partially, and it doesn't slide in and out from the side. It's just stationary in one place. What's wrong here?

NOTE: I've removed the Action Bar by writing NoActionBar in styles.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<
android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.navigationexample3.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"></LinearLayout>

   <
   android.support.design.widget.NavigationView
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:id="@+id/nv"
   >

   <ListView
       android:layout_width="200dp"
       android:layout_height="match_parent"
       android:id="@+id/listView"></ListView>

   </android.support.design.widget.NavigationView>

mainActivity.java

package com.example.nirvan.navigationexample3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView ls=(ListView)findViewById(R.id.listView);
    String[] values=
    {"one","two","three","four","five","six","seven","eight"};

    ArrayAdapter<String> adapter=new ArrayAdapter(this,
    R.layout.item,values);
    ls.setAdapter(adapter);
   }
 }

item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

</TextView>

Body:
In addition to Luiz Fernando's reply, don't forget to put

 </android.support.v4.widget.DrawerLayout>

At the end of your XML file.


问:
Spring issues after changing resource to consuming MULTIPART_FORM_DATA
I recently changed the following jersey resource by adding the following @Consumes annotation to accept an image file.

```<code>    @POST
    @PermitAll
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response addImage(@FormDataParam("file") InputStream uploadedInputStream) {
        imageService.addImage(uploadedInputStream);
        return Response.ok(200).build();
    }
</code>```

I also added the following parameter to my application initialization

```<code>registration.addInitParameter("jersey.config.server.provider.classnames",
                "org.glassfish.jersey.media.multipart.MultiPartFeature");
</code>```

Now several random unit tests are failing for the following reason:

```<code>    org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response package.webservice.resource.ImageResource.addImage(java.io.InputStream) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class package.webservice.resource.ImageResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@5a515e5d]}, definitionMethod=public javax.ws.rs.core.Response package.webservice.resource.ImageResource.addImage(java.io.InputStream), parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']
</code>```

is there something that I am missing?

EDIT: adding full registration:

```<code>registration.setFilter(filter);
    registration.setName("JerseyFilter");
    registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
    // Set the Jersey filter mapping and context path
    registration.addUrlPatterns("/*");
    registration.addInitParameter("jersey.config.servlet.filter.contextPath", "/");
    // Load the common package and application package
    registration.addInitParameter("jersey.config.server.provider.packages",
            "com.vanguard.jaxrs.feature;package.webservice.resource");
    // Enable javax security annotations on resources
    registration.addInitParameter("jersey.config.server.provider.classnames",
            "org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;org.glassfish.jersey.media.multipart.MultiPartFeature");
    // Enable media type mappings on the URI such as .xml and .json
    registration.addInitParameter("jersey.config.server.mediaTypeMappings",
            "xml:application/xml, json:application/json");
    // Enable Java bean validation integration
    registration.addInitParameter("jersey.config.beanValidation.enableOutputValidationErrorEntity.servers", "true");
    // Enable fall through to Spring MVC (allows forward to static content
    // if no jersey endpoint found)
    registration.addInitParameter("jersey.config.servlet.filter.forwardOn404", "true");
</code>```

答: The problem was actually with my lack of experience configuring JerseyTest. I had to use .register(MultiPartFeature.class); on my ResourceConfig when configuring JerseyTest. Doh!

Body:
I recently changed the following jersey resource by adding the following @Consumes annotation to accept an image file.

    @POST
    @PermitAll
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response addImage(@FormDataParam("file") InputStream uploadedInputStream) {
        imageService.addImage(uploadedInputStream);
        return Response.ok(200).build();
    }

I also added the following parameter to my application initialization

registration.addInitParameter("jersey.config.server.provider.classnames",
                "org.glassfish.jersey.media.multipart.MultiPartFeature");

Now several random unit tests are failing for the following reason:

    org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response package.webservice.resource.ImageResource.addImage(java.io.InputStream) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class package.webservice.resource.ImageResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@5a515e5d]}, definitionMethod=public javax.ws.rs.core.Response package.webservice.resource.ImageResource.addImage(java.io.InputStream), parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']

is there something that I am missing?

EDIT: adding full registration:

registration.setFilter(filter);
    registration.setName("JerseyFilter");
    registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
    // Set the Jersey filter mapping and context path
    registration.addUrlPatterns("/*");
    registration.addInitParameter("jersey.config.servlet.filter.contextPath", "/");
    // Load the common package and application package
    registration.addInitParameter("jersey.config.server.provider.packages",
            "com.vanguard.jaxrs.feature;package.webservice.resource");
    // Enable javax security annotations on resources
    registration.addInitParameter("jersey.config.server.provider.classnames",
            "org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;org.glassfish.jersey.media.multipart.MultiPartFeature");
    // Enable media type mappings on the URI such as .xml and .json
    registration.addInitParameter("jersey.config.server.mediaTypeMappings",
            "xml:application/xml, json:application/json");
    // Enable Java bean validation integration
    registration.addInitParameter("jersey.config.beanValidation.enableOutputValidationErrorEntity.servers", "true");
    // Enable fall through to Spring MVC (allows forward to static content
    // if no jersey endpoint found)
    registration.addInitParameter("jersey.config.servlet.filter.forwardOn404", "true");


问:
Weird behavior with Maven plugin management with maven-surefire-plugin
I have a parent pom which defines

<pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <parallel>classesAndMethods</parallel>
                        <threadCount>4</threadCount>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
```

I have a child project which inherits from the pom but does not declare the plugin in its plugin section.
I am still seeing the plugin take effect when I run maven test goal.

答:
This is normal because the maven-surefire-plugin is by default bound to the test phase as part of the built-in lifecycle bindings. No need to declare it in the child project.

In other words, the plugin is implicitly available to the child project because it binds itself to the test phase. The maven-scm-plugin (linked in the other question) is not bound by default to any phase so you have to declare it in the child to inherit the configuration from the parent. But because maven-surefire-plugin is bound by default to the test phase, you don't need to declare it in the child. Try running mvn help:effective-pom in your child module to see the effective POM which shows the final POM that Maven actually uses. Check http://maven.apache.org/ref/3.3.9/maven-core/default-bindings.html to see the default plugin bindings.

If you want to skip the plugin, just execute mvn install or pass -DskipTests=true. If you still need to run mvn test to run tests in other projects, you can skip tests in the child module's POM (although this is not recommended at all):

```<code><plugins>
     <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <configuration>
              <skipTests>true</skipTests>
         </configuration>
     </plugin>
</plugins>
</code>```

Body:
I have a parent pom which defines

<pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <parallel>classesAndMethods</parallel>
                        <threadCount>4</threadCount>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

I have a child project which inherits from the pom but does not declare the plugin in its plugin section.
I am still seeing the plugin take effect when I run maven test goal.

Body:
This is normal because the maven-surefire-plugin is by default bound to the test phase as part of the built-in lifecycle bindings. No need to declare it in the child project.

In other words, the plugin is implicitly available to the child project because it binds itself to the test phase. The maven-scm-plugin (linked in the other question) is not bound by default to any phase so you have to declare it in the child to inherit the configuration from the parent. But because maven-surefire-plugin is bound by default to the test phase, you don't need to declare it in the child. Try running mvn help:effective-pom in your child module to see the effective POM which shows the final POM that Maven actually uses. Check http://maven.apache.org/ref/3.3.9/maven-core/default-bindings.html to see the default plugin bindings.

If you want to skip the plugin, just execute mvn install or pass -DskipTests=true. If you still need to run mvn test to run tests in other projects, you can skip tests in the child module's POM (although this is not recommended at all):

<plugins>
     <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <configuration>
              <skipTests>true</skipTests>
         </configuration>
     </plugin>
</plugins>


问:
how to retrieve data from JSON into list?
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

```<code>[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]
</code>```

HTML:

```<code><div>
    <ul>

    </ul>
</div>
</code>```

script:

```<code><script>
$(document).ready( function(){

        $.getJSON('item.json', function(data) {
            $.each(data, function (i, f) {
                $("ul").append("<li><img src=" + f.content + "/></li>");
            });
  });
});
</script>
</code>```

答:
With your code example you can do this on (ES6)

```<code>let arr = [
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
];

arr.map((item,i) => {
   if(item.content != "nopic"){
    return (
      "<li><img src='"+item.content+"' /></li>"
    );
   }
});

on ES5

$.getJSON('item.json', function(data) {
   $.each(data, function (i, f) {
       if(f.content != "nopic"){
          $("ul").append("<li><img src=" + f.content + "/></li>");
       }
   });
});
</code>```

hope it helps

Body:
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]

HTML:

script:

Body:
With your code example you can do this on (ES6)

let arr = [
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
];

arr.map((item,i) => {
   if(item.content != "nopic"){
    return (
      "<li><img src='"+item.content+"' /></li>"
    );
   }
});

on ES5

$.getJSON('item.json', function(data) {
   $.each(data, function (i, f) {
       if(f.content != "nopic"){
          $("ul").append("<li><img src=" + f.content + "/></li>");
       }
   });
});

hope it helps


问:
Office web app - Remove buttons
Is there any way to remove buttons or complete ribbons from Office web apps. I want to remove Download, Add to one drive etc.

Sample url is below

https://view.officeapps.live.com/op/view.aspx?src=www.cse.lehigh.edu%2F~glennb%2Foose%2Fppt%2FCsharp_dotNET.ppt

答:
You have to edit the appropriate css files to:
.Class or #ID etc.
display: none;

Word can be found in:
"[drive here]:\microsoftwebapps\WebOneNote\Resources\1033\WordEditor.css"

Excel can be found in:
"[drive here]:\microsoftwebapps\ExcelServicesWfe_layouts\styles\excelribbon.css"

PowerPoint can be found in:
"[drive here]:\microsoftwebapps\WebPPTViewer\pptresources\1033\stylesEdit.css"

I used IE's DOM explorer to target specific classes & IDs of the buttons I wanted to remove.

Good luck, it is a huge pain in the a**

An example would be

"#btnOpenInClient{display:none;}"

This is my first answer. I didn't really have time to format, but it should help. I literally jsut did this for my OWAs

Title: Office web app - Remove buttons


问:
How to force int to string in Laravel JSON?
I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

答:
The best solution for me is to to use attribute casting and
Fractal transformers

Fractal transformers are extremely useful when you have complex responses with multiple relations included.


问:
Write and read a file in the internal storage (not in the app package)
I would like to create and read a file in the internal storage (not SD card) but I want a file accessible for the user in the Explorer.

How can I do ?

My code :

```<code>public void WriteFile(View v) {
        try {
            FileOutputStream fileout= getActivity().openFileOutput("password.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write("hello");
            outputWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ReadFile(View v) {
        try {
            FileInputStream fileIn=getActivity().openFileInput("hello.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();

            Toast.makeText(getActivity(), s + " ",Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

答: I found the solution using MODE_WORLD_READABLE instead of MODE_PRIVATE.

Body:
I would like to create and read a file in the internal storage (not SD card) but I want a file accessible for the user in the Explorer.

How can I do ?

My code :

public void WriteFile(View v) {
        try {
            FileOutputStream fileout= getActivity().openFileOutput("password.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write("hello");
            outputWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ReadFile(View v) {
        try {
            FileInputStream fileIn=getActivity().openFileInput("hello.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();

            Toast.makeText(getActivity(), s + " ",Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


问:
Dynamic task generation in an Airflow DAG
I want to use Airflow to generate client reports, I would like to have one DAG that loops through all clients and launches a task to generate their report. The list of clients is gathered by the first task in the DAG and cannot be hardcoded in.

Basically I have a task that uses a database hook in a python operator to generate a list. Then for each item in the list I would like to execute a task using a python operator with that item being passed as an argument to the python function. Is there a certain pattern I can use to achieve this?

答:
Trigger_dag concept

Let the task that uses a database hook in a python operator to generate a list" be the task in the controller dag and pass the each item in list to the trigger_dag in the params section.

You will find reference in the examples folder in your airflow installation

Good Luck!


问:
Managing the localization of Java properties files
I have a Web application written in Java that is targeting several countries, all of which speak different languages (and more often than not, several languages -- that's Europe for you).

We have a bunch of .properties files that hold the localized strings, and our current procedure is to e-mail the language-specific files to our partners for updating before doing major updates.

However, this process is rather error-prone, as sometimes people forget to translate new strings and sometimes new strings don't get added to every language file, thus small mistakes get through very easily.

Does anyone know of any existing software that could help us clear this mess?

At a bare minimum, I'm thinking of something that would allow you to load a master file (for example, in English), a localized file and then would highlight the keys that were added to or removed from the master file.

答:
I have been using JRC Editor for managing the resource bundles. It will highlight the keys that are missing values as shown in the below .

It also allows you to work with the bundles using native language (hence end user friendly) and it will convert the characters to "\uxxx" equivalent behind the scenes.


问:
assign value as per ratio defined
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

```<code>PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0
</code>```

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

Title: assign value as per ratio defined

Body:
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

Body:
A simple method is to maintain a count of how many pens each person should get. Then, as long as they are pens to distribute, you give one to the person which should get the most pens.

Here is a work through of your example:

60/13, 60/13, 10/13 -> 1, 0, 0

47/13, 60/13, 10/13 -> 1, 1, 0

47/13, 47/13, 10/13 -> 2, 1, 0

34/13, 47/13, 10/13 -> 2, 2, 0

34/13, 34/13, 10/13 -> 3, 2, 0

21/13, 34/13, 10/13 -> 3, 3, 0

21/13, 21/13, 10/13 -> 4, 3, 0

8/13,  21/13, 10/13 -> 4, 4, 0

8/13,  8/13,  10/13 -> 4, 4, 1

8/13,  8/13,  -3/13 -> 5, 4, 1

ContentLicense: CC BY-SA 4.0


问:
Writing bytes to a file
I have an array of bytes defined as :

unsigned char * pixels = new unsigned char[pixelsLen];

and I want write all bytes from this array to a .bmp file.

This is how it does not work:

```<code>ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
output.write( ( char * )&pixels, pixelsLen );
output.close();
</code>```

This is how it does work :

```<code>ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
for ( size_t i = 0; i < pixelsLen; i++ ) {
    output.write( ( char * )&pixels[i], 1 );
}
output.close();
</code>```

The question is why it works when I'm writing it byte by byte and does not work when I'm trying to write it at once ?

答:
Actually &pixels returns a pointer to pointer but std::ostream::write function gets pointer. So try this:

```<code>ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
output.write( reinterpret_cast<char *>(pixels), pixelsLen );
output.close();
</code>```

Also try to avoid C-style casting.

Title: Writing bytes to a file

Body:
I have an array of bytes defined as :

unsigned char * pixels = new unsigned char[pixelsLen];

and I want write all bytes from this array to a .bmp file.

This is how it does not work:

ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
output.write( ( char * )&pixels, pixelsLen );
output.close();

This is how it does work :

ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
for ( size_t i = 0; i < pixelsLen; i++ ) {
    output.write( ( char * )&pixels[i], 1 );
}
output.close();

The question is why it works when I'm writing it byte by byte and does not work when I'm trying to write it at once ?

Body:
Actually &pixels returns a pointer to pointer but std::ostream::write function gets pointer. So try this:

ifstream screen ( "input.bmp", ios::binary | ios::in );
ofstream output ( "output.bmp", ios::binary | ios::out | ios::app );
output.write( reinterpret_cast<char *>(pixels), pixelsLen );
output.close();

Also try to avoid C-style casting.


问:
Remove an item from a Set that doesn't match criteria
For a school project, the goal is to do a fuzzy match of a query string to a lyric string inside a Song object.  The overall data structure is a TreeMap of unique words paired with sets of songs that contain that word in the lyrics.

I have my preliminary match set of songs that contain the query string.  The twist here is that I have to assign each result song a rank based on the number of characters in the match section, spaces inclusive.  For example, searching for "she loves you" returns these among the matches:

"... She loves you ..."  The Beatles, rank= 13

"... She just loves you ..."  Bonnie Raitt, rank=18

"... She loves me, well you ..."  Elvis Presley, rank=23

The I'm using to sort the results is:

```<code>for (int i=0; i<lyrics.length; i++) {
  if (lyrics[i].equals(query[0])) { //got the start point
  start=i; //adjust the start index point

  //loop through lyrics from start point
  for (int j=1; j<query.length; j++) {
    if (lyrics[j].equals(query[query.length-1])) {
        end=i; //found the last word
    }

    //if next lyric word doesn't match this query word
    if (!lyrics[i+j].equals(query[j])) {

    //advance loop through lyrics. when a match is found, i is adjusted to
    //the match index
    for (int k= i+j+1; k<lyrics.length; k++) {
        if (lyrics[k].equals(query[j]) || lyrics[k].equals(query[0]))
            i=k++;
        } //end inner advance loop

    } //end query string test

  }//end query test loop

  song.setRanks(start, end); //start and end points for the rank algorithm.

} //end start point test
</code>```

Since all the songs in the result set contain the query words in any particular order, they will not all be included in the result printout.  Using this algorithm, how can I set a trigger to remove the song from the set if the query is not matched to any particular length?

Edit- Is Lucene a solution to this?  This is a gray area in the project, and one I will bring up in class tomorrow.  He is allowing us to choose whatever data structures for this project, but I don't know if using another implementation for string matching will pass muster.

Edit 2 @ belisarius- I don't see how edit distance applies here.  The most common application of Levenshtein distance requres a String a of length n and String b of length m, and the distance is the number of edits required for a==b.  For this project, all that is required is the rank of characters in a match, with the start and end points unknown.  With some changes to the code posted above, I am finding the start and end points accurately.  What I need is a way to remove the non-matches from the set if the the lyrics don't fit the search in any fashion.

答: Probably you want to have a look at the Levenstein distance. The Apache commons-lang library implemented it in version 2.1 in the StringUtils class.</p>

Body:
For a school project, the goal is to do a fuzzy match of a query string to a lyric string inside a Song object.  The overall data structure is a TreeMap of unique words paired with sets of songs that contain that word in the lyrics.

I have my preliminary match set of songs that contain the query string.  The twist here is that I have to assign each result song a rank based on the number of characters in the match section, spaces inclusive.  For example, searching for "she loves you" returns these among the matches:

"... She loves you ..."  The Beatles, rank= 13

"... She just loves you ..."  Bonnie Raitt, rank=18

"... She loves me, well you ..."  Elvis Presley, rank=23

The I'm using to sort the results is:

for (int i=0; i<lyrics.length; i++) {
  if (lyrics[i].equals(query[0])) { //got the start point
  start=i; //adjust the start index point

  //loop through lyrics from start point
  for (int j=1; j<query.length; j++) {
    if (lyrics[j].equals(query[query.length-1])) {
        end=i; //found the last word
    }

    //if next lyric word doesn't match this query word
    if (!lyrics[i+j].equals(query[j])) {

    //advance loop through lyrics. when a match is found, i is adjusted to
    //the match index
    for (int k= i+j+1; k<lyrics.length; k++) {
        if (lyrics[k].equals(query[j]) || lyrics[k].equals(query[0]))
            i=k++;
        } //end inner advance loop

    } //end query string test

  }//end query test loop

  song.setRanks(start, end); //start and end points for the rank algorithm.

} //end start point test

Since all the songs in the result set contain the query words in any particular order, they will not all be included in the result printout.  Using this algorithm, how can I set a trigger to remove the song from the set if the query is not matched to any particular length?

Edit- Is Lucene a solution to this?  This is a gray area in the project, and one I will bring up in class tomorrow.  He is allowing us to choose whatever data structures for this project, but I don't know if using another implementation for string matching will pass muster.

Edit 2 @ belisarius- I don't see how edit distance applies here.  The most common application of Levenshtein distance requres a String a of length n and String b of length m, and the distance is the number of edits required for a==b.  For this project, all that is required is the rank of characters in a match, with the start and end points unknown.  With some changes to the code posted above, I am finding the start and end points accurately.  What I need is a way to remove the non-matches from the set if the the lyrics don't fit the search in any fashion.


问:
How do I pass a value into CLASS in DIV tag?
I'm editing an existing code, for a Progress Bar. Initially, the progress bar can only accept progress value [min, max, progress]. For example [min=0, max=100, progress=30].

I would like to add new input that can change the color. For example, if color="yellow", the progress bar color is yellow. How do I do that?

I would like to make the CLASS value (progress-bar.html), to be changeable.

I've tried several ways, but due to lack of understanding about the syntax, I was unsuccessful.

main.html

```<code><progress-bar [min]="0" [max]="100" [progress]="30" [color]="yellow">
</progress-bar>
</code>```

progress-bar.ts

```<code> export class ProgressBarComponent {

  @Input()
  progress: number;

  @Input()
  min: number;

  @Input()
  max: number;

  @Input()
  color: any;

  constructor() {
  }
</code>```

progress-bar.html

```<code><div style="display:flex;padding-bottom:5px;">
<div class="red" [style.width]="((progress/max) *100) + '%'"></div>
<div class="background-bar" [style.width]="(100-((progress/max) *100)) + '%'"></div>
</code>```

progress-bar.scss

```<code>.red{
    height:10px;
    margin-top:20px;
    background-color:#E64B55;
     -webkit-transition: width 2s;
transition: width 2s;
}

.yellow{
    height:10px;
    margin-top:20px;
    background-color:#db6623;
     -webkit-transition: width 2s;
transition: width 2s;
}
.background-bar{
    height:10px;
    margin-top:20px;
    margin-left:0px;
    background-color:lightgrey;
}
</code>```

答: Set class={{color}} for the div you want the background color for .div class="warning {{color}}"  this color you got as input from parent component.</p>

Body:
I'm editing an existing code, for a Progress Bar. Initially, the progress bar can only accept progress value [min, max, progress]. For example [min=0, max=100, progress=30].

I would like to add new input that can change the color. For example, if color="yellow", the progress bar color is yellow. How do I do that?

I would like to make the CLASS value (progress-bar.html), to be changeable.

I've tried several ways, but due to lack of understanding about the syntax, I was unsuccessful.

main.html

<progress-bar [min]="0" [max]="100" [progress]="30" [color]="yellow">
</progress-bar>

progress-bar.ts

 export class ProgressBarComponent {

  @Input()
  progress: number;

  @Input()
  min: number;

  @Input()
  max: number;

  @Input()
  color: any;

  constructor() {
  }

progress-bar.html

progress-bar.scss

.red{
    height:10px;
    margin-top:20px;
    background-color:#E64B55;
     -webkit-transition: width 2s;
transition: width 2s;
}

.yellow{
    height:10px;
    margin-top:20px;
    background-color:#db6623;
     -webkit-transition: width 2s;
transition: width 2s;
}
.background-bar{
    height:10px;
    margin-top:20px;
    margin-left:0px;
    background-color:lightgrey;
}


答:
The way to fix this is to subclass UITableViewCell and put your code into layoutSubviews:

```<code>override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
}
</code>```

And put the rest of the code in your question in your init() code:

```<code>func init() {
    // other stuff...

    setupInitialView()
}

func setupInitialView() {
    initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
}
</code>```

My complete (working!) UITableViewCell class is as follows. Instead of using the PureLayout pod I used an extension method that basically does the same thing.

```<code>//
//  MyTableViewCell.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/31/17.
//  Free as in free beer!
//

import UIKit

class MyTableViewCell: UITableViewCell {

    private(set) lazy var initialView: UIView = {
        let initialView = UIView(frame: .zero)
        return initialView
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        //
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(initialView)

        setupInitialView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setupInitialView() {
        self.contentView.addConstraintsWithFormat("V:|-5-[v0]-5-|", views: initialView)
        self.contentView.addConstraintsWithFormat("H:|-5-[v0]-0-|", views: initialView)

        initialView.backgroundColor = UIColor.red
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        self.initialView.layer.cornerRadius = frame.size.width/2
    }
}

extension UIView {
    func addConstraintsWithFormat(_ format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()

        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}
</code>```

Here's a screenshot (with the UITableViewController returning view.frame.width for heightForRowAt):

If you want I can also post the UITableViewController I used to test this code.

Title: Corner Radius of View in UITableViewCell Subclass

Body:
I am trying to create a round view in my tablevviewcell subclass

i set the cornerRadius to half the width, but the frame is returning 0. so corner radius is not setting correctly.

initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
    initialView.layer.cornerRadius = initialView.frame.size.width/2

Thanks

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

Frame is still printing -> (0.0, 0.0, 0.0, 0.0)

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(initialView)
    contentView.addSubview(nameLabel)
    setupConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
    print(initialView.frame)

}

Body:
The way to fix this is to subclass UITableViewCell and put your code into layoutSubviews:

override func layoutSubviews() {
    super.layoutSubviews()

    initialView.layer.cornerRadius = initialView.frame.size.width/2
}

And put the rest of the code in your question in your init() code:

func init() {
    // other stuff...

    setupInitialView()
}

func setupInitialView() {
    initialView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(5.0, 5.0, 5.0, 0.0), excludingEdge: .trailing)
    initialView.autoMatch(.width, to: .height, of: initialView)
}

My complete (working!) UITableViewCell class is as follows. Instead of using the PureLayout pod I used an extension method that basically does the same thing.

//
//  MyTableViewCell.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/31/17.
//  Free as in free beer!
//

import UIKit

class MyTableViewCell: UITableViewCell {

    private(set) lazy var initialView: UIView = {
        let initialView = UIView(frame: .zero)
        return initialView
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        //
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(initialView)

        setupInitialView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setupInitialView() {
        self.contentView.addConstraintsWithFormat("V:|-5-[v0]-5-|", views: initialView)
        self.contentView.addConstraintsWithFormat("H:|-5-[v0]-0-|", views: initialView)

        initialView.backgroundColor = UIColor.red
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        self.initialView.layer.cornerRadius = frame.size.width/2
    }
}

extension UIView {
    func addConstraintsWithFormat(_ format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()

        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}

Here's a screenshot (with the UITableViewController returning view.frame.width for heightForRowAt):

If you want I can also post the UITableViewController I used to test this code.


答:
In your case I suggest to use Array.slice:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var data = [
  {
      "content": "nopic",
  },
  {
      "content": "pic1.jpg",
  },
  {
      "content": "pic2.jpg",
  },
  {
      "content": "pic3.jpg",
  }
];
//$.getJSON('item.json', function(data) {
  $.each(data.slice(1), function (i, f) {
      $("ul").append("
" + f.content + "
");
  });
//});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <ul>

  </ul>
</div></code>```

Title: how to retrieve data from JSON into list?

Body:
In your case I suggest to use Array.slice:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var data = [
  {
      "content": "nopic",
  },
  {
      "content": "pic1.jpg",
  },
  {
      "content": "pic2.jpg",
  },
  {
      "content": "pic3.jpg",
  }
];
//$.getJSON('item.json', function(data) {
  $.each(data.slice(1), function (i, f) {
      $("ul").append("<li><img src=" + f.content + "/>" + f.content + "</li>");
  });
//});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <ul>

  </ul>
</div>


答:
I could replicate your issue using Plunker: http://plnkr.co/edit/QxklTx0R6WcYwpRIpd98 has the fix. You weren't waiting for the DOM to be loaded before attempting to append to the object. See line 3:

```<code>$("document").ready(function() {
  buildResultTableDistances();
});
</code>```

Should work then.

Title: Generate HTML table and load it in div element

Body:
I'd like to load a HTML table into a div-element (id="resultDataDistancesTable") - but the generated string isn't processed (no matter if I use html(), append() or innerHTML). There is no error in the console.

When I paste the console.log(..) output directly to the HTML page I get the table that I want - so why doesn't my JavaScript code work? Is something wrong with the string?

var response = {"distances":[[0,4569,17264,6074,4986,12430,10936,11729,11280,23714,19112,24070,24974,25809,24157,27636,27323,15690,27970,22152],[4837,0,9160,1879,1872,12492,10755,15237,14468,21251,16649,17650,20574,23346,21694,31144,30831,13227,23141,19689],[17807,9681,0,8419,14314,25164,23427,28206,27140,11709,17204,18205,21130,23901,22249,30219,29906,4147,23696,10294],[6156,1736,8271,0,3191,12812,8437,16555,14788,22085,17483,18484,21408,24180,22528,30498,30185,14061,23975,20523],[5438,1642,14335,3147,0,12796,11058,15838,14771,20785,16183,17184,20108,22880,21228,31745,31432,12761,22674,19223],[12266,13371,25607,10970,13329,0,1842,20750,6094,32057,27455,28455,31380,34152,32500,37248,36935,24033,37581,30495],[10434,11651,16093,8428,11608,1842,0,19509,7092,30336,25734,26735,29659,32431,30779,35416,35104,22312,35750,28774],[12355,15633,28328,17138,16050,19963,20849,0,6457,34778,30176,26719,27624,33122,31702,30285,29973,26754,30619,33216],[11054,14433,26669,14776,14391,6088,9450,10828,0,33119,28517,36279,37184,35214,33562,39846,39533,25095,40179,31557],[21936,20085,11649,19803,18444,29293,27556,32335,31269,0,2943,8201,8702,10694,9042,17012,16699,8876,11268,5269],[19141,17291,16426,17009,15649,26499,24762,29541,28475,2924,0,5407,6515,9365,7713,15683,15370,14852,9082,6033],[22777,19065,18201,18783,17424,28274,26536,25758,31348,8188,5556,0,2979,5144,6115,10994,10681,16626,5493,10239],[23722,21760,20895,21478,20118,30968,29231,26703,32292,8634,6627,2994,0,2715,3388,4505,4192,19321,3110,11521],[29801,24947,24082,24665,23305,34155,32417,32782,38371,9673,8179,5136,2704,0,2345,4277,3964,22508,1703,15331],[25139,23289,22424,23007,21647,32497,30760,30797,34473,8016,6521,6129,3394,2340,0,5174,4862,20850,3779,13673],[26964,30242,30040,31748,30660,36952,35458,29945,35534,16511,10598,10365,4526,4274,5182,0,336,28466,1821,15492],[26628,29906,29704,31412,30324,36616,35122,29609,35198,16175,10262,10029,4190,3938,4846,313,0,28130,1485,15156],[16108,9772,4136,13975,12616,23466,21728,26507,25441,8931,10916,11916,14841,17613,15961,23930,23617,0,17407,7516],[27163,30441,23429,24012,22653,37151,35657,30144,35733,11168,9161,5495,3089,1703,3746,1686,1373,21855,0,14055],[22592,20741,10188,20459,19100,29949,28212,32991,31925,5369,5909,10225,11565,14414,12762,20732,20419,7415,14131,0]]};

buildResultTableDistances();

function buildResultTableDistances() {
    var tbl;
    var tr_head = "

distances [meters]	";
    for (var i = 0; i < 20; i++) {
        tr_head += "" + "dummy" + "	";
    }
    tr_head += "
";
    tbl = tr_head;

    for (var i = 0; i < 20; i++) {
        var row = "
" + "dummy" + "	";
        for (var ii = 0; ii < 20; ii++) {
            row += "" + response.distances[i][ii] + "	";
        }
        row += "
";
        tbl += row;
    }
    tbl += "
";
    console.log(tbl);
    $('#resultDataDistancesTable').html(tbl);
}

Body:
I could replicate your issue using Plunker: http://plnkr.co/edit/QxklTx0R6WcYwpRIpd98 has the fix. You weren't waiting for the DOM to be loaded before attempting to append to the object. See line 3:

$("document").ready(function() {
  buildResultTableDistances();
});

Should work then.


问:
QTreeWidgetItem hide child checkboxes but not parent checkboxes
I have a QTreeWidget with two levels.  Parent level is first and child level underneath.  I want the parent level to contain checkboxes, but I want the children to have no checkboxes.  In the following example, every QTreeWidgetItem shows a checkbox.  If I remove "child.setCheckState(0, Qt.Unchecked)" then ALL checkboxes disappear, not just the child checkboxes.

How can I hide the child checkboxes, but not the parent checkboxes?

```<code>from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

def main():
    app        = QApplication (sys.argv)
    tree       = QTreeWidget ()
    headerItem = QTreeWidgetItem()
    item       = QTreeWidgetItem()

    for i in xrange(2):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
            child.setText(0, "Child {}".format(x))
            #child.setCheckState(0, Qt.Unchecked)
    tree.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
Here "child.setCheckState(0, Qt.Unchecked)" -- does mean that "you are setting checkbox to column "0" with unchecked state".

Now revisit your code:

you are not setting it for parent which you want so do something like below:

set checkbox for parent item:

```<code>parent.setCheckState(0, Qt.Unchecked)
</code>```

Remove below code completely as it sets checkboxes for child which you do not want

```<code>child.setCheckState(0, Qt.Unchecked)
</code>```

Also Delete the flags setting, as we noticed setting flags to parent, are carried to child items.

The code Roughly looks somewhat like this in first for loop:

```<code>        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setText(0, "Child {}".format(x))
</code>```

Body:
I have a QTreeWidget with two levels.  Parent level is first and child level underneath.  I want the parent level to contain checkboxes, but I want the children to have no checkboxes.  In the following example, every QTreeWidgetItem shows a checkbox.  If I remove "child.setCheckState(0, Qt.Unchecked)" then ALL checkboxes disappear, not just the child checkboxes.

How can I hide the child checkboxes, but not the parent checkboxes?

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

def main():
    app        = QApplication (sys.argv)
    tree       = QTreeWidget ()
    headerItem = QTreeWidgetItem()
    item       = QTreeWidgetItem()

    for i in xrange(2):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
            child.setText(0, "Child {}".format(x))
            #child.setCheckState(0, Qt.Unchecked)
    tree.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
Here "child.setCheckState(0, Qt.Unchecked)" -- does mean that "you are setting checkbox to column "0" with unchecked state".

Now revisit your code:

you are not setting it for parent which you want so do something like below:

set checkbox for parent item:

parent.setCheckState(0, Qt.Unchecked)

Remove below code completely as it sets checkboxes for child which you do not want

child.setCheckState(0, Qt.Unchecked)

Also Delete the flags setting, as we noticed setting flags to parent, are carried to child items.

The code Roughly looks somewhat like this in first for loop:

        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setExpanded(True)
        parent.setCheckState(0, Qt.Unchecked)
        for x in xrange(3):
            child = QTreeWidgetItem(parent)
            child.setText(0, "Child {}".format(x))


问:
Error in node.js/express app: Can't set headers after they are sent
I have a problem with setting up a Node.js application with Express for routing and MongoDB (Mongolab) for the database. I've been looking around & found a lot of other users with the same problem, but couldn't find a solution for the problem yet.. Hope that someone can help.

The error I keep getting is Error: Can't set headers after they are sent.

I get the error after a POST /login request.
I've tried to use res.end();, res.redirect('/users/index'); and to return the render.. But no success yet..

Here the most important code:

Server.js

```<code>  /* LOAD ALL DEPENDENCIES
    ----------------------------------------- */
    const express = require('express');
    const path = require('path');
    const request = require('request');
    const session = require('express-session');
    const compression = require('compression');
    const bodyParser = require('body-parser');
    const app = express();

    /* MONGODB CONFIGURATION
    ----------------------------------------- */
    const MongoClient = require("mongodb").MongoClient;
    require('dotenv').config();
    const dbConfig = process.env.MONGODB_URI;

    MongoClient.connect(dbConfig, (err, database) => {
      if (err) return console.log(err)
      db = database
    });

    /* SESSIONS CONFIGURATION
    ----------------------------------------- */
    app.use(session({
        secret: "JA1d82JHYF9?nsdfDF635MuHe#ksd",
        resave: false,
        saveUninitialized: true
    }));

    /* SET PORT FOR HEROKU
    ----------------------------------------- */
    const port = process.env.PORT || 3000;
    const host = process.env.HOST ||'0.0.0.0';

    // Rest of the code ..

    app.use('/users', usersRouter);
    // Router is loaded earlier

    /* START THE NPM SERVER
    ----------------------------------------- */
    app.listen(port, host, function() {
        console.log(`Server started on port ${port}`);
    });
</code>```

users.js (route)

```<code>/* LOAD ALL DEPENDENCIES
----------------------------------------- */
const express = require('express');
const router = express.Router();
const passwordHash = require('password-hash');

/* INDEX ROUTE
----------------------------------------- */
router.get('/', function(req, res) {
  if (req.session.login) {
    res.render('users/index');
  } else {
    res.redirect('/users/login');
  }
});

router.get('/login', function(req, res) {
  res.render('users/login');
});

router.post('/login', function(req, res) {
  const loginName = req.body.username;
  const loginPassword = req.body.password;
  db.collection('users').find().toArray(function(err, results) {
    results.map(function(user) {
      if (user['username'] === loginName) {
        const pwCheck = passwordHash.verify(loginPassword, user['password']);
        if(pwCheck === true) {
          req.session.login = true;
          req.session.username = user['username'];
          res.render('users/index');
        } else {
          res.redirect('/users/')
        }
      }
    })
  });
});
</code>```

Full error

```<code>Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:725:10)
    at ServerResponse.send (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:170:12)
    at done (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:962:10)
    at tryHandleCache (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:208:10)
    at View.exports.renderFile [as engine] (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:412:10)
    at View.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/view.js:128:8)
    at tryRender (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:640:10)
    at EventEmitter.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:966:7)
</code>```

My question

What does this error mean exactly, what is going wrong? And how could I fix this in this situation?

I'm building in Node.JS with Express as router and mongoDB as database. Could it be that it has something to do with that?

I've checked a lot of similar issues on Stackoverflow, but couldn't solve my issue yet ..

Hope someone can help me, thanks in advance!

Just came up a thought:

Could the problem be that I'm testing on localhost, while the mongodb (mongolab) is set on Heroku?

答:
Your problem is that for each result value returned by your DB lookup that matches on password and username you're calling res.render(). You can only call res.render() one time per request. So in theory this will work if only 1 user is returned and their password matches but if the same user exists multiple times and has the same password you're going to make calls to res.render() after it was already sent once.

My suggestion would be to iterate through the list of returned users and then break out after the first time it matches.

Body:
I have a problem with setting up a Node.js application with Express for routing and MongoDB (Mongolab) for the database. I've been looking around & found a lot of other users with the same problem, but couldn't find a solution for the problem yet.. Hope that someone can help.

The error I keep getting is Error: Can't set headers after they are sent.

I get the error after a POST /login request.
I've tried to use res.end();, res.redirect('/users/index'); and to return the render.. But no success yet..

Here the most important code:

Server.js

  /* LOAD ALL DEPENDENCIES
    ----------------------------------------- */
    const express = require('express');
    const path = require('path');
    const request = require('request');
    const session = require('express-session');
    const compression = require('compression');
    const bodyParser = require('body-parser');
    const app = express();

    /* MONGODB CONFIGURATION
    ----------------------------------------- */
    const MongoClient = require("mongodb").MongoClient;
    require('dotenv').config();
    const dbConfig = process.env.MONGODB_URI;

    MongoClient.connect(dbConfig, (err, database) => {
      if (err) return console.log(err)
      db = database
    });

    /* SESSIONS CONFIGURATION
    ----------------------------------------- */
    app.use(session({
        secret: "JA1d82JHYF9?nsdfDF635MuHe#ksd",
        resave: false,
        saveUninitialized: true
    }));

    /* SET PORT FOR HEROKU
    ----------------------------------------- */
    const port = process.env.PORT || 3000;
    const host = process.env.HOST ||'0.0.0.0';

    // Rest of the code ..

    app.use('/users', usersRouter);
    // Router is loaded earlier

    /* START THE NPM SERVER
    ----------------------------------------- */
    app.listen(port, host, function() {
        console.log(`Server started on port ${port}`);
    });

users.js (route)

/* LOAD ALL DEPENDENCIES
----------------------------------------- */
const express = require('express');
const router = express.Router();
const passwordHash = require('password-hash');

/* INDEX ROUTE
----------------------------------------- */
router.get('/', function(req, res) {
  if (req.session.login) {
    res.render('users/index');
  } else {
    res.redirect('/users/login');
  }
});

router.get('/login', function(req, res) {
  res.render('users/login');
});

router.post('/login', function(req, res) {
  const loginName = req.body.username;
  const loginPassword = req.body.password;
  db.collection('users').find().toArray(function(err, results) {
    results.map(function(user) {
      if (user['username'] === loginName) {
        const pwCheck = passwordHash.verify(loginPassword, user['password']);
        if(pwCheck === true) {
          req.session.login = true;
          req.session.username = user['username'];
          res.render('users/index');
        } else {
          res.redirect('/users/')
        }
      }
    })
  });
});

Full error

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:725:10)
    at ServerResponse.send (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:170:12)
    at done (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:962:10)
    at tryHandleCache (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:208:10)
    at View.exports.renderFile [as engine] (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/ejs/lib/ejs.js:412:10)
    at View.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/view.js:128:8)
    at tryRender (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:640:10)
    at EventEmitter.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Users/camillesebastien/Documents/Programming/Mongo App/node_modules/express/lib/response.js:966:7)

My question

What does this error mean exactly, what is going wrong? And how could I fix this in this situation?

I'm building in Node.JS with Express as router and mongoDB as database. Could it be that it has something to do with that?

I've checked a lot of similar issues on Stackoverflow, but couldn't solve my issue yet ..

Hope someone can help me, thanks in advance!

Just came up a thought:

Could the problem be that I'm testing on localhost, while the mongodb (mongolab) is set on Heroku?


问:
How to add a:hover rule in js function?
I modified some jQuery slide gallery for my website. And I want to add .nav li a:hover{color:#00f;} in css, but it didn't work. I checked it in firebug, the css rule is be crossed off. I find something in the jquery slide galley's js file,like this:

```<code>function init(){
    g.find(".nav").children("li").css("margin","0").css("padding","5px");
    g.find(".nav").children("li").children("a").css("text-decoration","none").css("display","block");
}
</code>```

Is it should be add the a:hover css rule in the js files? How to add it? Thanks.

答:
You can do this in JS with

```<code>g.find(".nav").children("li").children("a").hover(
    function() {
        $(this).css('color', '#00f');
    },
    function() {
        $(this).css('color', '#000');
    }
);
</code>```

You could also modify the plugin stylesheet so you wouldn't have to override it.

Title: How to add a:hover rule in js function?

Body:
I modified some jQuery slide gallery for my website. And I want to add .nav li a:hover{color:#00f;} in css, but it didn't work. I checked it in firebug, the css rule is be crossed off. I find something in the jquery slide galley's js file,like this:

function init(){
    g.find(".nav").children("li").css("margin","0").css("padding","5px");
    g.find(".nav").children("li").children("a").css("text-decoration","none").css("display","block");
}

Is it should be add the a:hover css rule in the js files? How to add it? Thanks.

Body:
You can do this in JS with

g.find(".nav").children("li").children("a").hover(
    function() {
        $(this).css('color', '#00f');
    },
    function() {
        $(this).css('color', '#000');
    }
);

You could also modify the plugin stylesheet so you wouldn't have to override it.


问:
Copy command - deep or shallow copy?
When I am copying the object with copy command in iOS (swift / objective c), Will that be a shallow copy or a deep copy ?

```<code>var str = "Hello, playground"
var copyStr = str.copy()
</code>```

and

```<code>var originalArray = [1, 2, 3, 4] as NSArray
var copyArray = originalArray.copy()

withUnsafePointer(to: &originalArray) {
    print(" originall address: \($0)")
}

withUnsafePointer(to: &copyArray) {
    print(" copy address: \($0)")
}
</code>```

Help me with the lines above , is this a deep copy or a shallow copy ?

The issue is , this behaviour in objective c is showing me the same
  address with both string and array which is shallow copy and in swift3
  it is showing me different address which is deep copy

答:
The copy performs a shallow copy (a copy of the collection, but the objects in the array are not copied). E.g.

```<code>let obj1 = Object(value: 1)
let obj2 = Object(value: 2)
let obj3 = Object(value: 3)

let originalArray = [obj1, obj2, obj3] as NSArray
let copyArray = originalArray.copy() as! NSArray

print(String(format: "original address: %p", originalArray))

for obj in originalArray {
    print(String(format: "    %p", obj as! Object))
}

print(String(format: "copy address: %p", copyArray))

for obj in copyArray {
    print(String(format: "    %p", obj as! Object))
}
</code>```

Note, I use an object other than NSNumber and NSString, as those have optimizations that may make looking at addresses misleading.

The member objects of these two arrays point to the same objects (i.e. a shallow copy).

```<code>original address: 0x618000044920
    0x6180000277e0
    0x618000027f00
    0x618000027ea0
copy address: 0x618000044920
    0x6180000277e0
    0x618000027f00
    0x618000027ea0
</code>```

In fact, as you can see, because it's an immutable NSArray, it appears to optimize this where the copy is actually returning the same array instance. If you use mutable arrays, NSMutableArray, you'll see two unique arrays returned, as you'd expect, but they will still point to the same collection of objects.

But, if you use NSArray(array:copyItems:) with true for copyItems, you will get two unique arrays with unique copies of each member object:

```<code>let copyArray = NSArray(array: originalArray as! [Any], copyItems: true)
</code>```

That yields a deep copy (two unique arrays where the individual member objects are copied and they, too, have unique addresses):

```<code>original address: 0x618000059e60
    0x618000027ae0
    0x618000028340
    0x618000028280
copy address: 0x61800005ba20
    0x618000028800
    0x618000028aa0
    0x618000028400
</code>```

See the documentation for init(array:copyItems:) which says:

The copy(with:) method performs a shallow copy. If you have a collection of arbitrary depth, passing true for the flag parameter [of init(array:copyItems:)] will perform an immutable copy of the first level below the surface. If you pass false the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

Personally, though, if writing Swift, I'd generally use Array and Dictionary value types rather than the old NSArray and NSDictionary types.

Title: Copy command - deep or shallow copy?

Body:
When I am copying the object with copy command in iOS (swift / objective c), Will that be a shallow copy or a deep copy ?

var str = "Hello, playground"
var copyStr = str.copy()

and

var originalArray = [1, 2, 3, 4] as NSArray
var copyArray = originalArray.copy()

withUnsafePointer(to: &originalArray) {
    print(" originall address: \($0)")
}

withUnsafePointer(to: &copyArray) {
    print(" copy address: \($0)")
}

Help me with the lines above , is this a deep copy or a shallow copy ?

The issue is , this behaviour in objective c is showing me the same
  address with both string and array which is shallow copy and in swift3
  it is showing me different address which is deep copy

Body:
The copy performs a shallow copy (a copy of the collection, but the objects in the array are not copied). E.g.

let obj1 = Object(value: 1)
let obj2 = Object(value: 2)
let obj3 = Object(value: 3)

let originalArray = [obj1, obj2, obj3] as NSArray
let copyArray = originalArray.copy() as! NSArray

print(String(format: "original address: %p", originalArray))

for obj in originalArray {
    print(String(format: "    %p", obj as! Object))
}

print(String(format: "copy address: %p", copyArray))

for obj in copyArray {
    print(String(format: "    %p", obj as! Object))
}

Note, I use an object other than NSNumber and NSString, as those have optimizations that may make looking at addresses misleading.

The member objects of these two arrays point to the same objects (i.e. a shallow copy).

original address: 0x618000044920
    0x6180000277e0
    0x618000027f00
    0x618000027ea0
copy address: 0x618000044920
    0x6180000277e0
    0x618000027f00
    0x618000027ea0

In fact, as you can see, because it's an immutable NSArray, it appears to optimize this where the copy is actually returning the same array instance. If you use mutable arrays, NSMutableArray, you'll see two unique arrays returned, as you'd expect, but they will still point to the same collection of objects.

But, if you use NSArray(array:copyItems:) with true for copyItems, you will get two unique arrays with unique copies of each member object:

let copyArray = NSArray(array: originalArray as! [Any], copyItems: true)

That yields a deep copy (two unique arrays where the individual member objects are copied and they, too, have unique addresses):

original address: 0x618000059e60
    0x618000027ae0
    0x618000028340
    0x618000028280
copy address: 0x61800005ba20
    0x618000028800
    0x618000028aa0
    0x618000028400

See the documentation for init(array:copyItems:) which says:

The copy(with:) method performs a shallow copy. If you have a collection of arbitrary depth, passing true for the flag parameter [of init(array:copyItems:)] will perform an immutable copy of the first level below the surface. If you pass false the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

Personally, though, if writing Swift, I'd generally use Array and Dictionary value types rather than the old NSArray and NSDictionary types.


问:
Overload custom comparator to std::map
I am trying to solve this problem. I came up with this solution:

```<code>typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    inline bool operator() (const string &a, const string &b) const {
      return stocksDict.at(a) < stocksDict.at(b);
    }
  };

  stockDictType stocksDict;

  map<string, stockDictType::iterator, Comparator> stocksTicker; // this is where I need a custom comparator method

  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  // some other methods
};
</code>```

As is evident, this fails to compile: StockTicker::stocksDict is not a static member. Now I can't make it so because I could require multiple instances of the StockTicker class.

std::map uses a strict comparator function parameter definition (std::map will only pass in the keys to be compared), so I can't overload it to pass a reference to the current instance of the StockTicker class (which I could've used to get access to StockTicker::stocksDict through public getters)

I took inspiration from this SO question and the subsequent answer to do this:

```<code>typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    stockDictType &_stockDictRef;

    explicit Comparator(stockDictType &stocksDict): _stockDictRef(stocksDict) {}

    inline bool operator() (const string &a, const string &b) const {
      return _stockDictRef.at(a) < _stockDictRef.at(b);
    }
  };

  stockDictType stocksDict;
  map<string, stockDictType::iterator, Comparator> stocksTicker(Comparator{stocksDict});
  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  void addOrUpdate(string name, double price) {
    stocksDict[name] = price;
    stocksTicker.at(name) = stocksDict.find(name);
  }

  vector<stockDictType::iterator> top() {
    vector<stockDictType::iterator> ret(tickerSize);

    auto it = stocksTicker.begin();
    for(int i = 0; i < tickerSize; i++, it++)
      ret[i] = it->second;

    return ret;
  }
};
</code>```

This won't compile either. I get this kind of error in the StockTicker::addOrUpdate() and StockTicker::top() methods:
error: '((StockTicker*)this)->StockTicker::stocksTicker' does not have class type.

I tried a bunch of other stuff too (like declaring a public comparator method in the StockTicker class itself and trying to pass a function pointer of it to std::map. That failed as well; StockTicker::stocksTicker gets declared before the comparator method does and the compiler complains).

Any ideas on how to go about fixing this?

答:
```<code> std::map<std::string, stockDictType::iterator, Comparator> stocksTicker(Comparator(stocksDict));
</code>```

this defines a member function named stocksTicker that takes a stocksDict argument of type Comparator and returns a std::map.

```<code>std::map<std::string, stockDictType::iterator, Comparator> stocksTicker{Comparator{stocksDict}};
</code>```

This defines a member variable stocksTicker which, by default, is initialized with a Comparator, which in turn was initialized with the member variable stocksDict.

I assume you want the second.

Your syntax was partway between the two.  Whatever compiler you had got confused by this.

Live example

You should StockTicker(StockTicker &&)=delete and StockTicker& operator=(StockTicker &&)=delete, as maps containing references to their containing class are not safe to move or copy.

Generating an efficient move here is tricky.  I suspect C++17 node splicing might make it possible to do it.  You might have to embed a std::shared_ptr<stocksDict*> (yes, a shared pointer to a pointer), and use .key_comp to reseat the stocksDict in the target.

Title: Overload custom comparator to std::map

Body:
I am trying to solve this problem. I came up with this solution:

typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    inline bool operator() (const string &a, const string &b) const {
      return stocksDict.at(a) < stocksDict.at(b);
    }
  };

  stockDictType stocksDict;

  map<string, stockDictType::iterator, Comparator> stocksTicker; // this is where I need a custom comparator method

  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  // some other methods
};

As is evident, this fails to compile: StockTicker::stocksDict is not a static member. Now I can't make it so because I could require multiple instances of the StockTicker class.

std::map uses a strict comparator function parameter definition (std::map will only pass in the keys to be compared), so I can't overload it to pass a reference to the current instance of the StockTicker class (which I could've used to get access to StockTicker::stocksDict through public getters)

I took inspiration from this SO question and the subsequent answer to do this:

typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    stockDictType &_stockDictRef;

    explicit Comparator(stockDictType &stocksDict): _stockDictRef(stocksDict) {}

    inline bool operator() (const string &a, const string &b) const {
      return _stockDictRef.at(a) < _stockDictRef.at(b);
    }
  };

  stockDictType stocksDict;
  map<string, stockDictType::iterator, Comparator> stocksTicker(Comparator{stocksDict});
  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  void addOrUpdate(string name, double price) {
    stocksDict[name] = price;
    stocksTicker.at(name) = stocksDict.find(name);
  }

  vector<stockDictType::iterator> top() {
    vector<stockDictType::iterator> ret(tickerSize);

    auto it = stocksTicker.begin();
    for(int i = 0; i < tickerSize; i++, it++)
      ret[i] = it->second;

    return ret;
  }
};

This won't compile either. I get this kind of error in the StockTicker::addOrUpdate() and StockTicker::top() methods:
error: '((StockTicker*)this)->StockTicker::stocksTicker' does not have class type.

I tried a bunch of other stuff too (like declaring a public comparator method in the StockTicker class itself and trying to pass a function pointer of it to std::map. That failed as well; StockTicker::stocksTicker gets declared before the comparator method does and the compiler complains).

Any ideas on how to go about fixing this?

Body:
 std::map<std::string, stockDictType::iterator, Comparator> stocksTicker(Comparator(stocksDict));

this defines a member function named stocksTicker that takes a stocksDict argument of type Comparator and returns a std::map.

std::map<std::string, stockDictType::iterator, Comparator> stocksTicker{Comparator{stocksDict}};

This defines a member variable stocksTicker which, by default, is initialized with a Comparator, which in turn was initialized with the member variable stocksDict.

I assume you want the second.

Your syntax was partway between the two.  Whatever compiler you had got confused by this.

Live example

You should StockTicker(StockTicker &&)=delete and StockTicker& operator=(StockTicker &&)=delete, as maps containing references to their containing class are not safe to move or copy.

Generating an efficient move here is tricky.  I suspect C++17 node splicing might make it possible to do it.  You might have to embed a std::shared_ptr<stocksDict*> (yes, a shared pointer to a pointer), and use .key_comp to reseat the stocksDict in the target.