问:
while loop doesn't stop, with if statement as nested loop in python
The code doesn't stop even if 0 is fed as value. what could be the possible reason? see my code below:

```<code>x = -1
num = -9

print("For exit press 0")

while (x != 0):
    num = input("Enter a number  :")
    print("You entered: ", num)
    x = num
    if x == 0:
        break

print("Good bye!")
</code>```

Thanks!

答:
The problem is that you're comparing string to integer; Python is weakly typed, so no warning is given.

Additionally, input() casts the input in Python 2, but not Python 3. This is why the code works as intended in Python 2.

Notes:
You don't need parentheses for while condition.
Formatting the string is recommended for outputting things.

```<code>x = -1

print("To exit press 0")

while x != 0:
    num = input("Enter a number:")
    print("You entered: {}".format(num))
    x = int(num)
    if x == 0:
        break

print("Good bye!")
</code>```

Body:
The code doesn't stop even if 0 is fed as value. what could be the possible reason? see my code below:

x = -1
num = -9

print("For exit press 0")

while (x != 0):
    num = input("Enter a number  :")
    print("You entered: ", num)
    x = num
    if x == 0:
        break

print("Good bye!")

Thanks!

Body:
The problem is that you're comparing string to integer; Python is weakly typed, so no warning is given.

Additionally, input() casts the input in Python 2, but not Python 3. This is why the code works as intended in Python 2.

Notes:
You don't need parentheses for while condition.
Formatting the string is recommended for outputting things.

x = -1

print("To exit press 0")

while x != 0:
    num = input("Enter a number:")
    print("You entered: {}".format(num))
    x = int(num)
    if x == 0:
        break

print("Good bye!")


来源: stackexchange

问:
Find row-wise duplicates by groups
I have a data-set that may have duplicate products. If there are duplicate products, we would mark that order as "Y", and vice versa.

Here are my data:

```<code>dput(Test_File)
structure(list(Order = c(1234, 1234, 2345, 2345, 2345, 3456,
3456, 4567, 5678, 5678, 5678, 5678, 9999, 9999), Product = c("A12960",
"12960", "B3560", "3560", "A3850", "3850", "A3850", "A2920",
"2930", "2921", "A2921", "A2930", "A1234", "2345"), ASKU = c("Y",
"N", "N", "N", "Y", "N", "Y", "Y", "N", "N", "Y", "Y", "Y", "N"
)), .Names = c("Order", "Product", "ASKU"), row.names = c(NA,
14L), class = "data.frame")
</code>```

Commentary about the data: I have a column that says ASKU. This is mainly to identify whether a particular SKU starts with A. Also, please note that A1234 and 1234 would be considered duplicate. A1234 and 23456 wouldn't be considered duplicate. Similarly, B1234 and 1234 won't be considered duplicates. So, to identify duplicates, one would ignore A in ASKU column.

Expected Output:

```<code>dput(Output_File)
structure(list(Order = c(1234, 2345, 3456, 4567, 5678, 9999),
    Duplicate = c("Y", "N", "Y", "N", "Y", "N")), .Names = c("Order",
"Duplicate"), row.names = c(NA, 6L), class = "data.frame")
</code>```

My code (non-working):

I tried this code, but I am getting an error. The idea is to do row-wise comparison of SKUs after extracting string from SKU name.

Error: Duplicate identifiers for rows (3, 4), (8, 9), (10, 11)

```<code>Test_File$New_SKU<-NA_character_

Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"New_SKU"]<-sub("^A","",Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"Product"])

Test_File[Test_File$ASKU=="N","New_SKU"]<-Test_File[Test_File$ASKU=="N","Product"]

Test_File %>%
  dplyr::group_by(Order) %>%
  dplyr::mutate(DCount = n_distinct(ASKU)) %>%
  dplyr::filter(DCount>=2) %>%
  dplyr::ungroup() %>%
  dplyr::select(Order,New_SKU,ASKU) %>%
  dplyr::distinct() %>%
  tidyr::spread(key = ASKU,value = New_SKU)
</code>```

Can someone please help me? I would appreciate if you could help me with dplyr-based solution and data.table-based solution.

答:
We can use dplyr and remove the A from the Product which starts with it and then grouping by Order we can check if there are any duplicate values in that group.

```<code>library(dplyr)
Test_File %>%
  mutate(Product = sub("^A", "", Product)) %>%
  group_by(Order) %>%
  summarise(Duplicate = any(duplicated(Product)))

#  Order Duplicate
#  <dbl>     <lgl>
#1  1234      TRUE
#2  2345     FALSE
#3  3456      TRUE
#4  4567     FALSE
#5  5678      TRUE
#6  9999     FALSE
</code>```

If we need the output to be in Y/N format, the values of Duplicate columns can be easily replaced using ifelse

```<code>Test_File %>%
   mutate(Product = sub("^A", "", Product)) %>%
   group_by(Order) %>%
   summarise(Duplicate = ifelse(any(duplicated(Product)), "Y", "N"))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Find row-wise duplicates by groups

Body:
I have a data-set that may have duplicate products. If there are duplicate products, we would mark that order as "Y", and vice versa.

Here are my data:

dput(Test_File)
structure(list(Order = c(1234, 1234, 2345, 2345, 2345, 3456,
3456, 4567, 5678, 5678, 5678, 5678, 9999, 9999), Product = c("A12960",
"12960", "B3560", "3560", "A3850", "3850", "A3850", "A2920",
"2930", "2921", "A2921", "A2930", "A1234", "2345"), ASKU = c("Y",
"N", "N", "N", "Y", "N", "Y", "Y", "N", "N", "Y", "Y", "Y", "N"
)), .Names = c("Order", "Product", "ASKU"), row.names = c(NA,
14L), class = "data.frame")

Commentary about the data: I have a column that says ASKU. This is mainly to identify whether a particular SKU starts with A. Also, please note that A1234 and 1234 would be considered duplicate. A1234 and 23456 wouldn't be considered duplicate. Similarly, B1234 and 1234 won't be considered duplicates. So, to identify duplicates, one would ignore A in ASKU column.

Expected Output:

dput(Output_File)
structure(list(Order = c(1234, 2345, 3456, 4567, 5678, 9999),
    Duplicate = c("Y", "N", "Y", "N", "Y", "N")), .Names = c("Order",
"Duplicate"), row.names = c(NA, 6L), class = "data.frame")

My code (non-working):

I tried this code, but I am getting an error. The idea is to do row-wise comparison of SKUs after extracting string from SKU name.

Error: Duplicate identifiers for rows (3, 4), (8, 9), (10, 11)

Test_File$New_SKU<-NA_character_

Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"New_SKU"]<-sub("^A","",Test_File[grepl("^A",Test_File$Product,ignore.case = TRUE),"Product"])

Test_File[Test_File$ASKU=="N","New_SKU"]<-Test_File[Test_File$ASKU=="N","Product"]

Test_File %>%
  dplyr::group_by(Order) %>%
  dplyr::mutate(DCount = n_distinct(ASKU)) %>%
  dplyr::filter(DCount>=2) %>%
  dplyr::ungroup() %>%
  dplyr::select(Order,New_SKU,ASKU) %>%
  dplyr::distinct() %>%
  tidyr::spread(key = ASKU,value = New_SKU)

Can someone please help me? I would appreciate if you could help me with dplyr-based solution and data.table-based solution.

Body:
We can use dplyr and remove the A from the Product which starts with it and then grouping by Order we can check if there are any duplicate values in that group.

library(dplyr)
Test_File %>%
  mutate(Product = sub("^A", "", Product)) %>%
  group_by(Order) %>%
  summarise(Duplicate = any(duplicated(Product)))

#  Order Duplicate
#  <dbl>     <lgl>
#1  1234      TRUE
#2  2345     FALSE
#3  3456      TRUE
#4  4567     FALSE
#5  5678      TRUE
#6  9999     FALSE

If we need the output to be in Y/N format, the values of Duplicate columns can be easily replaced using ifelse

Test_File %>%
   mutate(Product = sub("^A", "", Product)) %>%
   group_by(Order) %>%
   summarise(Duplicate = ifelse(any(duplicated(Product)), "Y", "N"))


问:
Multiple Aggregates Pivot Table
I have a few columns of data I am wanting to put into a Pivot table. This is what the data currently looks like once the following query is ran:

```<code>SELECT
    t.clinic,
    t.fiscal_year,
    t.total,
    n.new_pats,
    (t.total - n.new_pats) AS active
