问:
How to check a regexp's relevance?
Let's say we have two regular expressions:

```<code>1234.*
</code>```

and

```<code>.*
</code>```

Input:

```<code>1234567
</code>```

Obviously they both match, but 1234.* matches better since it is more specific. i.e. is more relevant. Is there a standard way for checking which is more relevant?

edit:

Some clarification. I want to make decisions by checking which regexp matches the input best. In this case I am only matching numbers.

Example with telephone numbers:

Input:

```<code>31882481337
</code>```

We have a rule for each of the following regexps:

```<code>31.*
.*
</code>```

In this scenario I would like the rule to be used that is bound to 31.* because that is more specific for the input given. If I was not using regexps it would be easy, because I could use a scoring mechanism to check how much it matches, however these rules may have some more advanced regexps, like:

```<code>31[89].*
</code>```

答:
Has been a long time since I asked this question, but I wanted to let you know what I came up with in the end. I went for a far simpler approach, I just added a weight factor to my regular expressions. So you could say I defined the relevance of the regular expression myself instead of trying to define it using regular expressions:</p>

```<code>Expression      Relevance
31.*              1
.*              0
</code>```

Title: How to check a regexp's relevance?

Body:
Let's say we have two regular expressions:

1234.*

and

.*

Input:

1234567

Obviously they both match, but 1234.* matches better since it is more specific. i.e. is more relevant. Is there a standard way for checking which is more relevant?

edit:

Some clarification. I want to make decisions by checking which regexp matches the input best. In this case I am only matching numbers.

Example with telephone numbers:

Input:

31882481337

We have a rule for each of the following regexps:

31.*
.*

In this scenario I would like the rule to be used that is bound to 31.* because that is more specific for the input given. If I was not using regexps it would be easy, because I could use a scoring mechanism to check how much it matches, however these rules may have some more advanced regexps, like:

31[89].*

Body:
Has been a long time since I asked this question, but I wanted to let you know what I came up with in the end. I went for a far simpler approach, I just added a weight factor to my regular expressions. So you could say I defined the relevance of the regular expression myself instead of trying to define it using regular expressions:

Expression      Relevance
31.*              1
.*              0


来源: stackexchange

问:
error MSB3073: How do I fix this?
```<code>3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: The command "copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Release\EnergyLib.dll" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32\EnergyLib32.dll"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\EnergyDriver\objfre_win7_x86\i386\EnergyDriver.sys" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" exited with code 1.
</code>```

I was researching online, I think it has to do something with relative pathing; but I'm not sure. Can someone help explain what is wrong and how to fix this?

答:
For anyone else that comes across this question my problem was that the target directory contained spaces i.e.

```<code>C:\Users\Administrator\Documents\Visual Studio 2017\projects\blah
</code>```

So for me the solution was to wrap $(TargetDir) in double quotes i.e.

```<code>copy ..\resources\\* "$(TargetDir)" /Y
</code>```

ContentLicense: CC BY-SA 3.0

Title: error MSB3073: How do I fix this?

Body:
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: The command "copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Release\EnergyLib.dll" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32\EnergyLib32.dll"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\EnergyDriver\objfre_win7_x86\i386\EnergyDriver.sys" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" exited with code 1.

I was researching online, I think it has to do something with relative pathing; but I'm not sure. Can someone help explain what is wrong and how to fix this?

Body:
For anyone else that comes across this question my problem was that the target directory contained spaces i.e.

C:\Users\Administrator\Documents\Visual Studio 2017\projects\blah

So for me the solution was to wrap $(TargetDir) in double quotes i.e.

copy ..\resources\\* "$(TargetDir)" /Y

ContentLicense: CC BY-SA 4.0


问:
declaring a property in constructor with typescript react
From the draft-js documention, one can (in vanilla React, with no typescript) setup the Draft-js environment thus, noticing that the onChange property can be declared directly in the constructor:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    const {editorState} = this.state;
    return <Editor editorState={editorState} onChange={this.onChange} />;
  }
}
</code>```

However, when I try to do the same with Typescript/React (code below), I get this error

error TS2339: Property 'onChange' does not exist on type 'Main'.

```<code>class Main extends React.Component<MainProps, MainState> {

    constructor(props) {
    super(props);
    this.state = { todos: [], editorState: EditorState.createEmpty() };
    this.onChange = (editorState) => this.setState({ editorState });
  }
</code>```

I also tried adding onChange as a property to the props

```<code>interface MainProps {
    model: Model;
    onChange: Function;
}
</code>```

What is the appropriate way to declare such a function property in typescript/react?

答:
You can use handleChange method like this :

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Editor, EditorState } from 'draft-js';

interface MyEditorProps {
}

class MyEditor extends React.Component<MyEditorProps, any> {
  constructor(props: MyEditorProps) {
    super(props);

    this.state = { editorState: EditorState.createEmpty() };
  }
  handleChange(e: EditorState) {
    this.setState({ editorState: e });
  }
  render() {
    return (
      <Editor editorState={this.state.editorState} onChange={e => this.handleChange(e)} />
    );
  }
}

ReactDOM.render(
  <MyEditor />,
  document.getElementById('editor'),
);

export { MyEditor }```

Body:
From the draft-js documention, one can (in vanilla React, with no typescript) setup the Draft-js environment thus, noticing that the onChange property can be declared directly in the constructor:

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    const {editorState} = this.state;
    return <Editor editorState={editorState} onChange={this.onChange} />;
  }
}

However, when I try to do the same with Typescript/React (code below), I get this error

error TS2339: Property 'onChange' does not exist on type 'Main'.

class Main extends React.Component<MainProps, MainState> {

    constructor(props) {
    super(props);
    this.state = { todos: [], editorState: EditorState.createEmpty() };
    this.onChange = (editorState) => this.setState({ editorState });
  }

I also tried adding onChange as a property to the props

interface MainProps {
    model: Model;
    onChange: Function;
}

What is the appropriate way to declare such a function property in typescript/react?


问:
Printing array with Processingjs

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/project-selection-sort-visualizer .

The code is working and I can get it to print to the console but I need to be able to print to the canvas.

I've tried :

```<code>var displayArray = function(array) {
    textFont(createFont("monospace"), 12);
    println(array);

};
</code>```

Bu this again just prints to the console. How can I print to the canvas with processingjs?

答:
Specifically, add this to displayArray():

```<code>textAlign(LEFT, TOP);
fill(0);
print(array);
text(array, 0, 0);
</code>```

Or if you want it centered:

```<code>textAlign(CENTER, CENTER);
fill(0);
print(array);
text(array, 200, 200);
</code>```

Title: Printing array with Processingjs

Body:
I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/project-selection-sort-visualizer .

The code is working and I can get it to print to the console but I need to be able to print to the canvas.

I've tried :

var displayArray = function(array) {
    textFont(createFont("monospace"), 12);
    println(array);

};

Bu this again just prints to the console. How can I print to the canvas with processingjs?

Body:
Specifically, add this to displayArray():

textAlign(LEFT, TOP);
fill(0);
print(array);
text(array, 0, 0);

Or if you want it centered:

textAlign(CENTER, CENTER);
fill(0);
print(array);
text(array, 200, 200);


问:
Guide how date cell is read by Apache poi
I'm importing an excel file with many rows. Some columns are dates and i have to read them as such but the format of the cell is not correctly read by Apache poi.
Indeed the dates have to be dd/MM/YYYY but when i have 04/13/2017 the Apache poi library thinks it is in the format MM/dd/YYYY, and reads the date consequently.

How can i tell apache poi to read dates in the right format?

Below there is an example of my code:

```<code>                           case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    Date d = cell.getDateCellValue());
                                    System.out.println(myWorkBook.getSheetName(i) + "  " + cell.getNumericCellValue() + "\t");
}
</code>```

答:
The right way is using getDataFormatString as it is done in this answer Validating the excel date for MM/dd/yyyy format
But the builtin formats are limited.

If the limitation of the built-in formats bothers you, casting the value as a string is done through Data formatter

```<code>DataFormatter formatter = new DataFormatter();
String formattedValue = formatter.formatCellValue(cell);
</code>```

The validation of the date field is already performed from the Excel file, and the date is read as a string if it is not in the right format.

Body:
I'm importing an excel file with many rows. Some columns are dates and i have to read them as such but the format of the cell is not correctly read by Apache poi.
Indeed the dates have to be dd/MM/YYYY but when i have 04/13/2017 the Apache poi library thinks it is in the format MM/dd/YYYY, and reads the date consequently.

How can i tell apache poi to read dates in the right format?

Below there is an example of my code:

                           case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    Date d = cell.getDateCellValue());
                                    System.out.println(myWorkBook.getSheetName(i) + "  " + cell.getNumericCellValue() + "\t");
}

Body:
The right way is using getDataFormatString as it is done in this answer Validating the excel date for MM/dd/yyyy format
But the builtin formats are limited.

If the limitation of the built-in formats bothers you, casting the value as a string is done through Data formatter

DataFormatter formatter = new DataFormatter();
String formattedValue = formatter.formatCellValue(cell);

