问:
How to use an index on a variable
I have a list which I currently add items to in the following way:

```<code>public GameObject object1 = new GameObject("Example Data");
public GameObject object2 = new GameObject("Example Data");
public GameObject object3 = new GameObject("Example Data");
public GameObject object4 = new GameObject("Example Data");
public GameObject object5 = new GameObject("Example Data");
public GameObject object6 = new GameObject("Example Data");
public GameObject object7 = new GameObject("Example Data");
public GameObject object8 = new GameObject("Example Data");
public GameObject object9 = new GameObject("Example Data");
public GameObject object10 = new GameObject("Example Data");
List<GameObject> Objects = new List<GameObject>();

Objects.Add(object1);
Objects.Add(object2);
Objects.Add(object3);
Objects.Add(object4);
Objects.Add(object5);
Objects.Add(object6);
Objects.Add(object7);
Objects.Add(object8);
Objects.Add(object9);
Objects.Add(object10);
</code>```

How would I do this in C# using a foreach? I tried something like the following example but I couldn't get it to work:

```<code>foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add("object" + [number]);
}
</code>```

答:
It is possible with reflection.</p>

```<code>public class MyClass
{
    public GameObject object1 = new GameObject("g1");
    public GameObject object2 = new GameObject("g2");
    public GameObject object3 = new GameObject("g3");

    public void AddObject()
    {
        List<GameObject> list = new List<GameObject>();

        for (int i = 1; i <= 3; i++)
        {
            var o = this.GetType().GetField($"object{i}").GetValue(this) as GameObject;
            list.Add(o);
        }
    }
}
</code>```

Title: How to use an index on a variable

Body:
I have a list which I currently add items to in the following way:

public GameObject object1 = new GameObject("Example Data");
public GameObject object2 = new GameObject("Example Data");
public GameObject object3 = new GameObject("Example Data");
public GameObject object4 = new GameObject("Example Data");
public GameObject object5 = new GameObject("Example Data");
public GameObject object6 = new GameObject("Example Data");
public GameObject object7 = new GameObject("Example Data");
public GameObject object8 = new GameObject("Example Data");
public GameObject object9 = new GameObject("Example Data");
public GameObject object10 = new GameObject("Example Data");
List<GameObject> Objects = new List<GameObject>();

Objects.Add(object1);
Objects.Add(object2);
Objects.Add(object3);
Objects.Add(object4);
Objects.Add(object5);
Objects.Add(object6);
Objects.Add(object7);
Objects.Add(object8);
Objects.Add(object9);
Objects.Add(object10);

How would I do this in C# using a foreach? I tried something like the following example but I couldn't get it to work:

foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add("object" + [number]);
}

Body:
It is possible with reflection.

public class MyClass
{
    public GameObject object1 = new GameObject("g1");
    public GameObject object2 = new GameObject("g2");
    public GameObject object3 = new GameObject("g3");

    public void AddObject()
    {
        List<GameObject> list = new List<GameObject>();

        for (int i = 1; i <= 3; i++)
        {
            var o = this.GetType().GetField($"object{i}").GetValue(this) as GameObject;
            list.Add(o);
        }
    }
}


来源: stackexchange

问:
Enyojs add a loader effect for ajax call until successful response
I m new in enyojs. I have succesfully made an ajax call for listing data. What i need now is loader effect until data is loaded from ajax call. Any help is appreciated. Thanks in advance. </p>

答:
You can easily do something like use a Popup with a Spinner in it.  You can set a flag on your app/view when you begin the fetch:

```<code>this.app.set('fetchingData', true);
</code>```

and set it to false in the callback.  Then have the Popup show while fetching.  you can set this up with a binding if you like:

```<code>bindings: [
    {from: 'app.fetchingData', to: '$.popup.showing'}
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can easily do something like use a Popup with a Spinner in it.  You can set a flag on your app/view when you begin the fetch:

this.app.set('fetchingData', true);

and set it to false in the callback.  Then have the Popup show while fetching.  you can set this up with a binding if you like:

bindings: [
    {from: 'app.fetchingData', to: '$.popup.showing'}
]


问:
Run a .sh file with Python 3 Idle
I am trying run a sh file with python 3. My .sh file will work on Terminal. My operating system is Raspbian. I try that code :

```<code>import time
import os
import subprocess

# STEP 1
text='sudo somecode'
savefile=open('step1.sh','w')
savefile.write(text)
savefile.close()
time.sleep(2)

shellscript=subprocess.Popen(['./step1.sh'], stdin=subprocess.PIPE)
</code>```

but it not works...

答:
The is undoubtedly a permissions issue.  In order to be able to "directly" execute a file (a la "dot slash" - ./yourfile), the file in question needs the "execute bit" set.  Try using ls -l to see the file you've just created with your script.  I'll bet the file does not have the execute bit:

```<code>$ ls -l ./step.sh
-rw-r--r-- 1 furkan furkan 0 Nov 13 20:51 step.sh
</code>```

Note the lack of x in that first column.  You might chmod to add the execute bit:

```<code>$ chmod +x ./step.sh
$ ls -l ./step.sh
-rwxr-xr-x 1 furkan furkan 0 Nov 13 20:51 step.sh
</code>```

With the execute bit set, you could then use a "dot slash" construct.

However, I doubt you want to execute chmod from within your script, so instead tell your script the actual program you want to run step.sh, namely, sh:

```<code>shellscript=subprocess.Popen(['sh', './step1.sh'], stdin=subprocess.PIPE)
</code>```

Or in the simple case of your example, simply go directly to sudo:

```<code>shellscript=subprocess.Popen(['sudo', 'yourexecutable'], stdin=subprocess.PIPE)
</code>```

Note that if you're being robust, I might consider adding some absolute paths, or ensuring your PATH variable is set.  However the key to your problem is the misunderstanding of what 'executable' means.

Title: Run a .sh file with Python 3 Idle

Body:
I am trying run a sh file with python 3. My .sh file will work on Terminal. My operating system is Raspbian. I try that code :

import time
import os
import subprocess

# STEP 1
text='sudo somecode'
savefile=open('step1.sh','w')
savefile.write(text)
savefile.close()
time.sleep(2)

shellscript=subprocess.Popen(['./step1.sh'], stdin=subprocess.PIPE)

but it not works...

Body:
The is undoubtedly a permissions issue.  In order to be able to "directly" execute a file (a la "dot slash" - ./yourfile), the file in question needs the "execute bit" set.  Try using ls -l to see the file you've just created with your script.  I'll bet the file does not have the execute bit:

$ ls -l ./step.sh
-rw-r--r-- 1 furkan furkan 0 Nov 13 20:51 step.sh

Note the lack of x in that first column.  You might chmod to add the execute bit:

$ chmod +x ./step.sh
$ ls -l ./step.sh
-rwxr-xr-x 1 furkan furkan 0 Nov 13 20:51 step.sh

With the execute bit set, you could then use a "dot slash" construct.

However, I doubt you want to execute chmod from within your script, so instead tell your script the actual program you want to run step.sh, namely, sh:

shellscript=subprocess.Popen(['sh', './step1.sh'], stdin=subprocess.PIPE)

Or in the simple case of your example, simply go directly to sudo:

shellscript=subprocess.Popen(['sudo', 'yourexecutable'], stdin=subprocess.PIPE)

Note that if you're being robust, I might consider adding some absolute paths, or ensuring your PATH variable is set.  However the key to your problem is the misunderstanding of what 'executable' means.


问:
Inconsistent assigning of values to Variables using tf.assign()
I'm learning Tensor flow and trying to capture each iteration duration into a summary variable. I've identified it to a peculiar issue which I summarise in following code

1) define a tensor (to capture start / end time)

```<code>t = tf.Variable(0.0, tf.float64)
</code>```

2) run iterations and output time at each iteration

```<code>with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(20):
        _ = time.time()
        sess.run(tf.assign(t,_)) #update 't' tensor value to start time
        print("time_1: {}, time_2_tensor: {} ".format(_,sess.run(t)))
</code>```

when I run the code, I wonder why large discrepancy (4-5 sec) between time_1 & time_2_tensor value. Here's Output (time_1 seems more correct, and wonder why time_2_tensor seems future time and all the same value!

time_1: 1510622147.797711, time_2_tensor: 1510622208.0

time_1: 1510622147.823721, time_2_tensor: 1510622208.0

time_1: 1510622147.846073, time_2_tensor: 1510622208.0

time_1: 1510622147.872359, time_2_tensor: 1510622208.0

time_1: 1510622147.893345, time_2_tensor: 1510622208.0

time_1: 1510622147.913889, time_2_tensor: 1510622208.0

time_1: 1510622147.94033, time_2_tensor: 1510622208.0

time_1: 1510622147.960254, time_2_tensor: 1510622208.0

time_1: 1510622147.98226, time_2_tensor: 1510622208.0

time_1: 1510622148.007267, time_2_tensor: 1510622208.0

time_1: 1510622148.045414, time_2_tensor: 1510622208.0

time_1: 1510622148.072437, time_2_tensor: 1510622208.0

time_1: 1510622148.104469, time_2_tensor: 1510622208.0

time_1: 1510622148.124364, time_2_tensor: 1510622208.0

time_1: 1510622148.143735, time_2_tensor: 1510622208.0

time_1: 1510622148.161832, time_2_tensor: 1510622208.0

time_1: 1510622148.179756, time_2_tensor: 1510622208.0

time_1: 1510622148.216838, time_2_tensor: 1510622208.0

time_1: 1510622148.235228, time_2_tensor: 1510622208.0

time_1: 1510622148.254686, time_2_tensor: 1510622208.0

Thanks a lot for any insight into it!

答:
Your data type is not being considered when declaring the variable (it's taking the place of argument trainable, at least in v1.4) and becomes then a float32, which leads to precision issues.

It works if you add the keyword dtype.

```<code>t = tf.Variable(0.0, dtype=tf.float64)
</code>```

The 'experiment':

```<code>t_bad = tf.Variable(0.0, tf.float64)
t = tf.Variable(0.0, dtype=tf.float64)

