问:
scanner.hasNextInt() returns unexpected value
I'm very new in Java, and for practicing I'm trying to make a program that generates new, random words using some values (mostly letters). The program is meant to take these values from a text file. The next step is to define inventories (Arrays) that contain each letter of its kind (first by defining a variable (int) for the length of each array, and then filling each array with its proper letters (String)). While checking my progress, I realize that my code isn't updating the inventories lengths (cInv and vInv).

This is the relevant part of the code:

```<code>static File language;
static Scanner scanFile;
static Scanner scanInput = new Scanner(System.in);

static int cInv;
static int vInv;

//Getters go here

public static void setLanguage(File language) {Problem.language = language;}
public static void setCInv(int CInv) {Problem.cInv = cInv;}
public static void setVInv(int VInv) {Problem.vInv = vInv;}

//Asks for the file with the language values.
public static void takeFile() throws FileNotFoundException {
    String route = scanInput.nextLine();
    setLanguage(new File(route));

    BufferedReader br;
    br = new BufferedReader(new FileReader(language));
}

//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
    takeFile();
    scanFile = new Scanner(language);

    //Defines the inventory sizes. It seems the failure is here.
    if (scanFile.hasNextInt()) {setCInv(scanFile.nextInt());}
    if (scanFile.hasNextInt()) {setVInv(scanFile.nextInt());}
}

public static void main(String[] args) throws FileNotFoundException {
    readFile();
    //The following line is for checking the progress of my coding.
    System.out.println(cInv);
}
</code>```

This is the relevant part of the text file that it reads (or should be reading):

```<code>---Phonemes---
Consonants: 43
Vowels:     9
</code>```

And it's output is 0

I've tried typing 43 at the very beginning of the file, and I've also tried typing the number in the input, but I keep getting 0 nevertheless. Does someone know what I'm missing or doing wrong?

答:
First, change your assignments as you are reassigning the same static variables.

```<code>public static void setCInv(int CInv) {Problem.cInv = CInv;}
public static void setVInv(int VInv) {Problem.vInv = CInv;}
</code>```

Second, you need to move across all tokens in the file to identify the numbers and update the respective variable.

```<code>//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
    takeFile();
    scanFile = new Scanner(language);
    int num = 0;
    scanFile.nextLine(); //Skip ---Phonemes---
    setCInv(getInt(scanFile.nextLine()));
    setVInv(getInt(scanFile.nextLine()));
}

public static int getInt(String str){
    System.out.println(str);
    int num =0;
    Scanner line = new Scanner(str);
    //Splits the scanned line into tokens (accessed via next()) and search for numbers.
    //Similar thing could have been done using String.split(token);
    while(line.hasNext()){
        try{
            num = Integer.parseInt(line.next());
            return num;
        }catch(NumberFormatException e){}
    }
    return num;
}
</code>```

Body:
I'm very new in Java, and for practicing I'm trying to make a program that generates new, random words using some values (mostly letters). The program is meant to take these values from a text file. The next step is to define inventories (Arrays) that contain each letter of its kind (first by defining a variable (int) for the length of each array, and then filling each array with its proper letters (String)). While checking my progress, I realize that my code isn't updating the inventories lengths (cInv and vInv).

This is the relevant part of the code:

static File language;
static Scanner scanFile;
static Scanner scanInput = new Scanner(System.in);

static int cInv;
static int vInv;

//Getters go here

public static void setLanguage(File language) {Problem.language = language;}
public static void setCInv(int CInv) {Problem.cInv = cInv;}
public static void setVInv(int VInv) {Problem.vInv = vInv;}

//Asks for the file with the language values.
public static void takeFile() throws FileNotFoundException {
    String route = scanInput.nextLine();
    setLanguage(new File(route));

    BufferedReader br;
    br = new BufferedReader(new FileReader(language));
}

//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
    takeFile();
    scanFile = new Scanner(language);

    //Defines the inventory sizes. It seems the failure is here.
    if (scanFile.hasNextInt()) {setCInv(scanFile.nextInt());}
    if (scanFile.hasNextInt()) {setVInv(scanFile.nextInt());}
}

public static void main(String[] args) throws FileNotFoundException {
    readFile();
    //The following line is for checking the progress of my coding.
    System.out.println(cInv);
}

This is the relevant part of the text file that it reads (or should be reading):

---Phonemes---
Consonants: 43
Vowels:     9

And it's output is 0

I've tried typing 43 at the very beginning of the file, and I've also tried typing the number in the input, but I keep getting 0 nevertheless. Does someone know what I'm missing or doing wrong?

Body:
First, change your assignments as you are reassigning the same static variables.

public static void setCInv(int CInv) {Problem.cInv = CInv;}
public static void setVInv(int VInv) {Problem.vInv = CInv;}

Second, you need to move across all tokens in the file to identify the numbers and update the respective variable.

//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
    takeFile();
    scanFile = new Scanner(language);
    int num = 0;
    scanFile.nextLine(); //Skip ---Phonemes---
    setCInv(getInt(scanFile.nextLine()));
    setVInv(getInt(scanFile.nextLine()));
}

public static int getInt(String str){
    System.out.println(str);
    int num =0;
    Scanner line = new Scanner(str);
    //Splits the scanned line into tokens (accessed via next()) and search for numbers.
    //Similar thing could have been done using String.split(token);
    while(line.hasNext()){
        try{
            num = Integer.parseInt(line.next());
            return num;
        }catch(NumberFormatException e){}
    }
    return num;
}


来源: stackexchange

问:
Jxls Error : Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath
This question has been already asked once but no one gave a absolute solution to it.
Im trying to generate a xls file from a existing template but im getting an error which I dont know how to face out!

My code:
String nombre = "Manuel";

```<code>        try (InputStream templateFileName = ExportExcelServlet.class.getResourceAsStream("/segJBOSS/lib/xls/Tabla_Gestion.xlsx")) {
            try (OutputStream destFileName = new FileOutputStream("Tabla_Gestion.xls")) {
                ArrayList<String> array = new ArrayList<String>();
                array.add(nombre);
                Context context = new Context();
                context.putVar("gestion", array);
                JxlsHelper.getInstance().processTemplate(templateFileName, destFileName, context);
                } catch (Exception e) {
                // TODO: handle exception
                System.out.println(e.getMessage());
                e.printStackTrace();
                }

        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
</code>```

This is being implemented into a WebServlet.

```<code>17:08:43,472 ERROR [org.jxls.util.TransformerFactory] (default task-3) Method createTransformer of org.jxls.transform.poi.PoiTransformer class thrown an Exception: java.lang.reflect.InvocationTargetException

Caused by: java.lang.NullPointerException

17:08:43,478 INFO  [stdout] (default task-3) Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath
17:08:43,479 ERROR [stderr] (default task-3) java.lang.IllegalStateException: Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath
</code>```

Thanks alot!

答:
I also encountered the same issue when using maven profiles and resource filtering. It was fixed by turning off the resource filtering to your jxls excel templates.</p>