The validation of the date field is already performed from the Excel file, and the date is read as a string if it is not in the right format.


问:
Index every n-th element along each dimension of a N-dimensional numpy array
In one dimension it is possible to do:

```<code>np.arange(12)[::3]
</code>```

to obtain:

```<code>array([0, 3, 6, 9])
</code>```

What is an efficient way to do the same for N-dimensions?

For example, given:

```<code>np.random.random((10, 15, 20))
</code>```

how to obtain every third element in along each dimension?

答:
For 3d, you can do:

```<code>a = np.random.random((10, 15, 20))

a[::3,::3,::3].shape
# (4, 5, 7)

a.shape
# (10, 15, 20)
</code>```

For arbitrary dimension, you might use slice:

```<code>a[[slice(None,None,3)] * a.ndim].shape
# (4, 5, 7)
</code>```

Body:
In one dimension it is possible to do:

np.arange(12)[::3]

to obtain:

array([0, 3, 6, 9])

What is an efficient way to do the same for N-dimensions?

For example, given:

np.random.random((10, 15, 20))

how to obtain every third element in along each dimension?

Body:
For 3d, you can do:

a = np.random.random((10, 15, 20))

a[::3,::3,::3].shape
# (4, 5, 7)

a.shape
# (10, 15, 20)

For arbitrary dimension, you might use slice:

a[[slice(None,None,3)] * a.ndim].shape
# (4, 5, 7)


问:
hadoop No FileSystem for scheme: file
I am trying to run a simple NaiveBayesClassifer using hadoop, getting this error

```<code>Exception in thread "main" java.io.IOException: No FileSystem for scheme: file
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1375)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:95)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:180)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
    at org.apache.mahout.classifier.naivebayes.NaiveBayesModel.materialize(NaiveBayesModel.java:100)
</code>```

Code :

```<code>    Configuration configuration = new Configuration();
    NaiveBayesModel model = NaiveBayesModel.materialize(new Path(modelPath), configuration);// error in this line..
</code>```

modelPath is pointing to NaiveBayes.bin file, and configuration object is printing - Configuration: core-default.xml, core-site.xml

I think its because of jars, any ideas?

答:
If you are using sbt:

```<code>//hadoop
lazy val HADOOP_VERSION = "2.8.0"

lazy val dependenceList = Seq(

//hadoop
//The order is important: "hadoop-hdfs" and then "hadoop-common"
"org.apache.hadoop" % "hadoop-hdfs" % HADOOP_VERSION

,"org.apache.hadoop" % "hadoop-common" % HADOOP_VERSION
)
</code>```

Title: hadoop No FileSystem for scheme: file

Body:
I am trying to run a simple NaiveBayesClassifer using hadoop, getting this error

Exception in thread "main" java.io.IOException: No FileSystem for scheme: file
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1375)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:95)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:180)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
    at org.apache.mahout.classifier.naivebayes.NaiveBayesModel.materialize(NaiveBayesModel.java:100)

Code :

    Configuration configuration = new Configuration();
    NaiveBayesModel model = NaiveBayesModel.materialize(new Path(modelPath), configuration);// error in this line..

modelPath is pointing to NaiveBayes.bin file, and configuration object is printing - Configuration: core-default.xml, core-site.xml

I think its because of jars, any ideas?

Body:
If you are using sbt:

//hadoop
lazy val HADOOP_VERSION = "2.8.0"

lazy val dependenceList = Seq(

//hadoop
//The order is important: "hadoop-hdfs" and then "hadoop-common"
"org.apache.hadoop" % "hadoop-hdfs" % HADOOP_VERSION

,"org.apache.hadoop" % "hadoop-common" % HADOOP_VERSION
)


问:
warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) in MFC(VC++)
I am getting this warning "warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)" on below line of code :

```<code>if (g_objConfigurationDetails.bAutoScan !=  m_objScanNASBtn.GetCheck())
        {
            g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();
}
</code>```

both the lines are giving the same warning.
where bAutoScan  = bool
m_objScanNASBtn = CButton

答:
The reason is that MFC's GetCheck doesn't return a bool:

The return value from a button control created with the BS_AUTOCHECKBOX, BS_AUTORADIOBUTTON, BS_AUTO3STATE, BS_CHECKBOX, BS_RADIOBUTTON, or BS_3STATE style is one of the following values:

  - BST_UNCHECKED - Button state is unchecked.

  - BST_CHECKED - Button state is checked.

  - BST_INDETERMINATE - Button state is indeterminate (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).

So you probably want

```<code>if (g_objConfigurationDetails.bAutoScan
      != (m_objScanNASBtn.GetCheck() == BST_CHECKED))
</code>```

or