FROM (SELECT DISTINCT
    clinic,
    fiscal_year,
    COUNT(DISTINCT patient_id) AS total
FROM transactions t
JOIN period p
    ON (t.date_entered BETWEEN p.period_start AND p.period_end)
GROUP BY clinic, fiscal_year) t
JOIN (SELECT DISTINCT
    clinic,
    per.fiscal_year,
    COUNT(DISTINCT patient_id) AS new_pats
FROM patient pat
JOIN period per
    ON (pat.first_visit_date BETWEEN per.period_start AND per.period_end)
GROUP BY clinic, fiscal_year) n
    ON (t.clinic = n.clinic AND t.fiscal_year = n.fiscal_year)
</code>```

And I would like the data to be broken up by the three aggregates in their own rows and the years being the columns where it looks something like this:

This could also be broken into 3 separate columns per aggregate per year, but this is what I'm ideally aiming for. I haven't put together a Pivot table within SQL before and am at a loss. Is there a better way to go about formatting this data in the desired way?

答:
You could try this

```<code>SELECT clinic,
       aggregate_field,
       ISNULL([2009],0) AS [2009],
       ISNULL([2010],0) AS [2010],
       ISNULL([2016],0) AS [2016],
       ISNULL([2017],0) AS [2017]
FROM   (SELECT clinic,
               fiscal_year,
               aggregate_field,
               value
        FROM   (
                ------- This part is your original query -----------------
                SELECT t.clinic,
                       t.fiscal_year,
                       t.total,
                       n.new_pats,
                       ( t.total - n.new_pats ) AS active
                FROM   (SELECT DISTINCT clinic,
                                        fiscal_year,
                                        Count(DISTINCT patient_id) AS total
                        FROM   transactions t
                               JOIN period p
                                 ON ( t.date_entered BETWEEN
                                      p.period_start AND p.period_end )
                        GROUP  BY clinic, fiscal_year) t
                       JOIN (SELECT DISTINCT clinic,
                                             per.fiscal_year,
                                             Count(DISTINCT patient_id) AS new_pats
                             FROM   patient pat
                                    JOIN period per
                                      ON ( pat.first_visit_date BETWEEN
                                           per.period_start AND per.period_end )
                             GROUP  BY clinic, fiscal_year) n
                         ON ( t.clinic = n.clinic
                              AND t.fiscal_year = n.fiscal_year )
               -------------------------------------------------------------
               )
               unpivot_source
               UNPIVOT ( value
                       FOR aggregate_field IN (total,
                                               new_pats,
                                               active) ) unpivot_result) AS
       pivot_source
       PIVOT ( Max(value)
             FOR fiscal_year IN ([2009],
                                 [2010],
                                 [2016],
                                 [2017]) ) AS pivot_result
ORDER  BY clinic, aggregate_field DESC
</code>```

I've create a demo here http://rextester.com/MFHWV68715.

Title: Multiple Aggregates Pivot Table

Body:
I have a few columns of data I am wanting to put into a Pivot table. This is what the data currently looks like once the following query is ran:

SELECT
    t.clinic,
    t.fiscal_year,
    t.total,
    n.new_pats,
    (t.total - n.new_pats) AS active
FROM (SELECT DISTINCT
    clinic,
    fiscal_year,
    COUNT(DISTINCT patient_id) AS total
FROM transactions t
JOIN period p
    ON (t.date_entered BETWEEN p.period_start AND p.period_end)
GROUP BY clinic, fiscal_year) t
JOIN (SELECT DISTINCT
    clinic,
    per.fiscal_year,
    COUNT(DISTINCT patient_id) AS new_pats
FROM patient pat
JOIN period per
    ON (pat.first_visit_date BETWEEN per.period_start AND per.period_end)
GROUP BY clinic, fiscal_year) n
    ON (t.clinic = n.clinic AND t.fiscal_year = n.fiscal_year)

And I would like the data to be broken up by the three aggregates in their own rows and the years being the columns where it looks something like this:

This could also be broken into 3 separate columns per aggregate per year, but this is what I'm ideally aiming for. I haven't put together a Pivot table within SQL before and am at a loss. Is there a better way to go about formatting this data in the desired way?

Body:
You could try this

SELECT clinic,
       aggregate_field,
       ISNULL([2009],0) AS [2009],
       ISNULL([2010],0) AS [2010],
       ISNULL([2016],0) AS [2016],
       ISNULL([2017],0) AS [2017]
FROM   (SELECT clinic,
               fiscal_year,
               aggregate_field,
               value
        FROM   (
                ------- This part is your original query -----------------
                SELECT t.clinic,
                       t.fiscal_year,
                       t.total,
                       n.new_pats,
                       ( t.total - n.new_pats ) AS active
                FROM   (SELECT DISTINCT clinic,
                                        fiscal_year,
                                        Count(DISTINCT patient_id) AS total
                        FROM   transactions t
                               JOIN period p
                                 ON ( t.date_entered BETWEEN
                                      p.period_start AND p.period_end )
                        GROUP  BY clinic, fiscal_year) t
                       JOIN (SELECT DISTINCT clinic,
                                             per.fiscal_year,
                                             Count(DISTINCT patient_id) AS new_pats
                             FROM   patient pat
                                    JOIN period per
                                      ON ( pat.first_visit_date BETWEEN
                                           per.period_start AND per.period_end )
                             GROUP  BY clinic, fiscal_year) n
                         ON ( t.clinic = n.clinic
                              AND t.fiscal_year = n.fiscal_year )
               -------------------------------------------------------------
               )
               unpivot_source
               UNPIVOT ( value
                       FOR aggregate_field IN (total,
                                               new_pats,
                                               active) ) unpivot_result) AS
       pivot_source
       PIVOT ( Max(value)
             FOR fiscal_year IN ([2009],
                                 [2010],
                                 [2016],
                                 [2017]) ) AS pivot_result
ORDER  BY clinic, aggregate_field DESC

I've create a demo here http://rextester.com/MFHWV68715.


问:
How to Flatten a Multidimensional Array?
Is it possible, in PHP, to flatten a (bi/multi)dimensional array without using recursion or references?

I'm only interested in the values so the keys can be ignored, I'm thinking in the lines of array_map() and array_values().

Body:
<?php
//recursive solution

//test array
$nested_array = [[1,2,[3]],4,[5],[[[6,[7=>[7,8,9,10]]]]]];

/*-----------------------------------------
function call and return result to an array
------------------------------------------*/
$index_count = 1;
$flatered_array = array();
$flatered_array = flat_array($nested_array, $index_count);

/*-----------------------------------------
Print Result
-----------------------------------------*/
echo "<pre>";
print_r($flatered_array);

/*-----------------------------------------
function to flaten an array
-----------------------------------------*/
function flat_array($nested_array, & $index_count, & $flatered_array) {

  foreach($nested_array AS $key=>$val) {
      if(is_array($val)) {
        flat_array($val, $index_count, $flatered_array);
      }
      else {
        $flatered_array[$index_count] = $val;
        ++$index_count;
      }
  }

return $flatered_array;
}
?>


问:
How can i set double height to Imageview programmatically?
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

```<code>//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);
</code>```

答:
Finally I got a solution here is code for help to any person</p>

```<code>DisplayMetrics displayMetrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        Log.e("width",width+""+height);

        //--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        int height_final = (int) (final_height + 0.5f);
        Log.e("final height",""+height_final);
        holder.homeFragmentBusinessImageView.getLayoutParams().width  = final_width;
        holder.homeFragmentBusinessImageView.getLayoutParams().height = height_final;
</code>```

Body:
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);

Body:
Finally I got a solution here is code for help to any person

DisplayMetrics displayMetrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        Log.e("width",width+""+height);

        //--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        int height_final = (int) (final_height + 0.5f);
        Log.e("final height",""+height_final);
        holder.homeFragmentBusinessImageView.getLayoutParams().width  = final_width;
        holder.homeFragmentBusinessImageView.getLayoutParams().height = height_final;


问:
Can't make Jackson and Lombok work together
I am experimenting in combining Jackson and Lombok. Those are my classes:

package testelombok;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.experimental.Wither;

@Value
@Wither
@AllArgsConstructor(onConstructor=@__(@JsonCreator))
public class TestFoo {
    @JsonProperty("xoom")
    private String x;
    private int z;
}
```

<pre class="lang-java prettyprint-override"><code>package testelombok;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xebia.jacksonlombok.JacksonLombokAnnotationIntrospector;
import java.io.IOException;

public class TestLombok {