```<code>  <resource>
    <directory>src/main/resources/</directory>
    <filtering>false</filtering>
    <includes>
      <include>**/*.xlsx</include>
    </includes>
  </resource>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This question has been already asked once but no one gave a absolute solution to it.
Im trying to generate a xls file from a existing template but im getting an error which I dont know how to face out!

My code:
String nombre = "Manuel";

        try (InputStream templateFileName = ExportExcelServlet.class.getResourceAsStream("/segJBOSS/lib/xls/Tabla_Gestion.xlsx")) {
            try (OutputStream destFileName = new FileOutputStream("Tabla_Gestion.xls")) {
                ArrayList<String> array = new ArrayList<String>();
                array.add(nombre);
                Context context = new Context();
                context.putVar("gestion", array);
                JxlsHelper.getInstance().processTemplate(templateFileName, destFileName, context);
                } catch (Exception e) {
                // TODO: handle exception
                System.out.println(e.getMessage());
                e.printStackTrace();
                }

        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

This is being implemented into a WebServlet.

17:08:43,472 ERROR [org.jxls.util.TransformerFactory] (default task-3) Method createTransformer of org.jxls.transform.poi.PoiTransformer class thrown an Exception: java.lang.reflect.InvocationTargetException

Caused by: java.lang.NullPointerException

17:08:43,478 INFO  [stdout] (default task-3) Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath
17:08:43,479 ERROR [stderr] (default task-3) java.lang.IllegalStateException: Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath

Thanks alot!

Body:
I also encountered the same issue when using maven profiles and resource filtering. It was fixed by turning off the resource filtering to your jxls excel templates.

  <resource>
    <directory>src/main/resources/</directory>
    <filtering>false</filtering>
    <includes>
      <include>**/*.xlsx</include>
    </includes>
  </resource>


问:
How do I input multiple exogenous variables into a SARIMAX model in statsmodel?
In statsmodels, for the SARIMAX or ARIMA model, I would like to use more than one additional external variable (exogenous variables). E.g. I want to predict yield at time t using AR of lag 3 for the yield time series and AR of lag 4 with weather temperature time series and another variable of market price with AR of lag 3. It doesn't appear possible? Any examples or explanation of how this can be done? </p>

答:
First of all you have to define your exogenous input as an array-type structure with dimensions nobsxk where nobs is the number of your endogenous observations (i.e. supposing that you have a time series, the length of your time series) and k the number of your additional exogenous variables. Supposing that you use a ndarray for this purpose you may begin with something like

```<code>exog = np.empty([nobs, k])
</code>```

and then fill it with the values of your exogenous variables. Then, you define your model as in the following example:

```<code>model = sm.tsa.SARIMAX(endog=series, exog=exog, order=order, seasonal_order=seasonal_order).fit(start_params=[0, 0, 0, 0, 0, 1])
</code>```

where series is your original time series, exog the exogenous input, order a (p,d,q) tuple and seasonal_order a (P,D,Q,s) tuple. You should pay attention to the start_params list which I found essential for successfully building the sarimax model in my case.

When I did not use any exogenous input, the start_params list was start_params = [0, 0, 0, 1] for (p,d,q) = (1,0,0) and (P,D,Q,s) = (1,0,0,37).

When I added 3 new exogenous inputs, I set the start_params list to start_params = [0, 0, 0, 0, 1, 1] which if you notice has 2 additional elements.

I suppose (I do not know for sure neither checked it thoroughly) that if you add k exogenous inputs in your model you have to add k - 1 additional elements in your start_params list in order to build the sarimax model successfully.

Hope it helps. Cheers.

Body:
First of all you have to define your exogenous input as an array-type structure with dimensions nobsxk where nobs is the number of your endogenous observations (i.e. supposing that you have a time series, the length of your time series) and k the number of your additional exogenous variables. Supposing that you use a ndarray for this purpose you may begin with something like

exog = np.empty([nobs, k])

and then fill it with the values of your exogenous variables. Then, you define your model as in the following example:

model = sm.tsa.SARIMAX(endog=series, exog=exog, order=order, seasonal_order=seasonal_order).fit(start_params=[0, 0, 0, 0, 0, 1])

where series is your original time series, exog the exogenous input, order a (p,d,q) tuple and seasonal_order a (P,D,Q,s) tuple. You should pay attention to the start_params list which I found essential for successfully building the sarimax model in my case.

When I did not use any exogenous input, the start_params list was start_params = [0, 0, 0, 1] for (p,d,q) = (1,0,0) and (P,D,Q,s) = (1,0,0,37).

When I added 3 new exogenous inputs, I set the start_params list to start_params = [0, 0, 0, 0, 1, 1] which if you notice has 2 additional elements.

I suppose (I do not know for sure neither checked it thoroughly) that if you add k exogenous inputs in your model you have to add k - 1 additional elements in your start_params list in order to build the sarimax model successfully.

Hope it helps. Cheers.


问:
IronPython windows registry get installation paths
I'm trying to get what software's installed on my computer as well as the path they're installed to.

I found a link which provided code to get installed software, but I'm unsure how to get the installation paths, and how to associate a certain path(s) with a particular software package.

```<code># prints out the names of installed software
# just need to find the installtion paths
from Microsoft.Win32 import Registry
products = Registry.ClassesRoot.OpenSubKey("Installer\\Products")
for product_name in products.GetSubKeyNames():
    product_key = products.OpenSubKey(product_name)
    print product_key.GetValue("ProductName")
</code>```

As a side note, is there a tutorial/guide somewhere which details how to use the Windows Registry (such as the keys used above)?

答:
After playing around with regedit for a while, I found that installation paths are located at SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Folders

```<code>from Microsoft.Win32 import Registry
paths = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders").GetValueNames()
for ipy_path in paths:
    print ipy_path
</code>```

It doesn't tell me which path is associated with which program, but I can figure that out now that I have the paths.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get what software's installed on my computer as well as the path they're installed to.

I found a link which provided code to get installed software, but I'm unsure how to get the installation paths, and how to associate a certain path(s) with a particular software package.

# prints out the names of installed software
# just need to find the installtion paths
from Microsoft.Win32 import Registry
products = Registry.ClassesRoot.OpenSubKey("Installer\\Products")
for product_name in products.GetSubKeyNames():
    product_key = products.OpenSubKey(product_name)
    print product_key.GetValue("ProductName")

As a side note, is there a tutorial/guide somewhere which details how to use the Windows Registry (such as the keys used above)?

Body:
After playing around with regedit for a while, I found that installation paths are located at SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Folders

from Microsoft.Win32 import Registry
paths = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders").GetValueNames()
for ipy_path in paths:
    print ipy_path

It doesn't tell me which path is associated with which program, but I can figure that out now that I have the paths.


问:
Mysql query join table and let fill with empty if value same
I Have problem with joining 2 table
this is mysql query

select *
  from tbl_perspective a
  inner join tbl_objective b on b.idperspective=a.idperspective

The result is:
Query Result

I Want to display first row of perspectivename and blank or null

Final Result:
enter image description here

答: You need to use LEFT JOIN to include all results, like this : https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins</p>


问:
htaccess capture all domains + subdirectories except one and redirect
I would like to capture all domain names pointing to my server and redirect them to my main domain. This answer helped me part of the way in capturing all domains that aren't the main domain, but i would also like to capture all the sub directories and point them to the home page, for example:

a) old.com => example.com

b) old.com/test => example.com

c) old.com/variable/1/2/3/4 => example.com

my current code only works for point a)

RewriteCond %{HTTP_HOST} !.*example\.com$ [NC]
 RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]

答:
This seemed to do the trick.

RewriteCond %{HTTP_HOST} !.*example\.com$
RewriteCond %{HTTP_HOST} ^(?:www\.)?([a-z0-9-]+\.[a-z]+) [NC]


问:
pandas column containing list of objects, split this column based upon keynames and store values as comma separated values
I have a dataframe which contains column:

```<code>A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]
</code>```

Output should be such that:

```<code>A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz
</code>```

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

答:
Thought I'll take a shot at this. First, never use eval where you can avoid it. A better solution would be using ast:

```<code>import ast
df.A = df.A.apply(ast.literal_eval)
</code>```

Next, flatten your columns:

```<code>i = df.A.str.len().cumsum()   # we'll need this later
df = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df.A = df.A.astype(str)

df

     A    B
0   28  abc
1   29  def
2   30  hij
3   31  hij
4   32  abc
5   28  abc
6   28  abc
7   29  def
8   30  hij
9   28  abc
10  29  klm
11  30  nop
12  28  abc
13  29  xyz
</code>```

Now, perform a groupby using intervals made from i.

```<code>idx = pd.cut(df.index, bins=np.append([0], i), include_lowest=True, right=False)
df = df.groupby(idx, as_index=False).agg(','.join)

df

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz
</code>```

Had a little help from Bharath here.

A cool alternative to the IntervalIndex (proposed by Wen) involves the use of np.put:

```<code>i = df.A.str.len().cumsum()
df = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df.A = df.A.astype(str)

v = pd.Series(0, index=df.index)
np.put(v, i-1, [1] * len(i))

df = df.groupby(v[::-1].cumsum()).agg(','.join)[::-1].reset_index(drop=True)

df

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz
</code>```

Performance

```<code>df = pd.concat([df] * 1000, ignore_index=True)
</code>```

```<code>%%timeit
df.A.apply(pd.Series).stack().\
     apply(pd.Series).groupby(level=0).\
        agg(lambda x :','.join(x.astype(str)))

1 loop, best of 3: 8.76 s per loop
</code>```

```<code>%%timeit
A = df.A.values.tolist()
B = {
    (i, j, k): v
    for j, row in enumerate(A)
    for i, d in enumerate(row)
    for k, v in d.items()
}
pd.Series(B).astype(str).groupby(level=[1, 2]).apply(','.join).unstack()

1 loop, best of 3: 2.08 s per loop
</code>```

```<code>%%timeit
i = df.A.str.len().cumsum()
df2 = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df2.A = df2.A.astype(str)
idx = pd.cut(df2.index, bins=np.append([0], i), include_lowest=True, right=False)
df2.groupby(idx, as_index=False).agg(','.join)