print(t_bad.dtype)  # <dtype: 'float32_ref'>
print(t.dtype)  # <dtype: 'float64_ref'>
</code>```

Body:
I'm learning Tensor flow and trying to capture each iteration duration into a summary variable. I've identified it to a peculiar issue which I summarise in following code

1) define a tensor (to capture start / end time)

t = tf.Variable(0.0, tf.float64)

2) run iterations and output time at each iteration

with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(20):
        _ = time.time()
        sess.run(tf.assign(t,_)) #update 't' tensor value to start time
        print("time_1: {}, time_2_tensor: {} ".format(_,sess.run(t)))

when I run the code, I wonder why large discrepancy (4-5 sec) between time_1 & time_2_tensor value. Here's Output (time_1 seems more correct, and wonder why time_2_tensor seems future time and all the same value!

time_1: 1510622147.797711, time_2_tensor: 1510622208.0

time_1: 1510622147.823721, time_2_tensor: 1510622208.0

time_1: 1510622147.846073, time_2_tensor: 1510622208.0

time_1: 1510622147.872359, time_2_tensor: 1510622208.0

time_1: 1510622147.893345, time_2_tensor: 1510622208.0

time_1: 1510622147.913889, time_2_tensor: 1510622208.0

time_1: 1510622147.94033, time_2_tensor: 1510622208.0

time_1: 1510622147.960254, time_2_tensor: 1510622208.0

time_1: 1510622147.98226, time_2_tensor: 1510622208.0

time_1: 1510622148.007267, time_2_tensor: 1510622208.0

time_1: 1510622148.045414, time_2_tensor: 1510622208.0

time_1: 1510622148.072437, time_2_tensor: 1510622208.0

time_1: 1510622148.104469, time_2_tensor: 1510622208.0

time_1: 1510622148.124364, time_2_tensor: 1510622208.0

time_1: 1510622148.143735, time_2_tensor: 1510622208.0

time_1: 1510622148.161832, time_2_tensor: 1510622208.0

time_1: 1510622148.179756, time_2_tensor: 1510622208.0

time_1: 1510622148.216838, time_2_tensor: 1510622208.0

time_1: 1510622148.235228, time_2_tensor: 1510622208.0

time_1: 1510622148.254686, time_2_tensor: 1510622208.0

Thanks a lot for any insight into it!

Body:
Your data type is not being considered when declaring the variable (it's taking the place of argument trainable, at least in v1.4) and becomes then a float32, which leads to precision issues.

It works if you add the keyword dtype.

t = tf.Variable(0.0, dtype=tf.float64)

The 'experiment':

t_bad = tf.Variable(0.0, tf.float64)
t = tf.Variable(0.0, dtype=tf.float64)

print(t_bad.dtype)  # <dtype: 'float32_ref'>
print(t.dtype)  # <dtype: 'float64_ref'>


问:
UIPageViewController with previous and next buttons
How to add previous and next buttons to UIPageViewController and only on button click the page should change with horizontal scroll effect. Can anyone suggest me any tutorial to refer?
As I am new to Swift, I don't know how to implement this. Please help..</p>

答:
Get next and previous UIViewController

You should know what the current page and the previous page / next page are.

example:

```<code>@IBAction func onNext(btn:UIButton) {
    let currentVC = self
    let nextVC = getNextVC(from: currentVC)//implement it!
    // do stuff... (turn page)
}
</code>```

Turn page

This is very simple, UIPageViewController provides such a function.

example:

```<code>pageViewController.setViewControllers([nextVC], direction: .forward, animated: true, completion: nil)
</code>```

Body:
Get next and previous UIViewController

You should know what the current page and the previous page / next page are.

example:

@IBAction func onNext(btn:UIButton) {
    let currentVC = self
    let nextVC = getNextVC(from: currentVC)//implement it!
    // do stuff... (turn page)
}

Turn page

This is very simple, UIPageViewController provides such a function.

example:

pageViewController.setViewControllers([nextVC], direction: .forward, animated: true, completion: nil)


问:
IE structural problems
I have just made a very simple static side via wordpress. However, I made the theme from scratch with html and css. It looks perfect and exactly how I want in FFox,Chrome,Safari etc...but upon inspection in IE 6,7,8 is is not right.

Click {here} to see the site and if you don't have IE... Here is a screen shot of how it is rendering in there.

Any idea on what this may be or an idea on how to fix it would be greatly appreciated. I can't find any syntax errors in my css and the html seems right

Thanks

答:
In your document you don't set a DOCTYPE, so ie is forced to show it in quirks mode. You have to add the DOCTYPE in the start of your html code. You can find more information about DOCTYPE at http://www.w3.org/QA/2002/04/valid-dtd-list.html

Also you can find more information about quirks mode at http://www.quirksmode.org/

As last note, it's always valuable to validate your webpages using 3w validator. Doing this with your website, you can see that you get :

93 Errors, 15 warning(s)

and the first of all in the list is the following:

No DOCTYPE found! Checking with
  default XHTML 1.0 Transitional
  Document Type.

No DOCTYPE Declaration could be found
  or recognized in this document. This
  generally means that the document is
  not declaring its Document Type at the
  top. It can also mean that the DOCTYPE
  declaration contains a spelling error,
  or that it is not using the correct
  syntax.

The document was checked using a
  default "fallback" Document Type
  Definition that closely resembles
  “XHTML 1.0 Transitional”.

Learn how to add a doctype to your
  document from our FAQ.

Hope all the above information you be helpful understanding what happens with ie.

ContentLicense: CC BY-SA 2.5

Title: IE structural problems


问:
Query the most recent record based on an ID
I have a table as below. The set of records in the image have the same "name" and "id". I want to retrieve the most recent record from this dataset using "ID" as a factor, so Max(ID). My goal is to report the most recent "size". How do I go about doing this? I don't want to use a where condition using "Workbook_id" because there are many other records in the dataset with duplicate names.

答:
This is a bit of a spitball, but I believe this is what you're seeking:

```<code>with workbookz as (
  select
    w.*,
    max (w.id) over (partition by w.workbook_id) as max_id
  from workbooks w
)
select
  id, workbook_id, name, repository_url, size, revision
from workbookz
where id = max_id
</code>```

Obviously, if your table isn't named workbooks change that to whatever is appropriate.

Body:
This is a bit of a spitball, but I believe this is what you're seeking:

with workbookz as (
  select
    w.*,
    max (w.id) over (partition by w.workbook_id) as max_id
  from workbooks w
)
select
  id, workbook_id, name, repository_url, size, revision
from workbookz
where id = max_id

Obviously, if your table isn't named workbooks change that to whatever is appropriate.


问:
gatsby failed due to missing regenerator-runtime/runtime module
I am trying out gatsby

Here is how I install gatsby-cli:

```<code>$ npm install --global gatsby-cli
/Users/antkong/.nvm/versions/node/v4.8.6/bin/gatsby -> /Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli/lib/index.js
gatsby-cli@1.1.20 /Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli
├── convert-hrtime@2.0.0
├── hosted-git-info@2.5.0
├── stack-trace@0.0.10
├── resolve-cwd@2.0.0 (resolve-from@3.0.0)
├── source-map@0.5.7
├── bluebird@3.5.1
├── babel-code-frame@6.26.0 (js-tokens@3.0.2, esutils@2.0.2, chalk@1.1.3)
├── execa@0.8.0 (p-finally@1.0.0, strip-eof@1.0.0, is-stream@1.1.0, get-stream@3.0.0, signal-exit@3.0.2, npm-run-path@2.0.2, cross-spawn@5.1.0)
├── fs-extra@4.0.2 (universalify@0.1.1, jsonfile@4.0.0, graceful-fs@4.1.11)
├── common-tags@1.4.0
├── yargs@8.0.2 (decamelize@1.2.0, get-caller-file@1.0.2, camelcase@4.1.0, y18n@3.2.1, which-module@2.0.0, set-blocking@2.0.0, yargs-parser@7.0.0, require-main-filename@1.0.1, require-directory@2.1.1, string-width@2.1.1, cliui@3.2.0, os-locale@2.1.0, read-pkg-up@2.0.0)
├── yurnalist@0.2.1 (strip-bom@3.0.0, detect-indent@5.0.0, leven@2.1.0, semver@5.4.1, object-path@0.11.4, death@1.1.0, is-builtin-module@1.0.0, is-ci@1.0.10, chalk@1.1.3, debug@2.6.9, node-emoji@1.8.1, read@1.0.7, loud-rejection@1.6.0, invariant@2.2.2, rimraf@2.6.2, inquirer@3.3.0)
├── pretty-error@2.1.1 (utila@0.4.0, renderkid@2.0.1)
├── babel-runtime@6.26.0 (regenerator-runtime@0.11.0)
├── lodash@4.17.4
└── core-js@2.5.1
</code>```

Then when I tried to print out the version to see if the installation is successful, I got this:

```<code>$ gatsby --version
module.js:327
    throw err;
    ^

