问:
Manipulating reactive objects in Shiny - Error in <-: invalid (NULL) left side of assignment
I'm running into the error "Error in <-: invalid (NULL) left side of assignment" over and over again as I attempt to take a reactive object in Shiny and further manipulate it. I've provided an illustrative example below.

```<code> testdf <- data.frame(row1 = c(1,3,6), row2 = c(7, 5, 1))

 ui <- fluidPage(

   titlePanel("Education in Tanzania"),

   sidebarLayout(
     sidebarPanel(

       #Select aggregation level of data
       selectInput("AggregationSelect",
                   label = "Aggregation",
                   choices = list("School" = 1,
                                  "District" = 2,
                                  "Region" = 3),
                   selected = 1)
     ),

     mainPanel(
       DT::dataTableOutput("OutputTable")
     )
   )
 )

 server <- function(input, output) {

     Output1 <- reactive({
         testdf
     })

   observe({
     if(2 %in% input$AggregationSelect) {
       observe({Output1()$name[3] <- "b"})
     } else  if(3 %in% input$AggregationSelect) {
       observe({Output1()$name[2] <- "c"})
     } else  if(1 %in% input$AggregationSelect) {
       observe({Output1()$name[1] <- "a"})
     }
   })

   output$OutputTable <- {DT::renderDataTable({
     DT::datatable(Output1(),
                   options = list(pagelength = 25,
                                  searching = TRUE,
                                  paging = TRUE,
                                  lengthChange = FALSE),
                   rownames = FALSE)
     })
   }
 }

 shinyApp(ui = ui, server = server)
</code>```

What I need to do in my actual code is assemble a dataframe through the UI (which I am able to do and therefore have just subbed a random df in here) and then add some information (represented here with the added "names" column) based on what has been selected in the UI. It seems like it shouldn't be all that difficult to add a column to a df, but within the reactive object context, nothing I have attempted has worked. Other ways to modify reactive objects are welcome as long as they can be applied to more complex multi-step scenarios - there's no way I can get everything I need bundled into the initial assignment of the reactive object.

答:
As per my understanding of your problem, i've tweaked you code as following :

```<code>testdf <- data.frame(name = c(1,2,3), freq = c(100, 200, 300))

ui <- fluidPage(

titlePanel("Education in Tanzania"),

sidebarLayout(
sidebarPanel(

  #Select aggregation level of data
  selectInput("AggregationSelect",
              label = "Aggregation",
              choices = list("School" = 1,
                             "District" = 2,
                             "Region" = 3))
),

mainPanel(
  DT::dataTableOutput("OutputTable")
 )
))

server <- function(input, output) {

Output1 <- reactive({
input$AggregationSelect
selection <- input$AggregationSelect

if(2 %in% selection){
  testdf$name[3] <- "b"
}
else if(3 %in% selection){
  testdf$name[2] <- "c"
}
else if(1 %in% selection){
  testdf$name[1] <- "a"
}
testdf
})

output$OutputTable <- {DT::renderDataTable({
DT::datatable(Output1(),
              options = list(pagelength = 25,
                             searching = TRUE,
                             paging = TRUE,
                             lengthChange = FALSE),
              rownames = FALSE)
})
}}

shinyApp(ui = ui, server = server)
</code>```

Body:
I'm running into the error "Error in <-: invalid (NULL) left side of assignment" over and over again as I attempt to take a reactive object in Shiny and further manipulate it. I've provided an illustrative example below.

 testdf <- data.frame(row1 = c(1,3,6), row2 = c(7, 5, 1))

 ui <- fluidPage(

   titlePanel("Education in Tanzania"),

   sidebarLayout(
     sidebarPanel(

       #Select aggregation level of data
       selectInput("AggregationSelect",
                   label = "Aggregation",
                   choices = list("School" = 1,
                                  "District" = 2,
                                  "Region" = 3),
                   selected = 1)
     ),

     mainPanel(
       DT::dataTableOutput("OutputTable")
     )
   )
 )

 server <- function(input, output) {

     Output1 <- reactive({
         testdf
     })

   observe({
     if(2 %in% input$AggregationSelect) {
       observe({Output1()$name[3] <- "b"})
     } else  if(3 %in% input$AggregationSelect) {
       observe({Output1()$name[2] <- "c"})
     } else  if(1 %in% input$AggregationSelect) {
       observe({Output1()$name[1] <- "a"})
     }
   })

   output$OutputTable <- {DT::renderDataTable({
     DT::datatable(Output1(),
                   options = list(pagelength = 25,
                                  searching = TRUE,
                                  paging = TRUE,
                                  lengthChange = FALSE),
                   rownames = FALSE)
     })
   }
 }

 shinyApp(ui = ui, server = server)

What I need to do in my actual code is assemble a dataframe through the UI (which I am able to do and therefore have just subbed a random df in here) and then add some information (represented here with the added "names" column) based on what has been selected in the UI. It seems like it shouldn't be all that difficult to add a column to a df, but within the reactive object context, nothing I have attempted has worked. Other ways to modify reactive objects are welcome as long as they can be applied to more complex multi-step scenarios - there's no way I can get everything I need bundled into the initial assignment of the reactive object.

Body:
As per my understanding of your problem, i've tweaked you code as following :

testdf <- data.frame(name = c(1,2,3), freq = c(100, 200, 300))

ui <- fluidPage(

titlePanel("Education in Tanzania"),

sidebarLayout(
sidebarPanel(

  #Select aggregation level of data
  selectInput("AggregationSelect",
              label = "Aggregation",
              choices = list("School" = 1,
                             "District" = 2,
                             "Region" = 3))
),

mainPanel(
  DT::dataTableOutput("OutputTable")
 )
))

server <- function(input, output) {

Output1 <- reactive({
input$AggregationSelect
selection <- input$AggregationSelect

if(2 %in% selection){
  testdf$name[3] <- "b"
}
else if(3 %in% selection){
  testdf$name[2] <- "c"
}
else if(1 %in% selection){
  testdf$name[1] <- "a"
}
testdf
})

output$OutputTable <- {DT::renderDataTable({
DT::datatable(Output1(),
              options = list(pagelength = 25,
                             searching = TRUE,
                             paging = TRUE,
                             lengthChange = FALSE),
              rownames = FALSE)
})
}}

shinyApp(ui = ui, server = server)


来源: stackexchange

问:
acceleration-field for unity3D racing game, c#
for a motorcycle racing game I want some parts of the track to increase the speed of the motorcycle.

I have a public float for the speed, which shows the speed in the inspector.

I added a plane with a Collider, which is a trigger and has the tag "speedfield"
Now I thought, some simple code, attached to the motorcyclescript below, would do it:

```<code>void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        Speed = Speed + 50;
    }
}
</code>```

But nothing happens. I think I'm missing something obvious here. Hope you can help! Greetings from germany :)

```<code>void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;

    //Freezing rotation by Z axis.
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);

    //If crashed...
    if(!crashed){
        if(!changingGear)
            motorInput = Input.GetAxis("Vertical");
        else
            motorInput = Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
        steerInput = Input.GetAxis("Horizontal");
    }else{
        motorInput = 0;
        steerInput = 0;
    }

    //Reverse bool
    if(motorInput < 0  && transform.InverseTransformDirection(rigid.velocity).z < 0)
        reversing = true;
    else
        reversing = false;

}

void Engine (){

    //Steer Limit.
    SteerAngle = Mathf.Lerp(defsteerAngle, highSpeedSteerAngle, (Speed / highSpeedSteerAngleAtSpeed));
    FrontWheelCollider.steerAngle = SteerAngle * steerInput;

    //Engine RPM.
    EngineRPM = Mathf.Clamp((((Mathf.Abs((FrontWheelCollider.rpm + RearWheelCollider.rpm)) * gearShiftRate) + MinEngineRPM)) / (currentGear + 1), MinEngineRPM, MaxEngineRPM);

    // Applying Motor Torque.
    if(Speed > maxSpeed){
        RearWheelCollider.motorTorque = 0;
    }else if(!reversing && !changingGear){
        RearWheelCollider.motorTorque = EngineTorque  * Mathf.Clamp(motorInput, 0f, 1f) * engineTorqueCurve[currentGear].Evaluate(Speed);
    }

    if(reversing){
        if(Speed < 10){
            RearWheelCollider.motorTorque = (EngineTorque  * motorInput) / 5f;
        }else{
            RearWheelCollider.motorTorque = 0;
        }
    }

}
</code>```

答:
Make sure that all items in this checklist are satisfied:

The motorcycle has a Rigidbody component.

The plane doesn't have a Rigidbody component (it's useless and it could slow things down).

The Mesh Collider of the plane has Convex and isTrigger set to true.

The OnTriggerEnter method is in the motorcycle script.

The thickness of the plane trigger is wide enough: if the motorcycle speed is too high, it can pass thru the plane without the physics engine being able to register the trigger.

If this is the case, try to set the Collision Detection of the motorcycle Rigidbody to Continuous and/or decrease somewhat the Fixed Timestep in the Time project settings.

Most probably the problem is due to the last two bullet points.

ContentLicense: CC BY-SA 3.0

Body:
for a motorcycle racing game I want some parts of the track to increase the speed of the motorcycle.

I have a public float for the speed, which shows the speed in the inspector.

I added a plane with a Collider, which is a trigger and has the tag "speedfield"
Now I thought, some simple code, attached to the motorcyclescript below, would do it:

void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        Speed = Speed + 50;
    }
}

But nothing happens. I think I'm missing something obvious here. Hope you can help! Greetings from germany :)

void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;

    //Freezing rotation by Z axis.
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);

    //If crashed...
    if(!crashed){
        if(!changingGear)
            motorInput = Input.GetAxis("Vertical");
        else
            motorInput = Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
        steerInput = Input.GetAxis("Horizontal");
    }else{
        motorInput = 0;
        steerInput = 0;
    }

    //Reverse bool
    if(motorInput < 0  && transform.InverseTransformDirection(rigid.velocity).z < 0)
        reversing = true;
    else
        reversing = false;

}