```<code>bool bNASBtnChecked = (m_objScanNASBtn.GetCheck() == BST_CHECKED);
if (g_objConfigurationDetails.bAutoScan != bNASBtnChecked)
{
    g_objConfigurationDetails.bAutoScan = bNASBtnChecked;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am getting this warning "warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)" on below line of code :

if (g_objConfigurationDetails.bAutoScan !=  m_objScanNASBtn.GetCheck())
        {
            g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();
}

both the lines are giving the same warning.
where bAutoScan  = bool
m_objScanNASBtn = CButton

Body:
The reason is that MFC's GetCheck doesn't return a bool:

The return value from a button control created with the BS_AUTOCHECKBOX, BS_AUTORADIOBUTTON, BS_AUTO3STATE, BS_CHECKBOX, BS_RADIOBUTTON, or BS_3STATE style is one of the following values:

  - BST_UNCHECKED - Button state is unchecked.

  - BST_CHECKED - Button state is checked.

  - BST_INDETERMINATE - Button state is indeterminate (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).

So you probably want

if (g_objConfigurationDetails.bAutoScan
      != (m_objScanNASBtn.GetCheck() == BST_CHECKED))

or

bool bNASBtnChecked = (m_objScanNASBtn.GetCheck() == BST_CHECKED);
if (g_objConfigurationDetails.bAutoScan != bNASBtnChecked)
{
    g_objConfigurationDetails.bAutoScan = bNASBtnChecked;
}


问:
Angular 2: ng build --prod errors while ng serve run without erros
I tried to deploy my angular 2 app to heroku, but when I try to build for production, a long list of error appears. I should mention, that on ng serve, the app is running without problems and errors.
The list of errors is showed in attached photo

I'm cannot find any solution for this problems. All main modules are updated to latest version. Thank you

答:
My guess is that if you were to run ng-serve --prod you would get the same errors. When you don't specify --prod many different errors are ignored.

For instance without --prod it will compile and not warn you that properties are referencing are not mentioned on the type you specified. Now if you went and changed that object type to type any the errors would then go away.

Without your errors being listed here I am sure many of them are simple errors like above. You may need to go back and update your types to ensure any properties you reference in *.ts or *.html files are added to the class definition.


问:
Android app is not running on other device
i just made a simple android app with 6 buttons. Each button on click opens a new activity. I installed the app on my device via USB cable from Android studio and it runs fine on my device.

But here rises the problem, when I installed the app on my friends device after sharing via SHAREit the app installed on his device but did not run.

What could be the reason for this? And how can I solve this?

Please help. Thank you

答:
I have a solution for you:

Install Bluestacks Android Emulator.

Go to Tools, Android and click on Enable Adb Integration to disable it.

In android studios one Android Device for Bluestacks will appear while installation.

Share the installed app through shareit.

It will work on other device.

Hope it helps


问:
How to list all files added to the first commit of a GIT repository?
Current status:
I am using git diff-tree -r HASH to list all added, modified and deleted files in a specific commit. This worked until today.

The problem:
I want to list all added files in my first commit, however passing the first HASH as a parameter doesn't work. Why?

Main question:
How can I get the list of all files added in my first commit?

答:
This works for me</p>

```<code>git show <commit|branch-name> --name-only
</code>```

Body:
This works for me

git show <commit|branch-name> --name-only


问:
SI-prefixes for number format in MS Excel
Does anybody know if it is possible to show numbers in MS Excel with SI-prefixes?

I'd like to have

... 1 n, 1 µ, 1 m, 1, 1 k, 1M, 1 G, ...

instead of scientific format

... 1E-09, 1E-06, 1E-03, 1, 1E+03, 1E+06. 1E+09, ...

Perhaps adding an unit like V (volts), F (farad) etc.

I would be perfect, if the cell would still contain the number and not a string, so it can easily be changed to another format (back to scientific or whatever)

答:
There's no way I know of to do this as a number format (where you can then use the formatted number as you would any other numeric value for subsequent calculation), but for simply presenting the number using SI prefixes, here's the formula I use.  It takes the formula in the specified cell (usually next to it, in this case E28), scales the number, rounds to the specified number of significant figures (in this case 3), appends the appropriate SI prefix, and then appends the specified unit (in this case 'F' for Farads).  The advantage here is that the formula is self-contained and doesn't require any external reference tables.  This formula works for femto (10^-15) through Tera (10^12), but can easily be expanded for additional prefixes

```<code>=CONCAT(
    ROUND(
        IF(E28>1E12, E28/1E12,
            IF(E28>1E9, E28/1E9,
                IF(E28>1E6, E28/1E6,
                    IF(E28>1E3, E28/1E3,
                        IF(E28>1, E28,
                            IF(E28>1E-3, E28*1E3,
                                IF(E28>1E-6, E28*1E6,
                                    IF(E28>1E-9, E28*1E9,
                                        IF(E28>1E-12, E28*1E12,
                                            E28*1E15
        )   )   )   )   )   )   )   )   ),
        3 +N("This is the number of significant digits to round to")
        -(1+INT(LOG10(ABS(
            IF(E28>1E12, E28/1E12,
                IF(E28>1E9, E28/1E9,
                    IF(E28>1E6, E28/1E6,
                        IF(E28>1E3, E28/1E3,
                            IF(E28>1, E28,
                                IF(E28>1E-3, E28*1E3,
                                    IF(E28>1E-6, E28*1E6,
                                        IF(E28>1E-9, E28*1E9,
                                            IF(E28>1E-12, E28*1E12,
                                                E28*1E15
        )   )   )   )   )   )   )   )   )   ))))
    ),
    IF(E28>1E12, "T",
        IF(E28>1E9, "G",
            IF(E28>1E6, "M",
                IF(E28>1E3, "k",
                    IF(E28>1, "",
                        IF(E28>1E-3, "m",
                            IF(E28>1E-6, "µ",
                                IF(E28>1E-9, "n",
                                    IF(E28>1E-12, "p",
                                        "f"
    )   )   )   )   )   )   )   )   ),
    "F" +N("This is the unit symbol that will be appended to the end")
)
</code>```

If you want to round to a fixed number of decimal figures as opposed to significant figures, the formula is a little simpler:

```<code>=CONCAT(
    ROUND(
        IF(E28>1E12, E28/1E12,
            IF(E28>1E9, E28/1E9,
                IF(E28>1E6, E28/1E6,
                    IF(E28>1E3, E28/1E3,
                        IF(E28>1, E28,
                            IF(E28>1E-3, E28*1E3,
                                IF(E28>1E-6, E28*1E6,
                                    IF(E28>1E-9, E28*1E9,
                                        IF(E28>1E-12, E28*1E12,
                                            E28*1E15
        )   )   )   )   )   )   )   )   ),
        3 +N("This is the number of decimal digits to round to")
    ),
    IF(E28>1E12, "T",
        IF(E28>1E9, "G",
            IF(E28>1E6, "M",
                IF(E28>1E3, "k",
                    IF(E28>1, "",
                        IF(E28>1E-3, "m",
                            IF(E28>1E-6, "µ",
                                IF(E28>1E-9, "n",
                                    IF(E28>1E-12, "p",
                                        "f"
    )   )   )   )   )   )   )   )   ),
    "F" +N("This is the unit symbol that will be appended to the end")
)
</code>```

Note that I've written all of the scaling constants in exponential notation, Excel will change these to plain numbers when you enter the formula.  By using a relative cell reference, it's pretty easy to copy and paste the formula around where you need it.

The formula could be condensed into a single block of IF/CONCAT/ROUND statements, but arranging it as I've done here separates out the rounding constant into a single point in the formula, making it easier to change.

Body:
There's no way I know of to do this as a number format (where you can then use the formatted number as you would any other numeric value for subsequent calculation), but for simply presenting the number using SI prefixes, here's the formula I use.  It takes the formula in the specified cell (usually next to it, in this case E28), scales the number, rounds to the specified number of significant figures (in this case 3), appends the appropriate SI prefix, and then appends the specified unit (in this case 'F' for Farads).  The advantage here is that the formula is self-contained and doesn't require any external reference tables.  This formula works for femto (10^-15) through Tera (10^12), but can easily be expanded for additional prefixes

=CONCAT(
    ROUND(
        IF(E28>1E12, E28/1E12,
            IF(E28>1E9, E28/1E9,
                IF(E28>1E6, E28/1E6,
                    IF(E28>1E3, E28/1E3,
                        IF(E28>1, E28,
                            IF(E28>1E-3, E28*1E3,
                                IF(E28>1E-6, E28*1E6,
                                    IF(E28>1E-9, E28*1E9,
                                        IF(E28>1E-12, E28*1E12,
                                            E28*1E15
        )   )   )   )   )   )   )   )   ),
        3 +N("This is the number of significant digits to round to")
        -(1+INT(LOG10(ABS(
            IF(E28>1E12, E28/1E12,
                IF(E28>1E9, E28/1E9,
                    IF(E28>1E6, E28/1E6,
                        IF(E28>1E3, E28/1E3,
                            IF(E28>1, E28,
                                IF(E28>1E-3, E28*1E3,
                                    IF(E28>1E-6, E28*1E6,
                                        IF(E28>1E-9, E28*1E9,
                                            IF(E28>1E-12, E28*1E12,
                                                E28*1E15
        )   )   )   )   )   )   )   )   )   ))))
    ),
    IF(E28>1E12, "T",
        IF(E28>1E9, "G",
            IF(E28>1E6, "M",
                IF(E28>1E3, "k",
                    IF(E28>1, "",
                        IF(E28>1E-3, "m",
                            IF(E28>1E-6, "µ",
                                IF(E28>1E-9, "n",
                                    IF(E28>1E-12, "p",
                                        "f"
    )   )   )   )   )   )   )   )   ),
    "F" +N("This is the unit symbol that will be appended to the end")
)

If you want to round to a fixed number of decimal figures as opposed to significant figures, the formula is a little simpler:

=CONCAT(
    ROUND(
        IF(E28>1E12, E28/1E12,
            IF(E28>1E9, E28/1E9,
                IF(E28>1E6, E28/1E6,
                    IF(E28>1E3, E28/1E3,
                        IF(E28>1, E28,
                            IF(E28>1E-3, E28*1E3,
                                IF(E28>1E-6, E28*1E6,
                                    IF(E28>1E-9, E28*1E9,
                                        IF(E28>1E-12, E28*1E12,
                                            E28*1E15
        )   )   )   )   )   )   )   )   ),
        3 +N("This is the number of decimal digits to round to")
    ),
    IF(E28>1E12, "T",
        IF(E28>1E9, "G",
            IF(E28>1E6, "M",
                IF(E28>1E3, "k",
                    IF(E28>1, "",
                        IF(E28>1E-3, "m",
                            IF(E28>1E-6, "µ",
                                IF(E28>1E-9, "n",
                                    IF(E28>1E-12, "p",
                                        "f"
    )   )   )   )   )   )   )   )   ),
    "F" +N("This is the unit symbol that will be appended to the end")
)

Note that I've written all of the scaling constants in exponential notation, Excel will change these to plain numbers when you enter the formula.  By using a relative cell reference, it's pretty easy to copy and paste the formula around where you need it.

The formula could be condensed into a single block of IF/CONCAT/ROUND statements, but arranging it as I've done here separates out the rounding constant into a single point in the formula, making it easier to change.


问:
Checking values within a Base64 Encoded Image
Consider this Base64 encoded image string value:

```<code>data:application/pdf;base64,[encoded data, 12288 characters]
</code>```

This encoded string represents a 4 by 5 inch image with a string text in the middle "Image Title". Is there any way I can check this encoded Base64 string to validate that there is in fact a string with the value of "Image Title"?

The reason I need this is so I can unit test our Image Generation process to ensure that we are generating images properly.

答:
The fact that it's base 64 is not even slightly relevant or related. It would be no different to loading the image as a byte array.

Anyway, the underlying question here is basically "How do I check these pixels form the textual characters I want?". You need some kind of OCR to achieve this.

Body:
Consider this Base64 encoded image string value:

data:application/pdf;base64,[encoded data, 12288 characters]

This encoded string represents a 4 by 5 inch image with a string text in the middle "Image Title". Is there any way I can check this encoded Base64 string to validate that there is in fact a string with the value of "Image Title"?

The reason I need this is so I can unit test our Image Generation process to ensure that we are generating images properly.


问:
Sum multiple BigDecimals to a Map<String, BigDecimal>
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

```<code>BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

答:
First you create a class for collecting the result.

You then do the same as BigDecimal has, i.e. a ZERO constant and an add() method.

```<code>public class ChargesAndFees {
    private static final ZERO = new ChargesAndFees(BigDecimal.ZERO, BigDecimal.ZERO);

    private final BigDecimal charges;
    private final BigDecimal fees;

    // constructor and getters

    public ChargesAndFees add(ChargesAndFees that) {
        return new ChargesAndFees(this.charges.add(that.charges),
                                  this.fees.add(that.fees));
    }
}
</code>```

Now you can do the stream logic

```<code>ChargesAndFees totals = tableRowDataList.stream()
        .map(el -> new ChargesAndFees(el.getSums().getCharges(),
                                      el.getSums().getFees()))
        .reduce(ChargesAndFees.ZERO, ChargesAndFees::add);
</code>```

If you insist, you can then convert the values in totals into a Map.

Body:
I'm trying to sum multiple BigDecimals from a List. Currently, I'm using two streams, but would like to have only one stream if possible. I'm unsure how I can rewrite below in a performant way.