Error: Cannot find module 'regenerator-runtime/runtime'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli/lib/index.js:88:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
</code>```

My version of npm and node

```<code>$ node --version
v4.8.6
$ npm --version
2.15.11
</code>```

OS platform is macOS High Sierra

What did I miss during the installation?

答: We're not supporting Node 4 anymore — try upgrading to Node 8 & NPM 5 and it should be smooth sailing!</p>

Body:
I am trying out gatsby

Here is how I install gatsby-cli:

$ npm install --global gatsby-cli
/Users/antkong/.nvm/versions/node/v4.8.6/bin/gatsby -> /Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli/lib/index.js
gatsby-cli@1.1.20 /Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli
├── convert-hrtime@2.0.0
├── hosted-git-info@2.5.0
├── stack-trace@0.0.10
├── resolve-cwd@2.0.0 (resolve-from@3.0.0)
├── source-map@0.5.7
├── bluebird@3.5.1
├── babel-code-frame@6.26.0 (js-tokens@3.0.2, esutils@2.0.2, chalk@1.1.3)
├── execa@0.8.0 (p-finally@1.0.0, strip-eof@1.0.0, is-stream@1.1.0, get-stream@3.0.0, signal-exit@3.0.2, npm-run-path@2.0.2, cross-spawn@5.1.0)
├── fs-extra@4.0.2 (universalify@0.1.1, jsonfile@4.0.0, graceful-fs@4.1.11)
├── common-tags@1.4.0
├── yargs@8.0.2 (decamelize@1.2.0, get-caller-file@1.0.2, camelcase@4.1.0, y18n@3.2.1, which-module@2.0.0, set-blocking@2.0.0, yargs-parser@7.0.0, require-main-filename@1.0.1, require-directory@2.1.1, string-width@2.1.1, cliui@3.2.0, os-locale@2.1.0, read-pkg-up@2.0.0)
├── yurnalist@0.2.1 (strip-bom@3.0.0, detect-indent@5.0.0, leven@2.1.0, semver@5.4.1, object-path@0.11.4, death@1.1.0, is-builtin-module@1.0.0, is-ci@1.0.10, chalk@1.1.3, debug@2.6.9, node-emoji@1.8.1, read@1.0.7, loud-rejection@1.6.0, invariant@2.2.2, rimraf@2.6.2, inquirer@3.3.0)
├── pretty-error@2.1.1 (utila@0.4.0, renderkid@2.0.1)
├── babel-runtime@6.26.0 (regenerator-runtime@0.11.0)
├── lodash@4.17.4
└── core-js@2.5.1

Then when I tried to print out the version to see if the installation is successful, I got this:

$ gatsby --version
module.js:327
    throw err;
    ^

Error: Cannot find module 'regenerator-runtime/runtime'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/antkong/.nvm/versions/node/v4.8.6/lib/node_modules/gatsby-cli/lib/index.js:88:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)

My version of npm and node

$ node --version
v4.8.6
$ npm --version
2.15.11

OS platform is macOS High Sierra

What did I miss during the installation?


问:
Converting some hexadecimal string to a decimal integer
I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b (something with a letter) I got an error like this:

java.lang.NumberFormatException: For input string: " 100a"     at
java.lang.NumberFormatException.forInputString(Unknown Source)     at
java.lang.Integer.parseInt(Unknown Source)

How can I convert my string with letters to a decimal integer?

```<code>if(display.getText() != null)
{
    if(display.getText().contains("a") || display.getText().contains("b") ||
       display.getText().contains("c") || display.getText().contains("d") ||
       display.getText().contains("e") || display.getText().contains("f"))
    {
        temp1 = Integer.parseInt(display.getText(), 16);
        temp1 = (double) temp1;
    }
    else
    {
        temp1 = Double.parseDouble(String.valueOf(display.getText()));
    }
}
</code>```

答:
Since there is no brute-force approach which (done with it manualy). To know what exactly happened.

Given a hexadecimal number

KₙKₙ₋₁Kₙ₋₂....K₂K₁K₀

The equivalent decimal value is:

Kₙ * 16ₙ + Kₙ₋₁ * 16ₙ₋₁ + Kₙ₋₂ * 16ₙ₋₂ + .... + K₂ * 16₂ + K₁ * 16₁ + K₀ * 16₀

For example, the hex number AB8C is:

10 * 16₃ + 11 * 16₂ + 8 * 16₁ + 12 * 16₀ = 43916

Implementation:

```<code> //convert hex to decimal number
private static int hexToDecimal(String hex) {
    int decimalValue = 0;
    for (int i = 0; i < hex.length(); i++) {
        char hexChar = hex.charAt(i);
        decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
    }
    return decimalValue;
}
private static int hexCharToDecimal(char character) {
    if (character >= 'A' && character <= 'F')
        return 10 + character - 'A';
    else //character is '0', '1',....,'9'
        return character - '0';
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b (something with a letter) I got an error like this:

java.lang.NumberFormatException: For input string: " 100a"     at
java.lang.NumberFormatException.forInputString(Unknown Source)     at
java.lang.Integer.parseInt(Unknown Source)

How can I convert my string with letters to a decimal integer?

if(display.getText() != null)
{
    if(display.getText().contains("a") || display.getText().contains("b") ||
       display.getText().contains("c") || display.getText().contains("d") ||
       display.getText().contains("e") || display.getText().contains("f"))
    {
        temp1 = Integer.parseInt(display.getText(), 16);
        temp1 = (double) temp1;
    }
    else
    {
        temp1 = Double.parseDouble(String.valueOf(display.getText()));
    }
}

Body:
Since there is no brute-force approach which (done with it manualy). To know what exactly happened.

Given a hexadecimal number

KₙKₙ₋₁Kₙ₋₂....K₂K₁K₀

The equivalent decimal value is:

Kₙ * 16ₙ + Kₙ₋₁ * 16ₙ₋₁ + Kₙ₋₂ * 16ₙ₋₂ + .... + K₂ * 16₂ + K₁ * 16₁ + K₀ * 16₀

For example, the hex number AB8C is:

10 * 16₃ + 11 * 16₂ + 8 * 16₁ + 12 * 16₀ = 43916

Implementation:

 //convert hex to decimal number
private static int hexToDecimal(String hex) {
    int decimalValue = 0;
    for (int i = 0; i < hex.length(); i++) {
        char hexChar = hex.charAt(i);
        decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
    }
    return decimalValue;
}
private static int hexCharToDecimal(char character) {
    if (character >= 'A' && character <= 'F')
        return 10 + character - 'A';
    else //character is '0', '1',....,'9'
        return character - '0';
}


问:
PHPexcel rangeArray() how to output as table
I am new with PHPexcel and learning the library as i go on, i am able to get the data on a specific sheet and a specific range. below is my code.

```<code>require_once 'PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = './data/MYexcelData.xls';
$sheetname = 'Sheet1';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

$myDataArray = $objPHPExcel->getActiveSheet()->rangeToArray('A2:J30', NULL, True, True);
</code>```

I am able to get the data when i use print_r

```<code>print_r($myDataArray);
</code>```

Now i am stuck on how to output the data properly, i want a table td for now to make it look like a cell.

```<code> $i = 0 ;

    foreach($myDataArray as $row){

         echo "<td>".$row[$i]."</td>";

         $i++;

    }
</code>```

But i get a error. any suggestion would be great! thanks.

Notice: Undefined offset: 10

答:
It looks like you’re retrieving a multi-dimensional array of data, as you have multiple columns and multiple cells in your excel cell reference. So you’ll need to use two foreach loops, one inside the other.

```<code>foreach ($myDataArray as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        // use cell data here
    }
    echo "</tr>";
}
</code>```

Body:
I am new with PHPexcel and learning the library as i go on, i am able to get the data on a specific sheet and a specific range. below is my code.

require_once 'PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = './data/MYexcelData.xls';
$sheetname = 'Sheet1';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

$myDataArray = $objPHPExcel->getActiveSheet()->rangeToArray('A2:J30', NULL, True, True);

I am able to get the data when i use print_r

print_r($myDataArray);

Now i am stuck on how to output the data properly, i want a table td for now to make it look like a cell.

 $i = 0 ;

    foreach($myDataArray as $row){

         echo "".$row[$i]."	";

         $i++;

    }

But i get a error. any suggestion would be great! thanks.

Notice: Undefined offset: 10

Body:
It looks like you’re retrieving a multi-dimensional array of data, as you have multiple columns and multiple cells in your excel cell reference. So you’ll need to use two foreach loops, one inside the other.

foreach ($myDataArray as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        // use cell data here
    }
    echo "</tr>";
}