void Engine (){

    //Steer Limit.
    SteerAngle = Mathf.Lerp(defsteerAngle, highSpeedSteerAngle, (Speed / highSpeedSteerAngleAtSpeed));
    FrontWheelCollider.steerAngle = SteerAngle * steerInput;

    //Engine RPM.
    EngineRPM = Mathf.Clamp((((Mathf.Abs((FrontWheelCollider.rpm + RearWheelCollider.rpm)) * gearShiftRate) + MinEngineRPM)) / (currentGear + 1), MinEngineRPM, MaxEngineRPM);

    // Applying Motor Torque.
    if(Speed > maxSpeed){
        RearWheelCollider.motorTorque = 0;
    }else if(!reversing && !changingGear){
        RearWheelCollider.motorTorque = EngineTorque  * Mathf.Clamp(motorInput, 0f, 1f) * engineTorqueCurve[currentGear].Evaluate(Speed);
    }

    if(reversing){
        if(Speed < 10){
            RearWheelCollider.motorTorque = (EngineTorque  * motorInput) / 5f;
        }else{
            RearWheelCollider.motorTorque = 0;
        }
    }

}


问:
Angular2,Typescript:How to insert a key:value pair at a PARTICULAR index in an array?
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

```<code>  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}
</code>```

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.

答:
If you want to simply replace the existing element at an specific index:

```<code>this.quiz[index] = {
  "question-no":this.no,
  "Ans":this.ans
};
</code>```

E.g.:

```<code>this.quiz[4] = {
  "question-no":this.no,
  "Ans":this.ans
};
</code>```

Note that whatever was at index 4 will be gone.

Body:
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.

Body:
If you want to simply replace the existing element at an specific index:

this.quiz[index] = {
  "question-no":this.no,
  "Ans":this.ans
};

E.g.:

this.quiz[4] = {
  "question-no":this.no,
  "Ans":this.ans
};

Note that whatever was at index 4 will be gone.


问:
How can I prevent implicit conversions in a function template?
How can I define a function template to prevent implicit conversions?

It seems I can prevent implicit conversions using non-template functions but not using function templates.

Defining a forwarding reference function template as = delete is too aggressive as it prevents invocation with non-const lvalue references.

Defining an function template with a const rvalue argument as =delete [1]
does not prevent implicit conversions.

Defining an rvalue overload for a specific type as =delete works but I'd like to accomplish this with templates.

Minimal code example:

```<code>struct A {};

struct B {
  B() = default;

  B(const A&) {}
};

// Delete const rvalue reference.
template <class T>
void t_no_rvalue(const T&&) = delete; // 1

void t_no_rvalue(const B&) {}         // 2

// Delete forwarding reference.
template <class T>
void t_no_fwd_ref(T&&) = delete;     // 3

void t_no_fwd_ref(const B&) {}       // 4

// (non-template) Delete const rvalue reference.
void no_rvalue(const B&&) = delete;  // 5

void no_rvalue(const B&) {}          // 6

int main(int argc, char* argv[]) {
  A a;
  B b;

  // Undesired behaviour, implicit conversion allowed.
  t_no_rvalue(a);   // resolves to 2
  t_no_rvalue(b);   // resolves to 2

  // Undesired behaviour, invocation with non-const reference disallowed.
  t_no_fwd_ref(a);  // resolves to 3
  t_no_fwd_ref(b);  // resolves to 3

  // Desired behaviour.
  no_rvalue(a);     // resolves to 5
  no_rvalue(b);     // resolves to 6
}
</code>```

My real-world use case is hashing of variants where implicit conversion of a variant sub-type back to the variant-like type will cause infinite recursion if the hash function is not specialized for all the variant constituents. The sample code above is clearer though.

[1] Attempted in Why can I prevent implicit conversions for primitives but not user-defined types? but with a broken code example.

答:
The following overload will prevent implicit conversions:

```<code>template <class T>
void no_conversions(T) = delete; // 7

void no_conversions(const B&) {} // 8
</code>```

and leads to:

```<code>// Requested behaviour.
no_conversions(a); // resolves to 7
no_conversions(b); // resolves to 8
</code>```

A value-overload poisons the overload set for implicit conversions as it will be an exact match.

Edit:

```<code>template <class T>
void no_conversions(const T&) = delete; // 9

void no_conversions(const B&) {}        // 10
</code>```

works just as well.

Body:
How can I define a function template to prevent implicit conversions?

It seems I can prevent implicit conversions using non-template functions but not using function templates.

Defining a forwarding reference function template as = delete is too aggressive as it prevents invocation with non-const lvalue references.

Defining an function template with a const rvalue argument as =delete [1]
does not prevent implicit conversions.

Defining an rvalue overload for a specific type as =delete works but I'd like to accomplish this with templates.

Minimal code example:

struct A {};

struct B {
  B() = default;

  B(const A&) {}
};

// Delete const rvalue reference.
template <class T>
void t_no_rvalue(const T&&) = delete; // 1

void t_no_rvalue(const B&) {}         // 2

// Delete forwarding reference.
template <class T>
void t_no_fwd_ref(T&&) = delete;     // 3

void t_no_fwd_ref(const B&) {}       // 4

// (non-template) Delete const rvalue reference.
void no_rvalue(const B&&) = delete;  // 5

void no_rvalue(const B&) {}          // 6

int main(int argc, char* argv[]) {
  A a;
  B b;

  // Undesired behaviour, implicit conversion allowed.
  t_no_rvalue(a);   // resolves to 2
  t_no_rvalue(b);   // resolves to 2

  // Undesired behaviour, invocation with non-const reference disallowed.
  t_no_fwd_ref(a);  // resolves to 3
  t_no_fwd_ref(b);  // resolves to 3

  // Desired behaviour.
  no_rvalue(a);     // resolves to 5
  no_rvalue(b);     // resolves to 6
}

My real-world use case is hashing of variants where implicit conversion of a variant sub-type back to the variant-like type will cause infinite recursion if the hash function is not specialized for all the variant constituents. The sample code above is clearer though.

[1] Attempted in Why can I prevent implicit conversions for primitives but not user-defined types? but with a broken code example.

Body:
The following overload will prevent implicit conversions:

template <class T>
void no_conversions(T) = delete; // 7

void no_conversions(const B&) {} // 8

and leads to:

// Requested behaviour.
no_conversions(a); // resolves to 7
no_conversions(b); // resolves to 8

A value-overload poisons the overload set for implicit conversions as it will be an exact match.

Edit:

template <class T>
void no_conversions(const T&) = delete; // 9

void no_conversions(const B&) {}        // 10

works just as well.


问:
How to load binary data into a script or other HTML tag
I have the need to load binary data, say a ZIP file for example, into a webpage, but it cannot be loaded with AJAX due to the cross-domain policy. Can it be loaded into a script/img/link tag for example somehow?

How would I get access to that raw data to make a blob URL for example?

答:
You could just change the policy.

However since it would be rather difficult to do anything useful with a zip file in javascript, I presume you want the facility to download the target data. So just insert an iframe pointing to the resource.


问:
elasticsearch with angularjs no matter what I search, it always hits all data in the database
Question about Querys in AngularJs with Elasticsearch.
If I just use Kibana, the result of this will be 10 hits, which is make sense.

```<code>POST /_search
{
  "query": {
    "match": {
      "fieldname": "Obama"
    }
  }
}
</code>```

If I use q parameter like the official APIs describe:enter image description here
I will also get the answer by using

```<code>newsApp.controller('searchCtrl', function ($scope, client) {
    $scope.searchFunc = function(){
      client.search({
            q: "fildname: Obama""
      });
});
</code>```

It will also be fine.
But when I need more:

```<code>newsApp.controller('searchCtrl', function ($scope, client) {
        $scope.searchFunc = function(){
          //I have tried this:
          client.search({
               "query": {"match": {"fieldname" : "Obama"}}
          });

          //I have tried this:
          client.search(
          {
            body: {
              query: {
                match: {
                  fildname: "Obama"
                }
              }
            }
         });
});
</code>```

Then I could only get Nothing. So I don't know what kind of query I could really use??

enter image description here

答:
Try to add index and use the same the query format. see logs in callback function</p>

```<code>client.search({
  index: 'myindex',
  q: 'title:test'
}, function (error, response) {
  // ...
});
</code>```

Body:
Question about Querys in AngularJs with Elasticsearch.
If I just use Kibana, the result of this will be 10 hits, which is make sense.

POST /_search
{
  "query": {
    "match": {
      "fieldname": "Obama"
    }
  }
}

If I use q parameter like the official APIs describe:enter image description here
I will also get the answer by using