BigDecimal totalCharges = tableRowDataList.stream()
            .map(el -> el.getSums().getCharges())
            .reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalFees = tableRowDataList.stream()
            .map(el -> el.getSums().getFees())
            .reduce(BigDecimal.ZERO, BigDecimal::add);

As you can see, the streams are doing basically the same, only the call to getCharges/getFees differ.

What is the best way to get a resulting Map<String, BigDecimal> from above? (Where key would be charges/fees)

Body:
First you create a class for collecting the result.

You then do the same as BigDecimal has, i.e. a ZERO constant and an add() method.

public class ChargesAndFees {
    private static final ZERO = new ChargesAndFees(BigDecimal.ZERO, BigDecimal.ZERO);

    private final BigDecimal charges;
    private final BigDecimal fees;

    // constructor and getters

    public ChargesAndFees add(ChargesAndFees that) {
        return new ChargesAndFees(this.charges.add(that.charges),
                                  this.fees.add(that.fees));
    }
}

Now you can do the stream logic

ChargesAndFees totals = tableRowDataList.stream()
        .map(el -> new ChargesAndFees(el.getSums().getCharges(),
                                      el.getSums().getFees()))
        .reduce(ChargesAndFees.ZERO, ChargesAndFees::add);

If you insist, you can then convert the values in totals into a Map.


问:
Ruby on Rails: Why "edit" action does not work?
In views/products/edit.html.erb I use:

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
</code>```

which generates:

```<code><form method="post" action="/aircons/8" accept-charset="UTF-8">
</code>```

and I get the following error:

```<code>The action '8' could not be found for ProductsController
</code>```

when trying to update a product with id=8.

I think that form's method should be put. Is that right ? How should I fix this ?

Some controller code:

```<code>def edit
  @product = Product.find(params[:id])
end

def update
  update_params_with_new_values(params)

  @product = Product.find(params[:id])

  if @product.update_attributes(params[:product])
    flash[:notice] = "Product updated successfully."
    redirect_to(:product => 'index')
  else
    render('edit')
  end
end

def update_params_with_new_values(params)
  params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
  params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end
</code>```

routes.rb contains only the following two lines:

```<code>root :to => "products#index"
resources :products
</code>```

答:
Why don't you just use:

```<code><%= form_for @product do |f| %>
</code>```

?

If it won't work, please add your routes to question.

Body:
In views/products/edit.html.erb I use:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>

which generates:

<form method="post" action="/aircons/8" accept-charset="UTF-8">

and I get the following error:

The action '8' could not be found for ProductsController

when trying to update a product with id=8.

I think that form's method should be put. Is that right ? How should I fix this ?

Some controller code:

def edit
  @product = Product.find(params[:id])
end

def update
  update_params_with_new_values(params)

  @product = Product.find(params[:id])

  if @product.update_attributes(params[:product])
    flash[:notice] = "Product updated successfully."
    redirect_to(:product => 'index')
  else
    render('edit')
  end
end

def update_params_with_new_values(params)
  params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
  params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end

routes.rb contains only the following two lines:

root :to => "products#index"
resources :products

Body:
Why don't you just use:

<%= form_for @product do |f| %>

?

If it won't work, please add your routes to question.


问:
std::sort function not working in char array
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used  std::sort function .but it's not working.

here is my code

```<code>#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}
</code>```

test case:

```<code>1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm
</code>```

output:

```<code>lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting
</code>```

after sorting uppercase string don't even print.

答:
You have a bug with indexes, fix:

```<code>low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
</code>```

Exchanged k and j in this snippet.

Body:
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used  std::sort function .but it's not working.

here is my code

#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}

test case:

1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm

output:

lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting

after sorting uppercase string don't even print.

Body:
You have a bug with indexes, fix:

low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';

Exchanged k and j in this snippet.


问:
& replace or decode in Laravel 5.4
it is a newbie question. But i spend 3 hours to solve it with 0 result.

i want to convert this link:

```<code>http://127.0.0.1:8000/data?make%5B%5D=ACURA&model%5B%5D=LEGEND&score%5B%5D=6
</code>```

in to this:

```<code>http://127.0.0.1:8000/data?make%5B%5D=ACURA&model%5B%5D=LEGEND&score%5B%5D=6
</code>```

This is my controller:

```<code>public function index(Request $request)
    {
        $inputRAW    = $request->getQueryString();

        $inputDECODE = htmlspecialchars_decode($inputRAW);

        $input       = str_replace('&', '&', $inputDECODE);

        return view('lots.browse', compact('input'));
    }
</code>```

Some on know what im doing wrong?

答:
In order to change query string you should redirect it.

Have a look here: https://laravel.com/docs/5.4/redirects

Title: & replace or decode in Laravel 5.4

Body:
it is a newbie question. But i spend 3 hours to solve it with 0 result.

i want to convert this link:

http://127.0.0.1:8000/data?make%5B%5D=ACURA&model%5B%5D=LEGEND&score%5B%5D=6

in to this:

http://127.0.0.1:8000/data?make%5B%5D=ACURA&model%5B%5D=LEGEND&score%5B%5D=6

This is my controller:

public function index(Request $request)
    {
        $inputRAW    = $request->getQueryString();

        $inputDECODE = htmlspecialchars_decode($inputRAW);

        $input       = str_replace('&', '&', $inputDECODE);

        return view('lots.browse', compact('input'));
    }

Some on know what im doing wrong?


问:
SQL list of all the user defined functions in a database
I am looking for a SQL query that outputs the function definitions for all of the user defined functions in a database catalog.

I have found as far as

```<code>SELECT OBJECT_DEFINITION (OBJECT_ID(N'dbo.UserFunctionName')) AS [Object Definition]
</code>```

and

```<code>SELECT ROUTINE_NAME FROM information_schema.routines WHERE routine_type = 'function'
</code>```

but I can't think of or find a way to feed the ROUTINE_NAME list to the OBJECT_ID.

The purpose here is a searchable text of the user defined function definitions in a database for database change analysis, if something like a full SQL procedure or purposed helper program is easier, I will do that and post it.

答:
```<code>SELECT O.name, M.definition, O.type_desc, O.type
FROM sys.sql_modules M
INNER JOIN sys.objects O ON M.object_id=O.object_id
WHERE O.type IN ('IF','TF','FN')
</code>```

Body:
I am looking for a SQL query that outputs the function definitions for all of the user defined functions in a database catalog.

I have found as far as

SELECT OBJECT_DEFINITION (OBJECT_ID(N'dbo.UserFunctionName')) AS [Object Definition]

and

SELECT ROUTINE_NAME FROM information_schema.routines WHERE routine_type = 'function'

but I can't think of or find a way to feed the ROUTINE_NAME list to the OBJECT_ID.

The purpose here is a searchable text of the user defined function definitions in a database for database change analysis, if something like a full SQL procedure or purposed helper program is easier, I will do that and post it.


问:
Project refresh failed - Error:Cause: org/gradle/internal/TrueTimeProvider
Importing this project from github, I've run into this message:

```<code>Gradle 'GameOfLife-master' project refresh failed
Error:Cause: org/gradle/internal/TrueTimeProvider
</code>```

I've tried solutions posted here, cleaned/rebuilt (at least attempted to) the project, invalidated caches and tried a different version of Gradle. None of that worked. Anyone else got any ideas?

Module: app - build.gradle

```<code>buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "com.neenbedankt.gradle.plugins:android-apt:1.8"
        classpath 'com.jakewharton.hugo:hugo-plugin:1.1.0'
        classpath "net.rdrei.android.buildtimetracker:gradle-plugin:0.5.+"
        classpath 'io.fabric.tools:gradle:1.+'
        classpath 'hu.supercluster:paperwork-plugin:1.2.7'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'io.fabric'
apply plugin: 'hugo'
apply plugin: "build-time-tracker"
apply plugin: 'hu.supercluster.paperwork'

paperwork {
    set = [
            gitInfo:   gitInfo(),
            gitSha:    gitSha(),
            buildTime: buildTime("yyyy-MM-dd HH:mm:ss", "GMT+01:00")
    ]
}

def versionMajor = 1
def versionMinor = 2
def versionPatch = 0

android {
    compileSdkVersion androidCompileSdkVersion
    buildToolsVersion androidBuildToolsVersion

    defaultConfig {
        applicationId 'hu.supercluster.gameoflife'
        minSdkVersion androidMinSdkVersion
        targetSdkVersion androidTargetSdkVersion

        versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"

        testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
    }

    signingConfigs {
        alpha {}
        beta {}
        release {}
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
            resValue "string", "app_name_for_buildtype", "Game of Life (debug)"
            minifyEnabled false
            testCoverageEnabled = false
        }

        alpha {
            applicationIdSuffix ".alpha"
            versionNameSuffix "-alpha"
            resValue "string", "app_name_for_buildtype", "Game of Life (alpha)"
            minifyEnabled false
            testCoverageEnabled = false
            lintOptions {
                disable 'MissingTranslation'
            }
        }

        beta {
            applicationIdSuffix ".beta"
            versionNameSuffix "-beta"
            resValue "string", "app_name_for_buildtype", "Game of Life (beta)"
            minifyEnabled false
            testCoverageEnabled = false
        }

        release {
            resValue "string", "app_name_for_buildtype", "Game of Life"
            minifyEnabled false
            proguardFile 'proguard-project.txt'
        }
    }

    sourceSets.main {
        // src/gen is the target for generated content like json model
        java.srcDirs += 'build/generated/source/db'
    }

    // avoid errors with message 'Duplicate files copied in APK ...'
    packagingOptions {
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
}