问:
Kubernetes Statefulset: cannot join network of a non running container
I am trying to experiment with Statefulset template and the below spec (similar) works fine with hostNetwork: true and I am able to bring up two pods on each nodes, but when I remove it I get the error: rpc error: code = 2 desc = failed to start container "a9fe503a2fe76e1207ffe1a9267e324341383562927b800c93bde7443906c727": Error response from daemon: {"message":"cannot join network of a non running container: de6427d704d7fb7e48e344bc6ce31e218d9d30e2902
7c03f29674015fb3cc668"}

The yml spec:

```<code>apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: abc
spec:
  serviceName: abc
  replicas: 2
  template:
    metadata:
      labels:
        app: abc
    spec:
      #hostNetwork: true
      terminationGracePeriodSeconds: 10
      containers:
      - name: abc
        image: abc.xyz.com:9001/abc:01.00.00.00
        ports:
        - name: api-port
          containerPort: 9000
          hostPort: 9000
        readinessProbe:
          httpGet:
            path: /api
            port: api-port
            scheme: HTTPS
</code>```

What could be the reason for this issue? Other similar threads are suggesting to install a pod network but I am already using flannel, and as I mentioned with hostNetwork:true everything works fine. What more can I look into to understand the problem?

答: I don't know the exact reason why I was running into the problem, but changing the pod network from flannel to weave solved the issue.</p>

Body:
I am trying to experiment with Statefulset template and the below spec (similar) works fine with hostNetwork: true and I am able to bring up two pods on each nodes, but when I remove it I get the error: rpc error: code = 2 desc = failed to start container "a9fe503a2fe76e1207ffe1a9267e324341383562927b800c93bde7443906c727": Error response from daemon: {"message":"cannot join network of a non running container: de6427d704d7fb7e48e344bc6ce31e218d9d30e2902
7c03f29674015fb3cc668"}

The yml spec:

apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: abc
spec:
  serviceName: abc
  replicas: 2
  template:
    metadata:
      labels:
        app: abc
    spec:
      #hostNetwork: true
      terminationGracePeriodSeconds: 10
      containers:
      - name: abc
        image: abc.xyz.com:9001/abc:01.00.00.00
        ports:
        - name: api-port
          containerPort: 9000
          hostPort: 9000
        readinessProbe:
          httpGet:
            path: /api
            port: api-port
            scheme: HTTPS

What could be the reason for this issue? Other similar threads are suggesting to install a pod network but I am already using flannel, and as I mentioned with hostNetwork:true everything works fine. What more can I look into to understand the problem?


问:
Error when I try to install npm on Ubuntu 17.04
I'm trying to install npm on Ubuntu 17.04 but I'm not getting it. I've installed nodejs and nodejs-legacy and when I try to install npm, a message appears saying that npm depends on node-gyp (>= 0.10.9) and won't be installed. If a try to install node-gyp, another dependency appears and successively. Does anybody know how to fix it?</p>

答:
I suggest you don't use apt-install to install npm.You can download the bin file from official site.(https://nodejs.org/en/)

Just extract the tar file and setup the path to you system,you can get the latest version!


问:
While pipelining, can you consecutively write mov to the same register, or does it require 3 NOPs like add does?
This is the correct way to implement mov and add through x86 when incorporating pipelining and the necessary NOPs you need.

```<code> mov $10, eax
 NOP
 NOP
 NOP
 add $2, eax
</code>```

If I wanted to change eax with mov, could I immedietely overwrite it with another mov since you're just overwriting what is already there, or do I need to write 3 NOPs again so it can finish the WMEDF cycle?

```<code>mov $10, eax
mov $12, eax
</code>```

or

```<code>mov $10, eax
NOP
NOP
NOP
mov $12, eax
</code>```

答:
This is the correct way to implement mov and add through x86 when incorporating pipelining and the necessary NOPs you need.

Totally incorrect for x86.  NOP is never needed for correctness on x861.

If an input isn't ready for an instruction, it waits for it to be ready.  (Out-of-order execution can hide this waiting for multiple dependency chains in parallel...

I think I've read that some architectures has some instructions where you get unpredictable values if you read the results too soon.  That's only for a few instructions (like maybe multiply), and many architectures don't have any cases where NOPs (or useful work on other registers) are architecturally required.

Normal cases (like cache-miss loads) on simple in-order pipelines are handled with pipeline interlocks that effectively insert NOPs in hardware if required, without requiring software to contain useless instructions that will slow down high-performance (out-of-order) implementations of the same architecture running the same binaries.

or do I need to write 3 NOPs again so it can finish the WMEDF cycle?

The x86 ISA wasn't designed around the classic RISC pipeline (if that's what that abbreviation is supposed to indicate).  So even scalar in-order pipelined x86 implementations like i486 which are internally similar to what you're thinking of have to handle code that doesn't use NOPs to create delays.  i.e. they have to detect data dependencies themselves.

Of course, modern x86 implementations are all at least 2-wide superscalar (old Atom pre-Silvermont, or first-gen Xeon Phi, or P5 Pentium).  Those CPUs are in-order, but others are out-of-order with full register renaming (Tomasulo's algorithm), which avoids Write-After-Write hazards like the one you're talking about.  For example, Skylake can run

```<code>mov   $10, %eax
mov   $11, %eax
mov   $12, %eax
mov   $13, %eax
...
eventually jcc to make a loop
</code>```

at 4 mov instructions per cycle, even though they all write the same register.

But note that mov $1, %al merges into %rax on CPUs other than Intel P6-family (PPro/PII to Core2/Nehalem), and maybe Sandybridge (but not later CPUs like Haswell).  On those CPUs with partial-register renaming for the low 8, mov $1, %al can run a multiple instructions per cycle (limited by ALU ports).  But on others, it's like an add to %rax.  See How exactly do partial registers on Haswell/Skylake perform? Writing AL seems to have a false dependency on RAX, and AH is inconsistent.  (Fun fact, repeated mov %bl, %ah runs 4 per clock on Skylake, repeated mov $123, %ah runs 1 per clock.)

Further reading:

Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? Register renaming on x86 use Tomasulo's algorithm, and this is a case where the OP's code was slow because they were avoiding register reuse, not leaving enough registers for accumulators to hide the latency of FP add / FMA.

Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUs My answer says a bit more about the lack of WAW and WAR hazards on modern x86, including for memory.

Footnotes:

In an exploit where you don't know the exact jump target address, a NOP sled can be required for correctness so that a jump anywhere in the area will execute NOPs until it reaches your payload.

Body:
This is the correct way to implement mov and add through x86 when incorporating pipelining and the necessary NOPs you need.

 mov $10, eax
 NOP
 NOP
 NOP
 add $2, eax

If I wanted to change eax with mov, could I immedietely overwrite it with another mov since you're just overwriting what is already there, or do I need to write 3 NOPs again so it can finish the WMEDF cycle?

mov $10, eax
mov $12, eax

or

mov $10, eax
NOP
NOP
NOP
mov $12, eax

Body:
This is the correct way to implement mov and add through x86 when incorporating pipelining and the necessary NOPs you need.

Totally incorrect for x86.  NOP is never needed for correctness on x861.

If an input isn't ready for an instruction, it waits for it to be ready.  (Out-of-order execution can hide this waiting for multiple dependency chains in parallel...

I think I've read that some architectures has some instructions where you get unpredictable values if you read the results too soon.  That's only for a few instructions (like maybe multiply), and many architectures don't have any cases where NOPs (or useful work on other registers) are architecturally required.

Normal cases (like cache-miss loads) on simple in-order pipelines are handled with pipeline interlocks that effectively insert NOPs in hardware if required, without requiring software to contain useless instructions that will slow down high-performance (out-of-order) implementations of the same architecture running the same binaries.

or do I need to write 3 NOPs again so it can finish the WMEDF cycle?

The x86 ISA wasn't designed around the classic RISC pipeline (if that's what that abbreviation is supposed to indicate).  So even scalar in-order pipelined x86 implementations like i486 which are internally similar to what you're thinking of have to handle code that doesn't use NOPs to create delays.  i.e. they have to detect data dependencies themselves.

Of course, modern x86 implementations are all at least 2-wide superscalar (old Atom pre-Silvermont, or first-gen Xeon Phi, or P5 Pentium).  Those CPUs are in-order, but others are out-of-order with full register renaming (Tomasulo's algorithm), which avoids Write-After-Write hazards like the one you're talking about.  For example, Skylake can run

mov   $10, %eax
mov   $11, %eax
mov   $12, %eax
mov   $13, %eax
...
eventually jcc to make a loop

at 4 mov instructions per cycle, even though they all write the same register.

But note that mov $1, %al merges into %rax on CPUs other than Intel P6-family (PPro/PII to Core2/Nehalem), and maybe Sandybridge (but not later CPUs like Haswell).  On those CPUs with partial-register renaming for the low 8, mov $1, %al can run a multiple instructions per cycle (limited by ALU ports).  But on others, it's like an add to %rax.  See How exactly do partial registers on Haswell/Skylake perform? Writing AL seems to have a false dependency on RAX, and AH is inconsistent.  (Fun fact, repeated mov %bl, %ah runs 4 per clock on Skylake, repeated mov $123, %ah runs 1 per clock.)

Further reading:

Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? Register renaming on x86 use Tomasulo's algorithm, and this is a case where the OP's code was slow because they were avoiding register reuse, not leaving enough registers for accumulators to hide the latency of FP add / FMA.

Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUs My answer says a bit more about the lack of WAW and WAR hazards on modern x86, including for memory.

Footnotes:

In an exploit where you don't know the exact jump target address, a NOP sled can be required for correctness so that a jump anywhere in the area will execute NOPs until it reaches your payload.


问:
CSS: Change child on parent hover (only single child)
I can change child on parent hover like this:

.parent:hover .child{ ... }

Problem is, that this will change all childs in document.

(I'm using parent 10x on the page => it will change childs in all these parent)

Is there a CSS way, how to change only child of the parent, that I'm currently hovering over?

Example:

```<code><div class="parent">
   <p class="child"></p>
</div>

<div class="parent">
   <p class="child"></p>
</div>

<div class="parent">
   <p class="child"></p>
</div>
</code>```

If I hover over first .parent, I want change on its .child. But my mentioned solution will affect all childs.

答:
You'll want to directly select the child using the ">" or the "adjacent sibling combinator"

.parent:hover > .child{
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
   <p class="child">child one</p>
</div>

<div class="parent">
   <p class="child">child two</p>
</div>

<div class="parent">
   <p class="child">child three</p>
</div></code>```

Body:
I can change child on parent hover like this:

.parent:hover .child{ ... }

Problem is, that this will change all childs in document.

(I'm using parent 10x on the page => it will change childs in all these parent)

Is there a CSS way, how to change only child of the parent, that I'm currently hovering over?

Example:

If I hover over first .parent, I want change on its .child. But my mentioned solution will affect all childs.

Body:
You'll want to directly select the child using the ">" or the "adjacent sibling combinator"

.parent:hover > .child{
  background: red;
}

<div class="parent">
   <p class="child">child one</p>
</div>

<div class="parent">
   <p class="child">child two</p>
</div>

<div class="parent">
   <p class="child">child three</p>
</div>


问:
How to relocate the labels on a zoomable map?
I'm working on a map that is created by D3.js. I figured out how to zoom in the map and add labels by following Mike Bostock's tutorial. However, after I zoomed in the map, I don't know how to recalculate the coordinates of the labels.

I don't really understand how projection(data.geometry.coordinates) works. It seems projection() will recreate a pair of new coordinates based on the current svg, and somehow automatically place the labels for you. Thus, I tried to run projection() again in the clicked() function, but it doesn't work.

Here is the code that I'm working on, and I'm using d3 version 4, instead of 3.

答:
If you add your towns to the g selection (instead of the svg selection), then it should work fine, as the zoom applies to that selection.

```<code>var selection = g
        .selectAll("g.classTown")
        .data(towns);
</code>```

updated code: http://plnkr.co/edit/xJvh6LVweZqQUs7GFFH7?p=preview

Body:
If you add your towns to the g selection (instead of the svg selection), then it should work fine, as the zoom applies to that selection.

var selection = g
        .selectAll("g.classTown")
        .data(towns);

updated code: http://plnkr.co/edit/xJvh6LVweZqQUs7GFFH7?p=preview


问:
Regex: Disable Symbols
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

```<code>[a-zA-Z0-9]
</code>```

Because this ignores a lots of languages too not just the symbols.

答: JavaScript regular expressions do not have native Unicode support. An alternative to to validate (or sanitize) the string at server site, or to use a non-native regex library. While I've never used it, XRegExp is such a library, and it has a Unicode Plugin.</p>

Title: Regex: Disable Symbols

Body:
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

[a-zA-Z0-9]

Because this ignores a lots of languages too not just the symbols.


问:
reply to email in c#
How to reply back to an email message using gmail API in c# asp.net so that it make trails of all messages. Got solutions for python, php, javascript online but not for c#. I can get message details but don't know how to reply.

My code for getting message:

```<code>public void getmessage()
{
    UserCredential credential;
    using (var stream =
        new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);
        credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scope,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
    var re = service.Users.Messages.List("me");
    re.LabelIds = "INBOX";
    re.Q = "from:emailaddress AND subject:subject";

    var res = re.Execute();

    if (res != null && res.Messages != null)
    {
        DataTable dt = new DataTable("msgs");
        dt.Columns.Add("Date");
        dt.Columns.Add("From");
        dt.Columns.Add("Subject");
        dt.Columns.Add("Body");
        foreach (var email in res.Messages)
        {
            var emailInfoReq = service.Users.Messages.Get("me", email.Id);
            var emailInfoResponse = emailInfoReq.Execute();
            if (emailInfoResponse != null)
            {
                String from = "";
                String date = "";
                String subject = "";
                String body = "";
                //loop through the headers and get the fields we need...
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    if (mParts.Name == "Date")
                    {
                        date = mParts.Value;
                    }
                    else if (mParts.Name == "From")
                    {
                        from = mParts.Value;
                    }
                    else if (mParts.Name == "Subject")
                    {
                        subject = mParts.Value;
                    }
                    //else if (mParts.Name == "Message-ID")
                    //{
                    //    var abc = mParts.Value;
                    //}
                    if (date != "" && from != "")
                    {
                        if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
                            body = DecodeBase64String(emailInfoResponse.Payload.Body.Data);
                        else
                            body = GetNestedBodyParts(emailInfoResponse.Payload.Parts, "");

                    }
                }
                DataRow row = dt.NewRow();
                row[0] = date;
                row[1] = from;
                row[2] = subject;
                row[3] = body;
                dt.Rows.Add(row);
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
</code>```

Getting message-ID as well but no References and In-Rely-To for first email. Can send simple email message using MimeKit but have no idea about reply.

Any help would be appreciated. Thank you in advance!!

答:
Finally able to do it with the help of answer to this. Just posting answer if anybody wants.

First of all get specific message in RAW format using gmail API to which you wanna reply and convert it to MimeMessage to pass it to Reply method to create reply message and finally send it:

```<code>var emailInfoReq = service.Users.Messages.Get("me", email.Id);
emailInfoReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
var emailInfoResponse = emailInfoReq.Execute();
if (emailInfoResponse != null)
{
  var message = emailInfoResponse.Raw;
  byte[] Msg = Base64UrlDecode(message);
  MemoryStream mm = new MemoryStream(Msg);
  MimeKit.MimeMessage Message1  = MimeKit.MimeMessage.Load(mm);
  MimeKit.MimeMessage Message = Reply(Message1, false);
  Message message1 = new Message();
  message1.Raw = Base64UrlEncode(Message.ToString());
  var result = service.Users.Messages.Send(message1, "me").Execute();
}
</code>```

The Reply Method:

```<code>public static MimeKit.MimeMessage Reply(MimeKit.MimeMessage message, bool replyToAll)
{
 var reply = new MimeKit.MimeMessage();
 if (message.ReplyTo.Count > 0)
  {
   reply.To.AddRange(message.ReplyTo);
  }
 else if (message.From.Count > 0)
  {
  reply.To.AddRange(message.From);
  }
  else if (message.Sender != null)
  {
  reply.To.Add(message.Sender);
  }
  if (replyToAll)
  {
  reply.To.AddRange(message.To);
  reply.Cc.AddRange(message.Cc);
  }
  if (!message.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase))
    reply.Subject = "Re:" + message.Subject;
  else
    reply.Subject = message.Subject;
  if (!string.IsNullOrEmpty(message.MessageId))
  {
    reply.InReplyTo = message.MessageId;
    foreach (var id in message.References)
      reply.References.Add(id);
      reply.References.Add(message.MessageId);
  }
  using (var quoted = new StringWriter())
  {
    var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault();
    quoted.WriteLine("On {0}, {1} wrote:", message.Date.ToString("f"), !string.IsNullOrEmpty(sender.Name) ? sender.Name : sender.Address);
    using (var reader = new StringReader(message.TextBody))
    {
      string line;
      while ((line = reader.ReadLine()) != null)
      {
        quoted.Write("> ");
        quoted.WriteLine(line);
      }
    }
    reply.Body = new MimeKit.TextPart("plain")
    {
      Text = quoted.ToString()
    };
  }
  return reply;
}
</code>```

Title: reply to email in c#

Body:
How to reply back to an email message using gmail API in c# asp.net so that it make trails of all messages. Got solutions for python, php, javascript online but not for c#. I can get message details but don't know how to reply.

My code for getting message:

public void getmessage()
{
    UserCredential credential;
    using (var stream =
        new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);
        credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scope,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
    var re = service.Users.Messages.List("me");
    re.LabelIds = "INBOX";
    re.Q = "from:emailaddress AND subject:subject";

    var res = re.Execute();

    if (res != null && res.Messages != null)
    {
        DataTable dt = new DataTable("msgs");
        dt.Columns.Add("Date");
        dt.Columns.Add("From");
        dt.Columns.Add("Subject");
        dt.Columns.Add("Body");
        foreach (var email in res.Messages)
        {
            var emailInfoReq = service.Users.Messages.Get("me", email.Id);
            var emailInfoResponse = emailInfoReq.Execute();
            if (emailInfoResponse != null)
            {
                String from = "";
                String date = "";
                String subject = "";
                String body = "";
                //loop through the headers and get the fields we need...
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    if (mParts.Name == "Date")
                    {
                        date = mParts.Value;
                    }
                    else if (mParts.Name == "From")
                    {
                        from = mParts.Value;
                    }
                    else if (mParts.Name == "Subject")
                    {
                        subject = mParts.Value;
                    }
                    //else if (mParts.Name == "Message-ID")
                    //{
                    //    var abc = mParts.Value;
                    //}
                    if (date != "" && from != "")
                    {
                        if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
                            body = DecodeBase64String(emailInfoResponse.Payload.Body.Data);
                        else
                            body = GetNestedBodyParts(emailInfoResponse.Payload.Parts, "");

                    }
                }
                DataRow row = dt.NewRow();
                row[0] = date;
                row[1] = from;
                row[2] = subject;
                row[3] = body;
                dt.Rows.Add(row);
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

Getting message-ID as well but no References and In-Rely-To for first email. Can send simple email message using MimeKit but have no idea about reply.

Any help would be appreciated. Thank you in advance!!

Body:
Finally able to do it with the help of answer to this. Just posting answer if anybody wants.

First of all get specific message in RAW format using gmail API to which you wanna reply and convert it to MimeMessage to pass it to Reply method to create reply message and finally send it:

var emailInfoReq = service.Users.Messages.Get("me", email.Id);
emailInfoReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
var emailInfoResponse = emailInfoReq.Execute();
if (emailInfoResponse != null)
{
  var message = emailInfoResponse.Raw;
  byte[] Msg = Base64UrlDecode(message);
  MemoryStream mm = new MemoryStream(Msg);
  MimeKit.MimeMessage Message1  = MimeKit.MimeMessage.Load(mm);
  MimeKit.MimeMessage Message = Reply(Message1, false);
  Message message1 = new Message();
  message1.Raw = Base64UrlEncode(Message.ToString());
  var result = service.Users.Messages.Send(message1, "me").Execute();
}

The Reply Method:

public static MimeKit.MimeMessage Reply(MimeKit.MimeMessage message, bool replyToAll)
{
 var reply = new MimeKit.MimeMessage();
 if (message.ReplyTo.Count > 0)
  {
   reply.To.AddRange(message.ReplyTo);
  }
 else if (message.From.Count > 0)
  {
  reply.To.AddRange(message.From);
  }
  else if (message.Sender != null)
  {
  reply.To.Add(message.Sender);
  }
  if (replyToAll)
  {
  reply.To.AddRange(message.To);
  reply.Cc.AddRange(message.Cc);
  }
  if (!message.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase))
    reply.Subject = "Re:" + message.Subject;
  else
    reply.Subject = message.Subject;
  if (!string.IsNullOrEmpty(message.MessageId))
  {
    reply.InReplyTo = message.MessageId;
    foreach (var id in message.References)
      reply.References.Add(id);
      reply.References.Add(message.MessageId);
  }
  using (var quoted = new StringWriter())
  {
    var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault();
    quoted.WriteLine("On {0}, {1} wrote:", message.Date.ToString("f"), !string.IsNullOrEmpty(sender.Name) ? sender.Name : sender.Address);
    using (var reader = new StringReader(message.TextBody))
    {
      string line;
      while ((line = reader.ReadLine()) != null)
      {
        quoted.Write("> ");
        quoted.WriteLine(line);
      }
    }
    reply.Body = new MimeKit.TextPart("plain")
    {
      Text = quoted.ToString()
    };
  }
  return reply;
}


问:
Transferring an app with an attached database to another Heroku account
I made an application in Heroku with a PostgreSQL addon and I want to transfer them to another account.

I didn't find any "transfer to another account" option for the PostgreSQL addon. Does it move automatically with the app? Should I create another database in the destination account and link it to the app after transferring it?

Will the repository location be affected? Do the collaborators have to re-clone the repository?

How long will the transfer process take? While it is transferring, can we still view the app / push code to it?

答:
When you transfer a Heroku app its add-ons should come with it. Transfers take place very quickly once the receiver has accepted the transfer, and the transfer process shouldn't affect the running app.

The Heroku Git URL will change, but you shouldn't be using this as your main code repository:

Heroku provides the git service primarily for deployment, and the ability to clone from it is offered as a convenience. We strongly recommend you store your code in another git repository such as GitHub and treat that as canonical.

Nobody should be cloning from that URL. Either way, you'll have to update your Heroku remote's URL, e.g. using git remote --set-url.


问:
C++ how to pass unique_ptr to function and still benefit from polymorphism?
I have the following class definitions:

```<code>class A {...}
class B : public class A {...}
</code>```

and an owner class definition:

```<code>class C {
    A* a;
public:
    C (A* a) { this->a = a; }
}
</code>```

Then When I try to call the following, everything is fine:

```<code>B* b = new B();
C(b);
</code>```

But then I have the following owner class definition:

```<code>class C {
    std::unique_ptr<A> a;
public:
    C(std::unique_ptr<A>& a) { this->a = std::move(a); }
}
</code>```

And when I try to call the following, I get a compiler error saying cannot convert from unique_ptr of B to unique_ptr& of A:

```<code>std::unique_ptr<B> b(new B());
C(b);
</code>```

I do realize that std::unique_ptr& and std::unique_ptr is not the same. But I'm not sure what the standard protocol is for passing unique pointer to an owning class.

I tried the following:

```<code>class C {
    std::unique_ptr<A> a;
public:
    C(std::unique_ptr<A> a) { this->a = std::move(a); }
}
</code>```

and

```<code>std::unique_ptr<B> b = std::make_unique<B>();
C(std::move(b));
</code>```

This works but feels counter intuitive, because part of the purposes of using unique_ptr instead of shared_ptr is to get that performance increase from not having to copy memory address. But in this case, instead of copying memory address, it's creating a brand new unique_ptr to just pass it by value, only to toss it away after the function goes out of scope.

Note: I'm using VS C++11 compiler

答:
Don't pass unique pointers by mutable reference. You will have bugs such as this one.

Indeed the solution is to pass by value:

```<code>class C {
    std::unique_ptr<A> a;
public:
    C(std::unique_ptr<A> a) { this->a = std::move(a); }
}

// ...

auto b = std::make_unique<B>();
C(std::move(b));
</code>```

This works but feels counter intuitive, because part of the purposes of using unique_ptr instead of shared_ptr is to get that performance increase from not having to copy memory address.

No. The advantage of unique ptr is that they are a zero overhead abstraction over a pointer with a unique ownership.

Shared pointer have a cost. Each time they are copied, they are performing atomic ref-count. This hurts the cache and is not a negligible overhead. Also, shared pointer hide who owns who. The number of owners are determined at runtime, which makes the code harder to think about.

By the way, copying an address has negligible overhead. A reference is most of the time implemented in term of a pointer. Copying a raw pointer has the same cost as passing by reference. Since std::unique_ptr is a zero overhead abstraction, copying (or moving) a unique pointer has the same cost as copying a raw pointer, which in turn is about the same cost as passing by reference. You don't have to worry about the performance of copying pointers.

But in this case, instead of copying memory address, it's creating a brand new unique_ptr to just pass it by value, only to toss it away after the function goes out of scope.

Creating a brand new unique_ptr is the same cost as copying a memory address. Unlike other popular languages, C++ object are on the stack by default, offering the same performance as dealing with native types.

If you worry so much about performance, compile with optimization, profile your code and benchmark. Any statement about performance is meaningless unless you measure it. If you inspected the assembly output of the compiler, you'd notice that they are exactly the same.

Disclaimer: I did not compile using clang in the live example, because it elided the whole code away even on O2.

Body:
I have the following class definitions:

class A {...}
class B : public class A {...}

and an owner class definition:

class C {
    A* a;
public:
    C (A* a) { this->a = a; }
}

Then When I try to call the following, everything is fine:

B* b = new B();
C(b);

But then I have the following owner class definition:

class C {
    std::unique_ptr a;
public:
    C(std::unique_ptr& a) { this->a = std::move(a); }
}

And when I try to call the following, I get a compiler error saying cannot convert from unique_ptr of B to unique_ptr& of A:

std::unique_ptr b(new B());
C(b);

I do realize that std::unique_ptr& and std::unique_ptr is not the same. But I'm not sure what the standard protocol is for passing unique pointer to an owning class.

I tried the following:

class C {
    std::unique_ptr a;
public:
    C(std::unique_ptr a) { this->a = std::move(a); }
}

and

std::unique_ptr b = std::make_unique();
C(std::move(b));

This works but feels counter intuitive, because part of the purposes of using unique_ptr instead of shared_ptr is to get that performance increase from not having to copy memory address. But in this case, instead of copying memory address, it's creating a brand new unique_ptr to just pass it by value, only to toss it away after the function goes out of scope.

Note: I'm using VS C++11 compiler

Body:
Don't pass unique pointers by mutable reference. You will have bugs such as this one.

Indeed the solution is to pass by value:

class C {
    std::unique_ptr<A> a;
public:
    C(std::unique_ptr<A> a) { this->a = std::move(a); }
}

// ...

auto b = std::make_unique<B>();
C(std::move(b));

This works but feels counter intuitive, because part of the purposes of using unique_ptr instead of shared_ptr is to get that performance increase from not having to copy memory address.

No. The advantage of unique ptr is that they are a zero overhead abstraction over a pointer with a unique ownership.

Shared pointer have a cost. Each time they are copied, they are performing atomic ref-count. This hurts the cache and is not a negligible overhead. Also, shared pointer hide who owns who. The number of owners are determined at runtime, which makes the code harder to think about.

By the way, copying an address has negligible overhead. A reference is most of the time implemented in term of a pointer. Copying a raw pointer has the same cost as passing by reference. Since std::unique_ptr is a zero overhead abstraction, copying (or moving) a unique pointer has the same cost as copying a raw pointer, which in turn is about the same cost as passing by reference. You don't have to worry about the performance of copying pointers.

But in this case, instead of copying memory address, it's creating a brand new unique_ptr to just pass it by value, only to toss it away after the function goes out of scope.

Creating a brand new unique_ptr is the same cost as copying a memory address. Unlike other popular languages, C++ object are on the stack by default, offering the same performance as dealing with native types.

If you worry so much about performance, compile with optimization, profile your code and benchmark. Any statement about performance is meaningless unless you measure it. If you inspected the assembly output of the compiler, you'd notice that they are exactly the same.

Disclaimer: I did not compile using clang in the live example, because it elided the whole code away even on O2.


问:
IT Hit WebDAV with server side console application
Does anyone know the way to access IT Hit WebDAV Server's files from server side console application?

The DavContext generated inherits DavContextBaseAsync that depends on OwinContext or HttpContext.

答:
Yes, you can mount file system using 'net use' command:

```<code>net use https://server/path/
</code>```

Behind the scenes this command is using mini-redirector driver. After mounting you can use regular file system API and commands to manage the files on a WebDAV server.

Note that:

Your server must use Basic, Digest, NTLM, Kerberos authentication or
be anonymous. It does not support cookies/Forms authentication.

If you are using Basic authentication you need to use SSL/HTTPS or
enable insecure Basic authentication (for testing and dev purposes
only!)

If you are using 'net use' on the Windows Server you need to have
Desktop Experience Windows feature installed. By default this feature
is not installed on Windows Server.

Body:
Yes, you can mount file system using 'net use' command:

net use https://server/path/

Behind the scenes this command is using mini-redirector driver. After mounting you can use regular file system API and commands to manage the files on a WebDAV server.

Note that:

Your server must use Basic, Digest, NTLM, Kerberos authentication or
be anonymous. It does not support cookies/Forms authentication.

If you are using Basic authentication you need to use SSL/HTTPS or
enable insecure Basic authentication (for testing and dev purposes
only!)

If you are using 'net use' on the Windows Server you need to have
Desktop Experience Windows feature installed. By default this feature
is not installed on Windows Server.


问:
Why does creating a Path in hadoop cause a NullPointerException?
I'm new to hadoop and trying to create a file in HDFS from within the mapper of a map-reduce job.

The following code produces a NullPointerException in the last line:

```<code>DistributedFileSystem dfs = new DistributedFileSystem();
Path parent = dfs.getWorkingDirectory();
Path child = new Path("bar.txt");
Path path = new Path(parent, child);
</code>```

What am I doing wrong and why is this causing an Exception?

答: Most likely parent is null because getWorkingDirectory returned null.

Body:
I'm new to hadoop and trying to create a file in HDFS from within the mapper of a map-reduce job.

The following code produces a NullPointerException in the last line:

DistributedFileSystem dfs = new DistributedFileSystem();
Path parent = dfs.getWorkingDirectory();
Path child = new Path("bar.txt");
Path path = new Path(parent, child);

What am I doing wrong and why is this causing an Exception?


问:
parse a dot seperated string into dictionary variable
I have string values as,

```<code>"a"
"a.b"
"b.c.d"
</code>```

How to convert them into python dictionary variables as,

```<code>a
a["b"]
b["c"]["d"]
</code>```

The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys

答:
I ran into this same problem for parsing ini files with dot-delimited keys in different sections.  e.g.:

```<code>[app]
site1.ftp.host = hostname
site1.ftp.username = username
site1.database.hostname = db_host
; etc..
</code>```

So I wrote a little function to add "add_branch" to an existing dict tree:

```<code>def add_branch(tree, vector, value):
    """
    Given a dict, a vector, and a value, insert the value into the dict
    at the tree leaf specified by the vector.  Recursive!

    Params:
        data (dict): The data structure to insert the vector into.
        vector (list): A list of values representing the path to the leaf node.
        value (object): The object to be inserted at the leaf

    Example 1:
    tree = {'a': 'apple'}
    vector = ['b', 'c', 'd']
    value = 'dog'

    tree = add_branch(tree, vector, value)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog'}}}

    Example 2:
    vector2 = ['b', 'c', 'e']
    value2 = 'egg'

    tree = add_branch(tree, vector2, value2)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog', 'e': 'egg'}}}

    Returns:
        dict: The dict with the value placed at the path specified.

    Algorithm:
        If we're at the leaf, add it as key/value to the tree
        Else: If the subtree doesn't exist, create it.
              Recurse with the subtree and the left shifted vector.
        Return the tree.

    """
    key = vector[0]
    tree[key] = value \
        if len(vector) == 1 \
        else add_branch(tree[key] if key in tree else {},
                        vector[1:],
                        value)
    return tree
</code>```

Body:
I have string values as,

"a"
"a.b"
"b.c.d"

How to convert them into python dictionary variables as,

a
a["b"]
b["c"]["d"]

The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys

Body:
I ran into this same problem for parsing ini files with dot-delimited keys in different sections.  e.g.:

[app]
site1.ftp.host = hostname
site1.ftp.username = username
site1.database.hostname = db_host
; etc..

So I wrote a little function to add "add_branch" to an existing dict tree:

def add_branch(tree, vector, value):
    """
    Given a dict, a vector, and a value, insert the value into the dict
    at the tree leaf specified by the vector.  Recursive!

    Params:
        data (dict): The data structure to insert the vector into.
        vector (list): A list of values representing the path to the leaf node.
        value (object): The object to be inserted at the leaf

    Example 1:
    tree = {'a': 'apple'}
    vector = ['b', 'c', 'd']
    value = 'dog'

    tree = add_branch(tree, vector, value)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog'}}}

    Example 2:
    vector2 = ['b', 'c', 'e']
    value2 = 'egg'

    tree = add_branch(tree, vector2, value2)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog', 'e': 'egg'}}}

    Returns:
        dict: The dict with the value placed at the path specified.

    Algorithm:
        If we're at the leaf, add it as key/value to the tree
        Else: If the subtree doesn't exist, create it.
              Recurse with the subtree and the left shifted vector.
        Return the tree.

    """
    key = vector[0]
    tree[key] = value \
        if len(vector) == 1 \
        else add_branch(tree[key] if key in tree else {},
                        vector[1:],
                        value)
    return tree


问:
c# Regex pattern does not find any matches
I am using this code to find the state in a text file -

```<code>string pattern = @"Lender:\s(?'name'\w.*)\n\n(?'address'\w.*),\s(?'state'\w\w)";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = rgx.Matches(fileContents);
if (matches.Count > 0)
{
    return isStateAbbreviation(matches[0].Groups["state"].Value.Trim()) ? matches[0].Groups["state"].Value.Trim() : null;
}
</code>```

This is my sample string -

```<code>Lender: Monetary Management of California, Inc. d/b/a Money Mart

6311 DEBARR RD UNIT #U ANCHORAGE, AK 99504 907-644-0552
</code>```

The problem is that I count is always 0 but when I use an Online regex tester, it finds all the groups identified.  What is wrong with my Regex pattern?

答:
Following @NetMage's answer, it's better to have:</p>

```<code>string pattern = @"Lender:\s(?'name'\w.*)\r\n\r\n(?'address'\w.*),\s(?'state'\w\w)";
</code>```

Body:
I am using this code to find the state in a text file -

string pattern = @"Lender:\s(?'name'\w.*)\n\n(?'address'\w.*),\s(?'state'\w\w)";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = rgx.Matches(fileContents);
if (matches.Count > 0)
{
    return isStateAbbreviation(matches[0].Groups["state"].Value.Trim()) ? matches[0].Groups["state"].Value.Trim() : null;
}

This is my sample string -

Lender: Monetary Management of California, Inc. d/b/a Money Mart

6311 DEBARR RD UNIT #U ANCHORAGE, AK 99504 907-644-0552

The problem is that I count is always 0 but when I use an Online regex tester, it finds all the groups identified.  What is wrong with my Regex pattern?

Body:
Following @NetMage's answer, it's better to have:

string pattern = @"Lender:\s(?'name'\w.*)\r\n\r\n(?'address'\w.*),\s(?'state'\w\w)";


问:
Pass HashMap of fragments to bundle
I'm using HashMap of fragment's backstack. To save backstack and current fragment I use the code below:

```<code>public class MainActivity extends AppCompatActivity {

private HashMap<String, Stack<Fragment>> mStacks;
public static final String TAB_PROFILE  = "tab_profile";
public static final String TAB_DASHBOARD  = "tab_dashboard";
public static final String TAB_CHATS  = "tab_chats";
public static final String TAB_SETTINGS  = "tab_settings";

private String mCurrentTab;

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

    setupViews();
    if (savedInstanceState != null) {
        mCurrentTab = savedInstanceState.getString("currentTab");
        mStacks = (HashMap<String, Stack<Fragment>>) savedInstanceState.getSerializable("stacks");
    } else
        selectedTab(TAB_DASHBOARD);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("stacks", mStacks);
    outState.putString("currentTab", mCurrentTab);
}

private void setupViews() {
    mStacks = new HashMap<>();
    mStacks.put(TAB_PROFILE, new Stack<>());
    mStacks.put(TAB_DASHBOARD, new Stack<>());
    mStacks.put(TAB_CHATS, new Stack<>());
    mStacks.put(TAB_SETTINGS, new Stack<>());

    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);

    bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
    BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);

    bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
        switch (item.getItemId()) {
            case R.id.action_profile:
                selectedTab(TAB_PROFILE);
                return true;
            case R.id.action_dashboard:
                selectedTab(TAB_DASHBOARD);
                return true;
            case R.id.action_chats:
                selectedTab(TAB_CHATS);
                return true;
            case R.id.action_settings:
                selectedTab(TAB_SETTINGS);
                return true;
        }
        return true;
    });

    bottomNavigationView.setOnNavigationItemReselectedListener(item -> {
        if (mStacks.get(mCurrentTab).size() != 1) {
            mStacks.get(mCurrentTab).clear();
            switch (item.getItemId()) {
                case R.id.action_profile:
                    selectedTab(TAB_PROFILE);
                    break;
                case R.id.action_dashboard:
                    selectedTab(TAB_DASHBOARD);
                    break;
                case R.id.action_chats:
                    selectedTab(TAB_CHATS);
                    break;
                case R.id.action_settings:
                    selectedTab(TAB_SETTINGS);
                    break;
            }
        }
    });
}

private void selectedTab(String tabId) {
    mCurrentTab = tabId;

    if(mStacks.get(tabId).size() == 0){
        if(tabId.equals(TAB_PROFILE)){
            Fragment fragment = new ProfileFragment();
            Bundle args = new Bundle();
            args.putSerializable("user", Globals.getCurrentUser());
            fragment.setArguments(args);
            pushFragments(tabId, fragment,true);
        } else if(tabId.equals(TAB_DASHBOARD)){
            pushFragments(tabId, new DashboardFragment(),true);
        }else if(tabId.equals(TAB_CHATS)){
            pushFragments(tabId, new GroupsFragment(),true);
        }else if(tabId.equals(TAB_SETTINGS)){
            pushFragments(tabId, new SettingsFragment(),true);
        }
    }else {
        pushFragments(tabId, mStacks.get(tabId).lastElement(),false);
    }
}

public void pushFragments(String tag, Fragment fragment, boolean shouldAdd){
    if(shouldAdd)
        mStacks.get(tag).push(fragment);
    FragmentManager manager = getFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

public void popFragments(){
    Fragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2);

    mStacks.get(mCurrentTab).pop();

    FragmentManager manager = getFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

@Override
public void onBackPressed() {
    if(mStacks.get(mCurrentTab).size() == 1){
        finish();
        return;
    }

    popFragments();
}
}
</code>```

Set new fragments using

```<code>((MainActivity)context).pushFragments(MainActivity.TAB_CHATS, fragment,true);
</code>```

Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@color/background_material_light"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"/>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/waPrimary"
    app:itemIconTint="@color/white"
    app:itemTextColor="@color/white"
    app:menu="@menu/menu_bottom_navigation" />
</code>```

Everything works fine on screen rotation, but application crashes with exception on application hide.

java.lang.RuntimeException: Parcel: unable to marshal value %FragmentName%{c985244 #2 id=0x7f090051}

As I read, it happens when one of the objects I'm trying to pass is not Parceable, but have no idea how to fix this. Any thoughts?

UPD

After I made all of my fragments Serializable, new exception throws

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = %FragmentName%)

...

Caused by: java.io.NotSerializableException: android.support.v7.widget.RecyclerView

UPD2

Seems like a found a solution - transient property. Now I'm trying to make all non-serializeable objects transient.

UPD3

It helped, but I don't know is it efficient enough.

答:
Here's my suggestion:

Your activity maintains a reference to the four fragments it wants for the bottom navigation toggling.

On toggling bottom navigation, you replace the current fragment in the activity fragment manager.

While on a given fragment, as you interact with the UI, you push things on to the fragment child fragment manager.

This way, each fragment maintains its own backstack automatically, you don't have to save any state, and it all Just Works™.

Some sample code that might help.

```<code>public class MainActivity extends AppCompatActivity {

    private Fragment mProfileFragment;
    private Fragment mDashboardFragment;
    private Fragment mChatsFragment;
    private Fragment mSettingsFragment;

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

        if (savedInstanceState == null) {
            // Init fragments
        }
        else {
            // Find last active fragments in fragment manager
        }

        setupViews();
    }

    private void setupViews() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
        BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Fragment fragment;
            switch (item.getItemId()) {
                case R.id.action_profile:
                    fragment = mProfileFragment;
                    break;
                case R.id.action_dashboard:
                    fragment = mDashboardFragment;
                    break;
                case R.id.action_chats:
                    fragment = mChatsFragment;
                    break;
                case R.id.action_settings:
                    fragment = mSettingsFragment;
                    break;
            }

            // Replace the currently active fragment which will be
            // managing its own backstack
            getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frament_container, fragment)
                .commit();
        });
    }
}
</code>```

And one of your fragments would push stuff on its own stack like this:

```<code>public class ProfileFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.id.fragment_layout, container, false);
        Button button = view.findViewById(R.id.some_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment someFragmentToPush = new SomeFragmentToPush();
                // Use the child fragment manager to keep UI
                // local to this fragment instance, adding to backstack
                // for automatic popping on pressing back
                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_layout, someFragmentToPush)
                        .addToBackStack(null)
                        .commit();
            }
        });

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

Hope that helps!

Title: Pass HashMap of fragments to bundle

Body:
I'm using HashMap of fragment's backstack. To save backstack and current fragment I use the code below:

public class MainActivity extends AppCompatActivity {

private HashMap<String, Stack<Fragment>> mStacks;
public static final String TAB_PROFILE  = "tab_profile";
public static final String TAB_DASHBOARD  = "tab_dashboard";
public static final String TAB_CHATS  = "tab_chats";
public static final String TAB_SETTINGS  = "tab_settings";

private String mCurrentTab;

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

    setupViews();
    if (savedInstanceState != null) {
        mCurrentTab = savedInstanceState.getString("currentTab");
        mStacks = (HashMap<String, Stack<Fragment>>) savedInstanceState.getSerializable("stacks");
    } else
        selectedTab(TAB_DASHBOARD);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("stacks", mStacks);
    outState.putString("currentTab", mCurrentTab);
}

private void setupViews() {
    mStacks = new HashMap<>();
    mStacks.put(TAB_PROFILE, new Stack<>());
    mStacks.put(TAB_DASHBOARD, new Stack<>());
    mStacks.put(TAB_CHATS, new Stack<>());
    mStacks.put(TAB_SETTINGS, new Stack<>());

    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);

    bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
    BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);

    bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
        switch (item.getItemId()) {
            case R.id.action_profile:
                selectedTab(TAB_PROFILE);
                return true;
            case R.id.action_dashboard:
                selectedTab(TAB_DASHBOARD);
                return true;
            case R.id.action_chats:
                selectedTab(TAB_CHATS);
                return true;
            case R.id.action_settings:
                selectedTab(TAB_SETTINGS);
                return true;
        }
        return true;
    });

    bottomNavigationView.setOnNavigationItemReselectedListener(item -> {
        if (mStacks.get(mCurrentTab).size() != 1) {
            mStacks.get(mCurrentTab).clear();
            switch (item.getItemId()) {
                case R.id.action_profile:
                    selectedTab(TAB_PROFILE);
                    break;
                case R.id.action_dashboard:
                    selectedTab(TAB_DASHBOARD);
                    break;
                case R.id.action_chats:
                    selectedTab(TAB_CHATS);
                    break;
                case R.id.action_settings:
                    selectedTab(TAB_SETTINGS);
                    break;
            }
        }
    });
}

private void selectedTab(String tabId) {
    mCurrentTab = tabId;

    if(mStacks.get(tabId).size() == 0){
        if(tabId.equals(TAB_PROFILE)){
            Fragment fragment = new ProfileFragment();
            Bundle args = new Bundle();
            args.putSerializable("user", Globals.getCurrentUser());
            fragment.setArguments(args);
            pushFragments(tabId, fragment,true);
        } else if(tabId.equals(TAB_DASHBOARD)){
            pushFragments(tabId, new DashboardFragment(),true);
        }else if(tabId.equals(TAB_CHATS)){
            pushFragments(tabId, new GroupsFragment(),true);
        }else if(tabId.equals(TAB_SETTINGS)){
            pushFragments(tabId, new SettingsFragment(),true);
        }
    }else {
        pushFragments(tabId, mStacks.get(tabId).lastElement(),false);
    }
}

public void pushFragments(String tag, Fragment fragment, boolean shouldAdd){
    if(shouldAdd)
        mStacks.get(tag).push(fragment);
    FragmentManager manager = getFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

public void popFragments(){
    Fragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2);

    mStacks.get(mCurrentTab).pop();

    FragmentManager manager = getFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

@Override
public void onBackPressed() {
    if(mStacks.get(mCurrentTab).size() == 1){
        finish();
        return;
    }

    popFragments();
}
}

Set new fragments using

((MainActivity)context).pushFragments(MainActivity.TAB_CHATS, fragment,true);

Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@color/background_material_light"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"/>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/waPrimary"
    app:itemIconTint="@color/white"
    app:itemTextColor="@color/white"
    app:menu="@menu/menu_bottom_navigation" />

Everything works fine on screen rotation, but application crashes with exception on application hide.

java.lang.RuntimeException: Parcel: unable to marshal value %FragmentName%{c985244 #2 id=0x7f090051}

As I read, it happens when one of the objects I'm trying to pass is not Parceable, but have no idea how to fix this. Any thoughts?

UPD

After I made all of my fragments Serializable, new exception throws

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = %FragmentName%)

...

Caused by: java.io.NotSerializableException: android.support.v7.widget.RecyclerView

UPD2

Seems like a found a solution - transient property. Now I'm trying to make all non-serializeable objects transient.

UPD3

It helped, but I don't know is it efficient enough.

Body:
Here's my suggestion:

Your activity maintains a reference to the four fragments it wants for the bottom navigation toggling.

On toggling bottom navigation, you replace the current fragment in the activity fragment manager.

While on a given fragment, as you interact with the UI, you push things on to the fragment child fragment manager.

This way, each fragment maintains its own backstack automatically, you don't have to save any state, and it all Just Works™.

Some sample code that might help.

public class MainActivity extends AppCompatActivity {

    private Fragment mProfileFragment;
    private Fragment mDashboardFragment;
    private Fragment mChatsFragment;
    private Fragment mSettingsFragment;

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

        if (savedInstanceState == null) {
            // Init fragments
        }
        else {
            // Find last active fragments in fragment manager
        }

        setupViews();
    }

    private void setupViews() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
        BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Fragment fragment;
            switch (item.getItemId()) {
                case R.id.action_profile:
                    fragment = mProfileFragment;
                    break;
                case R.id.action_dashboard:
                    fragment = mDashboardFragment;
                    break;
                case R.id.action_chats:
                    fragment = mChatsFragment;
                    break;
                case R.id.action_settings:
                    fragment = mSettingsFragment;
                    break;
            }

            // Replace the currently active fragment which will be
            // managing its own backstack
            getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frament_container, fragment)
                .commit();
        });
    }
}

And one of your fragments would push stuff on its own stack like this:

public class ProfileFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.id.fragment_layout, container, false);
        Button button = view.findViewById(R.id.some_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment someFragmentToPush = new SomeFragmentToPush();
                // Use the child fragment manager to keep UI
                // local to this fragment instance, adding to backstack
                // for automatic popping on pressing back
                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_layout, someFragmentToPush)
                        .addToBackStack(null)
                        .commit();
            }
        });

        return view;
    }
}

Hope that helps!


问:
Can Idris infer indices in types of top-level constants?
For example, Agda allows me to write this:

```<code>open import Data.Vec
open import Data.Nat

myVec : Vec ℕ _
myVec = 0 ∷ 1 ∷ 2 ∷ 3 ∷ []
</code>```

and myVec will have type Vec ℕ 4 as expected.

But if I try the same in Idris:

```<code>import Data.Vect

myVec : Vect _ Nat
myVec = [0, 1, 2, 3]
</code>```

I get an error message from the typechecker:

```<code> When checking right hand side of myVec with expected type
         Vect len Nat

 Type mismatch between
         Vect 4 Nat (Type of [0, 1, 2, 3])
 and
         Vect len Nat (Expected type)

 Specifically:
         Type mismatch between
                 4
         and
                 len
</code>```

Is there a way to define myVec in Idris without manually specifying the index of the Vect?

答:
Per the comments, top-level holes in Idris was universally quantified, instead of being filled via term inference.

I believe (but, ultimately someone from the development team would have to confirm / deny) that this was done partially to encourage explicit types, and thus type-directed development, and partially to have a nice syntax for don't-care values in interface implementations like:

```<code>Uninhabited v => Uninhabited (_, v) where
    uninhabited (_, void) = uninhabited void
</code>```

This don't-care use of the underscore is adopted from it's use in patterns, rather than it's use in expressions.

For something like this (it's not exactly what you want, but it is robust against changes to the constant), you can use an explicit existential:

```<code>fst : DPair t _ -> t
fst (x ** _) = x

snd : (s : DPair _ p) -> p (fst s)
snd (_ ** prf) = prf

myVecEx : (n ** Vect n Nat)
myVecEx = (_ ** [0, 1, 2, 3])

myVec : Vect (fst myVecEx) Nat
myVec = snd myVecEx
</code>```

fst and snd might be in the standard library under different names, but I didn't find then in a quick search.

EDIT: An upvote recently drew this answer to my attention again.  If you are using Idris 2, I believe you can use a ? instead of a _ at the top level to have it filled in my idris.  _ at the top level, is an erased, implicit, unnamed parameter, still.  https://idris2.readthedocs.io/en/latest/implementation/overview.html#additional-type-inference

Body:
For example, Agda allows me to write this:

open import Data.Vec
open import Data.Nat

myVec : Vec ℕ _
myVec = 0 ∷ 1 ∷ 2 ∷ 3 ∷ []

and myVec will have type Vec ℕ 4 as expected.

But if I try the same in Idris:

import Data.Vect

myVec : Vect _ Nat
myVec = [0, 1, 2, 3]

I get an error message from the typechecker:

 When checking right hand side of myVec with expected type
         Vect len Nat

 Type mismatch between
         Vect 4 Nat (Type of [0, 1, 2, 3])
 and
         Vect len Nat (Expected type)

 Specifically:
         Type mismatch between
                 4
         and
                 len

Is there a way to define myVec in Idris without manually specifying the index of the Vect?

Body:
Per the comments, top-level holes in Idris was universally quantified, instead of being filled via term inference.

I believe (but, ultimately someone from the development team would have to confirm / deny) that this was done partially to encourage explicit types, and thus type-directed development, and partially to have a nice syntax for don't-care values in interface implementations like:

Uninhabited v => Uninhabited (_, v) where
    uninhabited (_, void) = uninhabited void

This don't-care use of the underscore is adopted from it's use in patterns, rather than it's use in expressions.

For something like this (it's not exactly what you want, but it is robust against changes to the constant), you can use an explicit existential:

fst : DPair t _ -> t
fst (x ** _) = x

snd : (s : DPair _ p) -> p (fst s)
snd (_ ** prf) = prf

myVecEx : (n ** Vect n Nat)
myVecEx = (_ ** [0, 1, 2, 3])

myVec : Vect (fst myVecEx) Nat
myVec = snd myVecEx

fst and snd might be in the standard library under different names, but I didn't find then in a quick search.

EDIT: An upvote recently drew this answer to my attention again.  If you are using Idris 2, I believe you can use a ? instead of a _ at the top level to have it filled in my idris.  _ at the top level, is an erased, implicit, unnamed parameter, still.  https://idris2.readthedocs.io/en/latest/implementation/overview.html#additional-type-inference