newsApp.controller('searchCtrl', function ($scope, client) {
    $scope.searchFunc = function(){
      client.search({
            q: "fildname: Obama""
      });
});

It will also be fine.
But when I need more:

newsApp.controller('searchCtrl', function ($scope, client) {
        $scope.searchFunc = function(){
          //I have tried this:
          client.search({
               "query": {"match": {"fieldname" : "Obama"}}
          });

          //I have tried this:
          client.search(
          {
            body: {
              query: {
                match: {
                  fildname: "Obama"
                }
              }
            }
         });
});

Then I could only get Nothing. So I don't know what kind of query I could really use??

enter image description here

Body:
Try to add index and use the same the query format. see logs in callback function

client.search({
  index: 'myindex',
  q: 'title:test'
}, function (error, response) {
  // ...
});


问:
How to change AM/PM Symbol to my own alphabet when using Java 8 date time API
We have an application where we accept the datetime format from the customer.

We recently started migrating to Java 8 new date time API's because they are thread safe. Look at the below code you can see before preparing the formatter we are setting A and P to be considered as AM & PM Strings. We get the formatter from customer & we simply apply the below logic to display the date time.

```<code>String[] AMPM = new String[2];
AMPM[0] = "A";
AMPM[1] = "P";
DateFormatSymbols dfs = new DateFormatSymbols(locale);
dfs.setAmPmStrings(AMPM);
sdf = new SimpleDateFormat(format, dfs);
</code>```

But with new Java 8 date time API I nowhere see how to define this. But after some googling I can see we have to use DateTimeFormatterBuilder but this is only useful if I am building the pattern myself; here we are receiving the full date time pattern from customer.

Any pointers on how to do this using Java 8.

答:
You can use DateTimeFormatterBuilder.appendText() method that takes a map with custom values.

According to javadoc, the field AMPM_OF_DAY can have the value 0 for AM and 1 for PM, so you just create a map with these values and pass it to the formatter:

```<code>import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.LocalTime;

// create map with custom values (0=AM, 1=PM, mapping to values "A" and "P")
Map<Long, String> map = new HashMap<>();
map.put(0L, "A"); // AM mapped to "A"
map.put(1L, "P"); // PM mapped to "P"

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // hour/minute/second (change to whatever pattern you need)
    .appendPattern("hh:mm:ss ")
    // use the mapped values
    .appendText(ChronoField.AMPM_OF_DAY, map)
    // create formatter
    .toFormatter();

// testing
System.out.println(formatter.format(LocalTime.of(10, 30, 45))); // 10:30:45 A
System.out.println(formatter.format(LocalTime.of(22, 30, 45))); // 10:30:45 P
</code>```

The output will be:

10:30:45 A

  10:30:45 P

And it also works to parse a String:

```<code>System.out.println(LocalTime.parse("10:20:30 A", formatter)); // 10:20:30
System.out.println(LocalTime.parse("10:20:30 P", formatter)); // 22:20:30
</code>```

The output will be:

10:20:30

  22:20:30

If you don't control the pattern, you can look for a letter a (the pattern corresponding to the AM/PM field) and replace it by the custom version.

One alternative is to split the format String, using a as the delimiter, then you don't lose the rest of the pattern:

```<code>// format with day/month/year hour:minute:second am/pm timezone
String format = "dd/MM/yyyy hh:mm:ss a z";

// split the format ("a" is the AM/PM field)
String[] formats = format.split("a");

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
    // first part of the pattern (everything before "a")
    .appendPattern(formats[0])
    // use the AM/PM mapped values
    .appendText(ChronoField.AMPM_OF_DAY, map);

// if there's something after the "a", add it
if (formats.length > 1) {
    builder.appendPattern(formats[1]);
}

// create formatter
DateTimeFormatter formatter = builder.toFormatter();

//test
ZonedDateTime z = ZonedDateTime.of(2017, 5, 1, 10, 20, 30, 0, ZoneId.of("America/Sao_Paulo"));
// AM replaced by "A"
System.out.println(formatter.format(z)); // 01/05/2017 10:20:30 A BRT
</code>```

This algorithm also works if the a is in the beginning or end, or even if there's no a (in this case, I'm adding in the end, I'm not sure if it must be added if not present).

```<code>// "a" in the end
String format = "hh:mm:ss a";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // 03:30:00 P

// "a" in the beginning
String format = "a hh:mm:ss";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // P 03:30:00

// no "a" (field is added in the end)
String format = "HH:mm:ss";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // 03:30:00P
</code>```

You can make some improvements, like if the format doesn't contain a, then don't add it (or add with a space before it), or whatever you want.

PS: this code doesn't handle literals (text inside ') like "dd/MM/yyyy 'at' hh:mm:ss a" (the "at" is a literal and shouldn't be removed/replaced).

I'm not a regex expert (so I'm not 100% sure if it works for all cases), but you can do something like this:

```<code>String[] formats = format.split("(?<!\'[^\']{0,20})a|a(?![^\']{0,20}\')");
</code>```

This regex will ignore a inside quoted text. I have to use {0,20} quantifier because lookahead and lookbehinds (the (? patterns) don't accept *, so this will work if the quoted text before or after the "a" has at most 20 characters (just change this value to what you think it fits best your use cases).

Some tests:

```<code>String format = "\'Time: at\' hh:mm:ss a";
DateTimeFormatter formatter = // use same code above, but with the modified regex split
System.out.println(formatter.format(LocalTime.of(15, 30))); // Time: at 03:30:00 P

String format = "dd/MM/yyyy \'at\' hh:mm:ss a z";
DateTimeFormatter formatter = // use same code above, but with the modified regex split
ZonedDateTime z = ZonedDateTime.of(2017, 5, 1, 10, 20, 30, 0, ZoneId.of("America/Sao_Paulo"));
System.out.println(formatter.format(z)); // 01/05/2017 at 10:20:30 A BRT
</code>```

Body:
We have an application where we accept the datetime format from the customer.

We recently started migrating to Java 8 new date time API's because they are thread safe. Look at the below code you can see before preparing the formatter we are setting A and P to be considered as AM & PM Strings. We get the formatter from customer & we simply apply the below logic to display the date time.

String[] AMPM = new String[2];
AMPM[0] = "A";
AMPM[1] = "P";
DateFormatSymbols dfs = new DateFormatSymbols(locale);
dfs.setAmPmStrings(AMPM);
sdf = new SimpleDateFormat(format, dfs);

But with new Java 8 date time API I nowhere see how to define this. But after some googling I can see we have to use DateTimeFormatterBuilder but this is only useful if I am building the pattern myself; here we are receiving the full date time pattern from customer.

Any pointers on how to do this using Java 8.

Body:
You can use DateTimeFormatterBuilder.appendText() method that takes a map with custom values.

According to javadoc, the field AMPM_OF_DAY can have the value 0 for AM and 1 for PM, so you just create a map with these values and pass it to the formatter:

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.LocalTime;

// create map with custom values (0=AM, 1=PM, mapping to values "A" and "P")
Map<Long, String> map = new HashMap<>();
map.put(0L, "A"); // AM mapped to "A"
map.put(1L, "P"); // PM mapped to "P"

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // hour/minute/second (change to whatever pattern you need)
    .appendPattern("hh:mm:ss ")
    // use the mapped values
    .appendText(ChronoField.AMPM_OF_DAY, map)
    // create formatter
    .toFormatter();

// testing
System.out.println(formatter.format(LocalTime.of(10, 30, 45))); // 10:30:45 A
System.out.println(formatter.format(LocalTime.of(22, 30, 45))); // 10:30:45 P

The output will be:

10:30:45 A

  10:30:45 P

And it also works to parse a String:

System.out.println(LocalTime.parse("10:20:30 A", formatter)); // 10:20:30
System.out.println(LocalTime.parse("10:20:30 P", formatter)); // 22:20:30

The output will be:

10:20:30

  22:20:30

If you don't control the pattern, you can look for a letter a (the pattern corresponding to the AM/PM field) and replace it by the custom version.

One alternative is to split the format String, using a as the delimiter, then you don't lose the rest of the pattern:

// format with day/month/year hour:minute:second am/pm timezone
String format = "dd/MM/yyyy hh:mm:ss a z";

// split the format ("a" is the AM/PM field)
String[] formats = format.split("a");

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
    // first part of the pattern (everything before "a")
    .appendPattern(formats[0])
    // use the AM/PM mapped values
    .appendText(ChronoField.AMPM_OF_DAY, map);

// if there's something after the "a", add it
if (formats.length > 1) {
    builder.appendPattern(formats[1]);
}

// create formatter
DateTimeFormatter formatter = builder.toFormatter();

//test
ZonedDateTime z = ZonedDateTime.of(2017, 5, 1, 10, 20, 30, 0, ZoneId.of("America/Sao_Paulo"));
// AM replaced by "A"
System.out.println(formatter.format(z)); // 01/05/2017 10:20:30 A BRT

This algorithm also works if the a is in the beginning or end, or even if there's no a (in this case, I'm adding in the end, I'm not sure if it must be added if not present).

// "a" in the end
String format = "hh:mm:ss a";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // 03:30:00 P

// "a" in the beginning
String format = "a hh:mm:ss";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // P 03:30:00

// no "a" (field is added in the end)
String format = "HH:mm:ss";
DateTimeFormatter formatter = // use same code above
System.out.println(formatter.format(LocalTime.of(15, 30))); // 03:30:00P

You can make some improvements, like if the format doesn't contain a, then don't add it (or add with a space before it), or whatever you want.

PS: this code doesn't handle literals (text inside ') like "dd/MM/yyyy 'at' hh:mm:ss a" (the "at" is a literal and shouldn't be removed/replaced).

I'm not a regex expert (so I'm not 100% sure if it works for all cases), but you can do something like this:

String[] formats = format.split("(?<!\'[^\']{0,20})a|a(?![^\']{0,20}\')");

This regex will ignore a inside quoted text. I have to use {0,20} quantifier because lookahead and lookbehinds (the (? patterns) don't accept *, so this will work if the quoted text before or after the "a" has at most 20 characters (just change this value to what you think it fits best your use cases).

Some tests:

String format = "\'Time: at\' hh:mm:ss a";
DateTimeFormatter formatter = // use same code above, but with the modified regex split
System.out.println(formatter.format(LocalTime.of(15, 30))); // Time: at 03:30:00 P

String format = "dd/MM/yyyy \'at\' hh:mm:ss a z";
DateTimeFormatter formatter = // use same code above, but with the modified regex split
ZonedDateTime z = ZonedDateTime.of(2017, 5, 1, 10, 20, 30, 0, ZoneId.of("America/Sao_Paulo"));
System.out.println(formatter.format(z)); // 01/05/2017 at 10:20:30 A BRT


问:
Recognizing multiple objects in an image with convolutional neural networks
I've seen quite a few CNN code examples for ID'ing images, but they generally relate to a 1-to-1 input to target relationship (like the MNISt handwritten numerals set), and most seem to use similar image dimensions (pixels) for the input image and training images.

So...what is the usual approach for identifying multiple objects in one image?  (like several people, or any other relatively complex scene).  I've seen it done often enough, but haven't seen design approaches mentioned.  Does this require some type of preprocessing or can this be handled directly by a CNN?

答:
I would say the most known family of techniques to retrieve multiple objects from an images would be the Detection family.

With Detection, the basic idea is to have one or more Proposal windows of different sizes and ratios within an image, generated with either a calculated or random array of algorithms.

For each Proposal window, the Classification algorithm is then executed to reveal what that specific area of the image represents.

The next step would usually be to run a Merge process to combine all neighbouring areas into one single classification output.

Note: A None class is often also used to represent an area with no specific class found.


问:
Android: Task sequential on a thread in JAVA
Have use case where BroadcastReceiver action events received and need execute them in sequential order.

Here as below Event1 and Event2 can be received back to back. Event1 work has to be completed and then Event2 work should be started.

How to make it sequential?

```<code>BroadcastReceiver{

onReceive(){

Event1:
Task1 doing Something different.//Cant run network operations here.

Event2:
Task2 doing Something different.//Cant run network operations here.

}

}
</code>```

executors.newsinglethreadexecutor() or handlerthread is are option i am looking at..any other good way of doing this?

答: Found that executors.newsinglethreadexecutor() or handlerthread both can handle the task sequential..</p>

Body:
Have use case where BroadcastReceiver action events received and need execute them in sequential order.

Here as below Event1 and Event2 can be received back to back. Event1 work has to be completed and then Event2 work should be started.

How to make it sequential?

BroadcastReceiver{

onReceive(){

Event1:
Task1 doing Something different.//Cant run network operations here.

Event2:
Task2 doing Something different.//Cant run network operations here.

}

}

executors.newsinglethreadexecutor() or handlerthread is are option i am looking at..any other good way of doing this?


问:
Center Input box and Font Awesome icons
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

```<code><div>
    <i class='icon icon-3x icon-camera'></i>
    <span id="inputfield">
      <input type="text" value="input here">
    </span>
</div>

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}
</code>```

答:
A(nother) flexbox solution

* {
  box-sizing: border-box;
}

#inputfield {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 0;
}

#inputfield::before {
  font-family: FontAwesome;
  font-size: 48px;
  content: "\f030";
  margin: 0 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div>
  <div id="inputfield">
    <input type="text" value="input here">
  </div>
</div></code>```

Title: Center Input box and Font Awesome icons

Body:
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

      <input type="text" value="input here">

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}

Body:
A(nother) flexbox solution

* {
  box-sizing: border-box;
}

#inputfield {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 0;
}

#inputfield::before {
  font-family: FontAwesome;
  font-size: 48px;
  content: "\f030";
  margin: 0 5px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div>
  <div id="inputfield">
    <input type="text" value="input here">
  </div>
</div>


问:
Issue using Zend Framework on NetBeans
I am learning about Zend Framework, I want to use NetBeans to start, but when I try to do this on NB: Tools -> Options -> PHP -> Zend -> Click on 'Register Provider' the next error appear on output window:

```<code>PHP Warning:  include_once(NetBeansCommandsProvider.php): failed to open stream: No such file or directory in /usr/share/php/libzend-framework-php/Zend/Loader.php on line 146
PHP Warning:  include_once(): Failed opening 'NetBeansCommandsProvider.php' for inclusion (include_path='/usr/share/php/libzend-framework-php:/usr/share/php/libzend-framework-php:.:/usr/share/php:/usr/share/pear') in /usr/share/php/libzend-framework-php/Zend/Loader.php on line 146
</code>```

What can I do to resolve that problem?

答:
I could go one step further by adding the right path for NetBeansCommandsProvider.php.
Just replace the .zf.ini content with:

```<code>php.include_path = "/usr/share/php/libzend-framework-php:.:/usr/share/php:/usr/share/pear:/home/username/.netbeans/6.9/zend/"
</code>```

and replace username with your username.

Title: Issue using Zend Framework on NetBeans

Body:
I am learning about Zend Framework, I want to use NetBeans to start, but when I try to do this on NB: Tools -> Options -> PHP -> Zend -> Click on 'Register Provider' the next error appear on output window:

PHP Warning:  include_once(NetBeansCommandsProvider.php): failed to open stream: No such file or directory in /usr/share/php/libzend-framework-php/Zend/Loader.php on line 146
PHP Warning:  include_once(): Failed opening 'NetBeansCommandsProvider.php' for inclusion (include_path='/usr/share/php/libzend-framework-php:/usr/share/php/libzend-framework-php:.:/usr/share/php:/usr/share/pear') in /usr/share/php/libzend-framework-php/Zend/Loader.php on line 146

What can I do to resolve that problem?

Body:
I could go one step further by adding the right path for NetBeansCommandsProvider.php.
Just replace the .zf.ini content with:

php.include_path = "/usr/share/php/libzend-framework-php:.:/usr/share/php:/usr/share/pear:/home/username/.netbeans/6.9/zend/"

and replace username with your username.

ContentLicense: CC BY-SA 2.5


问:
Cannot read file within jar file
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

```<code>public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }
</code>```

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?

答:
Use http://jd.benow.ca/ Jd GUI drop your jar file there and

check is the file is there in the jar

If Yes then see the path/folder structure where it is placed.

If Yes folder exists Access the File using "/<path>/myFile.csv"

ContentLicense: CC BY-SA 4.0

Title: Cannot read file within jar file

Body:
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?


问:
multiline text to hash to YAML conversion produces last line
1) I am trying to read strings from data.txt

```<code>Christopher Plummer;Dec 13, 1927
Christopher Walken;Mar 31, 1943
The King of Spain;Jan  5, 1938
</code>```

2) split all strings at ';' and convert them to hash

3) hash to YAML

4) write YAML to file

problem: writing YAML to file produces only the last line

```<code>data = Hash.new
require 'yaml'
filename = 'Ydata.txt'