1 loop, best of 3: 810 ms per loop
</code>```

```<code>%%timeit
i = df.A.str.len().cumsum()
df2 = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df2.A = df2.A.astype(str)
v = pd.Series(0, index=df2.index)
np.put(v, i-1, [1] * len(i))
df2.groupby(v[::-1].cumsum()).agg(','.join)[::-1].reset_index(drop=True)

1 loop, best of 3: 548 ms per loop
</code>```

Body:
I have a dataframe which contains column:

A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]

Output should be such that:

A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

Body:
Thought I'll take a shot at this. First, never use eval where you can avoid it. A better solution would be using ast:

import ast
df.A = df.A.apply(ast.literal_eval)

Next, flatten your columns:

i = df.A.str.len().cumsum()   # we'll need this later
df = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df.A = df.A.astype(str)

df

     A    B
0   28  abc
1   29  def
2   30  hij
3   31  hij
4   32  abc
5   28  abc
6   28  abc
7   29  def
8   30  hij
9   28  abc
10  29  klm
11  30  nop
12  28  abc
13  29  xyz

Now, perform a groupby using intervals made from i.

idx = pd.cut(df.index, bins=np.append([0], i), include_lowest=True, right=False)
df = df.groupby(idx, as_index=False).agg(','.join)

df

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz

Had a little help from Bharath here.

A cool alternative to the IntervalIndex (proposed by Wen) involves the use of np.put:

i = df.A.str.len().cumsum()
df = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df.A = df.A.astype(str)

v = pd.Series(0, index=df.index)
np.put(v, i-1, [1] * len(i))

df = df.groupby(v[::-1].cumsum()).agg(','.join)[::-1].reset_index(drop=True)

df

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz

Performance

df = pd.concat([df] * 1000, ignore_index=True)

%%timeit
df.A.apply(pd.Series).stack().\
     apply(pd.Series).groupby(level=0).\
        agg(lambda x :','.join(x.astype(str)))

1 loop, best of 3: 8.76 s per loop

%%timeit
A = df.A.values.tolist()
B = {
    (i, j, k): v
    for j, row in enumerate(A)
    for i, d in enumerate(row)
    for k, v in d.items()
}
pd.Series(B).astype(str).groupby(level=[1, 2]).apply(','.join).unstack()

1 loop, best of 3: 2.08 s per loop

%%timeit
i = df.A.str.len().cumsum()
df2 = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df2.A = df2.A.astype(str)
idx = pd.cut(df2.index, bins=np.append([0], i), include_lowest=True, right=False)
df2.groupby(idx, as_index=False).agg(','.join)

1 loop, best of 3: 810 ms per loop

%%timeit
i = df.A.str.len().cumsum()
df2 = pd.DataFrame.from_dict(np.concatenate(df.A).tolist())
df2.A = df2.A.astype(str)
v = pd.Series(0, index=df2.index)
np.put(v, i-1, [1] * len(i))
df2.groupby(v[::-1].cumsum()).agg(','.join)[::-1].reset_index(drop=True)

1 loop, best of 3: 548 ms per loop


问:
How to create multiple log files of different content with log4j
I'm tried to create multiple log files of different content with log4j.

This is my log4j.properties file

```<code># Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/dhanushka/Documents/log4j.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

log4j.appender.testng=org.apache.log4j.RollingFileAppender
log4j.appender.testng.File=/home/dhanushka/Documents/TestNGlog.log
log4j.appender.testng.MaxFileSize=1MB
log4j.appender.testng.MaxBackupIndex=1
log4j.appender.testng.layout=org.apache.log4j.PatternLayout
log4j.appender.testng.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Root logger option
log4j.rootLogger=INFO, file, admin, stdout, testng

# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO

# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL
</code>```

Here is how I implemented in code.

```<code>public class VerifyAmenities {

private static Logger defaultLogger = Logger.getLogger("file");
private static Logger testNGlogger = Logger.getLogger("testng");
.
.
}
defaultLogger.info("This is default Logger");
testNGlogger.info("This is testNG Logger");
</code>```

By this it creates two log files. But Both has same logs. Appreciate any ones reply.

答:
Finally I found the way of doing this.

```<code># Root logger option
log4j.rootLogger=TRACE, stdout, file

log4j.category.testngLogger=DEBUG, testng
log4j.additivity.testngLogger=false
</code>```

In rootLogger, that is like a father of all logs. It inherit by default. Root logger option should be like that.

If you additivity set to false it will never goes to rootLogger

In log4j.xml file it will goes like this.

```<code><logger name="testngLogger" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="testngLogger" />
</logger>

<root>
    <priority value="INFO" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="fileLogger" />
</root>
</code>```

Body:
I'm tried to create multiple log files of different content with log4j.

This is my log4j.properties file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/dhanushka/Documents/log4j.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

log4j.appender.testng=org.apache.log4j.RollingFileAppender
log4j.appender.testng.File=/home/dhanushka/Documents/TestNGlog.log
log4j.appender.testng.MaxFileSize=1MB
log4j.appender.testng.MaxBackupIndex=1
log4j.appender.testng.layout=org.apache.log4j.PatternLayout
log4j.appender.testng.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Root logger option
log4j.rootLogger=INFO, file, admin, stdout, testng

# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO

# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL

Here is how I implemented in code.

public class VerifyAmenities {

private static Logger defaultLogger = Logger.getLogger("file");
private static Logger testNGlogger = Logger.getLogger("testng");
.
.
}
defaultLogger.info("This is default Logger");
testNGlogger.info("This is testNG Logger");

By this it creates two log files. But Both has same logs. Appreciate any ones reply.

Body:
Finally I found the way of doing this.

# Root logger option
log4j.rootLogger=TRACE, stdout, file

log4j.category.testngLogger=DEBUG, testng
log4j.additivity.testngLogger=false

In rootLogger, that is like a father of all logs. It inherit by default. Root logger option should be like that.

If you additivity set to false it will never goes to rootLogger

In log4j.xml file it will goes like this.

<logger name="testngLogger" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="testngLogger" />
</logger>

<root>
    <priority value="INFO" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="fileLogger" />
</root>


问:
SQL query in Oracle to find number within ranges-field that represented in varchar column
I have Colors table in Oracle, with data like:

```<code>ID    Color    Ranges (nvarchar2!)
--    -----    -------------------------
1     Blue     1-9,23.5-25.1,27.11,99.14
2     Red      4
3     Green    4.44-5.3
4     Black    18-22,101
</code>```

As you can guess, the Ranges column represents some numbers and numbers-ranges.

I can't save the ranges in some other tables (like RangesTable with ColorID, MinVal, MaxVal), but I can normalize this Ranges-column in some ways (allways sorted, or, represting single-numbers as ranges ("4-4" instead of "4"), or such).

The problem: I'm searching for a way to query my Oracle according to this field, by asking it: Which colors (or ids...) do I have that its ranges contains 5? (the answer is Blue and Green), or Which color overlaps "5-6" range? (answer is, again, Blue [1-9] and Green [4.44-5.3]).

How can it be done? (I guess Regex won't help here...).

Is it sensable to write in-DB function that capable to split those ranges and search in it? Any other suggestion?

Thank you!

答:
I have done this by using a SQL nested table and a pipelined function to provide a third option.

Firstly create the SQL type and related nested table:

```<code>create or replace type range_type as object (range_from number, range_to number);
create or replace type range_table as table of range_type;
</code>```

Then create a pipelined function that can decode the range column. The function can probably easily be rewritten to take advantage of the apex_util.string_to_table function used above.

```<code>create or replace function range_to_nested_table(i_ranges in varchar2)
  return range_table pipelined is

  thisRange varchar2(4000);
  loop_counter number := 1;

  output_row range_type;

begin

  loop
    thisRange := rtrim(regexp_substr(i_ranges, '[^,]*,?', 1, loop_counter), ',');

    exit when thisRange is null;
    loop_counter := loop_counter + 1;

    if thisRange like '%-%' then
      output_row := range_type(to_number(regexp_substr(thisRange, '[^-]*', 1, 1)),
                               to_number(regexp_substr(thisRange, '[^-]*(-|$)', 1, 2)));
    else
      output_row := range_type(to_number(thisRange), to_number(thisRange));
    end if;

    pipe row(output_row);

  end loop;

  RETURN;