    public static void main(String[] args) throws IOException {
        TestFoo tf = new TestFoo("a", 5);
        System.out.println(tf.withX("b"));
        ObjectMapper om = new ObjectMapper().setAnnotationIntrospector(new JacksonLombokAnnotationIntrospector());
        System.out.println(om.writeValueAsString(tf));
        TestFoo tf2 = om.readValue(om.writeValueAsString(tf), TestFoo.class);
        System.out.println(tf2);
    }

}
</code>```

Those are the JARs that I'm adding into the classpth:

Lombok: https://projectlombok.org/downloads/lombok.jar (version 1.16.10)

Jackson annotations: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.8.2/jackson-annotations-2.8.2.jar

Jackson core: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.8.2/jackson-core-2.8.2.jar

Jackson databind: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.2/jackson-databind-2.8.2.jar

Jackson-lombok: http://repo1.maven.org/maven2/io/paradoxical/jackson-lombok/1.1/jackson-lombok-1.1.jar

I am compiling it with Netbeans (I don't think that this is really relevant, but I am reporting this anyway to make it perfectly and faithfully reproducible). The five JARs above are kept in a folder called "lib" inside the project folder (along with "src", "nbproject", "test" and "build"). I added them to Netbeans via the "Add JAR/Folder" button in the project properties and they are listed in the exact order as the list above. The project is a standard "Java application" type project.

Further, the Netbeans project is configured to "do NOT compile on save", "generate debugging info", "report deprecated APIs", "track java dependencies", "activacte annotation proccessing" and "activacte annotation proccessing in the editor". No annotation processor or annotation processing option is explicitly configured in Netbeans. Also, the "-Xlint:all" command line option is passed in the compiler command line, and the compiler runs on an external VM.

My javac's version is 1.8.0_72 and my java's version is 1.8.0_72-b15. My Netbeans is 8.1.

My project compiles fine. However, it throws an exception in its execution. The exception don't seems to be anything that looks easily or obvious fixable. Here is the output, including the stacktrace:

TestFoo(x=b, z=5)
{"z":5,"xoom":"a"}
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=@java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
 at [Source: {"z":5,"xoom":"a"}; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:296)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:269)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:475)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3890)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3785)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2833)
    at testelombok.TestLombok.main(TestLombok.java:14)
Caused by: java.lang.IllegalArgumentException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=@java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._addDeserializerConstructors(BasicDeserializerFactory.java:511)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:323)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:253)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:219)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:141)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:406)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
    ... 7 more
```

I already tried about randomly poking with the @Value and @AllArgsConstructor annotations, but I couldn't make it any better.

I google'd the exception and found an old bug report on jackson, and another one that is open, but seems to be related to something else. However, this still do not tells anything about what is this bug or how to fix it. Also, I could not find anything useful looking that somewhere else.

Since what I am trying to do is very basic usage of both lombok and jackson, it seems odd that I couldn't find any more useful information about how to workaround this issue. Maybe I missed something?

Other than just saying "don't use lombok" or "don't use jackson", do anybody has any idea about how to solve this?

答:
I've all my classes annotated like this:

```<code>@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@Data
@Accessors(fluent = true)
@NoArgsConstructor
@AllArgsConstructor
</code>```

It worked with all Lombok and Jackson versions for, at least, a couple of years.

Example:

```<code>@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@Data
@Accessors(fluent = true)
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    String id;
    String first;
    String last;
}
</code>```

And that's it.
Lombok and Jackson play together like a charm.

Body:
I am experimenting in combining Jackson and Lombok. Those are my classes:

package testelombok;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.experimental.Wither;

@Value
@Wither
@AllArgsConstructor(onConstructor=@__(@JsonCreator))
public class TestFoo {
    @JsonProperty("xoom")
    private String x;
    private int z;
}

package testelombok;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xebia.jacksonlombok.JacksonLombokAnnotationIntrospector;
import java.io.IOException;

public class TestLombok {

    public static void main(String[] args) throws IOException {
        TestFoo tf = new TestFoo("a", 5);
        System.out.println(tf.withX("b"));
        ObjectMapper om = new ObjectMapper().setAnnotationIntrospector(new JacksonLombokAnnotationIntrospector());
        System.out.println(om.writeValueAsString(tf));
        TestFoo tf2 = om.readValue(om.writeValueAsString(tf), TestFoo.class);
        System.out.println(tf2);
    }

}

Those are the JARs that I'm adding into the classpth:

Lombok: https://projectlombok.org/downloads/lombok.jar (version 1.16.10)

Jackson annotations: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.8.2/jackson-annotations-2.8.2.jar

Jackson core: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.8.2/jackson-core-2.8.2.jar

Jackson databind: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.2/jackson-databind-2.8.2.jar

Jackson-lombok: http://repo1.maven.org/maven2/io/paradoxical/jackson-lombok/1.1/jackson-lombok-1.1.jar

I am compiling it with Netbeans (I don't think that this is really relevant, but I am reporting this anyway to make it perfectly and faithfully reproducible). The five JARs above are kept in a folder called "lib" inside the project folder (along with "src", "nbproject", "test" and "build"). I added them to Netbeans via the "Add JAR/Folder" button in the project properties and they are listed in the exact order as the list above. The project is a standard "Java application" type project.

Further, the Netbeans project is configured to "do NOT compile on save", "generate debugging info", "report deprecated APIs", "track java dependencies", "activacte annotation proccessing" and "activacte annotation proccessing in the editor". No annotation processor or annotation processing option is explicitly configured in Netbeans. Also, the "-Xlint:all" command line option is passed in the compiler command line, and the compiler runs on an external VM.

My javac's version is 1.8.0_72 and my java's version is 1.8.0_72-b15. My Netbeans is 8.1.

My project compiles fine. However, it throws an exception in its execution. The exception don't seems to be anything that looks easily or obvious fixable. Here is the output, including the stacktrace:

TestFoo(x=b, z=5)
{"z":5,"xoom":"a"}
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=@java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
 at [Source: {"z":5,"xoom":"a"}; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:296)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:269)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:475)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3890)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3785)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2833)
    at testelombok.TestLombok.main(TestLombok.java:14)
Caused by: java.lang.IllegalArgumentException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=@java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._addDeserializerConstructors(BasicDeserializerFactory.java:511)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:323)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:253)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:219)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:141)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:406)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
    ... 7 more

I already tried about randomly poking with the @Value and @AllArgsConstructor annotations, but I couldn't make it any better.

I google'd the exception and found an old bug report on jackson, and another one that is open, but seems to be related to something else. However, this still do not tells anything about what is this bug or how to fix it. Also, I could not find anything useful looking that somewhere else.

Since what I am trying to do is very basic usage of both lombok and jackson, it seems odd that I couldn't find any more useful information about how to workaround this issue. Maybe I missed something?

Other than just saying "don't use lombok" or "don't use jackson", do anybody has any idea about how to solve this?

Body:
I've all my classes annotated like this:

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@Data
@Accessors(fluent = true)
@NoArgsConstructor
@AllArgsConstructor

It worked with all Lombok and Jackson versions for, at least, a couple of years.

Example:

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@Data
@Accessors(fluent = true)
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    String id;
    String first;
    String last;
}

And that's it.
Lombok and Jackson play together like a charm.


问:
How do I make more than one date format in a single view in Swift?
I am trying to save data to a database and am using a date that shows seconds as the key but I want to show a smaller date in the value that is going to be displayed. The problem is to use the date formatter you need to set it like this and I cant figure out how to set another one without overwriting the current format.</p>

```<code>DateFormatter.dateFormat = "MM-dd-yy hh:mm:ss a"
</code>```

答:
This is how to have multiple DateFormatter in a single View.

Formatter1

```<code>let formatter = DateFormatter()
 formatter.dateFormat = "QQQQ\ryyyy" //Shows Financial Quarter for Date
 let formattedDate = formatter.string(from: date)
</code>```

Formatter2

```<code>let formatter1 = DateFormatter()
 formatter1.dateFormat = "EEEE, MMM d, yyyy" //Wednesday, Mar 29, 2017
 let formattedDate1 = formatter1.string(from: date)
</code>```

Refer to this site to know more about DateFormatter. Hope this helps. Happy Coding !

Body:
I am trying to save data to a database and am using a date that shows seconds as the key but I want to show a smaller date in the value that is going to be displayed. The problem is to use the date formatter you need to set it like this and I cant figure out how to set another one without overwriting the current format.

DateFormatter.dateFormat = "MM-dd-yy hh:mm:ss a"

Body:
This is how to have multiple DateFormatter in a single View.

Formatter1