File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
end

File.open filename, 'w' do |f|
   f.write data
end
</code>```

答:
This line is setting data to be the last value converted to yaml.  So it's completely replaced every loop.

```<code>data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
</code>```

Better would be...

```<code>data = {}
File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data[line[0]] = line[1]
end

File.open filename, 'w' do |f|
   f.write data.to_yaml
end
</code>```

Alternatively, if you want to write out each item individually to the filename file, you can open the output file and do the File.read in a loop within the output file block...

```<code>File.open filename, 'w' do |f|
  File.read('Data.txt').each_line do |line|
    line = line.chomp
    line = line.split ';'
    data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
    f.write data.to_yml
  end
end
</code>```

Body:
1) I am trying to read strings from data.txt

Christopher Plummer;Dec 13, 1927
Christopher Walken;Mar 31, 1943
The King of Spain;Jan  5, 1938

2) split all strings at ';' and convert them to hash

3) hash to YAML

4) write YAML to file

problem: writing YAML to file produces only the last line

data = Hash.new
require 'yaml'
filename = 'Ydata.txt'

File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
end

File.open filename, 'w' do |f|
   f.write data
end

Body:
This line is setting data to be the last value converted to yaml.  So it's completely replaced every loop.

data = { "#{line[0]}" => "#{line[1]}" }.to_yaml

Better would be...

data = {}
File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data[line[0]] = line[1]
end

File.open filename, 'w' do |f|
   f.write data.to_yaml
end

Alternatively, if you want to write out each item individually to the filename file, you can open the output file and do the File.read in a loop within the output file block...

File.open filename, 'w' do |f|
  File.read('Data.txt').each_line do |line|
    line = line.chomp
    line = line.split ';'
    data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
    f.write data.to_yml
  end
end


问:
how to remove stopwords from a text in pre processing of spark
I have a requirement to pre process the data in the spark before running the algorithms
One of the pre processing logic was to remove the stopwords from the text. I tried with spark StopWordsRemover.  StopWordsRemover requires input and output should be Array[String]. After running the program the final column output is shown as collection of strings, i would require a plain string.

My code as follows.

```<code>val tokenizer: RegexTokenizer = new RegexTokenizer().setInputCol("raw").setOutputCol("token")
val stopWordsRemover = new StopWordsRemover().setInputCol("token").setOutputCol("final")
stopWordsRemover.setStopWords(stopWordsRemover.getStopWords ++ customizedStopWords)
val tokenized: DataFrame = tokenizer.transform(hiveDF)
val transformDF = stopWordsRemover.transform(tokenized)
</code>```

Actual Output

```<code>["rt messy support need help with bill"]
</code>```

Required Output:

```<code>rt messy support need help with bill
</code>```

My output should be like a string but not as array of string. Is there any way to do this. I require the output of the column in the dataframe as string.

Also I would need suggestion on the below options to remove stopwords from the text in the spark program.

StopWordsRemover from SparkMlib

Standford CoreNLP Library.

Which of the option gives better performance when parsing huge files.

Any help appreciated.

Thanks in advance.

答:
You may use this to get string instead of array-of-strings - df.collect()[0] - if you are sure only first item is in your interest.

However, that should not be any issue here as long as you traverse the array and get each items there.

Ultimately HiveDF will give you RDD[String] - and it becomes Array[String] when you convert from RDD.

Body:
I have a requirement to pre process the data in the spark before running the algorithms
One of the pre processing logic was to remove the stopwords from the text. I tried with spark StopWordsRemover.  StopWordsRemover requires input and output should be Array[String]. After running the program the final column output is shown as collection of strings, i would require a plain string.

My code as follows.

val tokenizer: RegexTokenizer = new RegexTokenizer().setInputCol("raw").setOutputCol("token")
val stopWordsRemover = new StopWordsRemover().setInputCol("token").setOutputCol("final")
stopWordsRemover.setStopWords(stopWordsRemover.getStopWords ++ customizedStopWords)
val tokenized: DataFrame = tokenizer.transform(hiveDF)
val transformDF = stopWordsRemover.transform(tokenized)

Actual Output

["rt messy support need help with bill"]

Required Output:

rt messy support need help with bill

My output should be like a string but not as array of string. Is there any way to do this. I require the output of the column in the dataframe as string.

Also I would need suggestion on the below options to remove stopwords from the text in the spark program.

StopWordsRemover from SparkMlib

Standford CoreNLP Library.

Which of the option gives better performance when parsing huge files.

Any help appreciated.

Thanks in advance.


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
It seems to me that the question calls for a query that would return best, and second best in the same row for each month and year, like so:

```<code>month, year, best, second best
...
...
</code>```

and not two rows for the same month and year containing best and second best value.

This is the solution that I came up with, so if anyone has a simpler way of achieving this, I would like to know.

```<code>with ranks as (
    select
        year(entrydate) as [year],
        month(entrydate) as [month],
        views,
        rank() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
    from product
)
select
    t1.year,
    t1.month,
    t1.views as [best],
    t2.views as [second best]