end;
</code>```

Then run the following query to retrieve the data:

```<code>with my_sample_data as (
  select 1 as id, 'Blue' as color, '1-9,23.5-25.1,27.11,99.14' as range from dual union all
  select 2 as id, 'Red' as color, '4' as range from dual union all
  select 3 as id, 'Green' as color, '4.44-5.3' as range from dual union all
  select 4 as id, 'Black' as color, '18-22,101' as range from dual
)
select id, color, range, b.*
from my_sample_data a, table(range_to_nested_table(a.range)) b
where 5 between b.range_from and b.range_to
</code>```

Body:
I have Colors table in Oracle, with data like:

ID    Color    Ranges (nvarchar2!)
--    -----    -------------------------
1     Blue     1-9,23.5-25.1,27.11,99.14
2     Red      4
3     Green    4.44-5.3
4     Black    18-22,101

As you can guess, the Ranges column represents some numbers and numbers-ranges.

I can't save the ranges in some other tables (like RangesTable with ColorID, MinVal, MaxVal), but I can normalize this Ranges-column in some ways (allways sorted, or, represting single-numbers as ranges ("4-4" instead of "4"), or such).

The problem: I'm searching for a way to query my Oracle according to this field, by asking it: Which colors (or ids...) do I have that its ranges contains 5? (the answer is Blue and Green), or Which color overlaps "5-6" range? (answer is, again, Blue [1-9] and Green [4.44-5.3]).

How can it be done? (I guess Regex won't help here...).

Is it sensable to write in-DB function that capable to split those ranges and search in it? Any other suggestion?

Thank you!

Body:
I have done this by using a SQL nested table and a pipelined function to provide a third option.

Firstly create the SQL type and related nested table:

create or replace type range_type as object (range_from number, range_to number);
create or replace type range_table as table of range_type;

Then create a pipelined function that can decode the range column. The function can probably easily be rewritten to take advantage of the apex_util.string_to_table function used above.

create or replace function range_to_nested_table(i_ranges in varchar2)
  return range_table pipelined is

  thisRange varchar2(4000);
  loop_counter number := 1;

  output_row range_type;

begin

  loop
    thisRange := rtrim(regexp_substr(i_ranges, '[^,]*,?', 1, loop_counter), ',');

    exit when thisRange is null;
    loop_counter := loop_counter + 1;

    if thisRange like '%-%' then
      output_row := range_type(to_number(regexp_substr(thisRange, '[^-]*', 1, 1)),
                               to_number(regexp_substr(thisRange, '[^-]*(-|$)', 1, 2)));
    else
      output_row := range_type(to_number(thisRange), to_number(thisRange));
    end if;

    pipe row(output_row);

  end loop;

  RETURN;

end;

Then run the following query to retrieve the data:

with my_sample_data as (
  select 1 as id, 'Blue' as color, '1-9,23.5-25.1,27.11,99.14' as range from dual union all
  select 2 as id, 'Red' as color, '4' as range from dual union all
  select 3 as id, 'Green' as color, '4.44-5.3' as range from dual union all
  select 4 as id, 'Black' as color, '18-22,101' as range from dual
)
select id, color, range, b.*
from my_sample_data a, table(range_to_nested_table(a.range)) b
where 5 between b.range_from and b.range_to


问:
Cannot read property 'create' of undefined -- react-dates error
While adding SingleDatePicker from 'react-dates' library, I got this error. Tried everything but couldn't find the error. The code is just to display the calender and display the selected date from the user. Please help!
Here is the code:

```<code>import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  state = {
    createdAt: moment(),
    calenderFocused: false
  };
  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (
      <div>
        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>
      </div>
    );
  }
};
</code>```

The error I am getting in the chrome-dev-tool:

```<code>Uncaught TypeError: Cannot read property 'create' of undefined
    at Object.createLTR [as create] (ThemedStyleSheet.js?17e6:46)
    at WithStyles.maybeCreateStyles (withStyles.js?55c9:121)
    at WithStyles.componentWillMount (withStyles.js?55c9:107)
    at callComponentWillMount (react-dom.development.js?cada:6337)
    at mountClassInstance (react-dom.development.js?cada:6393)
    at updateClassComponent (react-dom.development.js?cada:7849)
    at beginWork (react-dom.development.js?cada:8233)
    at performUnitOfWork (react-dom.development.js?cada:10215)
    at workLoop (react-dom.development.js?cada:10279)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
The above error occurred in the <withStyles(SingleDatePicker)> component:
    in withStyles(SingleDatePicker) (created by ExpenseForm)
    in form (created by ExpenseForm)
    in div (created by ExpenseForm)
    in ExpenseForm (created by AddExpensePage)
    in div (created by AddExpensePage)
    in AddExpensePage (created by Route)
    in Route (created by AppRouter)
    in Switch (created by AppRouter)
    in div (created by AppRouter)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by AppRouter)
    in AppRouter
    in Provider
</code>```

答:
You're not initlizing state properly. You should use a constructor, like so:</p>

```<code>import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  constructor(props){
      super(props);
      this.state = {
         createdAt: moment(),
         calenderFocused: false
      }
  }

  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (
      <div>
        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>
      </div>
    );
  }
};
</code>```

Body:
While adding SingleDatePicker from 'react-dates' library, I got this error. Tried everything but couldn't find the error. The code is just to display the calender and display the selected date from the user. Please help!
Here is the code:

import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  state = {
    createdAt: moment(),
    calenderFocused: false
  };
  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (

        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>

    );
  }
};

The error I am getting in the chrome-dev-tool:

Uncaught TypeError: Cannot read property 'create' of undefined
    at Object.createLTR [as create] (ThemedStyleSheet.js?17e6:46)
    at WithStyles.maybeCreateStyles (withStyles.js?55c9:121)
    at WithStyles.componentWillMount (withStyles.js?55c9:107)
    at callComponentWillMount (react-dom.development.js?cada:6337)
    at mountClassInstance (react-dom.development.js?cada:6393)
    at updateClassComponent (react-dom.development.js?cada:7849)
    at beginWork (react-dom.development.js?cada:8233)
    at performUnitOfWork (react-dom.development.js?cada:10215)
    at workLoop (react-dom.development.js?cada:10279)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
The above error occurred in the <withStyles(SingleDatePicker)> component:
    in withStyles(SingleDatePicker) (created by ExpenseForm)
    in form (created by ExpenseForm)
    in div (created by ExpenseForm)
    in ExpenseForm (created by AddExpensePage)
    in div (created by AddExpensePage)
    in AddExpensePage (created by Route)
    in Route (created by AppRouter)
    in Switch (created by AppRouter)
    in div (created by AppRouter)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by AppRouter)
    in AppRouter
    in Provider

Body:
You're not initlizing state properly. You should use a constructor, like so:

import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  constructor(props){
      super(props);
      this.state = {
         createdAt: moment(),
         calenderFocused: false
      }
  }

  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (
      <div>
        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>
      </div>
    );
  }
};


问:
Excel VBA run macro across dynamic range of sheets
As an extension from the last question I asked, I'm trying to run a macro across all worksheets, which you guys successfully helped me to do.
I've been told that the worksheet names can't be hardcoded, so I'm going to have to modify my current solution.

```<code>Sub RemoveCarriageReturns()
Dim MyRange As Range
Dim NameList() As Variant
NameList = Array("OTCUEXTR", "OTFBCUDS", "OTFBCUEL")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For i = 0 To 2
    With Worksheets(NameList(i))
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

I've tried to populate the array with a For loop that gathers names of each worksheet however I feel after 2 days blankly staring at this,  my limited VBA knowledge has run out and I'm stuck, I would really appreciate some pointers on how to get this macro to work across an range of sheets that can change in quantity and names.

Happy to provide any more information you need in a comment

答:
You can do it like this (or could use the index along the lines of your original code).</p>

```<code>Sub RemoveCarriageReturns()

Dim MyRange As Range
Dim ws As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each ws In Worksheets
    With ws
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next ws

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub
</code>```

Body:
As an extension from the last question I asked, I'm trying to run a macro across all worksheets, which you guys successfully helped me to do.
I've been told that the worksheet names can't be hardcoded, so I'm going to have to modify my current solution.

Sub RemoveCarriageReturns()
Dim MyRange As Range
Dim NameList() As Variant
NameList = Array("OTCUEXTR", "OTFBCUDS", "OTFBCUEL")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For i = 0 To 2
    With Worksheets(NameList(i))
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

I've tried to populate the array with a For loop that gathers names of each worksheet however I feel after 2 days blankly staring at this,  my limited VBA knowledge has run out and I'm stuck, I would really appreciate some pointers on how to get this macro to work across an range of sheets that can change in quantity and names.

Happy to provide any more information you need in a comment

Body:
You can do it like this (or could use the index along the lines of your original code).

Sub RemoveCarriageReturns()

Dim MyRange As Range
Dim ws As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each ws In Worksheets
    With ws
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next ws

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub


问:
Setter for computed property obtained from store in vue.js
I'd like to make two checkboxes which get value from store.js and send them to backend through a form:

Notify me
    <input type="checkbox" v-model="notification" value="notification" />

Email me
    <input type="checkbox" v-model="email" value="email" />

```
<p>I get the values as a computed property:</p>
<pre class="lang-js prettyprint-override"><code>computed: {
  BASE_URL () {
    return this.$store.state.BASE_URL;
  },
  notification () {
    return this.$store.state.notification;
  },

  email () {
    return this.$store.state.email;
  }
}
</code>```

The problem is that checking the checkboxes does not change the values in the store, and in addition to that I get this warning in the console, like:

```<code>vue.esm.js?65d7:479 [Vue warn]: Computed property "notification" was assigned to but it has no setter.
</code>```

I know that one can define setter in computed property, as described in the vue.js docs, but I don't know how to do that when there are multiple values to set, like in my particular case.

So appreciate your help to fix this.

答:
To change Vuex state, you will need a mutation.

Provided you have a mutation setNotification for changing the notification state, you can configure the property in your component like this:

```<code>computed: {
    notification: {
        get() { return this.$store.state.notification; },
        set(value) { this.$store.commit('setNotification', value); },
    },
},
</code>```

You can now bind to it with v-model="notification" as normal.

See Form Handling in the docs for more info.

Since this is a frequent thing that I do in my projects, I have written a helper function which generates the computed properties:

```<code>function mapStateTwoWay(...args) {
    const result = {};

    if (args.length === 1) {
        for (const prop of Object.keys(args[0])) {
            result[prop] = {
                get() { return this.$store.state[prop]; },
                set(value) { this.$store.commit(args[0][prop], value); },
            };
        }
    } else {
        for (const prop of Object.keys(args[1])) {
            result[prop] = {
                get() { return this.$store.state[args[0]][prop]; },
                set(value) { this.$store.commit(args[0] + '/' + args[1][prop], value); },
            };
        }
    }

    return result;
}
</code>```

Use it like this:

```<code>computed: {
    ...mapStateTwoWay({
        notifications: 'setNotifications',
        email: 'setEmail',
    }),

    // Namespaced
    ...mapStateTwoWay('namespace', {
        notifications: 'setNotifications',
        email: 'setEmail',
    }),
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to make two checkboxes which get value from store.js and send them to backend through a form:

Notify me
    <input type="checkbox" v-model="notification" value="notification" />

Email me
    <input type="checkbox" v-model="email" value="email" />

I get the values as a computed property:

computed: {
  BASE_URL () {
    return this.$store.state.BASE_URL;
  },
  notification () {
    return this.$store.state.notification;
  },

  email () {
    return this.$store.state.email;
  }
}

The problem is that checking the checkboxes does not change the values in the store, and in addition to that I get this warning in the console, like:

vue.esm.js?65d7:479 [Vue warn]: Computed property "notification" was assigned to but it has no setter.

I know that one can define setter in computed property, as described in the vue.js docs, but I don't know how to do that when there are multiple values to set, like in my particular case.

So appreciate your help to fix this.

Body:
To change Vuex state, you will need a mutation.

Provided you have a mutation setNotification for changing the notification state, you can configure the property in your component like this:

computed: {
    notification: {
        get() { return this.$store.state.notification; },
        set(value) { this.$store.commit('setNotification', value); },
    },
},

You can now bind to it with v-model="notification" as normal.

See Form Handling in the docs for more info.

Since this is a frequent thing that I do in my projects, I have written a helper function which generates the computed properties:

function mapStateTwoWay(...args) {
    const result = {};

    if (args.length === 1) {
        for (const prop of Object.keys(args[0])) {
            result[prop] = {
                get() { return this.$store.state[prop]; },
                set(value) { this.$store.commit(args[0][prop], value); },
            };
        }
    } else {
        for (const prop of Object.keys(args[1])) {
            result[prop] = {
                get() { return this.$store.state[args[0]][prop]; },
                set(value) { this.$store.commit(args[0] + '/' + args[1][prop], value); },
            };
        }
    }

    return result;
}

Use it like this:

computed: {
    ...mapStateTwoWay({
        notifications: 'setNotifications',
        email: 'setEmail',
    }),

    // Namespaced
    ...mapStateTwoWay('namespace', {
        notifications: 'setNotifications',
        email: 'setEmail',
    }),
}


问:
Angular 4 RouterModule
I have some issue when i try to add RouterModule on my application.
After i added router system on my app.module.ts file. i got this error again and again:

compiler.es5.js:1689 Uncaught Error: RouterModule cannot be used as an entry component.

Also here is my app.module.ts code:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { FormsModule  }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { AppComponent } from './app.component';
import { ContactComponent } from './components/contact.component';

const appRoutes : Routes = [
    { path: 'test1', component : ContactComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],

  providers: [],
  bootstrap: [AppComponent, RouterModule]
 })
export class AppModule { }
</code>```

答:
Remove RouterModule from bootstrap</p>

```<code> bootstrap: [AppComponent]
</code>```

Title: Angular 4 RouterModule

Body:
I have some issue when i try to add RouterModule on my application.
After i added router system on my app.module.ts file. i got this error again and again:

compiler.es5.js:1689 Uncaught Error: RouterModule cannot be used as an entry component.

Also here is my app.module.ts code:

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule  }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { AppComponent } from './app.component';
import { ContactComponent } from './components/contact.component';

const appRoutes : Routes = [
    { path: 'test1', component : ContactComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],

  providers: [],
  bootstrap: [AppComponent, RouterModule]
 })
export class AppModule { }

Body:
Remove RouterModule from bootstrap

 bootstrap: [AppComponent]


答:
Remove RouterModule from AppModule's bootstrap array:

```<code>@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  bootstrap: [
    AppComponent <-- only AppComponent should be in boostrap array
  ]
 })
export class AppModule { }
</code>```

I'm curious, why did you add it to bootstrap array in the first place?

Title: Angular 4 RouterModule

Body:
Remove RouterModule from AppModule's bootstrap array:

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  bootstrap: [
    AppComponent <-- only AppComponent should be in boostrap array
  ]
 })
export class AppModule { }

I'm curious, why did you add it to bootstrap array in the first place?


问:
Append data to json file
I have a .json file which looks like this for now:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}
</code>```

I want to append a line in Python directly after {"name" : "test2}.
Other questions I found will give me this solution:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}{"name" : "test3"} # <-- Wrong place it shouldn't be here
</code>```

This is what it should look like:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"},
        {"name" : "test3"}  # <-- new line here
    ]
}     # <-- not here
</code>```

答:
Quite simply: parse your json to get a Python object, update the python object, and dump it back to json.

```<code>import json
with open("myfile.json") as f:
    obj = json.load(f)
obj["users"].append({"name":"was that so complicated, really ?"})
with open("myfile.json", "w") as f:
    json.dump(f, obj)