let formatter = DateFormatter()
 formatter.dateFormat = "QQQQ\ryyyy" //Shows Financial Quarter for Date
 let formattedDate = formatter.string(from: date)

Formatter2

let formatter1 = DateFormatter()
 formatter1.dateFormat = "EEEE, MMM d, yyyy" //Wednesday, Mar 29, 2017
 let formattedDate1 = formatter1.string(from: date)

Refer to this site to know more about DateFormatter. Hope this helps. Happy Coding !


问:
best way to stop ondraw() opengl for a time
I use opengl to draw values from an array. The values are from the 3 Android sensors. I want to turn of the renderer during I collect the values. It seems that drawing and gathering at the same time have differenet results, so I want to turn off rendering while I gathering sensorvalues. At the moment I use a boolean in the ondraw() to stop drawing. But is there a better way to do this? There happen freaky things when I stop drawing , like the stuff I draw jittering a little bit some times, but it can't be because there are no drawing( ondraw(){ if(boolean){.........}}

Thank you so much for your help :-)

答: You can ask GLSurfaceView to only draw when asked via setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY), then call requestRender() when you're ready to draw.

ContentLicense: CC BY-SA 2.5


问:
Debugging Arduino with the Eclipse IDE
I have eclipse configured properly in order to upload a file onto my arduino. But now I would like to know if it is possible to debug an arduino only with the eclipse ide? if so are there any instructions which outline how to achieve the same?</p>

答: I've also tried to debug arduino, but it does not seem possible, besides using printf() or some conditional variables.

Title: Debugging Arduino with the Eclipse IDE


问:
How to get values of two columns only when both column values are present using bash script
1

2

3   5

4   6

9

I have two columns, if 2nd column contain no values then skip the row  else I want result like two column values only  when both column values are present

sample output

3 5

4 6

答:
This should work:</p>

```<code>$ awk '/[0-9]+ [0-9]+/' temp.txt
</code>```

Body:
This should work:

$ awk '/[0-9]+ [0-9]+/' temp.txt


问:
My jquery click isnt working
I am making a website and I included jQuery.

When I use click events, it isn't working.

HTML

```<code><body>
  <header>
    <h1 class="text-center">Pomodoro Clock</h1>
  </header>

  <section class="container">

    <div id="counter-main">
      <h1>Session Time</h1>
      <a href="#" class="btn btn-primary" id="plusCounterMain">-</a>
      <h2 id="timerMain">5</h2>
      <a href="#" class="btn btn-primary" id="minusCounterMain">+</a>
    </div>
    <div id="resetDiv">
      <a href="#" class="btn btn-primary" id="resetMain">Reset</a>
    </div>

    <div id="break-main">
      <h1>Session Time</h1>
      <a href="#" class="btn btn-primary" id="plusBreakMain">-</a>
      <h2 id="breakCount">5</h2>
      <a href="#" class="btn btn-primary" id="minusBreakMain">+</a>
    </div>
    <div id="startDiv">
      <button class="btn btn-primary" id="start">Start</button>
    </div>
  </section>
  <!-- jQuery library -->
  <script type="text/javascript" src="jquery-3.2.0"></script>
</body>
</code>```

Here is my JavaScript(jQuery) code:

```<code>$(document).ready(function(){
  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var break = parseInt(break_count.html());

  $("plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function{
    var counter = setInterval(timer,1000);

    function timer() {
      count -=1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }
  });
});
</code>```

I have no idea where I went wrong.

I was trying to make a pomodoro clock, so I used the setInterval function to execute code every second.

Where have I went wrong?

答:
```<code>$(document).ready(function(){
var timer_main = $("#timerMain");
var break_count = $("#breakCount");

var count = parseInt(timer_main.html());
/*var break = parseInt(break_count.html()); */

$("#plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
});

$("#start").click(function(){
    var counter = setInterval(timer,1000);

    function timer() {
        count -=1;
        if (count === 0) {
            clearInterval(counter);
        }
        $("#timerMain").text(count.toString());
    }
});
</code>```

<p>});</p>

Title: My jquery click isnt working

Body:
I am making a website and I included jQuery.

When I use click events, it isn't working.

HTML

Pomodoro Clock

Session Time

      -

5

      +

      Reset

Session Time

      -

5

      +

      <button class="btn btn-primary" id="start">Start</button>

Here is my JavaScript(jQuery) code:

$(document).ready(function(){
  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var break = parseInt(break_count.html());

  $("plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function{
    var counter = setInterval(timer,1000);

    function timer() {
      count -=1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }
  });
});

I have no idea where I went wrong.

I was trying to make a pomodoro clock, so I used the setInterval function to execute code every second.

Where have I went wrong?

Body:
$(document).ready(function(){
var timer_main = $("#timerMain");
var break_count = $("#breakCount");

var count = parseInt(timer_main.html());
/*var break = parseInt(break_count.html()); */

$("#plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
});

$("#start").click(function(){
    var counter = setInterval(timer,1000);

    function timer() {
        count -=1;
        if (count === 0) {
            clearInterval(counter);
        }
        $("#timerMain").text(count.toString());
    }
});

});


问:
Create my own local and remote branch and pull from a remote branch only once
So in our repository we currently have the following branches:

```<code>Master
Dev1
</code>```

I would like to create my own local and remote branch called Dev2 and would like it to initially pull from the remote Dev1 instead of Master (since Dev1 is the most up-to-date and hasn't merged into the Master branch yet). When I then push to my remote branch I want to be pushin to Dev2 which should be a completely detached and independent branch from Dev1.

How could I do this? I am new to using Git, if you couldn't tell :)

答:
You need to first fetch the remote branch on your local system by

git fetch remote_name remote_branch_name

in your case the remote_branch_name would be Dev1

Now you need to create a new branch from Dev1, which you can do like this

git checkout -b new_branch_name remote_name/remote_branch_name

new_branch_name for you would be Dev2

Now whenever you'll push, you can do

git push remote_name new_branch_name

Body:
So in our repository we currently have the following branches:

Master
Dev1

I would like to create my own local and remote branch called Dev2 and would like it to initially pull from the remote Dev1 instead of Master (since Dev1 is the most up-to-date and hasn't merged into the Master branch yet). When I then push to my remote branch I want to be pushin to Dev2 which should be a completely detached and independent branch from Dev1.

How could I do this? I am new to using Git, if you couldn't tell :)


问:
HashMap get method in Java 6 & Java 8
I am looking at HashMap get method in Java 6 & Java 8, the implementation in Java 8 is little complex, I am not able to get it.

This is from Java 6:

```<code>public V get(Object key) {
    if (key == null)
        return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}
</code>```

Here in Java 6, it is getting the right Entry element and trying to find the corresponding value based on given key.

This code if from Java 8:

```<code>    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

 final Node<K,V> getNode(int hash, Object key) {

     Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

     if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {

            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k)))) {
                return first;
            }

            if ((e = first.next) != null) {

                if (first instanceof TreeNode) {
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                }

                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        return e;
                    }
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
</code>```

I am not able to understand the logic in Java 8.

How they are taking the first element:

```<code> (first = tab[(n - 1) & hash]) != null)
</code>```

and what is this extra logic:

```<code>        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
</code>```

答:
Regarding:

```<code>(first = tab[(n - 1) & hash]) != null)
</code>```

That comes from how the entry is added to the table, shown below:

```<code>if ((p = tab[i = (n - 1) & hash]) == null)
    tab[i] = newNode(hash, key, value, null);
</code>```

AND-ing (n-1) and hash allows entries with hashCode=hash to be spread over the n entries of the table. (n-1) is used to prevent the edge case of attempting to insert into tab[n] - which could lead to ArrayIndexOutOfBoundsException since tab.length is n.

The "extra logic" that you are referring to:

```<code>if (first.hash == hash && // always check first node
    ((k = first.key) == key || (key != null && key.equals(k))))
    return first;
</code>```

The above returns the very first Node from the table which not only matches the hashCode of the key being searched, but also exactly "equals" that key.

```<code>if ((e = first.next) != null) {
    if (first instanceof TreeNode)
        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
</code>```

The above returns the Node if the bucket has been "Treeified" - details about which as pointed in one of the comments is specified in the "Implementation Notes" of this class.

Title: HashMap get method in Java 6 & Java 8

Body:
I am looking at HashMap get method in Java 6 & Java 8, the implementation in Java 8 is little complex, I am not able to get it.

This is from Java 6:

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}

Here in Java 6, it is getting the right Entry element and trying to find the corresponding value based on given key.

This code if from Java 8:

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

 final Node<K,V> getNode(int hash, Object key) {

     Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

     if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {

            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k)))) {
                return first;
            }

            if ((e = first.next) != null) {

                if (first instanceof TreeNode) {
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                }

                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        return e;
                    }
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