from ranks t1
    inner join ranks t2
        on t1.year = t2.year
        and t1.month = t2.month
        and t1.rank = 1
        and t2.rank = 2
</code>```

EDIT: Just out of curiosity I did a bit more testing and ended up with a simpler variation on the Stephanie Page's answer that doesn't use an aditional subquery. And I changed the rank() function to row_number() as it doesn't work when two max values are the same.

```<code>with ranks as (
    select
        year(entrydate) as [year],
        month(entrydate) as [month],
        views,
        row_number() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
    from product
)
select
    t1.year,
    t1.month,
    max(case when t1.rank = 1 then t1.views else 0 end) as [best],
    max(case when t1.rank = 2 then t1.views else 0 end) as [second best]
from
    ranks t1
where
    t1.rank in (1,2)
group by
    t1.year, t1.month
</code>```

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

Body:
It seems to me that the question calls for a query that would return best, and second best in the same row for each month and year, like so:

month, year, best, second best
...
...

and not two rows for the same month and year containing best and second best value.

This is the solution that I came up with, so if anyone has a simpler way of achieving this, I would like to know.

with ranks as (
    select
        year(entrydate) as [year],
        month(entrydate) as [month],
        views,
        rank() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
    from product
)
select
    t1.year,
    t1.month,
    t1.views as [best],
    t2.views as [second best]
from ranks t1
    inner join ranks t2
        on t1.year = t2.year
        and t1.month = t2.month
        and t1.rank = 1
        and t2.rank = 2

EDIT: Just out of curiosity I did a bit more testing and ended up with a simpler variation on the Stephanie Page's answer that doesn't use an aditional subquery. And I changed the rank() function to row_number() as it doesn't work when two max values are the same.

with ranks as (
    select
        year(entrydate) as [year],
        month(entrydate) as [month],
        views,
        row_number() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
    from product
)
select
    t1.year,
    t1.month,
    max(case when t1.rank = 1 then t1.views else 0 end) as [best],
    max(case when t1.rank = 2 then t1.views else 0 end) as [second best]
from
    ranks t1
where
    t1.rank in (1,2)
group by
    t1.year, t1.month


问:
Google Analytics sends tracking to a country domain, so it gets blocked by CSP
I embed analytics like this:

```<code><script type="text/javascript" async="" src="http://www.google-analytics.com/plugins/ua/linkid.js"></script>
</code>```

Then I added some google domains to CSP like this:

```<code>BrowserPolicy.content.allowScriptOrigin("*.google-analytics.com");
BrowserPolicy.content.allowImageOrigin("*.google.com");
</code>```

This loads fine, however as soon as Analytics tries to send some tracking info, it sometimes tries to load image from google.pl (based on location). Is there any way to make sure that only .com is used? I obviously can't list all google domains in CSP headers.

The exact error is:

Refused to load the image 'https://www.google.pl/blabla' because it
  violates the following Content Security Policy directive: "img-src
  data: 'self' http://*.doubleclick.net https://*.doubleclick.net
  http://*.facebook.com https://*.facebook.com http://*.google.com
  https://*.google.com http://www.google-analytics.com
  https://www.google-analytics.com".

If it is of importance, frameworks used here are: Meteor 1.3.5.1, and browser policy package browser-policy@1.0.9

答: One solution is to use Geo IP to try to guess the domain. You could probably always include .com and the country domain dynamically, but I doubt this is a reliable solution.</p>

Body:
I embed analytics like this:

Then I added some google domains to CSP like this:

BrowserPolicy.content.allowScriptOrigin("*.google-analytics.com");
BrowserPolicy.content.allowImageOrigin("*.google.com");

This loads fine, however as soon as Analytics tries to send some tracking info, it sometimes tries to load image from google.pl (based on location). Is there any way to make sure that only .com is used? I obviously can't list all google domains in CSP headers.

The exact error is:

Refused to load the image 'https://www.google.pl/blabla' because it
  violates the following Content Security Policy directive: "img-src
  data: 'self' http://*.doubleclick.net https://*.doubleclick.net
  http://*.facebook.com https://*.facebook.com http://*.google.com
  https://*.google.com http://www.google-analytics.com
  https://www.google-analytics.com".

If it is of importance, frameworks used here are: Meteor 1.3.5.1, and browser policy package browser-policy@1.0.9


问:
Java_why print member variable give actual value?
```<code>class Customer {
    public String name;

    public Customer(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Customer c = new Customer("Sally");
        System.out.println(c);
        System.out.println(c.name);
    }
}
</code>```

It's a simple question and we all know the output, but there's one quesiton about it

Please see the code above and the Picture here Passing Value

Question:

if I print out a reference of a object like this: System.out.println(c);, the IDE would generate a memory address for me: Customer@60e53b93

But, in the video tutorial(screenshot, see the image link Passing Value)

, the object have a member variable which is a reference to a String -> "Sally", why when I do System.out.println(c.name), trying to print out a reference(name), it give a real String object("Sally "). Shouldn't it print a memory address of the real Object("Sally")???

答:
Note: println() is a overloaded method in System class. When you call

```<code>    Customer c = new Customer("Sally");
    System.out.println(c);
</code>```

This will call the println() method that take object as a parameter. If you refer documentation you will see this:

```<code>public void println(Object x)
</code>```

Prints an Object and then terminate the line. This method calls at
  first String.valueOf(x) to get the printed object's string value, then
  behaves as though it invokes print(String) and then println().

Parameters:
      x - The Object to be printed.

When you call println(c.name), name is a String variable, this will call the println() method that take String as the parameter:

```<code>System.out.println(c.name);
</code>```

In documentation:

println

```<code>public void println(String x)
</code>```

Prints a String and then terminate the line. This method behaves as
  though it invokes print(String) and then println().

Parameters:
       x - The String to be printed.

Also refer these: q1 and this q2.

Body:
class Customer {
    public String name;

    public Customer(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Customer c = new Customer("Sally");
        System.out.println(c);
        System.out.println(c.name);
    }
}

It's a simple question and we all know the output, but there's one quesiton about it

Please see the code above and the Picture here Passing Value

Question:

if I print out a reference of a object like this: System.out.println(c);, the IDE would generate a memory address for me: Customer@60e53b93

But, in the video tutorial(screenshot, see the image link Passing Value)

, the object have a member variable which is a reference to a String -> "Sally", why when I do System.out.println(c.name), trying to print out a reference(name), it give a real String object("Sally "). Shouldn't it print a memory address of the real Object("Sally")???

Body:
Note: println() is a overloaded method in System class. When you call

    Customer c = new Customer("Sally");
    System.out.println(c);

This will call the println() method that take object as a parameter. If you refer documentation you will see this:

public void println(Object x)

Prints an Object and then terminate the line. This method calls at
  first String.valueOf(x) to get the printed object's string value, then
  behaves as though it invokes print(String) and then println().

Parameters:
      x - The Object to be printed.

When you call println(c.name), name is a String variable, this will call the println() method that take String as the parameter:

System.out.println(c.name);

In documentation:

println

public void println(String x)

Prints a String and then terminate the line. This method behaves as
  though it invokes print(String) and then println().

Parameters:
       x - The String to be printed.

Also refer these: q1 and this q2.


问:
How to get element color with Selenium
I want to check the color of an element in an html page.
The color of this element is set with a javascript, look at the image

The element with div-id "Ab_banco_M1T1_switch" can assume 4 values, of course only one of them is displayed according to the value of "val" variable.
The val variable is set from the server somehow, it seemes the script polls the server every X-seconds and update the value of val.

I've tried to get the color of the element as follow:

```<code>WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Ab_banco_M1T1_switch")));

element.getAttribute("background")
element.getAttribute("style")
element.getAttribute("background-color")
element.getCssValue("style")
element.getCssValue("color")
</code>```

with no success, they return "null" or the backgorund-color of the page.

The only way to get the color is to use the Xpath
    /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[3]/div (for red, if I want the green
   /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[2]/div)

But it is not what I want. Indeed, the Xpath localizes the element, but it doesn't tell me if the color displayed is red or another one, I can know it only by looking at the web page.

In other words, I would like to access the  current displayed color as Firebug does, look at the panel on right side, you can see that element.style ->background-Color = red.

When I invoke element,getCssCValue("background-color") I get the backgorund-color of #body_right_div.

Thank you in advance.

答:
try this, worked perfect for me:

```<code>import org.openqa.selenium.support.Color;