</code>```

I understand this might be a bit less obvious for a beginner, but given json specs, you can easily understand why the only reliable way to modify a json content is to actually parse it. Appending to the file won't work obviously as you already noticed (you'll get invalid json). Trying to read the file line by line, detect the end of the user array and insert a newline here won't work either (or only accidentally) since the json format does not mandate newlines anywhere, so you could as well have everything crammed in one single line ie:

```<code>{"users":[{"name":"test"},{"name":"test2"}]}
</code>```

wrt/ memory comsuption / perfs etc, json is not designed for huge datasets anyway (you want jsonlines or something similar for this) so you shouldn't worry about it - and that's your only option anyway.

Title: Append data to json file

Body:
I have a .json file which looks like this for now:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}

I want to append a line in Python directly after {"name" : "test2}.
Other questions I found will give me this solution:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}{"name" : "test3"} # <-- Wrong place it shouldn't be here

This is what it should look like:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"},
        {"name" : "test3"}  # <-- new line here
    ]
}     # <-- not here

Body:
Quite simply: parse your json to get a Python object, update the python object, and dump it back to json.

import json
with open("myfile.json") as f:
    obj = json.load(f)
obj["users"].append({"name":"was that so complicated, really ?"})
with open("myfile.json", "w") as f:
    json.dump(f, obj)

I understand this might be a bit less obvious for a beginner, but given json specs, you can easily understand why the only reliable way to modify a json content is to actually parse it. Appending to the file won't work obviously as you already noticed (you'll get invalid json). Trying to read the file line by line, detect the end of the user array and insert a newline here won't work either (or only accidentally) since the json format does not mandate newlines anywhere, so you could as well have everything crammed in one single line ie:

{"users":[{"name":"test"},{"name":"test2"}]}

wrt/ memory comsuption / perfs etc, json is not designed for huge datasets anyway (you want jsonlines or something similar for this) so you shouldn't worry about it - and that's your only option anyway.


问:
trailing "=" being trimmed in angular2 url
I have a problem in an angular2 project where I'm generating a URL to be sent to a user via email. The URL in the email needs to contain a special ID which is passed in the router as:

{ path: somepath/:id }

The user then clicks on the url which will be:

http://localhost/somepath/{id}

My problem is that the id can contain a trailing "=" character which gets automatically trimmed off when navigating to the url (and therefore making the ID now incorrect)

I have tried encoding the id before adding it to the url making the url:

http://localhost/somepath/XXX%3D

but the encoded "=" (%3D) still gets trimmed off.

Is there any reason why encoded url values are still being trimmed off and is there any way to prevent this?

答:
Ok was just a massive oversight on my part....

I the actual id was being masked by a random encryption generator that includes symbols and usually ends in "=". What I didn't notice however, was that there was a ")" that was being included in a couple of cases as well, which does not get encoded and was causing everything after it to be trimmed off when loading the URL.

Ended up fixing it by replacing the ")" with a different symbol that doesn't get encoded but one that doesn't have another function in Angular2 (in this case a "*").


问:
Jenkins job-dsl generated job missing SCM
I have a seed job creating Jenkins jobs and while the jobs are created, they're missing things like SCM, labels, and wrappers.

Here's a simple job script that gets created:

```<code>job(jobName) {
  label('pdfs')
  description jobDesc
  parameters {
    textParam('PDF_BRANCH', 'release/server_2.11.1', '')
  }
  scm {
    git {
      remote {
        url('https://stash.domain.com/scm/project/repo.git')
        credentials('repo-user-creds')
      }
      branch('*/master')
    }
  }
  triggers {
    scm 'H/5 * * * *'
  }
  steps {
    shell jobScript
  }
  wrappers {
    rbenv('1.9.3-p484') {
      ignoreLocalVersion()
      gems('bundler', 'rake')
    }
  }
}
</code>```

But the resulting job has no SCM or label:

The XML on the server seems to include SCM and label:

```<code><?xml version="1.0" encoding="UTF-8"?><project>
    <actions/>
    <description>Testing pdf creation job against Elemental Server</description>
    <keepDependencies>false</keepDependencies>
    <properties>
        <hudson.model.ParametersDefinitionProperty>
            <parameterDefinitions>
                <hudson.model.TextParameterDefinition>
                    <name>PDF_BRANCH</name>
                    <defaultValue>release/server_2.11.1</defaultValue>
                    <description/>
                </hudson.model.TextParameterDefinition>
            </parameterDefinitions>
        </hudson.model.ParametersDefinitionProperty>
    </properties>
    <canRoam>false</canRoam>
    <disabled>false</disabled>
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
    <triggers>
        <hudson.triggers.SCMTrigger>
            <spec>H/5 * * * *</spec>
            <ignorePostCommitHooks>false</ignorePostCommitHooks>
        </hudson.triggers.SCMTrigger>
    </triggers>
    <concurrentBuild>false</concurrentBuild>
    <builders>
        <hudson.tasks.Shell>
            <command>
# REMOVED FOR BREVITY
</command>
        </hudson.tasks.Shell>
    </builders>
    <publishers/>
    <buildWrappers>
        <ruby-proxy-object>
            <ruby-object ruby-class="Jenkins::Tasks::BuildWrapperProxy" pluginid="rbenv">
                <pluginid ruby-class="String" pluginid="rbenv">rbenv</pluginid>
                <object ruby-class="RbenvWrapper" pluginid="rbenv">
                    <version ruby-class="String" pluginid="rbenv">1.9.3-p484</version>
                    <ignore__local__version ruby-class="String" pluginid="rbenv">true</ignore__local__version>
                    <gem__list ruby-class="String" pluginid="rbenv">bundler,rake</gem__list>
                    <rbenv__root ruby-class="String" pluginid="rbenv">$HOME/.rbenv</rbenv__root>
                    <rbenv__repository ruby-class="String" pluginid="rbenv">https://github.com/sstephenson/rbenv.git</rbenv__repository>
                    <rbenv__revision ruby-class="String" pluginid="rbenv">master</rbenv__revision>
                    <ruby__build__repository ruby-class="String" pluginid="rbenv">https://github.com/sstephenson/ruby-build.git</ruby__build__repository>
                    <ruby__build__revision ruby-class="String" pluginid="rbenv">master</ruby__build__revision>
                </object>
            </ruby-object>
        </ruby-proxy-object>
    </buildWrappers>
    <assignedNode>pdfs</assignedNode>
    <scm class="hudson.plugins.git.GitSCM">
        <userRemoteConfigs>
            <hudson.plugins.git.UserRemoteConfig>
                <url>https://stash.domain.com/scm/project/repo.git</url>
                <credentialsId>repo-user-creds</credentialsId>
            </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
            <hudson.plugins.git.BranchSpec>
                <name>*/master</name>
            </hudson.plugins.git.BranchSpec>
        </branches>
        <configVersion>2</configVersion>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <gitTool>Default</gitTool>
    </scm>
</code>```

I'm very new to Jenkins job-dsl so I'm sure I'm missing something fairly obvious but I just don't know what it is. Any help is very much appreciated, thanks!

答:
Try validating your code here
job DSL playground

If all the tags are coming fine then u might have to check the DSL plugin version and any updates to the DSL methods

Body:
I have a seed job creating Jenkins jobs and while the jobs are created, they're missing things like SCM, labels, and wrappers.

Here's a simple job script that gets created:

job(jobName) {
  label('pdfs')
  description jobDesc
  parameters {
    textParam('PDF_BRANCH', 'release/server_2.11.1', '')
  }
  scm {
    git {
      remote {
        url('https://stash.domain.com/scm/project/repo.git')
        credentials('repo-user-creds')
      }
      branch('*/master')
    }
  }
  triggers {
    scm 'H/5 * * * *'
  }
  steps {
    shell jobScript
  }
  wrappers {
    rbenv('1.9.3-p484') {
      ignoreLocalVersion()
      gems('bundler', 'rake')
    }
  }
}

But the resulting job has no SCM or label:

The XML on the server seems to include SCM and label:

<?xml version="1.0" encoding="UTF-8"?><project>
    <actions/>
    <description>Testing pdf creation job against Elemental Server</description>
    <keepDependencies>false</keepDependencies>
    <properties>
        <hudson.model.ParametersDefinitionProperty>
            <parameterDefinitions>
                <hudson.model.TextParameterDefinition>
                    <name>PDF_BRANCH</name>
                    <defaultValue>release/server_2.11.1</defaultValue>
                    <description/>
                </hudson.model.TextParameterDefinition>
            </parameterDefinitions>
        </hudson.model.ParametersDefinitionProperty>
    </properties>
    <canRoam>false</canRoam>
    <disabled>false</disabled>
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
    <triggers>
        <hudson.triggers.SCMTrigger>
            <spec>H/5 * * * *</spec>
            <ignorePostCommitHooks>false</ignorePostCommitHooks>
        </hudson.triggers.SCMTrigger>
    </triggers>
    <concurrentBuild>false</concurrentBuild>
    <builders>
        <hudson.tasks.Shell>
            <command>
# REMOVED FOR BREVITY
</command>
        </hudson.tasks.Shell>
    </builders>
    <publishers/>
    <buildWrappers>
        <ruby-proxy-object>
            <ruby-object ruby-class="Jenkins::Tasks::BuildWrapperProxy" pluginid="rbenv">
                <pluginid ruby-class="String" pluginid="rbenv">rbenv</pluginid>
                <object ruby-class="RbenvWrapper" pluginid="rbenv">
                    <version ruby-class="String" pluginid="rbenv">1.9.3-p484</version>
                    <ignore__local__version ruby-class="String" pluginid="rbenv">true</ignore__local__version>
                    <gem__list ruby-class="String" pluginid="rbenv">bundler,rake</gem__list>
                    <rbenv__root ruby-class="String" pluginid="rbenv">$HOME/.rbenv</rbenv__root>
                    <rbenv__repository ruby-class="String" pluginid="rbenv">https://github.com/sstephenson/rbenv.git</rbenv__repository>
                    <rbenv__revision ruby-class="String" pluginid="rbenv">master</rbenv__revision>
                    <ruby__build__repository ruby-class="String" pluginid="rbenv">https://github.com/sstephenson/ruby-build.git</ruby__build__repository>
                    <ruby__build__revision ruby-class="String" pluginid="rbenv">master</ruby__build__revision>
                </object>
            </ruby-object>
        </ruby-proxy-object>
    </buildWrappers>
    <assignedNode>pdfs</assignedNode>
    <scm class="hudson.plugins.git.GitSCM">
        <userRemoteConfigs>
            <hudson.plugins.git.UserRemoteConfig>
                <url>https://stash.domain.com/scm/project/repo.git</url>
                <credentialsId>repo-user-creds</credentialsId>
            </hudson.plugins.git.UserRemoteConfig>
        </userRemoteConfigs>
        <branches>
            <hudson.plugins.git.BranchSpec>
                <name>*/master</name>
            </hudson.plugins.git.BranchSpec>
        </branches>
        <configVersion>2</configVersion>
        <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
        <gitTool>Default</gitTool>
    </scm>

I'm very new to Jenkins job-dsl so I'm sure I'm missing something fairly obvious but I just don't know what it is. Any help is very much appreciated, thanks!


问:
Excel VBA code to copy and paste rows to new sheet failing
Hi I have the following VBA code that I am trying to use for excel to copy and paste rows that meet a certain criteria to a new sheet.

The code runs to the point of copying the first match in the sheet but fails pasting on the second sheet with the error

Run-time error '14004': Application-defined or object-defined error

Can anyone help here?

```<code>Sub mileStone()
    Dim r As Long, pasteRowIndex As Long
    Dim lastRow As Long
    'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

    lastRow = 24 ' need to include function to retrieve the last used row number

    pasteRowIndex = 1

    For r = 11 To lastRow 'Loop through sheet1 and search for your criteria

        If Cells(r, Columns("E").Column).Value = "defect resolution" Then 'Found

            'Copy the current row
            Rows(r).Select
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1

            'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select
        End If
    Next r