I am not able to understand the logic in Java 8.

How they are taking the first element:

 (first = tab[(n - 1) & hash]) != null)

and what is this extra logic:

        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);

Body:
Regarding:

(first = tab[(n - 1) & hash]) != null)

That comes from how the entry is added to the table, shown below:

if ((p = tab[i = (n - 1) & hash]) == null)
    tab[i] = newNode(hash, key, value, null);

AND-ing (n-1) and hash allows entries with hashCode=hash to be spread over the n entries of the table. (n-1) is used to prevent the edge case of attempting to insert into tab[n] - which could lead to ArrayIndexOutOfBoundsException since tab.length is n.

The "extra logic" that you are referring to:

if (first.hash == hash && // always check first node
    ((k = first.key) == key || (key != null && key.equals(k))))
    return first;

The above returns the very first Node from the table which not only matches the hashCode of the key being searched, but also exactly "equals" that key.

if ((e = first.next) != null) {
    if (first instanceof TreeNode)
        return ((TreeNode<K,V>)first).getTreeNode(hash, key);

The above returns the Node if the bucket has been "Treeified" - details about which as pointed in one of the comments is specified in the "Implementation Notes" of this class.


问:
Facebook like button ignoring URL depth
I have an URL like:
mywebsite.com/news/

and a facebook like button on each page. The problem is that when you like a page, the counter for all pages is affected, e.g.:

```<code>mywebsite.com/news/news-1/
mywebsite.com/news/?new_id=1
mywebsite.com/news/1/

mywebsite.com/news/news-2/
mywebsite.com/news/?new_id=2
mywebsite.com/news/2/
</code>```

all this as well as mywebsite.com/news/ will have the increased counter as if you've "liked" them all.

I was using the  and switched to the < fb:like > but the bug still occurs.

I've found this thread: http://forum.developers.facebook.net/viewtopic.php?pid=252714 where the people seemed to have the same problem that somehow got fix for one of them, but still persist for me.

Any ideas how to fix it?

答:
This tool gives you specific information what is parsed by Facebook and where the error could be. I found it really helpful:
http://developers.facebook.com/tools/lint/</p>

Title: Facebook like button ignoring URL depth

Body:
I have an URL like:
mywebsite.com/news/

and a facebook like button on each page. The problem is that when you like a page, the counter for all pages is affected, e.g.:

mywebsite.com/news/news-1/
mywebsite.com/news/?new_id=1
mywebsite.com/news/1/

mywebsite.com/news/news-2/
mywebsite.com/news/?new_id=2
mywebsite.com/news/2/

all this as well as mywebsite.com/news/ will have the increased counter as if you've "liked" them all.

I was using the  and switched to the < fb:like > but the bug still occurs.

I've found this thread: http://forum.developers.facebook.net/viewtopic.php?pid=252714 where the people seemed to have the same problem that somehow got fix for one of them, but still persist for me.

Any ideas how to fix it?


问:
Pass object array into member function
Here is the class defination:

```<code>class Unit
{
    public:
     Unit();
     ~Unit();
     void set_unit(int a);
     void modify_flag(Unit&);
     void modify_array(Unit array[], int len);  // ?? The problem
     int show_unit();

    private:
     int ai;

};
</code>```

And the implementation of the member functions:

```<code>void Unit::set_unit(int a)
{
     ai = a;
}

void Unit::modify_flag(Unit& u)
{
     u.set_unit(20);
}

void Unit::modify_array(Unit array[], int len)  // ?? The problem
{
     for (int i = 0; i < len; ++i)
     {
        modify_flag(array[i]);
        array[i].modify_array(array, len);
     }
}

int Unit::show_unit()
{
    return ai;
}
</code>```

And finally the main code:

```<code>int main(int argc, char const *argv[])
{
    int len = 10;
    Unit* array = new Unit[len];

    for (int i = 0; i < len; ++i)
    {
        array[i].set_unit(0);
    }

    array[5].modify_array(array,len);  // ?? The problem

    for (int i = 0; i < len; ++i)
    {
        cout << array[i].show_unit() << endl;
    }

    delete [] array;

    return 0;
}
</code>```

I passed an array of objects into the member function of the class as the parameter, but it aborted suddenly.  I have checked my code many times to make sure the counter did not accumulate over the array length. Therefore, I think there must be something wrong with the object array as the parameter, but I could not figure it out.  What happened with my code ??

答:
Thanks user4581301 for help! I finally found the mistake I made.
The code I had written was to modify the whole array with a random starting index, so I tried to do it by resursive calls. I forgot to put the terminal condition, which must be the most important part, in my recursive function. </p>

```<code>void Unit::modify_array(Unit array[], int len)
{
 for (int i = 0; i < len; ++i)
  {
     if(need_to_modify(array[i]))
       array[i].modify_array(array, len);
   }
}
</code>```

<p>Something like this to jump out the loop. This was the my practice to get familiar with the recursive function. Thanks everyone. </p>

Title: Pass object array into member function

Body:
Here is the class defination:

class Unit
{
    public:
     Unit();
     ~Unit();
     void set_unit(int a);
     void modify_flag(Unit&);
     void modify_array(Unit array[], int len);  // ?? The problem
     int show_unit();

    private:
     int ai;

};

And the implementation of the member functions:

void Unit::set_unit(int a)
{
     ai = a;
}

void Unit::modify_flag(Unit& u)
{
     u.set_unit(20);
}

void Unit::modify_array(Unit array[], int len)  // ?? The problem
{
     for (int i = 0; i < len; ++i)
     {
        modify_flag(array[i]);
        array[i].modify_array(array, len);
     }
}

int Unit::show_unit()
{
    return ai;
}

And finally the main code:

int main(int argc, char const *argv[])
{
    int len = 10;
    Unit* array = new Unit[len];

    for (int i = 0; i < len; ++i)
    {
        array[i].set_unit(0);
    }

    array[5].modify_array(array,len);  // ?? The problem

    for (int i = 0; i < len; ++i)
    {
        cout << array[i].show_unit() << endl;
    }

    delete [] array;

    return 0;
}

I passed an array of objects into the member function of the class as the parameter, but it aborted suddenly.  I have checked my code many times to make sure the counter did not accumulate over the array length. Therefore, I think there must be something wrong with the object array as the parameter, but I could not figure it out.  What happened with my code ??

Body:
Thanks user4581301 for help! I finally found the mistake I made.
The code I had written was to modify the whole array with a random starting index, so I tried to do it by resursive calls. I forgot to put the terminal condition, which must be the most important part, in my recursive function.

void Unit::modify_array(Unit array[], int len)
{
 for (int i = 0; i < len; ++i)
  {
     if(need_to_modify(array[i]))
       array[i].modify_array(array, len);
   }
}

Something like this to jump out the loop. This was the my practice to get familiar with the recursive function. Thanks everyone.


问:
Using mongo gems in Rails 5 -- should it be this hard?
Am I missing something incredibly obvious?

I generate a new rails 5 application, and per the mongo doc, added the gem to the Gemfile:

```<code>gem 'mongo', '~> 2.4'
</code>```

bundle install installs the gem (and gem dependencies) fine, but when I just try to bring up a rails console:

```<code>$ rails c
Could not find bson-4.2.1 in any of the sources
Run `bundle install` to install missing gems.
</code>```

Are there some further installation instructions buried somewhere?

FWIW, ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin14]

and

```<code>$ rails -v
Rails 5.0.2
</code>```

答:
The runtime dependencies for gem 'mongo', '~> 2.4' is

```<code>gem 'bson', '~> 4.2', '>= 4.2.1'
</code>```

please check ref:
https://rubygems.org/gems/mongo/versions/2.4.1

so you need to install the above gem 'bson'.

Body:
Am I missing something incredibly obvious?

I generate a new rails 5 application, and per the mongo doc, added the gem to the Gemfile:

gem 'mongo', '~> 2.4'

bundle install installs the gem (and gem dependencies) fine, but when I just try to bring up a rails console:

$ rails c
Could not find bson-4.2.1 in any of the sources
Run `bundle install` to install missing gems.

Are there some further installation instructions buried somewhere?

FWIW, ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin14]

and

$ rails -v
Rails 5.0.2

Body:
The runtime dependencies for gem 'mongo', '~> 2.4' is