String color = driver.findElement(By.xpath("xpath_value")).getCssValue("color");
System.out.println(color);
String hex = Color.fromString(color).asHex();
System.out.println(hex);
</code>```

So you can get color using getCssValue("color"); and  getCssValue("background-color");.
However, that would be in RGB, so you need to convert to hex. With hex code you can then compare the value and print it out so that you can see what you are getting after each getCssValue.

Title: How to get element color with Selenium

Body:
I want to check the color of an element in an html page.
The color of this element is set with a javascript, look at the image

The element with div-id "Ab_banco_M1T1_switch" can assume 4 values, of course only one of them is displayed according to the value of "val" variable.
The val variable is set from the server somehow, it seemes the script polls the server every X-seconds and update the value of val.

I've tried to get the color of the element as follow:

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Ab_banco_M1T1_switch")));

element.getAttribute("background")
element.getAttribute("style")
element.getAttribute("background-color")
element.getCssValue("style")
element.getCssValue("color")

with no success, they return "null" or the backgorund-color of the page.

The only way to get the color is to use the Xpath
    /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[3]/div (for red, if I want the green
   /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[2]/div)

But it is not what I want. Indeed, the Xpath localizes the element, but it doesn't tell me if the color displayed is red or another one, I can know it only by looking at the web page.

In other words, I would like to access the  current displayed color as Firebug does, look at the panel on right side, you can see that element.style ->background-Color = red.

When I invoke element,getCssCValue("background-color") I get the backgorund-color of #body_right_div.

Thank you in advance.

Body:
try this, worked perfect for me:

import org.openqa.selenium.support.Color;

String color = driver.findElement(By.xpath("xpath_value")).getCssValue("color");
System.out.println(color);
String hex = Color.fromString(color).asHex();
System.out.println(hex);

So you can get color using getCssValue("color"); and  getCssValue("background-color");.
However, that would be in RGB, so you need to convert to hex. With hex code you can then compare the value and print it out so that you can see what you are getting after each getCssValue.


问:
Ionic desgin --> button / slide item background-color and round button / sqaure avatar questions
I have some problems with the desgin of an ionic app page.
My App page should look like this:

but I'm unable to get the color of the sliding bar buttons changed.
The actual state of the page:

Furhtermore, I don't know how to make such an "circle" button.
I know, that I could use the < ion-fab > button option, but then I'm unable to format it the way I want to. (the button above the label and the item-slider, but it's allways in front of the other items if I use < ion-fab > )

And my last question would be, if there is a < ion-avatar > option, or a similar approach to the < ion-avatar > option, that doesn't cut of edges off of my pictures.

My actual html part:

```<code> <ion-content>
    <img class="img-head" src="assets/img/header_daten_dokumente.jpg">
    <hr>
    <ion-searchbar no lines (ionInput)="getItems($event)" placeholder="{{'Suche nach Dokumenten'|translate}}">
    </ion-searchbar>
    <div class="center">
        <button ion-button round color="hnwGruen1" (click)="addDocument()">
          <ion-icon name="add" large></ion-icon>
        </button>
        <ion-label class="hnw-label" >{{"Daten/Dokumente hinzufügen"|translate}}</ion-label>

      <!--        -->
    </div>
    <ion-item-sliding *ngFor="let document of myData.documentsData">
      <button ion-item color="black" (click)="editDocument(document)">
          <ion-avatar item-left>
            <img src="assets/img/Icon_dokumente.svg">
          </ion-avatar>
          <ion-avatar item-right>
            <img src="assets/img/icon-aerzte.svg">
          </ion-avatar>
          <h3 ion-text>{{document.doc.xName}}</h3>
          <p ion-text *ngIf="document.doc.arzt!=''">{{document.doc.arzt}}</p>

      </button>
        <ion-item-options  side="left">
          <button ion-button color="hnwGruen1">
              <ion-icon name="send"></ion-icon>
              {{"Versenden"|translate}}
            </button>
          <button ion-button color="hnwGruen2" (click)="editDocument(document.doc)">
              <ion-icon name="create"></ion-icon>
              {{"Editieren"|translate}}
            </button>
          <button ion-button color="hnwGruen3" (click)="deleteDocument(document.doc._id)">
              <ion-icon name="cut"></ion-icon>
              {{"Löschen"|translate}}
            </button>
        </ion-item-options>
      </ion-item-sliding>
  </ion-content>
</code>```

The functionality was pretty easy to implement, compared to the design ;-(

Thank you for help

答:
Okay, I solved it by ms self.

```<code><ion-list class="ion-list">
    <ion-item-sliding  *ngFor="let item of myData.arztData">
      <ion-item class="ion-item1" tappable (click)="openArzt(item.doc)"  style="background-color: oldlace">
        <ion-row >
          <img class="img-left" src="assets/img/Icon_dokumente.svg">
          <p class="output">{{item.doc.xName}} <br> {{item.doc.fachrichtung}}<br> {{item.doc.tel}} <br>
          </p>
           <img class="img-right" src="assets/icon/auswahl_button.svg">
        </ion-row>
      </ion-item>
      <ion-item-options side="left">
         <button ion-button color="hnwGruen2" (click)="openArzt(item.doc)">
            <ion-icon name="create"></ion-icon>
            {{"Editieren"|translate}}
          </button>
         <button ion-button color="hnwGruen3" (click)="deleteArzt(item.doc._id)">
            <ion-icon name="cut"></ion-icon>
            {{"Löschen"|translate}}
          </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</code>```

and:

```<code>.ion-list{
    margin-left: -30px!important;
}
.ion-item1{
    width: 100% !important;
    height: 100%;
    margin-left: 0px!important;
}
.img-left{
    margin-left: 0px!important;
    margin-right: 10px!important;
    width: 10% !important;
    height:30px !important;
}
.img-right{
    margin-left: 0px!important;
    margin-right: 0px!important;
    width: 5% !important;
    height:30px !important;
    text-align: right;
}
.output{
    margin-left: 30px!important;
    width: 70% !important;
}
</code>```

Made it for me. I still don't know if that is the right apporach, but what ever. For now it works ;-)

Body:
I have some problems with the desgin of an ionic app page.
My App page should look like this:

but I'm unable to get the color of the sliding bar buttons changed.
The actual state of the page:

Furhtermore, I don't know how to make such an "circle" button.
I know, that I could use the < ion-fab > button option, but then I'm unable to format it the way I want to. (the button above the label and the item-slider, but it's allways in front of the other items if I use < ion-fab > )

And my last question would be, if there is a < ion-avatar > option, or a similar approach to the < ion-avatar > option, that doesn't cut of edges off of my pictures.

My actual html part:

 <ion-content>

    <ion-searchbar no lines (ionInput)="getItems($event)" placeholder="{{'Suche nach Dokumenten'|translate}}">
    </ion-searchbar>

        <button ion-button round color="hnwGruen1" (click)="addDocument()">
          <ion-icon name="add" large></ion-icon>
        </button>
        <ion-label class="hnw-label" >{{"Daten/Dokumente hinzufügen"|translate}}</ion-label>

    <ion-item-sliding *ngFor="let document of myData.documentsData">
      <button ion-item color="black" (click)="editDocument(document)">
          <ion-avatar item-left>

          </ion-avatar>
          <ion-avatar item-right>

          </ion-avatar>

{{document.doc.xName}}

{{document.doc.arzt}}

      </button>
        <ion-item-options  side="left">
          <button ion-button color="hnwGruen1">
              <ion-icon name="send"></ion-icon>
              {{"Versenden"|translate}}
            </button>
          <button ion-button color="hnwGruen2" (click)="editDocument(document.doc)">
              <ion-icon name="create"></ion-icon>
              {{"Editieren"|translate}}
            </button>
          <button ion-button color="hnwGruen3" (click)="deleteDocument(document.doc._id)">
              <ion-icon name="cut"></ion-icon>
              {{"Löschen"|translate}}
            </button>
        </ion-item-options>
      </ion-item-sliding>
  </ion-content>

The functionality was pretty easy to implement, compared to the design ;-(

Thank you for help

Body:
Okay, I solved it by ms self.

<ion-list class="ion-list">
    <ion-item-sliding  *ngFor="let item of myData.arztData">
      <ion-item class="ion-item1" tappable (click)="openArzt(item.doc)"  style="background-color: oldlace">
        <ion-row >
          <img class="img-left" src="assets/img/Icon_dokumente.svg">
          <p class="output">{{item.doc.xName}} <br> {{item.doc.fachrichtung}}<br> {{item.doc.tel}} <br>
          </p>
           <img class="img-right" src="assets/icon/auswahl_button.svg">
        </ion-row>
      </ion-item>
      <ion-item-options side="left">
         <button ion-button color="hnwGruen2" (click)="openArzt(item.doc)">
            <ion-icon name="create"></ion-icon>
            {{"Editieren"|translate}}
          </button>
         <button ion-button color="hnwGruen3" (click)="deleteArzt(item.doc._id)">
            <ion-icon name="cut"></ion-icon>
            {{"Löschen"|translate}}
          </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>

and:

.ion-list{
    margin-left: -30px!important;
}
.ion-item1{
    width: 100% !important;
    height: 100%;
    margin-left: 0px!important;
}
.img-left{
    margin-left: 0px!important;
    margin-right: 10px!important;
    width: 10% !important;
    height:30px !important;
}
.img-right{
    margin-left: 0px!important;
    margin-right: 0px!important;
    width: 5% !important;
    height:30px !important;
    text-align: right;
}
.output{
    margin-left: 30px!important;
    width: 70% !important;
}

Made it for me. I still don't know if that is the right apporach, but what ever. For now it works ;-)


问:
Form URL change data POST
I have a URL:

```<code>http://domanin.com/search-result/?start=06%2F08%2F2017&end=06%2F09%2F2017&room_num_search=1&adult_number=1&children_num=0
</code>```

And I have a Bootstrap form:

```<code><form class="form-inline search-hotel-box">
  <div class="form-group">
    <label><span class="flaticon-time"></span></label>
    <input type="text" class="form-control" id="checkin" placeholder="Check In" value="">
  </div>
  <div class="form-group">
    <input type="text" class="form-control" id="checkout" placeholder="Check Out" value="">
  </div>
  <div class="form-group">
    <label><span class="flaticon-door-key"></span></label>
    <select class="form-control">
    <option disabled selected>Rooms</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
  </select>
    <i class="fa fa-angle-down"></i>
  </div>
  <div class="form-group">
    <label><span class="flaticon-profile-1"></span></label>
    <select class="form-control">
    <option disabled selected>Adults</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
  </select>
    <i class="fa fa-angle-down"></i>
  </div>
  <button type="submit" class="btn btn-default">Search Hotel</button>
</form>
</code>```

How can I make a POST to that URL, changing the data of the URL? I don't know how it could be if I used PHP, or is it possible to use jQuery to do this? Would appreciate any help with this.

答:
So if you want to POST data to a particular webpage then you can do this using action and method attribute of form element as:

```<code><form class="form-inline search-hotel-box" action="http://domanin.com/search-result/demo.php" method="POST">
</code>```

You also need to provide name to all the different form fields as:

```<code><input type="text" name="start" class="form-control" id="checkin" placeholder="Check In" value="">