End Sub
</code>```

答:
```<code>Sub Copy_Filtered_Sections()

Dim Section As Long, NextRow As Long

For Section = 1 To 32

    NextRow = Sheets("Results").Range("A" & Rows.Count).End(xlUp).Row + 1 'Next empty row

    Sheets("Function Test Procedure").Select

    Range("FTPSec" & Section).Columns("A:H").SpecialCells(xlCellTypeVisible).Copy _
    Destination:=Sheets("Results").Range("A" & NextRow)

'        Range("FTPSec" & Section).Columns("G:H").SpecialCells(xlCellTypeVisible).Copy _
'            Destination:=Sheets("Results").Range("N" & NextRow)

Next Section

End Sub
</code>```

Acceptance Test Procedure Script

```<code>Sub Copy_ATP_Tables()

Dim SectionATP As Long, NextRow As Long

For SectionATP = 1 To 32

    NextRow = Sheets("Results").Range("A" & Rows.Count).End(xlUp).Row + 1 'Next empty row

    Sheets("Acceptance Test Procedure").Select

    Range("ATPSec" & SectionATP).Columns("A:H").SpecialCells(xlCellTypeVisible).Copy _
    Destination:=Sheets("Results").Range("A" & NextRow)

'           Range("FTPSec" & Section).Columns("G:H").SpecialCells(xlCellTypeVisible).Copy _
'                Destination:=Sheets("Results").Range("N" & NextRow)

Next SectionATP

End Sub
</code>```

Body:
Hi I have the following VBA code that I am trying to use for excel to copy and paste rows that meet a certain criteria to a new sheet.

The code runs to the point of copying the first match in the sheet but fails pasting on the second sheet with the error

Run-time error '14004': Application-defined or object-defined error

Can anyone help here?

Sub mileStone()
    Dim r As Long, pasteRowIndex As Long
    Dim lastRow As Long
    'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

    lastRow = 24 ' need to include function to retrieve the last used row number

    pasteRowIndex = 1

    For r = 11 To lastRow 'Loop through sheet1 and search for your criteria

        If Cells(r, Columns("E").Column).Value = "defect resolution" Then 'Found

            'Copy the current row
            Rows(r).Select
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1

            'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select
        End If
    Next r
End Sub

Body:
Sub Copy_Filtered_Sections()

Dim Section As Long, NextRow As Long

For Section = 1 To 32

    NextRow = Sheets("Results").Range("A" & Rows.Count).End(xlUp).Row + 1 'Next empty row

    Sheets("Function Test Procedure").Select

    Range("FTPSec" & Section).Columns("A:H").SpecialCells(xlCellTypeVisible).Copy _
    Destination:=Sheets("Results").Range("A" & NextRow)

'        Range("FTPSec" & Section).Columns("G:H").SpecialCells(xlCellTypeVisible).Copy _
'            Destination:=Sheets("Results").Range("N" & NextRow)

Next Section

End Sub

Acceptance Test Procedure Script

Sub Copy_ATP_Tables()

Dim SectionATP As Long, NextRow As Long

For SectionATP = 1 To 32

    NextRow = Sheets("Results").Range("A" & Rows.Count).End(xlUp).Row + 1 'Next empty row

    Sheets("Acceptance Test Procedure").Select

    Range("ATPSec" & SectionATP).Columns("A:H").SpecialCells(xlCellTypeVisible).Copy _
    Destination:=Sheets("Results").Range("A" & NextRow)

'           Range("FTPSec" & Section).Columns("G:H").SpecialCells(xlCellTypeVisible).Copy _
'                Destination:=Sheets("Results").Range("N" & NextRow)

Next SectionATP

End Sub


问:
ant build java program could not find targets
I am maintaining a java program that is not mine. I used eclipse and I could build the program with Ant. I don't know very much about Ant. Everything was installed fine on my eclipse IDE and the build worked perfect till today. I didn't change anything, so I don't know why it doesn't work anymore.

When I look at the external Tools Configurations,I see that the targets are missing. I have the message "No targets could be determined for the build file". Previously I could select some targets. Does someone know how it come that the targets disappeared?

答:
This helped for me:
remove the build file from Ant view and add it again.</p>


问:
Entity Framework Connection to localDb
I am trying to follow the pluralsight course ASP.NET MVC 4 Fundamentals. But can't have my database connected.

Here is the error I got:

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

I have visual studio 2013 professional and SQL server 2012 installed on my machine. When I installed my SQL server, I created a server name "ABC" on my computer.

I have also installed sql localdb 11.0 separately, but it seems VS can't find the localDb connection. When I check Server Explorer -> add Connection, under server name list, only "ABC" is shown up.

Here is the connection string.

I also tried to use "Data Source = ABC; ...." it doesn't work either.

Update

Here is my connection string

```<code><add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-eManager.Web-20141223223418;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-eManager.Web-20141223223418.mdf" providerName="System.Data.SqlClient" />
</code>```

答:
Run this command to make sure what is the version of your LocalDB
sqllocaldb info

So in my case the version is MSSQLLocalDB then the connection string will look like this

<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=IdentityManagerDB;Integrated Security=True"
providerName="System.Data.SqlClient" />

Title: Entity Framework Connection to localDb

Body:
I am trying to follow the pluralsight course ASP.NET MVC 4 Fundamentals. But can't have my database connected.

Here is the error I got:

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

I have visual studio 2013 professional and SQL server 2012 installed on my machine. When I installed my SQL server, I created a server name "ABC" on my computer.

I have also installed sql localdb 11.0 separately, but it seems VS can't find the localDb connection. When I check Server Explorer -> add Connection, under server name list, only "ABC" is shown up.

Here is the connection string.

I also tried to use "Data Source = ABC; ...." it doesn't work either.

Update

Here is my connection string

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-eManager.Web-20141223223418;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-eManager.Web-20141223223418.mdf" providerName="System.Data.SqlClient" />


问:
Flash redundant code copy to microcontroller flash memory
I am working on a satellite-based project and part of the project is to store a redundant copy of the program code in flash memory. I have looked everywhere and found nothing. Is there anyway to use the c++ linker to place code copies in two areas of memory? I have limited ken of linker code. Is there maybe a different way to do this if not with the linker other than using a startup routine when the microcontroller initially boots up after flashing?

Just to be clear: there will be an executable version of the code in one region of the flash memory and a copy and, if possible, non-executable version of the code in another region of the flash memory. The program code includes all interrupt vectors. I have already modified the linker code to divide the flash memory into the segments I want.

Thank you in advance.

答: IMHO if you are trying to protect your system this way (double instance) because you are expecting bit flips due to the radiation in space, then your chances of a system surviving longer than around 10x the estimated mean time between incidents (radiation changing a bit) are rather slim. Checksum error detection is for the 1 defect in 10^6 samples in mass production devices with fail-silent requirements. It is unsuited for fail-active systems where the risk vs cost of the system fits on a more or less 4 point coordiante system.</p>


问:
Can't update \tools - Android SDK Command Line Tools for Windows
I have just downloaded the Android SDK Command Line tools for Windows (26.0.2). I am attempting to download selected SDK components using \tools\bin\sdkmanager.bat, as well as updating \tools. The installation fails with the following message:

Warning: An error occurred during installation: Failed to move away or delete existing target file: C:\testinstall\sdk\tools
  Move it away manually and try again..

I don't see how I can remove \tools manually because it contains \bin\sdkmanager.bat.

Screenshot of the sdkmanager command:

All other components appear to install without error. See below for the components specified in my package file:

答:
You could temporarily rename to tools.old, run it to install new version in tools and then remove the old one.

```<code>cd YOUR-ANDROID-SDK-LOCATION
ren tools tools.old
tools.old\bin\sdkmanager.bat "tools"
dir tools*
del tools.old /q /s
tools\bin\sdkmanager.bat --list
</code>```

Body:
You could temporarily rename to tools.old, run it to install new version in tools and then remove the old one.

cd YOUR-ANDROID-SDK-LOCATION
ren tools tools.old
tools.old\bin\sdkmanager.bat "tools"
dir tools*
del tools.old /q /s
tools\bin\sdkmanager.bat --list


问:
How to edit application configuration settings? App.config best way to go?
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

```<code>    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }
</code>```

Gives me a read-only error when I compile.

答:
EDIT: My mistake.  I misunderstood the purpose of the original question.

ORIGINAL TEXT:

We often setup our settings directly in the app.config file, but usually this is for our custom settings.

Example app.config:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <connectionStrings>
        <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <MySection>
        <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
        <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
        <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
    </MySection>
</configuration>
</code>```