afterEvaluate {
    def propsFile = rootProject.file('keystore.properties')
    def configName = 'release'

    if (propsFile.exists() && android.signingConfigs.hasProperty(configName)) {
        def props = new Properties()
        props.load(new FileInputStream(propsFile))
        android.signingConfigs[configName].storeFile = rootProject.file(props['storeFile'])
        android.signingConfigs[configName].storePassword = props['storePassword']
        android.signingConfigs[configName].keyAlias = props['keyAlias']
        android.signingConfigs[configName].keyPassword = props['keyPassword']
    }
}

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:support-annotations:24.2.0'
    compile 'com.android.support:support-v13:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'

    // ---------

    compile 'com.github.tslamic.adn:library:1.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') { transitive = true }
    compile 'com.jakewharton.timber:timber:2.5.1'
    compile 'com.squareup:otto:1.3.6'
    compile 'hu.supercluster:paperwork:1.2.7'

    // ---------

    apt "org.androidannotations:androidannotations:" + androidAnnotationsVersion
    compile("org.androidannotations:androidannotations-api:" + androidAnnotationsAPIVersion )

    testCompile 'junit:junit:4.11'
    testCompile 'org.mockito:mockito-core:1.9.5'
    testCompile('com.squareup:fest-android:1.0.+') { exclude module: 'support-v4' }
    testCompile "org.robolectric:robolectric:3.0"

    androidTestCompile 'com.google.guava:guava:14.0.1',
            'com.squareup.dagger:dagger:1.1.0',
            'org.hamcrest:hamcrest-integration:1.1',
            'org.hamcrest:hamcrest-core:1.1',
            'org.hamcrest:hamcrest-library:1.1',
            'com.jakewharton.espresso:espresso:1.1-r3'
}

apt {
    arguments {
        resourcePackageName android.defaultConfig.applicationId
        androidManifestFile variant.outputs[0]?.processResources?.manifestFile
    }
}

apply plugin: 'idea'

idea {
    module {
        //and some extra test source dirs
        testSourceDirs += file('src/test')
    }
}

apply from: 'build-time-tracker.gradle'
</code>```

答:
You could run with --stacktrace to get a full exception stack trace

Gradle has the concept of public API and private API. Basically anything in org.gradle.internal is a part of the private API and the gradle team can change / remove these classes between gradle versions. Ideally plugins should never reference internal classes. Any plugin author referencing internal API's must understand that this code may break with a new release of Gradle.

It looks like one of your plugins is referencing the internal API (org.gradle.internal.TrueTimeProvider) and the plugin was built against one version of Gradle and you are running with a different version of gradle.

To fix, you'll need to determine which plugin is throwing the exception (--stacktrace will help here). Then you'll either need to change the plugin version to one compatible with your version of gradle, or change the gradle version you are running with.

Body:
Importing this project from github, I've run into this message:

Gradle 'GameOfLife-master' project refresh failed
Error:Cause: org/gradle/internal/TrueTimeProvider

I've tried solutions posted here, cleaned/rebuilt (at least attempted to) the project, invalidated caches and tried a different version of Gradle. None of that worked. Anyone else got any ideas?

Module: app - build.gradle

buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "com.neenbedankt.gradle.plugins:android-apt:1.8"
        classpath 'com.jakewharton.hugo:hugo-plugin:1.1.0'
        classpath "net.rdrei.android.buildtimetracker:gradle-plugin:0.5.+"
        classpath 'io.fabric.tools:gradle:1.+'
        classpath 'hu.supercluster:paperwork-plugin:1.2.7'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'io.fabric'
apply plugin: 'hugo'
apply plugin: "build-time-tracker"
apply plugin: 'hu.supercluster.paperwork'

paperwork {
    set = [
            gitInfo:   gitInfo(),
            gitSha:    gitSha(),
            buildTime: buildTime("yyyy-MM-dd HH:mm:ss", "GMT+01:00")
    ]
}

def versionMajor = 1
def versionMinor = 2
def versionPatch = 0

android {
    compileSdkVersion androidCompileSdkVersion
    buildToolsVersion androidBuildToolsVersion

    defaultConfig {
        applicationId 'hu.supercluster.gameoflife'
        minSdkVersion androidMinSdkVersion
        targetSdkVersion androidTargetSdkVersion

        versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"

        testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
    }

    signingConfigs {
        alpha {}
        beta {}
        release {}
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
            resValue "string", "app_name_for_buildtype", "Game of Life (debug)"
            minifyEnabled false
            testCoverageEnabled = false
        }

        alpha {
            applicationIdSuffix ".alpha"
            versionNameSuffix "-alpha"
            resValue "string", "app_name_for_buildtype", "Game of Life (alpha)"
            minifyEnabled false
            testCoverageEnabled = false
            lintOptions {
                disable 'MissingTranslation'
            }
        }

        beta {
            applicationIdSuffix ".beta"
            versionNameSuffix "-beta"
            resValue "string", "app_name_for_buildtype", "Game of Life (beta)"
            minifyEnabled false
            testCoverageEnabled = false
        }

        release {
            resValue "string", "app_name_for_buildtype", "Game of Life"
            minifyEnabled false
            proguardFile 'proguard-project.txt'
        }
    }

    sourceSets.main {
        // src/gen is the target for generated content like json model
        java.srcDirs += 'build/generated/source/db'
    }

    // avoid errors with message 'Duplicate files copied in APK ...'
    packagingOptions {
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
}

afterEvaluate {
    def propsFile = rootProject.file('keystore.properties')
    def configName = 'release'

    if (propsFile.exists() && android.signingConfigs.hasProperty(configName)) {
        def props = new Properties()
        props.load(new FileInputStream(propsFile))
        android.signingConfigs[configName].storeFile = rootProject.file(props['storeFile'])
        android.signingConfigs[configName].storePassword = props['storePassword']
        android.signingConfigs[configName].keyAlias = props['keyAlias']
        android.signingConfigs[configName].keyPassword = props['keyPassword']
    }
}

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:support-annotations:24.2.0'
    compile 'com.android.support:support-v13:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'

    // ---------

    compile 'com.github.tslamic.adn:library:1.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') { transitive = true }
    compile 'com.jakewharton.timber:timber:2.5.1'
    compile 'com.squareup:otto:1.3.6'
    compile 'hu.supercluster:paperwork:1.2.7'

    // ---------

    apt "org.androidannotations:androidannotations:" + androidAnnotationsVersion
    compile("org.androidannotations:androidannotations-api:" + androidAnnotationsAPIVersion )

    testCompile 'junit:junit:4.11'
    testCompile 'org.mockito:mockito-core:1.9.5'
    testCompile('com.squareup:fest-android:1.0.+') { exclude module: 'support-v4' }
    testCompile "org.robolectric:robolectric:3.0"

    androidTestCompile 'com.google.guava:guava:14.0.1',
            'com.squareup.dagger:dagger:1.1.0',
            'org.hamcrest:hamcrest-integration:1.1',
            'org.hamcrest:hamcrest-core:1.1',
            'org.hamcrest:hamcrest-library:1.1',
            'com.jakewharton.espresso:espresso:1.1-r3'
}

apt {
    arguments {
        resourcePackageName android.defaultConfig.applicationId
        androidManifestFile variant.outputs[0]?.processResources?.manifestFile
    }
}

apply plugin: 'idea'

idea {
    module {
        //and some extra test source dirs
        testSourceDirs += file('src/test')
    }
}

apply from: 'build-time-tracker.gradle'


问:
Reliable Directory.Exists using C#
According to this MSDN article, Directory.Exists can return false negatives (the directory exists, but you can't read it or similar). I was wondering if there's a similar method that, instead of returning true or false, returns something more informative... like "access denied" or maybe "path too long"...</p>

答:
source

this code can differentiate between if a file actually exists, and if the file does but the user doesn't have access

```<code>enum ExistState { exist, notExist, inaccessible };