gem 'bson', '~> 4.2', '>= 4.2.1'

please check ref:
https://rubygems.org/gems/mongo/versions/2.4.1

so you need to install the above gem 'bson'.


问:
Navigate in code with react-router-dom 4.0?
Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.

I've search StackOverflow but haven't found any answers that work with 4.0.  Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

```<code>import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);
</code>```

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

```<code><Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);
</code>```

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

```<code><Route path="/" render={({ match, context, history}) => {
</code>```

Is there a way to get to this from outside a route?  For example a navbar component that will navigate to other components, but is not inside a Route itself...

答:
Had to read into the docs more.  The history object is only passed as a property using the component (or other) attributes on a Route.  Apparently need to include the 'history' package and use createBrowserHistory and pass it to the Router, then specify the component in a Route.  I think this should work fine since exact isn't specified...

```<code>import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
ReactDOM.render( (
    <Router history={ history }>
      <Route path="/" component={ App } />
    </Router>
  ),
  document.getElementById('root')
);
</code>```

Before I just had <App/> inside <Router> and didn't have access to those properties.

Body:
Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.

I've search StackOverflow but haven't found any answers that work with 4.0.  Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

<Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

<Route path="/" render={({ match, context, history}) => {

Is there a way to get to this from outside a route?  For example a navbar component that will navigate to other components, but is not inside a Route itself...

Body:
Had to read into the docs more.  The history object is only passed as a property using the component (or other) attributes on a Route.  Apparently need to include the 'history' package and use createBrowserHistory and pass it to the Router, then specify the component in a Route.  I think this should work fine since exact isn't specified...

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
ReactDOM.render( (
    <Router history={ history }>
      <Route path="/" component={ App } />
    </Router>
  ),
  document.getElementById('root')
);

Before I just had <App/> inside <Router> and didn't have access to those properties.


问:
Jmeter only runs the first thread
I'm still new to Jmeter and I'm having trouble running more than one thread in my test plan.

I'm trying to run the tests using the GUI (just to make check that they pass), but when I run the test plan, it only seems to run the first thread in the plan. Is there something I've done wrong in my test plan?

答:
Add "View result tree" listener in your test plan level instead of adding it individually for each thread group. This will solve your issue.

Hope this helps..

Title: Jmeter only runs the first thread


问:
Date/Time Revit Shared Parameter
I am a brazilian student and I work on a research Project where I need to develop plug-ins for Autodesk Revit.
In the midst of my research, some doubts have arisen.
How can I do to insert into a Revit family a shared parameter/project parameter in date/time format ? </p>

答: Use a string and format it any way you like. Revit parameters do not provide built-in support for date and time.</p>

Title: Date/Time Revit Shared Parameter


问:
ExtJS custom Paging parameters
I have an Extjs Grid with a Paging toolbar.
I need to pass the server custom parameters for each request I make when paging the data.
I have tried setting the params in the store load event , but it seems the pager does not remember the last options used for loading the store when the next button is clicked.

Here is some code:

```<code>var sourceGrid = new Ext.grid.EditorGridPanel({
    region: 'center',
    title: localize.sourceView,
    store: sourceStore,
    trackMouseOver: true,
    disableSelection: false,
    loadMask: true,
    stripeRows: true,
    autoExpandColumn: "label",

    // grid columns
    columns: [
         { header: 'ID', dataIndex: 'id', width: 50, hidden: true, sortable: true },
         { header: 'Language ID', dataIndex: 'languageID', width: 50, hidden: true, sortable: true },
         { header: 'Language', dataIndex: 'language', width: 20, hidden: true, sortable: true },
         { header: 'Key ID', dataIndex: 'keyID', width: 30, hidden: true, sortable: true },
         { header: 'Key', dataIndex: 'keyValue', width: 40, sortable: true },
         { header: 'Label', dataIndex: 'label', sortable: true, editor: new Ext.form.TextField({ allowBlank: false }) },
         { header: 'Description', dataIndex: 'keyDesc', width: 30 },
         { header: 'Tool Tip', dataIndex: 'toolTip', width: 80, sortable: true, editor: new Ext.form.TextField({ allowBlank: true }) }
    ],

    // customize view config
    viewConfig: {
        forceFit: true,
        enableRowBody: true,
        showPreview: false
    },

    sm: new Ext.grid.RowSelectionModel({
        singleSelect: false,
        moveEditorOnEnter: true
    }),

    // actions buttons
    tbar: new Ext.Toolbar({
        items: [{
            text: localize.create,
            handler: function () {
                onAddLabelClick();
            }
        }, '|', {
            text: localize.deleteText,
            handler: function (tb, e) { onLabelDeleteAttempt() }
        }, '|', {
            text: localize.importFromExcel,
            handler: function (tb, e) {
                showUploadWin(getUploadLabelsForm());
            }
        }, '|', {
            id: 'export-toExcel-tbar',
            text: localize.exportToExcl,
            handler: function (tb, e) {
                onExportToExcelClick(tb);
            }
        }, '|', {
            id: 'search-label-textbox',
            xtype: 'textfield',
            width:200,
            blankText: localize.searchLabels
        }, {
            id: 'search-label-button',
            text: 'Search',
            handler: function (t, e) {

            }
        }
        ]
    }),

    // paging bar on the bottom
    bbar: new Ext.PagingToolbar({
        id: 'labelsBbr',
        pageSize: 36,
        store: sourceStore,
        displayInfo: true,
        displayMsg: localize.displayLabels,
        emptyMsg: localize.noLablesToDisplay
    }),

    // right click menu
    contextMenu: new Ext.menu.Menu({
        items: [{
            id: 'export-excel',
            text: localize.exportToExcl
        }],
        listeners: {
            itemclick: function (item) {
                switch (item.id) {
                    case 'export-excel':
                        onExportToExcelClick(item);
                        break;
                }
            }
        }
    }),

    listeners: {
        keydown: {
            scope: this,
            fn: function (e) {
                if (e.getCharCode() == 46) {
                    onLabelDeleteAttempt();
                }
            }
        },
        rowcontextmenu: function (g, ri, e) {
            var m = g.contextMenu;
            m.contextNode = g;
            m.showAt(e.getXY());
        },
        // privant default browser menu on client right click.
        render: function (grid) {
            grid.getEl().on('contextmenu', Ext.emptyFn, null, { preventDefault: true });
        }
    }
});
var sourceStore = new Ext.data.JsonStore({
    url: hp,
    storeId: 'labels-data-store',
    idProperty: 'id',
    totalProperty: 'totalCount',
    root: 'translations',
    fields: [
        { name: 'id', type: 'string' },
        { name: 'languageID', type: 'string' },
        { name: 'language', type: 'string' },
        { name: 'keyID', type: 'string' },
        { name: 'keyValue', type: 'string' },
        { name: 'keyDesc', type: 'string' },
        { name: 'label', type: 'string' },
        { name: 'toolTip', type: 'string' }
    ],
    paramNames: {
        start:'start',
        limit:'limit',
        sort:'sort',
        dir:'dir',
        actionName:'actionName',
        lanID:'lanID'
    },
    sortInfo: {
        field: 'id',
        direction: "DESC"
    },
    // set aditional parameters for the store in this event.
    listeners: {
        'exception': function (sp, type, action, options, response, arg) {
            Ext.MessageBox.alert(localize.unKnownError, arg);
        }
    }
});
sourceStore.load({
        params: {
            start: 0,
            limit: Ext.getCmp('labelsBbr').pageSize,
            actionName: 'TranslationPaging',
            lanID: getSelectedLanguageID()
        }
    });
</code>```

I need for each "Next Page" call to the server to have the lanID param and the actionName param.

Can it be done?

答:
Set the baseParams for your store.

baseParams : Object

  An object containing properties which
  are to be sent as parameters for every
  HTTP request. Parameters are encoded
  as standard HTTP parameters using
  Ext.urlEncode.

```<code>var sourceStore = new Ext.data.JsonStore({
    // your configs
    baseParams: {
        actionName: 'TranslationPaging',
        lanID: getSelectedLanguageID()
    }
});

// After initialization, to change the baseParams, use:
sourceStore.setBaseParam( 'lanID', getSelectedLanguageID() );
</code>```

setBaseParam may be new with ExtJS 3.3, so see if it's available in your version (if you're not up to date).  Otherwise you can access the store's baseParams directly with store.baseParams.

Title: ExtJS custom Paging parameters

Body:
I have an Extjs Grid with a Paging toolbar.
I need to pass the server custom parameters for each request I make when paging the data.
I have tried setting the params in the store load event , but it seems the pager does not remember the last options used for loading the store when the next button is clicked.

Here is some code:

var sourceGrid = new Ext.grid.EditorGridPanel({
    region: 'center',
    title: localize.sourceView,
    store: sourceStore,
    trackMouseOver: true,
    disableSelection: false,
    loadMask: true,
    stripeRows: true,
    autoExpandColumn: "label",

    // grid columns
    columns: [
         { header: 'ID', dataIndex: 'id', width: 50, hidden: true, sortable: true },
         { header: 'Language ID', dataIndex: 'languageID', width: 50, hidden: true, sortable: true },
         { header: 'Language', dataIndex: 'language', width: 20, hidden: true, sortable: true },
         { header: 'Key ID', dataIndex: 'keyID', width: 30, hidden: true, sortable: true },
         { header: 'Key', dataIndex: 'keyValue', width: 40, sortable: true },
         { header: 'Label', dataIndex: 'label', sortable: true, editor: new Ext.form.TextField({ allowBlank: false }) },
         { header: 'Description', dataIndex: 'keyDesc', width: 30 },
         { header: 'Tool Tip', dataIndex: 'toolTip', width: 80, sortable: true, editor: new Ext.form.TextField({ allowBlank: true }) }
    ],

    // customize view config
    viewConfig: {
        forceFit: true,
        enableRowBody: true,
        showPreview: false
    },

    sm: new Ext.grid.RowSelectionModel({
        singleSelect: false,
        moveEditorOnEnter: true
    }),

    // actions buttons
    tbar: new Ext.Toolbar({
        items: [{
            text: localize.create,
            handler: function () {
                onAddLabelClick();
            }
        }, '|', {
            text: localize.deleteText,
            handler: function (tb, e) { onLabelDeleteAttempt() }
        }, '|', {
            text: localize.importFromExcel,
            handler: function (tb, e) {
                showUploadWin(getUploadLabelsForm());
            }
        }, '|', {
            id: 'export-toExcel-tbar',
            text: localize.exportToExcl,
            handler: function (tb, e) {
                onExportToExcelClick(tb);
            }
        }, '|', {
            id: 'search-label-textbox',
            xtype: 'textfield',
            width:200,
            blankText: localize.searchLabels
        }, {
            id: 'search-label-button',
            text: 'Search',
            handler: function (t, e) {

            }
        }
        ]
    }),

    // paging bar on the bottom
    bbar: new Ext.PagingToolbar({
        id: 'labelsBbr',
        pageSize: 36,
        store: sourceStore,
        displayInfo: true,
        displayMsg: localize.displayLabels,
        emptyMsg: localize.noLablesToDisplay
    }),

    // right click menu
    contextMenu: new Ext.menu.Menu({
        items: [{
            id: 'export-excel',
            text: localize.exportToExcl
        }],
        listeners: {
            itemclick: function (item) {
                switch (item.id) {
                    case 'export-excel':
                        onExportToExcelClick(item);
                        break;
                }
            }
        }
    }),

    listeners: {
        keydown: {
            scope: this,
            fn: function (e) {
                if (e.getCharCode() == 46) {
                    onLabelDeleteAttempt();
                }
            }
        },
        rowcontextmenu: function (g, ri, e) {
            var m = g.contextMenu;
            m.contextNode = g;
            m.showAt(e.getXY());
        },
        // privant default browser menu on client right click.
        render: function (grid) {
            grid.getEl().on('contextmenu', Ext.emptyFn, null, { preventDefault: true });
        }
    }
});
var sourceStore = new Ext.data.JsonStore({
    url: hp,
    storeId: 'labels-data-store',
    idProperty: 'id',
    totalProperty: 'totalCount',
    root: 'translations',
    fields: [
        { name: 'id', type: 'string' },
        { name: 'languageID', type: 'string' },
        { name: 'language', type: 'string' },
        { name: 'keyID', type: 'string' },
        { name: 'keyValue', type: 'string' },
        { name: 'keyDesc', type: 'string' },
        { name: 'label', type: 'string' },
        { name: 'toolTip', type: 'string' }
    ],
    paramNames: {
        start:'start',
        limit:'limit',
        sort:'sort',
        dir:'dir',
        actionName:'actionName',
        lanID:'lanID'
    },
    sortInfo: {
        field: 'id',
        direction: "DESC"
    },
    // set aditional parameters for the store in this event.
    listeners: {
        'exception': function (sp, type, action, options, response, arg) {
            Ext.MessageBox.alert(localize.unKnownError, arg);
        }
    }
});
sourceStore.load({
        params: {
            start: 0,
            limit: Ext.getCmp('labelsBbr').pageSize,
            actionName: 'TranslationPaging',
            lanID: getSelectedLanguageID()
        }
    });

I need for each "Next Page" call to the server to have the lanID param and the actionName param.

Can it be done?

Body:
Set the baseParams for your store.

baseParams : Object

  An object containing properties which
  are to be sent as parameters for every
  HTTP request. Parameters are encoded
  as standard HTTP parameters using
  Ext.urlEncode.

var sourceStore = new Ext.data.JsonStore({
    // your configs
    baseParams: {
        actionName: 'TranslationPaging',
        lanID: getSelectedLanguageID()
    }
});

// After initialization, to change the baseParams, use:
sourceStore.setBaseParam( 'lanID', getSelectedLanguageID() );

setBaseParam may be new with ExtJS 3.3, so see if it's available in your version (if you're not up to date).  Otherwise you can access the store's baseParams directly with store.baseParams.