OwnerDisplayName: MattRuma

Body:
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

LastEditorDisplayName: MattRuma

Body:
EDIT: My mistake.  I misunderstood the purpose of the original question.

ORIGINAL TEXT:

We often setup our settings directly in the app.config file, but usually this is for our custom settings.

Example app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <connectionStrings>
        <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <MySection>
        <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
        <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
        <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
    </MySection>
</configuration>

OwnerDisplayName: Jay S

LastEditorDisplayName: Jay S


问:
Casting const void* to const int*
I haven't used void* and const_correctness before so I am not understanding what I am doing wrong in the below code. All I want is to cast a void* returned by a member function of a const object to int*. Please suggest better approaches. Thank you.

I get the following error

```<code>passing 'const MyClass' as 'this' argument of 'void* MyClass::getArr()' discards qualifiers
</code>```

So here's the actual program that I had problem with

```<code> class MyClassImpl{
    CvMat* arr;
    public:
        MyClassImpl(){arr = new CvMat[10];}
        CvMat *getArr(){return arr;}
};
class MyClass{
    MyClassImpl *d;
    public:
        const void *getArr()const{ return (void*)d->getArr(); }

};
void print(const MyClass& obj){
    const int* ptr = static_cast<const int *>(obj.getArr());
}
int main(){
    MyClass obj1;
    print(obj1);
}
</code>```

Only the methods such as 'print()' in this case know the datatype returned by 'getData'. I can't use templates because the user doesn't know how MyClass is implemented. Thank you. Feel free to suggest alternatives.

答:
I think the problem is not in the cast from your array to a void * but in trying to call obj.getArr() when obj is marked const and MyClass::getArr() is not a const member function.  If you change your definition of that member function to

```<code> const void *getArr() const { return static_cast<const void*>(arr); }
</code>```

Then this error should resolve itself.  You might want to do a const-overload as well:

```<code> const void *getArr() const { return static_cast<const void*>(arr); }
       void *getArr()       { return static_cast<      void*>(arr); }
</code>```

Title: Casting const void* to const int*

Body:
I haven't used void* and const_correctness before so I am not understanding what I am doing wrong in the below code. All I want is to cast a void* returned by a member function of a const object to int*. Please suggest better approaches. Thank you.

I get the following error

passing 'const MyClass' as 'this' argument of 'void* MyClass::getArr()' discards qualifiers

So here's the actual program that I had problem with

 class MyClassImpl{
    CvMat* arr;
    public:
        MyClassImpl(){arr = new CvMat[10];}
        CvMat *getArr(){return arr;}
};
class MyClass{
    MyClassImpl *d;
    public:
        const void *getArr()const{ return (void*)d->getArr(); }

};
void print(const MyClass& obj){
    const int* ptr = static_cast<const int *>(obj.getArr());
}
int main(){
    MyClass obj1;
    print(obj1);
}

Only the methods such as 'print()' in this case know the datatype returned by 'getData'. I can't use templates because the user doesn't know how MyClass is implemented. Thank you. Feel free to suggest alternatives.

Body:
I think the problem is not in the cast from your array to a void * but in trying to call obj.getArr() when obj is marked const and MyClass::getArr() is not a const member function.  If you change your definition of that member function to

 const void *getArr() const { return static_cast<const void*>(arr); }

Then this error should resolve itself.  You might want to do a const-overload as well:

 const void *getArr() const { return static_cast<const void*>(arr); }
       void *getArr()       { return static_cast<      void*>(arr); }


问:
I can not see the app as I would like it
I'm doing this exercise with the fragments .. how do i see from the code i have developed .. i have my two classes fragment1 and fragment2, in the java / layout folder. There are then the two .xml files of the interfaces .. what is difficult now is to understand why this does not work properly .. what I have to get is: the screen must show two parts one with the script "This is the fragment 1" and on the other side "This is the fragment 2" ... but this is not visible I even attach the screens .. if you have time and patience, look up your news .. thanks and good day :)
fragment1.java

```<code>    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment1 extends Fragment {
    public fragment1(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1,container,false);
    }
}
</code>```

fragment2.java

```<code>    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment2 extends Fragment {
    public fragment2(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment2, container,false);
    }
}
</code>```

fragment1.xml

```<code>    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 1"
        android:textSize="25sp"/>

</LinearLayout>
</code>```

fragment2.xml

```<code>    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 2"
        android:textSize="25sp"/>

</LinearLayout>
</code>```

activity_main.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:baselineAligned="false"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.test.testfragment.MainActivity">

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="0px"
        android:name="layout.fragment1"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/fragment1" />

    <fragment
        android:name="layout.fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

activity_main (Design)

Error

答: The error is not for the code, it is built successfully, try unistalling the app from the device and clean build the project then try running again. That should work.</p>

Body:
I'm doing this exercise with the fragments .. how do i see from the code i have developed .. i have my two classes fragment1 and fragment2, in the java / layout folder. There are then the two .xml files of the interfaces .. what is difficult now is to understand why this does not work properly .. what I have to get is: the screen must show two parts one with the script "This is the fragment 1" and on the other side "This is the fragment 2" ... but this is not visible I even attach the screens .. if you have time and patience, look up your news .. thanks and good day :)
fragment1.java

    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment1 extends Fragment {
    public fragment1(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1,container,false);
    }
}

fragment2.java

    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment2 extends Fragment {
    public fragment2(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment2, container,false);
    }
}

fragment1.xml

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 1"
        android:textSize="25sp"/>

</LinearLayout>

fragment2.xml

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 2"
        android:textSize="25sp"/>

</LinearLayout>

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:baselineAligned="false"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.test.testfragment.MainActivity">

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="0px"
        android:name="layout.fragment1"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/fragment1" />

    <fragment
        android:name="layout.fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>

activity_main (Design)

Error


问:
How to query List of Maps in DynamoDb
I have of the non-primary key column in DynamoDb which is of List type as this:

```<code>logs=[{
m1:{"key1":"pair1",
"key2":"pair2",
"timestamp":2189321.212
},
m2:{"key1":"pair1",
"key2":"pair2",
"timestamp":2112321.212
},
...
}]
</code>```

So problem statement is I want to get a list of items, which are 30 days old.
I am not able to query this one.

答:
It is not possible to do that directly using DynamoDB functions.

You could load and serialise each table log item into an object in your code, then sort and filter the objects. If you had a lot of log files this could use up a lot of memory.

If you are in control of how the log data is stored, you may want to remodel your tables, so that the logs are stored as table items. You could make log id your partition key and the timestamp a range key, which would make time based queries very fast.

If you went down that route, be aware that you would need to make your timestamp a number in DynamoDB in order to use it as a range key.

Title: How to query List of Maps in DynamoDb

Body:
I have of the non-primary key column in DynamoDb which is of List type as this:

logs=[{
m1:{"key1":"pair1",
"key2":"pair2",
"timestamp":2189321.212
},
m2:{"key1":"pair1",
"key2":"pair2",
"timestamp":2112321.212
},
...
}]

So problem statement is I want to get a list of items, which are 30 days old.
I am not able to query this one.