<input type="text" name="end" class="form-control" id="checkout" placeholder="Check Out" value="">

<select class="form-control" name="room_no_search">

<select class="form-control" name="adult_no">
</code>```

Now when anyone fills all the info and clicks submit then all the data will be posted to the URL that is provided in the action attribute.
If you want to sent data by appending in URL then use GET instead of POST.

The data which is sent can be easily retrieved using php as follows:

```<code>$var = $_GET['start'];
</code>```

or

```<code>$var = $_POST['start'];
</code>```

Title: Form URL change data POST

Body:
I have a URL:

http://domanin.com/search-result/?start=06%2F08%2F2017&end=06%2F09%2F2017&room_num_search=1&adult_number=1&children_num=0

And I have a Bootstrap form:

<form class="form-inline search-hotel-box">

    <input type="text" class="form-control" id="checkin" placeholder="Check In" value="">

    <input type="text" class="form-control" id="checkout" placeholder="Check Out" value="">

    <select class="form-control">
    <option disabled selected>Rooms</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
  </select>

    <select class="form-control">
    <option disabled selected>Adults</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
  </select>

  <button type="submit" class="btn btn-default">Search Hotel</button>
</form>

How can I make a POST to that URL, changing the data of the URL? I don't know how it could be if I used PHP, or is it possible to use jQuery to do this? Would appreciate any help with this.

Body:
So if you want to POST data to a particular webpage then you can do this using action and method attribute of form element as:

<form class="form-inline search-hotel-box" action="http://domanin.com/search-result/demo.php" method="POST">

You also need to provide name to all the different form fields as:

<input type="text" name="start" class="form-control" id="checkin" placeholder="Check In" value="">

<input type="text" name="end" class="form-control" id="checkout" placeholder="Check Out" value="">

<select class="form-control" name="room_no_search">

<select class="form-control" name="adult_no">

Now when anyone fills all the info and clicks submit then all the data will be posted to the URL that is provided in the action attribute.
If you want to sent data by appending in URL then use GET instead of POST.

The data which is sent can be easily retrieved using php as follows:

$var = $_GET['start'];

or

$var = $_POST['start'];


问:
Why ninject gets different Db instances in nunit?
I write integration tests for ASP.NET MVC based application, and I try to resolve ninject registration issue.

So for my ASP.NET MVC registration I have

```<code> kernel.Bind(typeof(ICustomDbContext), typeof(IUnitOfWork))
                .ToMethod(ctx => ctx.Kernel.Get<CustomDbContext>())
                .InRequestScope();
</code>```

Just to clarify  CustomDbContext implements IUnitOfWork and ICustomDbContext.

With that registration i guarantee that i have one unique instance per request for CustomDbContext. That registration works properly in scope of ASP.NET.

The problem is when i write integration tests.

```<code>[SetUp]
public void SetUp()
{
    kernel = NinjectConfig.CreateKernel();
}

[Test]
public async Task Test()
{
    // Arrange
    var claaService = kernel.Get<IService>();

}
</code>```

On set up step i load my composition root (which is in ASP.NET MVC project).

The problem is when i get IService (Implementation of IService.cs is Service.cs and that service has dependencies to IUnitOfWork.cs and IGenericRepository.cs.  IGenericRepository.cs has dependency to ICustomDbContext).

At the end when i access IService i should have same instance of CustomDbContext (and as I said in works in scope of MVC).

I have tried  to resolve it in child scope, but the result is the same (they still have different hash code):

```<code>using (var childKernel1 = new ChildKernel(kernel))
{
    childKernel1.Rebind(typeof(ICustomDbContext), typeof(IUnitOfWork))
    .ToMethod(ctx => ctx.Kernel.Get<CustomDbContext>())
    .InThreadScope();

    var claaService = childKernel1.Get<IClassService>();

}
</code>```

My questions are:

Why this is happening ?

How can I resolve it (it works if i do not use ninject, but i want to find a way with Ninject, even if i have to add additional configuration in integration tests) ?

答:
Why this is happening ?

Ninject's scoping is limited to the lifetime of the container. You have setup the container to be created for each [Test] because you are using [SetUp].

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called.

```<code>[SetUp]
public void SetUp()
{
    kernel = NinjectConfig.CreateKernel();
}
</code>```

If you want to use the same container across multiple tests in the same [TestFixture] (assuming this because you said "instance is not the same", but you didn't mention same as what), you need to use [OneTimeSetup] instead.

This attribute is to identify methods that are called once prior to executing any of the tests in a fixture.

```<code>[OneTimeSetUp]
public void OneTimeSetUp()
{
    kernel = NinjectConfig.CreateKernel();
}
</code>```

This of course assumes all of your relevant integration tests are in a single class.

In short, your Ninject container is being re-initialized on every test, which means all instances it manages are also being re-initialized.

Body:
I write integration tests for ASP.NET MVC based application, and I try to resolve ninject registration issue.

So for my ASP.NET MVC registration I have

 kernel.Bind(typeof(ICustomDbContext), typeof(IUnitOfWork))
                .ToMethod(ctx => ctx.Kernel.Get<CustomDbContext>())
                .InRequestScope();

Just to clarify  CustomDbContext implements IUnitOfWork and ICustomDbContext.

With that registration i guarantee that i have one unique instance per request for CustomDbContext. That registration works properly in scope of ASP.NET.

The problem is when i write integration tests.

[SetUp]
public void SetUp()
{
    kernel = NinjectConfig.CreateKernel();
}

[Test]
public async Task Test()
{
    // Arrange
    var claaService = kernel.Get<IService>();

}

On set up step i load my composition root (which is in ASP.NET MVC project).

The problem is when i get IService (Implementation of IService.cs is Service.cs and that service has dependencies to IUnitOfWork.cs and IGenericRepository.cs.  IGenericRepository.cs has dependency to ICustomDbContext).

At the end when i access IService i should have same instance of CustomDbContext (and as I said in works in scope of MVC).

I have tried  to resolve it in child scope, but the result is the same (they still have different hash code):

using (var childKernel1 = new ChildKernel(kernel))
{
    childKernel1.Rebind(typeof(ICustomDbContext), typeof(IUnitOfWork))
    .ToMethod(ctx => ctx.Kernel.Get<CustomDbContext>())
    .InThreadScope();

    var claaService = childKernel1.Get<IClassService>();

}

My questions are:

Why this is happening ?

How can I resolve it (it works if i do not use ninject, but i want to find a way with Ninject, even if i have to add additional configuration in integration tests) ?

Body:
Why this is happening ?

Ninject's scoping is limited to the lifetime of the container. You have setup the container to be created for each [Test] because you are using [SetUp].

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called.

[SetUp]
public void SetUp()
{
    kernel = NinjectConfig.CreateKernel();
}

If you want to use the same container across multiple tests in the same [TestFixture] (assuming this because you said "instance is not the same", but you didn't mention same as what), you need to use [OneTimeSetup] instead.

This attribute is to identify methods that are called once prior to executing any of the tests in a fixture.

[OneTimeSetUp]
public void OneTimeSetUp()
{
    kernel = NinjectConfig.CreateKernel();
}

This of course assumes all of your relevant integration tests are in a single class.

In short, your Ninject container is being re-initialized on every test, which means all instances it manages are also being re-initialized.


问:
QDialog not centered on parent
I know that QDialog's are supposed to default to being positioned centered on the parent window but I'm apparently missing some subtlety. I have an object, derived from QWidget, and am trying to create a child dialog centered on that using the following test code

```<code>QDialog *dialog = new QDialog(this);
QPoint dialogPos = dialog->mapToGlobal(dialog->pos());
QPoint thisPos = mapToGlobal(this->pos());
dialog->exec();
</code>```

When I do this, the dialog is showing up in the top left corner of my window. dialogPos is (0,0) and thisPos is (808, 371).

What am I missing? Why is the dialog not showing up centered as I would expect?

答:
How to center QDialog to it`s parent QWidget</p>

```<code>void Dialog::showEvent( QShowEvent* )
{
    QRect parentRect( parentWidget()->mapToGlobal( QPoint( 0, 0 ) ),
parentWidget()->size() );
    move( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, size(),
parentRect ).topLeft() );
}
</code>```

Title: QDialog not centered on parent

Body:
I know that QDialog's are supposed to default to being positioned centered on the parent window but I'm apparently missing some subtlety. I have an object, derived from QWidget, and am trying to create a child dialog centered on that using the following test code

QDialog *dialog = new QDialog(this);
QPoint dialogPos = dialog->mapToGlobal(dialog->pos());
QPoint thisPos = mapToGlobal(this->pos());
dialog->exec();

When I do this, the dialog is showing up in the top left corner of my window. dialogPos is (0,0) and thisPos is (808, 371).

What am I missing? Why is the dialog not showing up centered as I would expect?

Body:
How to center QDialog to it`s parent QWidget

void Dialog::showEvent( QShowEvent* )
{
    QRect parentRect( parentWidget()->mapToGlobal( QPoint( 0, 0 ) ),
parentWidget()->size() );
    move( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, size(),
parentRect ).topLeft() );
}


问:
Dynamic Datasource Connection in Spring
When my application starts it creates connection with one database. During runtime I fetched other databases names in same database server. How can I create connection for other databases too at runtime? Currently I am passing dbNameto method like:

```<code>@Bean
@Scope("prototype")
public DataSource getDataSource(String dbName) {

    String dbUrl = DATABASE_JDBC_URL + dbName;

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(DRIVER_CLASS_NAME);
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(DATABASE_USERNAME);
    dataSource.setPassword(DATABASE_PASSWORD);

    return dataSource;
}
</code>```

When I pass parameter dbName in above @Bean getDataSource(String dbName) method I am getting following exception

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
</code>```

答:
You can create a wrapper around Datasource, something like :</p>