问:
Black bar flashes at top of UITableView when pushing to view with "Hides Bottom Bar When Pushed" in IB
This is a weird error that may just be an issue in Xcode for all I know. I have a tab bar controller where the first view is a UITableView with (obviously) a number of cells. When you select a cell, I've set up a segue on the MainStoryboard to go to a detail view controller. I want the tab bar to be hidden when I go to the detail view, so I went into the storyboard, chose my detail view, and clicked "Hides Bottom Bar on Push" in the editor screen that starts with "Simulated Metrics."

Everything works just fine, except that when I tap on a cell, a black bar flashes at the top of the UITableView screen, dropping the tableview cells down (as if the cells are falling down below the tab bar at the bottom), just before the screen pushes over to the detail view. The effect isn't harmful at all, but it's very disconcerting, and I'd like to smooth that out.

The only fix I've found is to uncheck the "Hides Bottom Bar when Pushed" option on the storyboard. That indeed does get rid of that black bar flash, but of course the tab bar stays on the screen when I go to the detail view, which is what I don't want.

Any ideas?

Just for completeness' sake, I went ahead and ran

```<code>[self.navigationController setToolbarHidden:YES animated: YES];
</code>```

on the detail view controller's viewWillAppear method (and even tried it with the storyboard option both on and off), but there was no difference. The toolbar did indeed hide just fine, but I still got that black line at the top. So weird.

答:
I know it is a bit late, but I have same problem and I can't solve it with any of the previous answers. (I suppose this is the reason non was accepted).

The problem is that view size of the SecondViewController is same as view size of a previous ViewController, so too small to fit in a ViewController with Toolbar hidden. Thats why black background of a UITabBarController is visible at the top when transition is happening, and on a viewDidAppear view will stretch on right size.

For me it help to subclass root UITabBarController and set background color to same background color as SecondViewController has.

```<code>class RootViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = Style.backgroundColor
    }
}
</code>```

Then you can leave checkbox checked inside storyboard and it will look ok.

P.S.

If you have some views, that is position on the bottom part of the view, you need to set bottom constraints so they are smaller by 49 (because this is the height of the toolbar), and then on viewDidAppear set the right constraint.

For example:

I have view that need to be position 44 px from bottom edge. Before, I have constraint set to 44 and I have some strange behaviour of that view. It was placed to height and then jump on the right place.

I fix this with setting constraint to -5 (44-49), and then in viewDidAppear set the constraint back to 44. Now I have normal behaviour of that view.

Body:
This is a weird error that may just be an issue in Xcode for all I know. I have a tab bar controller where the first view is a UITableView with (obviously) a number of cells. When you select a cell, I've set up a segue on the MainStoryboard to go to a detail view controller. I want the tab bar to be hidden when I go to the detail view, so I went into the storyboard, chose my detail view, and clicked "Hides Bottom Bar on Push" in the editor screen that starts with "Simulated Metrics."

Everything works just fine, except that when I tap on a cell, a black bar flashes at the top of the UITableView screen, dropping the tableview cells down (as if the cells are falling down below the tab bar at the bottom), just before the screen pushes over to the detail view. The effect isn't harmful at all, but it's very disconcerting, and I'd like to smooth that out.