void Check(string name) {
    DirectoryInfo di = new DirectoryInfo(name);
    ExistState state = ExistState.exist;
    if (!di.Exists) {
        try {
            if ((int)di.Attributes == -1) {
                state = ExistState.notExist;
            }
        } catch (UnauthorizedAccessException) {
            state = ExistState.inaccessible;
        }
    }
    Console.WriteLine("{0} {1}", name, state);
}
</code>```

explanation from the source

"The DirectoryInfo.Attributes property is incorrectly documented and does not raise the FileNotFound or DirectoryNotFound exceptions but instead returns the error value from the underlying win api function, which is 0xFFFFFFFF or -1.

If a path exists but access is disallowed then an attempt to retrieve the attributes will throw an exception.

If the path does not exist then the attributes will be -1."

Title: Reliable Directory.Exists using C#

Body:
source

this code can differentiate between if a file actually exists, and if the file does but the user doesn't have access

enum ExistState { exist, notExist, inaccessible };

void Check(string name) {
    DirectoryInfo di = new DirectoryInfo(name);
    ExistState state = ExistState.exist;
    if (!di.Exists) {
        try {
            if ((int)di.Attributes == -1) {
                state = ExistState.notExist;
            }
        } catch (UnauthorizedAccessException) {
            state = ExistState.inaccessible;
        }
    }
    Console.WriteLine("{0} {1}", name, state);
}

explanation from the source

"The DirectoryInfo.Attributes property is incorrectly documented and does not raise the FileNotFound or DirectoryNotFound exceptions but instead returns the error value from the underlying win api function, which is 0xFFFFFFFF or -1.

If a path exists but access is disallowed then an attempt to retrieve the attributes will throw an exception.

If the path does not exist then the attributes will be -1."


问:
How to divide the value of current row with the following one?
In Spark-Sql version 1.6, using DataFrames, is there a way to calculate, for a specific column, the fraction of dividing current row and the next one, for every row?

For example, if I have a table with one column, like so

```<code>Age
100
50
20
4
</code>```

I'd like the following output

```<code>Franction
2
2.5
5
</code>```

The last row is dropped because it has no "next row" to be added to.

Right now I am doing it by ranking the table and joining it with itself, where the rank is equals to rank+1.

Is there a better way to do this?
Can this be done with a Window function?

答:
Window function should do only partial tricks. Other partial trick can be done by defining a udf function

```<code>def div = udf((age: Double, lag: Double) => lag/age)
</code>```

First we need to find the lag using Window function and then pass that lag and age in udf function to find the div
    import sqlContext.implicits._
    import org.apache.spark.sql.functions._

```<code>val dataframe = Seq(
  ("A",100),
  ("A",50),
  ("A",20),
  ("A",4)
).toDF("person", "Age")

val windowSpec = Window.partitionBy("person").orderBy(col("Age").desc)
val newDF = dataframe.withColumn("lag", lag(dataframe("Age"), 1) over(windowSpec))
</code>```

And finally cal the udf function

```<code>newDF.filter(newDF("lag").isNotNull).withColumn("div", div(newDF("Age"), newDF("lag"))).drop("Age", "lag").show
</code>```

Final output would be

```<code>+------+---+
|person|div|
+------+---+
|     A|2.0|
|     A|2.5|
|     A|5.0|
+------+---+
</code>```

Edited
As @Jacek has suggested a better solution to use .na.drop instead of .filter(newDF("lag").isNotNull) and use / operator , so we don't even need to call the udf function

```<code>newDF.na.drop.withColumn("div", newDF("lag")/newDF("Age")).drop("Age", "lag").show
</code>```

Body:
In Spark-Sql version 1.6, using DataFrames, is there a way to calculate, for a specific column, the fraction of dividing current row and the next one, for every row?

For example, if I have a table with one column, like so

Age
100
50
20
4

I'd like the following output

Franction
2
2.5
5

The last row is dropped because it has no "next row" to be added to.

Right now I am doing it by ranking the table and joining it with itself, where the rank is equals to rank+1.

Is there a better way to do this?
Can this be done with a Window function?

Body:
Window function should do only partial tricks. Other partial trick can be done by defining a udf function

def div = udf((age: Double, lag: Double) => lag/age)

First we need to find the lag using Window function and then pass that lag and age in udf function to find the div
    import sqlContext.implicits._
    import org.apache.spark.sql.functions._

val dataframe = Seq(
  ("A",100),
  ("A",50),
  ("A",20),
  ("A",4)
).toDF("person", "Age")

val windowSpec = Window.partitionBy("person").orderBy(col("Age").desc)
val newDF = dataframe.withColumn("lag", lag(dataframe("Age"), 1) over(windowSpec))

And finally cal the udf function

newDF.filter(newDF("lag").isNotNull).withColumn("div", div(newDF("Age"), newDF("lag"))).drop("Age", "lag").show

Final output would be

+------+---+
|person|div|
+------+---+
|     A|2.0|
|     A|2.5|
|     A|5.0|
+------+---+

Edited
As @Jacek has suggested a better solution to use .na.drop instead of .filter(newDF("lag").isNotNull) and use / operator , so we don't even need to call the udf function

newDF.na.drop.withColumn("div", newDF("lag")/newDF("Age")).drop("Age", "lag").show


问:
Can I just inject super class when use dagger2 for dependency injection?
I use Dagger2 for DI in my android application. I found that I have to write inject method for every class that uses @Inject field. Is there a way that I can just inject the parent class so that I don't have to call inject on every subclass?
Take Activity for example. I have a BaseActivity that that every Activity extends from. Is there a way that I can just create an inject method in the component for BaseActivity and just call inject in BaseActivity's onCreate, and @inject fields in sub activities get injected automatically?

答:
You can do a little hack using reflection:

public class UiInjector {

    private static final String METHOD_NAME = "inject";

    private final UIComponent component;

    public UiInjector(final UIComponent component) {
        this.component = component;
    }

    public void inject(final Object subject) {
        try {
            component.getClass()
                    .getMethod(METHOD_NAME, subject.getClass())
                    .invoke(component, subject);
        } catch (final NoSuchMethodException exception) {
            throwNoInjectMethodForType(component, subject.getClass());
        } catch (final Exception exception) {
            throwUnknownInjectionError(exception);
        }
    }

    private void throwNoInjectMethodForType(final Object component, final Class subjectType) {
        throw new RuntimeException(component.getClass().getSimpleName() +
                " doesn't have inject method with parameter type : " + subjectType);
    }

    private void throwUnknownInjectionError(final Exception cause) {
        throw new RuntimeException("Unknown injection error", cause);
    }
}```

In this case, you still need to write inject method in a component, but you don't need 'inject' method in each activity, fragment, view, whatever.

Why it's work? when we use getClass() on injection subject will get a descendant class, not base.

Caution! In case you use Proguard, you need to add next
-keep class <ComponentClass> { *; } to your rules in order to keep inject methods as is in component

Body:
You can do a little hack using reflection:

public class UiInjector {

    private static final String METHOD_NAME = "inject";

    private final UIComponent component;

    public UiInjector(final UIComponent component) {
        this.component = component;
    }

    public void inject(final Object subject) {
        try {
            component.getClass()
                    .getMethod(METHOD_NAME, subject.getClass())
                    .invoke(component, subject);
        } catch (final NoSuchMethodException exception) {
            throwNoInjectMethodForType(component, subject.getClass());
        } catch (final Exception exception) {
            throwUnknownInjectionError(exception);
        }
    }

    private void throwNoInjectMethodForType(final Object component, final Class subjectType) {
        throw new RuntimeException(component.getClass().getSimpleName() +
                " doesn't have inject method with parameter type : " + subjectType);
    }

    private void throwUnknownInjectionError(final Exception cause) {
        throw new RuntimeException("Unknown injection error", cause);
    }
}

In this case, you still need to write inject method in a component, but you don't need 'inject' method in each activity, fragment, view, whatever.

Why it's work? when we use getClass() on injection subject will get a descendant class, not base.

Caution! In case you use Proguard, you need to add next
-keep class <ComponentClass> { *; } to your rules in order to keep inject methods as is in component


问:
Linked List K Alternate Reverse Program
Can Anyone Explain me why the function *kAltReverse return node type prev and how it will work when you call node->next in print function to get the next element from the struct node & print and how it points to next data?

I don't understand how the data is printed using just prev in *kAltReverse function?

Help is very very highly appreciated!!!

Question Source: GeeksforGeeks

```<code>#include<stdio.h>
#include<stdlib.h>

struct node {
int data;
struct node* next; };

struct node *kAltReverse(struct node *head, int k) {
    struct node* current = head;
    struct node* next;
    struct node* prev = NULL;
    int count = 0;

    while (current != NULL && count < k)
    {
      next  = current->next;
      current->next = prev;
      prev = current;
      current = next;
      count++;
    }

   if(head != NULL)
      head->next = current;

   count = 0;
   while(count < k-1 && current != NULL )
   {
      current = current->next;
      count++;
   }

   if(current !=  NULL)
       current->next = kAltReverse(current->next, k);

   return prev;
}

void push(struct node** head_ref, int new_data) {
   struct node* new_node =
        (struct node*) malloc(sizeof(struct node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct node *node) {
int count = 0;
while(node != NULL)
{
    printf("%d  ", node->data);
    node = node->next;
    count++;
}
}

int main(void) {
struct node* head = NULL;

for(int i = 20; i > 0; i--)
  push(&head, i);

 printf("\n Given linked list \n");
 printList(head);
 head = kAltReverse(head, 3);

 printf("\n Modified Linked list \n");
 printList(head);

 getchar();
 return(0);
 }
</code>```