```<code>@Component
public class DataSourceManager implements DataSource{

    private DataSource dataSource;

    @PostConstruct
    public void init() {
        // init the datasource
    }

    public DataSource getDataSource(String dbName) {
        return dataSource;
    }

    public void switchDataSource(String name) {
        // re init the datasource
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    .... wrap all the other DataSource methods

}
</code>```

Title: Dynamic Datasource Connection in Spring

Body:
When my application starts it creates connection with one database. During runtime I fetched other databases names in same database server. How can I create connection for other databases too at runtime? Currently I am passing dbNameto method like:

@Bean
@Scope("prototype")
public DataSource getDataSource(String dbName) {

    String dbUrl = DATABASE_JDBC_URL + dbName;

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(DRIVER_CLASS_NAME);
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(DATABASE_USERNAME);
    dataSource.setPassword(DATABASE_PASSWORD);

    return dataSource;
}

When I pass parameter dbName in above @Bean getDataSource(String dbName) method I am getting following exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)

Body:
You can create a wrapper around Datasource, something like :

@Component
public class DataSourceManager implements DataSource{

    private DataSource dataSource;

    @PostConstruct
    public void init() {
        // init the datasource
    }

    public DataSource getDataSource(String dbName) {
        return dataSource;
    }

    public void switchDataSource(String name) {
        // re init the datasource
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    .... wrap all the other DataSource methods

}


问:
How to eval inside a Handlebars expression?
I have a backbone model returning something like this:

```<code>{
    language: "us",
    us: {
        title: "Gigs",
        subtitle: "Stay tune to my upcoming gigs"
    },
    br: {
        title: "Shows",
        subtitle: "Fique ligado na minha agenda"
    }
}
</code>```

The language is being updated dynamically, so it will determinate which object I'm gonna print, using Handlebars. Usually I would do:

```<code><h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
</code>```

But I need to do some kind of concat:

```<code><h1>{{language.title}}</h1>
<h2>{{language.subtitle}}</h2>
</code>```

Of course this will not work. That's my question: How can I make the expression to be dynamically concat?

So that if the language is "us", it calls:

```<code><h1>{{us.language.title}}</h1>
<h2>{{us.language.subtitle}}</h2>
</code>```

And if it's "br", it calls:

```<code><h1>{{br.language.title}}</h1>
<h2>{{br.language.subtitle}}</h2>
</code>```

答:
Try using with helper in Handlebars along with either a function like @George Mauer suggested or a local function while passing parameters in the template

Suppose we have a function returning the current language

```<code>var lang = model[String(model.language)]; // or this, depending on where your model lives
</code>```

you would pass the lang variable in your template (depending on how you implement Handlebars templates in your application there are many ways)

in your template you'd have

```<code>{{#with lang}}
  <h1>{{title}}</h1>
  <h2>{{subtitle}}</h2>
{{/with}}
</code>```

Body:
I have a backbone model returning something like this:

{
    language: "us",
    us: {
        title: "Gigs",
        subtitle: "Stay tune to my upcoming gigs"
    },
    br: {
        title: "Shows",
        subtitle: "Fique ligado na minha agenda"
    }
}

The language is being updated dynamically, so it will determinate which object I'm gonna print, using Handlebars. Usually I would do:

{{title}}

{{subtitle}}

But I need to do some kind of concat:

{{language.title}}

{{language.subtitle}}

Of course this will not work. That's my question: How can I make the expression to be dynamically concat?

So that if the language is "us", it calls:

{{us.language.title}}

{{us.language.subtitle}}

And if it's "br", it calls:

{{br.language.title}}

{{br.language.subtitle}}

Body:
Try using with helper in Handlebars along with either a function like @George Mauer suggested or a local function while passing parameters in the template

Suppose we have a function returning the current language

var lang = model[String(model.language)]; // or this, depending on where your model lives

you would pass the lang variable in your template (depending on how you implement Handlebars templates in your application there are many ways)

in your template you'd have

{{#with lang}}
  <h1>{{title}}</h1>
  <h2>{{subtitle}}</h2>
{{/with}}


问:
Angular ui-view load slowly
Is there a fadeIn effect for loading your ui-view?

Because sometimes the images are loading a bit slowly.

答:
Add ngAnimate as a dependency to your Angular application (or read https://docs.angularjs.org/api/ngAnimate)

```<code><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
or
npm install --save angular-animate@X.Y.Z
</code>```

Add ngAnimate as a dependency to your application like this:

```<code>angular
    .module('app', ['ui.router', 'ngAnimate'])
</code>```

Add a CSS class to your ui-view

```<code><div ui-view class="main"></div>
</code>```

Animate with CSS

```<code>.main.ng-enter {
    transition: 0.25s;
    opacity: 0;
}
.main.ng-enter-active {
    opacity: 1;
}
.main.ng-leave {
    transition: 0.25s;
    opacity: 1;
}
.main.ng-leave-active {
    opacity: 0;
}
</code>```

See JSFiddle

Title: Angular ui-view load slowly

Body:
Add ngAnimate as a dependency to your Angular application (or read https://docs.angularjs.org/api/ngAnimate)

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
or
npm install --save angular-animate@X.Y.Z

Add ngAnimate as a dependency to your application like this:

angular
    .module('app', ['ui.router', 'ngAnimate'])

Add a CSS class to your ui-view

<div ui-view class="main"></div>

Animate with CSS

.main.ng-enter {
    transition: 0.25s;
    opacity: 0;
}
.main.ng-enter-active {
    opacity: 1;
}
.main.ng-leave {
    transition: 0.25s;
    opacity: 1;
}
.main.ng-leave-active {
    opacity: 0;
}

See JSFiddle


问:
SimpleXML changing file encoding
I am trying to write a function which could read an existing XML file and create a new one with all the data from the first one, but in a different encoding. As far I understand it, SimpleXML saves the file in UTF-8 encoding. My original XML file is Windows-1257.

Code:

```<code>public static function toUTF8()
{
    $remote_file = "data/test/import/test.xml";
    $xml = simplexml_load_file($remote_file);
    $xml->asXml('data/test/import/utf8/test.xml');

    echo var_dump('done');
    exit;
}
</code>```

This way the encoding of file is still not good. I wanted to try this:

```<code>$newXML = new SimpleXMLElement($xml);
</code>```

But this takes only plain XML code as a parameter. How could I get the whole XML code from the object? Or how else could I create a new UTF-8 XML object and insert all the data from the old file?

答:
Unless I'm wrong, the SimpleXML extension will just use the same encoding all the way through. UTF-8 is the default if no encoding is given but, if the original document has encoding information such encoding will be used.

You can use DOMDocument as proxy:

```<code>$xml = simplexml_load_file(__DIR__ . '/test.xml');

$doc = dom_import_simplexml($xml)->ownerDocument;
$doc->encoding = 'UTF-8';

$xml->asXml('as-utf-8.xml');
</code>```

Title: SimpleXML changing file encoding

Body:
I am trying to write a function which could read an existing XML file and create a new one with all the data from the first one, but in a different encoding. As far I understand it, SimpleXML saves the file in UTF-8 encoding. My original XML file is Windows-1257.

Code:

public static function toUTF8()
{
    $remote_file = "data/test/import/test.xml";
    $xml = simplexml_load_file($remote_file);
    $xml->asXml('data/test/import/utf8/test.xml');

    echo var_dump('done');
    exit;
}

This way the encoding of file is still not good. I wanted to try this:

$newXML = new SimpleXMLElement($xml);

But this takes only plain XML code as a parameter. How could I get the whole XML code from the object? Or how else could I create a new UTF-8 XML object and insert all the data from the old file?

Body:
Unless I'm wrong, the SimpleXML extension will just use the same encoding all the way through. UTF-8 is the default if no encoding is given but, if the original document has encoding information such encoding will be used.

You can use DOMDocument as proxy:

$xml = simplexml_load_file(__DIR__ . '/test.xml');

$doc = dom_import_simplexml($xml)->ownerDocument;
$doc->encoding = 'UTF-8';

$xml->asXml('as-utf-8.xml');


问:
SQL dates Overlapping
I have  a following table with data in sql. I wanted to know the dates which are overlapping.

```<code>ARN NO      From Date   To Date
1   106739  1/1/2015    3/31/2015
2   106739  1/1/2015    2/28/2015
3   106739  3/1/2015    3/31/2015
4   106739  5/1/2015    6/30/2015
5   106739  7/1/2015    9/30/2015
6   106739  9/1/2015    9/30/2015
7   106739  10/1/2015   12/31/2015
8   106739  10/1/2015   12/31/2015
</code>```

In the above table, the first three records are overlapping. How do I write a query to find out? I need the below output

```<code>   NO  ARN NO   From Date   To Date
   4    106739  5/1/2015    6/30/2015
</code>```

Thanks

答:
You can use exists:

```<code>select t.*
from t
where exists (select 1
              from t t2
              where t2.arnno = t.arrno and
                    t2.fromdate < t.todate and
                    t2.todate > t.fromdate
             );
</code>```

Two time periods overlap if the first starts before the second ends and ends after the second starts.

Title: SQL dates Overlapping

Body:
I have  a following table with data in sql. I wanted to know the dates which are overlapping.

ARN NO      From Date   To Date
1   106739  1/1/2015    3/31/2015
2   106739  1/1/2015    2/28/2015
3   106739  3/1/2015    3/31/2015
4   106739  5/1/2015    6/30/2015
5   106739  7/1/2015    9/30/2015
6   106739  9/1/2015    9/30/2015
7   106739  10/1/2015   12/31/2015
8   106739  10/1/2015   12/31/2015

In the above table, the first three records are overlapping. How do I write a query to find out? I need the below output

   NO  ARN NO   From Date   To Date
   4    106739  5/1/2015    6/30/2015

Thanks

Body:
You can use exists:

select t.*
from t
where exists (select 1
              from t t2
              where t2.arnno = t.arrno and
                    t2.fromdate < t.todate and
                    t2.todate > t.fromdate
             );

Two time periods overlap if the first starts before the second ends and ends after the second starts.