The only fix I've found is to uncheck the "Hides Bottom Bar when Pushed" option on the storyboard. That indeed does get rid of that black bar flash, but of course the tab bar stays on the screen when I go to the detail view, which is what I don't want.

Any ideas?

Just for completeness' sake, I went ahead and ran

[self.navigationController setToolbarHidden:YES animated: YES];

on the detail view controller's viewWillAppear method (and even tried it with the storyboard option both on and off), but there was no difference. The toolbar did indeed hide just fine, but I still got that black line at the top. So weird.

Body:
I know it is a bit late, but I have same problem and I can't solve it with any of the previous answers. (I suppose this is the reason non was accepted).

The problem is that view size of the SecondViewController is same as view size of a previous ViewController, so too small to fit in a ViewController with Toolbar hidden. Thats why black background of a UITabBarController is visible at the top when transition is happening, and on a viewDidAppear view will stretch on right size.

For me it help to subclass root UITabBarController and set background color to same background color as SecondViewController has.

class RootViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = Style.backgroundColor
    }
}

Then you can leave checkbox checked inside storyboard and it will look ok.

P.S.

If you have some views, that is position on the bottom part of the view, you need to set bottom constraints so they are smaller by 49 (because this is the height of the toolbar), and then on viewDidAppear set the right constraint.

For example:

I have view that need to be position 44 px from bottom edge. Before, I have constraint set to 44 and I have some strange behaviour of that view. It was placed to height and then jump on the right place.

I fix this with setting constraint to -5 (44-49), and then in viewDidAppear set the constraint back to 44. Now I have normal behaviour of that view.


问:
write multiple lines in a file in python
I have the following code:

```<code>line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
</code>```

Here target is the file object and line1, line2, line3 are the user inputs.
I want to use only a single target.write() command to write this script. I have tried using the following:

```<code>target.write("%s \n %s \n %s \n") % (line1, line2, line3)
</code>```

But doesn't that put a string inside another string but if I use the following:

```<code>target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)
</code>```

The Python interpreter(I'm using Microsoft Powershell) says invalid syntax.
How would I able to do it?

答:
Assuming you don't want a space at each new line use:

```<code>print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
</code>```

This works for version 3.6

Body:
I have the following code:

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

Here target is the file object and line1, line2, line3 are the user inputs.
I want to use only a single target.write() command to write this script. I have tried using the following:

target.write("%s \n %s \n %s \n") % (line1, line2, line3)

But doesn't that put a string inside another string but if I use the following:

target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)

The Python interpreter(I'm using Microsoft Powershell) says invalid syntax.
How would I able to do it?

Body:
Assuming you don't want a space at each new line use:

print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))

This works for version 3.6


问:
Swipe to back navigation not working for Localization app
In my app I'm using two languages English and Arabic. When I change my language from one to another the swipe to back navigation is working as my previous language.

Eg: English swipe left to right, Arabic swipe right to left. But in my case English popping right to left, Arabic popping left to right. This happens for the first time of the app launch after changing language. For the next time its working fine.

After changing language the user need to restart the app. I use this below code to set the language,

In main.m

```<code>        if ([languageSelected isEqualToString:@"en_US"]) {
            NSArray* languages = [NSArray arrayWithObjects:@"en", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
        } else if ([languageSelected isEqualToString:@"ar"]) {
            NSArray* languages = [NSArray arrayWithObjects:@"ar", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        }
</code>```

Could anyone give some suggestion?
Thanks in advance!!

答:
I found the solution, we need to set language at the time of app terminates like below

```<code>- (void)applicationWillTerminate:(UIApplication *)application {
        if ([languageSelected isEqualToString:@"en_US"]) {
            LocalizationSetLanguage(@"en");
            NSArray* languages = [NSArray arrayWithObjects:@"en", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
        } else if ([languageSelected isEqualToString:@"ar"]) {
            LocalizationSetLanguage(@"ar");
            NSArray* languages = [NSArray arrayWithObjects:@"ar", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        }
}
</code>```

Hope some one get use of it.

Body:
In my app I'm using two languages English and Arabic. When I change my language from one to another the swipe to back navigation is working as my previous language.

Eg: English swipe left to right, Arabic swipe right to left. But in my case English popping right to left, Arabic popping left to right. This happens for the first time of the app launch after changing language. For the next time its working fine.

After changing language the user need to restart the app. I use this below code to set the language,

In main.m

        if ([languageSelected isEqualToString:@"en_US"]) {
            NSArray* languages = [NSArray arrayWithObjects:@"en", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
        } else if ([languageSelected isEqualToString:@"ar"]) {
            NSArray* languages = [NSArray arrayWithObjects:@"ar", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        }

Could anyone give some suggestion?
Thanks in advance!!

Body:
I found the solution, we need to set language at the time of app terminates like below

- (void)applicationWillTerminate:(UIApplication *)application {
        if ([languageSelected isEqualToString:@"en_US"]) {
            LocalizationSetLanguage(@"en");
            NSArray* languages = [NSArray arrayWithObjects:@"en", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
        } else if ([languageSelected isEqualToString:@"ar"]) {
            LocalizationSetLanguage(@"ar");
            NSArray* languages = [NSArray arrayWithObjects:@"ar", nil];
            [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        }
}

Hope some one get use of it.


问:
Logging Method signature using swift
I am trying to rewrite my logging class and I would like to know how to substitute PRETTY_FUNCTION or NSStringFromSelector(_cmd) in a swift file in order to track the method calls?

答:
Swift 3 support debugLog object with date, function name, file name, line number:</p>

```<code>public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
    let className = (fileName as NSString).lastPathComponent
    print("\(NSDate()): <\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
}
</code>```

Title: Logging Method signature using swift

Body:
Swift 3 support debugLog object with date, function name, file name, line number:

public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
    let className = (fileName as NSString).lastPathComponent
    print("\(NSDate()): <\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
}


问:
MySql database doesn't submit the values of my form
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

```<code>   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

    <div class="registaration-logo">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <img src="images/translogo.png" alt=" ">
            </div>
        </div>
    </div>

    <form class="form-registration" action="reg_db.php" method="post">
              <h2> Registration </h2>
        <div class="form-group-row">
            <label for="Name" class="col-2 col-form-label">Name</label>
            <div class="col-10">
                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name"> </div>
        </div>
        <div class="form-group-row">
            <label for="Surname" class="col-2 col-form-label">Surname</label>
            <div class="col-10">
                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname"> </div>
        </div>
        <div class="form-group-row">
            <label for="Email" class="col-2 col-form-label">Email</label>
            <div class="col-10">
                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Confirm Email" class="col-2 col-form-label"> Confirm Email</label>
            <div class="col-10">
                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Telephone" class="col-2 col-form-label">Telephone Number</label>
            <div class="col-10">
                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number"> </div>
        </div>
        <div class="form-group-row">
            <label for="ID_Number" class="col-2 col-form-label">ID Number</label>
            <div class="col-10">
                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number"> </div>
        </div>
        <div class="form-group-row">
            <div class="col-sm-10">
                    <a href="verify.html" class="btn btn-default1" role="button" type="submit">Submit</a>
            </div>
        </div>

        <div class="panel panel-default">
  <div class="panel-body">
    <h3> Disclaimer</h3>
      <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  </div>
        </div>
 </form>

</body>

</html>

 VERIFY.HTML PAGE
    <!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

   <div class="verify">
  <div class="jumbotron">
    <h2>Thank You</h2>
    <p>We will send you your login information when you are verified.</p>
  </div>
       </div>
</body>

</html>
</code>```

答:
Its probably due to the fact that you are sending your forms post variables to reg_db.php when the code is on the same file.

Change

```<code><form class="form-registration" action="reg_db.php" method="post">
</code>```

To...

```<code><form class="form-registration" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
</code>```

Body:
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>

    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

    <form class="form-registration" action="reg_db.php" method="post">

 Registration

            Name

                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name">

            Surname

                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname">

            Email

                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email">

             Confirm Email

                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email">

            Telephone Number

                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number">

            ID Number

                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number">

                    Submit

 Disclaimer

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

 </form>

 VERIFY.HTML PAGE
    <!DOCTYPE html>

    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

Thank You

We will send you your login information when you are verified.

Body:
Its probably due to the fact that you are sending your forms post variables to reg_db.php when the code is on the same file.

Change

<form class="form-registration" action="reg_db.php" method="post">

To...

<form class="form-registration" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">