答:
Looks like there is a problem with int count = 0;.
It should be static int count = 0;, otherwise it would not behave as expected.

This reverses 1st 'k' elements of the linked list using recursion. Its like in 1st iteration of the loop, the 1st element will be placed at Kth position and 2nd element at 1st position, and in next iteration, with k reduced by 1, it will placed the 2nd value(the current 1st value after iteration) to the (k-1)th position (last position for current iteration). This goes on till count reaches to 'k'.

Title: Linked List K Alternate Reverse Program

Body:
Can Anyone Explain me why the function *kAltReverse return node type prev and how it will work when you call node->next in print function to get the next element from the struct node & print and how it points to next data?

I don't understand how the data is printed using just prev in *kAltReverse function?

Help is very very highly appreciated!!!

Question Source: GeeksforGeeks

#include<stdio.h>
#include<stdlib.h>

struct node {
int data;
struct node* next; };

struct node *kAltReverse(struct node *head, int k) {
    struct node* current = head;
    struct node* next;
    struct node* prev = NULL;
    int count = 0;

    while (current != NULL && count < k)
    {
      next  = current->next;
      current->next = prev;
      prev = current;
      current = next;
      count++;
    }

   if(head != NULL)
      head->next = current;

   count = 0;
   while(count < k-1 && current != NULL )
   {
      current = current->next;
      count++;
   }

   if(current !=  NULL)
       current->next = kAltReverse(current->next, k);

   return prev;
}

void push(struct node** head_ref, int new_data) {
   struct node* new_node =
        (struct node*) malloc(sizeof(struct node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct node *node) {
int count = 0;
while(node != NULL)
{
    printf("%d  ", node->data);
    node = node->next;
    count++;
}
}

int main(void) {
struct node* head = NULL;

for(int i = 20; i > 0; i--)
  push(&head, i);

 printf("\n Given linked list \n");
 printList(head);
 head = kAltReverse(head, 3);

 printf("\n Modified Linked list \n");
 printList(head);

 getchar();
 return(0);
 }


问:
how to use run time permissions for database in android
I have problem with runtime permission for database.I dont know how use and write permissions for my code. and I very search but at lost to understand.
the code is:

```<code>public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}
</code>```

}
please help me

答:
Here is a very good guide to request permissions at run time. Basically, the code for checking and asking for the permission is:

```<code>// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}
</code>```

Then, you get the results at:

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

Body:
I have problem with runtime permission for database.I dont know how use and write permissions for my code. and I very search but at lost to understand.
the code is:

public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}

}
please help me

Body:
Here is a very good guide to request permissions at run time. Basically, the code for checking and asking for the permission is:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

Then, you get the results at:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


问:
navigation menu top and bottom,no drop up at the bottom

<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

```

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

答:
Remove overflow hidden from ulf, add bottom: 46px to .dropup-content to get it above the bottom nav.

<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

```

Body:
<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

Body:
Remove overflow hidden from ulf, add bottom: 46px to .dropup-content to get it above the bottom nav.

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}
</style>
<style>
ulf {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: #333;
    position: fixed;
    bottom: 0%;
    width: 100%;

}

lif {
    float: left;
  border-right: 1px solid #bbb;

}

lif a, .dropbtn {

    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

lif a:hover, .dropup:hover .dropbtn {

   background-color: red;

}

lif.dropup {
    display: inline-block;
}

.dropup-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    bottom:46px;

}

.dropup-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;

}

.dropup-content a:hover {
background-color: #f1f1f1

}

.dropup:hover .dropup-content {
    display: block;

}
</style>
</head>
<body>

<ul>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Sales</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
<li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Search</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Transfers</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
   <li class="dropdown">
   <a href="javascript:void(0)" class="dropbtn">Returns</a>
     <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
 </li>

</ul>

<ulf>
<lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Order</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
<lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Reports</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
  <lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Exports/Imports</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
   <lif class="dropup">
   <a href="javascript:void(0)" class="dropbtn">Settings</a>
     <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
 </lif>

</ulf>

</body>
</html>


问:
jasmine throws "Cannot find module" when using require.main.require
I'm using require.main.require in a node module to require another module to avoid relative paths.

jasmine will throw a not found exception when I test that module.

Is there anyway to keep using require.main.require? Any best practice?

答:
in case someone is looking for the answer:

require.main.require points to the root file, in this case, to Jasmin (not your app.js, etc). You need to create a jasmine helper that overrides your require.main.require function like so:

```<code>const path = require('path');

require.main.require = function(pathName) {
  //path to root app:
  const newPath = path.join(__dirname, '../', pathName);

  return require(newPath);
}
</code>```

Body:
in case someone is looking for the answer:

require.main.require points to the root file, in this case, to Jasmin (not your app.js, etc). You need to create a jasmine helper that overrides your require.main.require function like so:

const path = require('path');

require.main.require = function(pathName) {
  //path to root app:
  const newPath = path.join(__dirname, '../', pathName);

  return require(newPath);
}


问:
Is it possible to work android 2.2 application on other android versions (1.5 to 2.1)?
I developed one application based on android 2.2 version.
Is it possible to work that application on other android versions (1.5 to 2.1)? </p>

答: It is possible unless you use specific things like programm installation on sd-card or a2dm features which are available only in FroYo.</p>


问:
how to use Font awesome icons in dynamically on android application?
this is my code,

```<code>String str = ""; // this my dynamic font code
</code>```

ref url is
How to use icons and symbols from "Font Awesome" on Native Android Application

答: You could try this library on GitHub that allows you to easily create a drawable from the FontAwesome icons.</p>

Body:
this is my code,

String str = ""; // this my dynamic font code

ref url is
How to use icons and symbols from "Font Awesome" on Native Android Application


问:
Filter cell by row in dataframe
I have a dataframe with project information including a column with staff and roles. I'm trying to filter the staff according to their role.

The data look like:

```<code>project, staff
project1, 'jane (role1), john (role2), bob (role3)'
project2, 'sue (role2), bob (role3)'
project3, 'mike (role1), claire (role3)'
</code>```

I'm trying to filter out names by role, but can't get it to work. So, for example, if I want only role 2, the output would be:

```<code>project, staff
project1, john
project2, sue
project3, NA
</code>```

I've tried variations on

```<code>str_subset(str_split(df$staff,","),"role2")
</code>```

and

```<code>grep('role2',str_split(df$staff`,","),value=TRUE)
</code>```

but it doesn't work.

If no one on the team is in role 2, I get an empty list (that's good). If someone on the team is in role 2, I get a list of all team members (not good). There appears to be an issue with the order of operations - it's checking the string for role2, then splitting. I don't understand why.

Any suggestions?

Thanks.

Brandon

答:
Try this (see comments in code for explanation):</p>

```<code>df <- data.frame(project = c("project1","project2","project3"),
                 staff = c('jane (role1), john (role2), bob (role3)','sue (role2), bob (role3)','mike (role1), claire (role3)'))

# 1st we split the concatenated field and cbind it to the project, then rbind it all
df2 <- setNames(as.data.frame(do.call(rbind,apply(df,1,function(row){cbind(row[1],strsplit(row[2],", ")[[1]])}))),c("project","staff"))
# then we separate name and role
df2$role <- gsub(".*\\((.*)\\)", "\\1", df2[,2])
df2$name <- gsub(" \\((.*)\\)", "", df2[,2])
# then we subset what we need
subset(df2,role=="role2")
# project        staff  role name
# 2 project1 john (role2) role2 john
# 4 project2  sue (role2) role2  sue
</code>```

Title: Filter cell by row in dataframe

Body:
I have a dataframe with project information including a column with staff and roles. I'm trying to filter the staff according to their role.

The data look like:

project, staff
project1, 'jane (role1), john (role2), bob (role3)'
project2, 'sue (role2), bob (role3)'
project3, 'mike (role1), claire (role3)'

I'm trying to filter out names by role, but can't get it to work. So, for example, if I want only role 2, the output would be:

project, staff
project1, john
project2, sue
project3, NA

I've tried variations on

str_subset(str_split(df$staff,","),"role2")

and

grep('role2',str_split(df$staff`,","),value=TRUE)

but it doesn't work.

If no one on the team is in role 2, I get an empty list (that's good). If someone on the team is in role 2, I get a list of all team members (not good). There appears to be an issue with the order of operations - it's checking the string for role2, then splitting. I don't understand why.

Any suggestions?

Thanks.

Brandon

Body:
Try this (see comments in code for explanation):

df <- data.frame(project = c("project1","project2","project3"),
                 staff = c('jane (role1), john (role2), bob (role3)','sue (role2), bob (role3)','mike (role1), claire (role3)'))

# 1st we split the concatenated field and cbind it to the project, then rbind it all
df2 <- setNames(as.data.frame(do.call(rbind,apply(df,1,function(row){cbind(row[1],strsplit(row[2],", ")[[1]])}))),c("project","staff"))
# then we separate name and role
df2$role <- gsub(".*\\((.*)\\)", "\\1", df2[,2])
df2$name <- gsub(" \\((.*)\\)", "", df2[,2])
# then we subset what we need
subset(df2,role=="role2")
# project        staff  role name
# 2 project1 john (role2) role2 john
# 4 project2  sue (role2) role2  sue


问:
akka sharding proxy cannot contact with coordinator
I'm building an app with two kind of nodes (front and back) on akka 2.5.1, I'm using akka sharding for load and data distribution across the back nodes. The front node uses a shard proxy to send messages to the back. Shards initialisation is as follow:

```<code>  val renditionManager: ActorRef =
if(nodeRole == "back")
  clusterSharding.start(
    typeName = "Rendition",
    entityProps = Manger.props,
    settings = ClusterShardingSettings(system),
    extractEntityId = Manager.idExtractor,
    extractShardId = Manager.shardResolver)
else
  clusterSharding.startProxy(
    typeName = "Rendition",
    role = None,
    extractEntityId = Manager.idExtractor,
    extractShardId = Manager.shardResolver)
</code>```

And i got some dead letters logs (omit most of the entries for brevity):

```<code>[info] [INFO] [06/02/2017 11:39:13.770] [wws-renditions-akka.actor.default-dispatcher-26] [akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] Message [akka.cluster.sharding.ShardCoordinator$Internal$Register] from Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/Rendition#1607279929] to Actor[akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] was not delivered. [8] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[info] [INFO] [06/02/2017 11:39:15.607] [wws-renditions-akka.actor.default-dispatcher-21] [akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] Message [akka.cluster.sharding.ShardCoordinator$Internal$RegisterProxy] from Actor[akka://wws-renditions/system/sharding/Rendition#-267271026] to Actor[akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] was not delivered. [9] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[info] [INFO] [06/02/2017 11:39:15.762] [wws-renditions-akka.actor.default-dispatcher-21] [akka://wws-renditions/system/sharding/replicator] Message [akka.cluster.ddata.Replicator$Internal$Status] from Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/replicator#-126233532] to Actor[akka://wws-renditions/system/sharding/replicator] was not delivered. [10] dead letters encountered, no more dead letters will be logged. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
</code>```

and if i tried to use the proxy it fails to deliver and shows:

```<code>[info] [WARN] [06/02/2017 12:12:28.047] [wws-renditions-akka.actor.default-dispatcher-15] [akka.tcp://wws-renditions@127.0.0.1:2551/system/sharding/Rendition] Retry request for shard [51] homes from coordinator at [Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/RenditionCoordinator/singleton/coordinator#-1550443839]]. [1] buffered messages.
</code>```

In the other hand, if I start a non-proxy shard in both nodes (front and back) it works properly.

Any advise? Thanks.

UPDATE

I finally figure it out why it was trying to connect to shards in wrong nodes. If it is only intended to start a shard in a single kind of node it is needed to add the following configuration

```<code>akka.cluster.sharding {
  role = "yourRole"
}
</code>```

This way, akka sharding only will lookup on nodes tagged with role "yourRole"

Proxy is still not able to connect with shard coordinator and deliver messages to shards and got the following log trace:

```<code>[WARN] [06/06/2017 12:09:25.754] [cluster-nodes-akka.actor.default-dispatcher-16] [akka.tcp://cluster-nodes@127.0.0.1:2551/system/sharding/Manager] Retry request for shard [52] homes from coordinator at [Actor[akka.tcp://cluster-nodes@127.0.0.1:2552/system/sharding/ManagerCoordinator/singleton/coordinator#-2111378619]]. [1] buffered messages.
</code>```

so help would be nice :)

答:
Got it!

I made 2 mistakes, for the first one check the UPDATE section in the main question.

The second is due to, for some reason, it is needed 2 shard regions up within the cluster (For testing purposes I was using only one), no clue if this is stated somewhere in the Akka docs.

Body:
I'm building an app with two kind of nodes (front and back) on akka 2.5.1, I'm using akka sharding for load and data distribution across the back nodes. The front node uses a shard proxy to send messages to the back. Shards initialisation is as follow:

  val renditionManager: ActorRef =
if(nodeRole == "back")
  clusterSharding.start(
    typeName = "Rendition",
    entityProps = Manger.props,
    settings = ClusterShardingSettings(system),
    extractEntityId = Manager.idExtractor,
    extractShardId = Manager.shardResolver)
else
  clusterSharding.startProxy(
    typeName = "Rendition",
    role = None,
    extractEntityId = Manager.idExtractor,
    extractShardId = Manager.shardResolver)

And i got some dead letters logs (omit most of the entries for brevity):

[info] [INFO] [06/02/2017 11:39:13.770] [wws-renditions-akka.actor.default-dispatcher-26] [akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] Message [akka.cluster.sharding.ShardCoordinator$Internal$Register] from Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/Rendition#1607279929] to Actor[akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] was not delivered. [8] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[info] [INFO] [06/02/2017 11:39:15.607] [wws-renditions-akka.actor.default-dispatcher-21] [akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] Message [akka.cluster.sharding.ShardCoordinator$Internal$RegisterProxy] from Actor[akka://wws-renditions/system/sharding/Rendition#-267271026] to Actor[akka://wws-renditions/system/sharding/RenditionCoordinator/singleton/coordinator] was not delivered. [9] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[info] [INFO] [06/02/2017 11:39:15.762] [wws-renditions-akka.actor.default-dispatcher-21] [akka://wws-renditions/system/sharding/replicator] Message [akka.cluster.ddata.Replicator$Internal$Status] from Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/replicator#-126233532] to Actor[akka://wws-renditions/system/sharding/replicator] was not delivered. [10] dead letters encountered, no more dead letters will be logged. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

and if i tried to use the proxy it fails to deliver and shows:

[info] [WARN] [06/02/2017 12:12:28.047] [wws-renditions-akka.actor.default-dispatcher-15] [akka.tcp://wws-renditions@127.0.0.1:2551/system/sharding/Rendition] Retry request for shard [51] homes from coordinator at [Actor[akka.tcp://wws-renditions@127.0.0.1:2552/system/sharding/RenditionCoordinator/singleton/coordinator#-1550443839]]. [1] buffered messages.

In the other hand, if I start a non-proxy shard in both nodes (front and back) it works properly.

Any advise? Thanks.

UPDATE

I finally figure it out why it was trying to connect to shards in wrong nodes. If it is only intended to start a shard in a single kind of node it is needed to add the following configuration

akka.cluster.sharding {
  role = "yourRole"
}

This way, akka sharding only will lookup on nodes tagged with role "yourRole"

Proxy is still not able to connect with shard coordinator and deliver messages to shards and got the following log trace:

[WARN] [06/06/2017 12:09:25.754] [cluster-nodes-akka.actor.default-dispatcher-16] [akka.tcp://cluster-nodes@127.0.0.1:2551/system/sharding/Manager] Retry request for shard [52] homes from coordinator at [Actor[akka.tcp://cluster-nodes@127.0.0.1:2552/system/sharding/ManagerCoordinator/singleton/coordinator#-2111378619]]. [1] buffered messages.

so help would be nice :)


问:
Shift columns but retain headers
Good afternoon,

I have a worksheet 'Example' with two blank columns that contain headers (B & C), and two data-containing columns that have no headers (E & F).

I want to be able to use VBA to shift columns to the left without affecting the headers (like using 'Range("B:B,C:C").Delete' but without getting rid of the 'Job' & 'City' headers). As below:

From this -

```<code> A        B        C         D              E               F
Name     Job     City     Country
----------------------------------------------------------------
Andrew                    Doctor        Manchester     England
George                    Lawyer        New York       America
Paul                      Engineer      Birmingham     England
Carl                      Technician    London         England
Joe                       Optician      Detroit        America
</code>```

To this -

```<code> A          B               C             D            E             F
Name       Job            City         Country
-----------------------------------------------------------------------
Andrew    Doctor        Manchester     England
George    Lawyer        New York       America
Paul      Engineer      Birmingham     England
Carl      Technician    London         England
Joe       Optician      Detroit        America
</code>```

I hope this makes sense. Let me know if you need further clarification.

Thank-you.

Title: Shift columns but retain headers

Body:
Good afternoon,

I have a worksheet 'Example' with two blank columns that contain headers (B & C), and two data-containing columns that have no headers (E & F).

I want to be able to use VBA to shift columns to the left without affecting the headers (like using 'Range("B:B,C:C").Delete' but without getting rid of the 'Job' & 'City' headers). As below:

From this -

 A        B        C         D              E               F
Name     Job     City     Country
----------------------------------------------------------------
Andrew                    Doctor        Manchester     England
George                    Lawyer        New York       America
Paul                      Engineer      Birmingham     England
Carl                      Technician    London         England
Joe                       Optician      Detroit        America

To this -

 A          B               C             D            E             F
Name       Job            City         Country
-----------------------------------------------------------------------
Andrew    Doctor        Manchester     England
George    Lawyer        New York       America
Paul      Engineer      Birmingham     England
Carl      Technician    London         England
Joe       Optician      Detroit        America

I hope this makes sense. Let me know if you need further clarification.

Thank-you.

Body: Worksheets("Example").Range("B2:C99999").Delete Shift:=xlToLeft