问:
How to copy Gulden blockchain data from one wallet to another
Which files should I copy from the blocks directory to copy all available blockchain data to another wallet.

Should I include:

The blk*.dat files?

The rev*.dat files?

The index directory and its contents?

Furthermore would it be safe to symlink all but the latest .dat files instead of copying to save storage (assuming that the earlier .dat files never change).

After copying/linking, should I run the GuldenD with additional command line arguments like -rescan?

答:
I'm working off https://github.com/Gulden/gulden-official/blob/master/doc/files.md as a reference of the data directory structure for Gulden.
Relevant parts below:

blocks/blk000??.dat: block data (custom, 128 MiB per file);

blocks/rev000??.dat; block undo data (custom);

blocks/index/*; block index (LevelDB);

chainstate/*; block chain state database (LevelDB);

The above four essentially contain the blockchain, so would be required:

blocks/blk*.dat - The actual blocks are written here

blocks/index/* - A fast index into the above files is stored here, technically it is possible to find the blocks without this but it becomes a slow process

chainstate/* - The UTXO (list of all unspent transactions) is stored here this is needed for verifying blocks - this can be regenerated if lost but is an expensive process.

blocks/rev*.dat - This contains chainstate 'undo' information for the most recent blocks so that if the chain is reorganised the changes to the chainstate can be rolled back easily.

Under usual circumstances the older blocks/*.dat files would not be touched but there are possibly edge cases (pruning) where they might be, and future developments may want to touch them in order to free up space etc. - so I don't know if this is a safe assumption to rely on.

If the aim is to save space while hosting multiple wallets on one server a dedup filesystem is perhaps a safer way to do this without relying on a symlink.

If you are setting up a new GuldenD then no rescan or additional options are necessary after copying into place, if it is a GuldenD with existing addresses which may have received funds in the past then you would want to run a rescan.


来源: stackexchange

问:
How do I save/load a tensorflow contrib.learn regressor?
I have a tensorflow contrib.learn.DNNRegressor that I have trained as part of the following code snippet:

```<code>regressor = tf.contrib.learn.DNNRegressor(feature_columns=fc,
                                          hidden_units=hu_array,
                                          optimizer=tf.train.AdamOptimizer(
                                                       learning_rate=0.001,
                                                    ),
                                          enable_centered_bias=False,
                                          activation_fn=tf.tanh,
                                          model_dir="./models/my_model/",
                                          )

regressor.fit(x=training_features, y=training_labels, steps=10000)
</code>```

The trained network performs quite well, and I'd like to use it as a part of some other code, on another machine.  I have tried copying over the models/my_model directory, and constructing a new DNNRegressor pointing just at the model_dir, but it requires that I supply feature_columns and hidden_units definitions.   Shouldn't that information be available via the snapshots stored in model_dir?  Is there a better way to save/recover a trained model which is performing well, to be used as a predictor, without having to separately save the feature_columns and hidden_units?

答:
When training

You call DNNRegressor(..., model_dir) and then call the fit() and evaluate() method.

When testing

You call DNNRegressor(..., model_dir) and then can call predict() methods. Your model will find a trained model in the model_dir and will load the trained model params.

Reference

Issue #3340 of TF

ContentLicense: CC BY-SA 3.0

Body:
I have a tensorflow contrib.learn.DNNRegressor that I have trained as part of the following code snippet:

regressor = tf.contrib.learn.DNNRegressor(feature_columns=fc,
                                          hidden_units=hu_array,
                                          optimizer=tf.train.AdamOptimizer(
                                                       learning_rate=0.001,
                                                    ),
                                          enable_centered_bias=False,
                                          activation_fn=tf.tanh,
                                          model_dir="./models/my_model/",
                                          )

regressor.fit(x=training_features, y=training_labels, steps=10000)

The trained network performs quite well, and I'd like to use it as a part of some other code, on another machine.  I have tried copying over the models/my_model directory, and constructing a new DNNRegressor pointing just at the model_dir, but it requires that I supply feature_columns and hidden_units definitions.   Shouldn't that information be available via the snapshots stored in model_dir?  Is there a better way to save/recover a trained model which is performing well, to be used as a predictor, without having to separately save the feature_columns and hidden_units?


问:
User Name is not taking from Dataabase
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.</p>

```<code><?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>
</code>```

答:
Try to do something like this -</p>

```<code><?php
//checking for GET variable
if(isset($_GET['username'])) $user=$_GET['username'];
else exit("Username is missing");

//IGNORE this if your DB connection is set from other files
//If so make a connection call and get the connection object.
$servername = "localhost";  //your db servername
$username = "username";   //your db username
$password = "password";   //your db password
$dbname = "myDB";   //your db name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//Your Query
$sql = "SELECT user_name FROM user_reg WHERE user_name='$user'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //  found a row with the user entry.
    //  then the username exists in the database.
    echo "Valid User";

} else {
    echo "User not found";
}
$conn->close();
?>
</code>```

Title: User Name is not taking from Dataabase

Body:
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.

<?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>

Body:
Try to do something like this -

<?php
//checking for GET variable
if(isset($_GET['username'])) $user=$_GET['username'];
else exit("Username is missing");

//IGNORE this if your DB connection is set from other files
//If so make a connection call and get the connection object.
$servername = "localhost";  //your db servername
$username = "username";   //your db username
$password = "password";   //your db password
$dbname = "myDB";   //your db name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//Your Query
$sql = "SELECT user_name FROM user_reg WHERE user_name='$user'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //  found a row with the user entry.
    //  then the username exists in the database.
    echo "Valid User";

} else {
    echo "User not found";
}
$conn->close();
?>


问:
Bootstrap - styling the toggle button on nav for mobile?
I've tried googling this but am struggling to find the correct selector/class and I'm still quite new to bootstrap.

I'm trying to style my navigation menu on mobile. Here's an image, for reference; I'd like to change the glyphicon here (I believe it's a hamburger at the minute), and its colour.

I'd also like to increase the distance between the nav bar and the cascading bottom menu here:

At the minute it looks like a 1px line.

I've tried modifying quite a few selectors in css but I'm not sure what I'm doing wrong. Any advice?

答:
Assuming Bootstrap 3

To change the icon find:

```<code><span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</code>```

and replace with:

```<code><span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</code>```

And to change the color of the new glyphicon add to your CSS:

```<code>.navbar-toggle span {
    color: RED;
}
</code>```

Line below toggle

```<code>.navbar-collapse {
    border-top-width: 10px;
}
</code>```

Body:
Assuming Bootstrap 3

To change the icon find:

<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>

and replace with:

<span class="glyphicon glyphicon-search" aria-hidden="true"></span>

And to change the color of the new glyphicon add to your CSS:

.navbar-toggle span {
    color: RED;
}

Line below toggle

.navbar-collapse {
    border-top-width: 10px;
}


问:
How to exclude some word from regexp search?
I have XML-file with this structure

```<code><item><rank>15</rank>...<price>100</price></item>
<item><rank>15</rank>...<price>200</price></item>
<item><rank>15</rank>...<price>500</price></item>
</code>```

from the above xml the ... means: some different tags which describe item somehow (may be any tag)

So I need to find item with price=500 and replace rank for it.

```<code><item><rank>\d+<\/rank>(.*)<price>500<\/price><\/item>
</code>```

But this RegExp will find be content of these three tags starting from first <item> and <price>500</price></item> at the end.

So I need to exclude </item> from (.*) in the search.

答:
See this regex

```<code>/(?:<item>(?:<rank>(\d+)<\/rank>)(?:(?!<\/item>).)*(?:<price>500<\/price>)<\/item>)/igm
</code>```

by using parentheses, you create capturing group ; the ?: is a non-capturing group (meaning you're not interested in its content).

igm means case insensitive, global and multiline.

(?!sth) is a negative lookahead, meaning we will discard sth.

Step by step: (from outer tags)

```<code>(?:<item> ... <\/item>) # we're interested in things beginning with <item> and ending with </item> and we're not capturing the group

... (?:<rank>(\d+)<\/rank>) ... # there's a rank tag, we're not capturing it, but we're capturing the digits within the tag

... (?:(?!<\/item>).)* ... # the crux of the problem, we're looking at any character except <\/item>

... (?:<price>500<\/price>)<\/item>) # the "line" ends with these tags
</code>```

Hope it helped.

Body:
I have XML-file with this structure

<item><rank>15</rank>...<price>100</price></item>
<item><rank>15</rank>...<price>200</price></item>
<item><rank>15</rank>...<price>500</price></item>

from the above xml the ... means: some different tags which describe item somehow (may be any tag)

So I need to find item with price=500 and replace rank for it.

<item><rank>\d+<\/rank>(.*)<price>500<\/price><\/item>

But this RegExp will find be content of these three tags starting from first <item> and <price>500</price></item> at the end.

So I need to exclude </item> from (.*) in the search.

Body:
See this regex

/(?:<item>(?:<rank>(\d+)<\/rank>)(?:(?!<\/item>).)*(?:<price>500<\/price>)<\/item>)/igm

by using parentheses, you create capturing group ; the ?: is a non-capturing group (meaning you're not interested in its content).

igm means case insensitive, global and multiline.

(?!sth) is a negative lookahead, meaning we will discard sth.

Step by step: (from outer tags)

(?:<item> ... <\/item>) # we're interested in things beginning with <item> and ending with </item> and we're not capturing the group

... (?:<rank>(\d+)<\/rank>) ... # there's a rank tag, we're not capturing it, but we're capturing the digits within the tag

... (?:(?!<\/item>).)* ... # the crux of the problem, we're looking at any character except <\/item>

... (?:<price>500<\/price>)<\/item>) # the "line" ends with these tags

Hope it helped.


问:
How to reuse a router pipeline definiton in another pipeline definition in phoenix framework?
I need to define two pipelines in my web/router.ex file as follows:

```<code>pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end
</code>```

You can clearly see that steps from the :api pipeline are duplicated in the :restricted_api pipeline.

Is there a way to reuse the :api pipeline in the :restricted_api pipeline?

I am thinking about something similar to inheritance:

```<code>pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  extend :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end
</code>```

答:
The pipeline macro creates a function plug. Therefore it can be used in other pipelines like any other plug with plug :pipeline. In the provided example:

```<code>pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end
</code>```

Body:
I need to define two pipelines in my web/router.ex file as follows:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end

You can clearly see that steps from the :api pipeline are duplicated in the :restricted_api pipeline.

Is there a way to reuse the :api pipeline in the :restricted_api pipeline?

I am thinking about something similar to inheritance:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  extend :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end

Body:
The pipeline macro creates a function plug. Therefore it can be used in other pipelines like any other plug with plug :pipeline. In the provided example:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end


问:
Can't import .json file to Firebase database.x
I'm trying to import my json file (called users.json), this is the file content:

```<code>{
  users:{

  },
  friends:{

  }
}
</code>```

I'm trying to import it to the firebase but it says "invalid json file".
What am I doing wrong?

答:
A JSON File shoul look like this:

```<code>{
  "users" : {
    "UID1" : {
      "userEmail" : "name1@email,com",
      "userName" : "name1",
    },
    "UID2" : {
      "userEmail" : "name2@email,com",
      "userName" : "name2",
    },
  },
    "friends" : {
    //
  }
}
</code>```

Hope it helps.

Body:
I'm trying to import my json file (called users.json), this is the file content:

{
  users:{

  },
  friends:{

  }
}

I'm trying to import it to the firebase but it says "invalid json file".
What am I doing wrong?

Body:
A JSON File shoul look like this:

{
  "users" : {
    "UID1" : {
      "userEmail" : "name1@email,com",
      "userName" : "name1",
    },
    "UID2" : {
      "userEmail" : "name2@email,com",
      "userName" : "name2",
    },
  },
    "friends" : {
    //
  }
}

Hope it helps.


问:
How to label duplicate groups in pandas?
I have a DataFrame:

```<code>>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar
</code>```

I need to find all the duplicate groups and label them with sequential dgroup_id's:

```<code>>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2
</code>```

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
</code>```

This leads to:

```<code>>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0
</code>```

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

答:
Use chained operation to first get value_count for each A, calculate the sequence number for each group, and then join back to the original DF.

```<code>(
    pd.merge(df,
             df.A.value_counts().apply(lambda x: 1 if x>1 else np.nan)
               .cumsum().rename('dgroup_id').to_frame(),
             left_on='A', right_index=True).sort_index()
)
Out[49]:
     A  dgroup_id
0  foo        1.0
1  bar        2.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        2.0
</code>```

If you need Nan for unique groups, you can't have int as the datatype which is a pandas limitation at the moment. If you are ok with set 0 for unique groups, you can do something like:

```<code>(
    pd.merge(df,
             df.A.value_counts().apply(lambda x: 1 if x>1 else np.nan)
               .cumsum().rename('dgroup_id').to_frame().fillna(0).astype(int),
             left_on='A', right_index=True).sort_index()
)

     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz          0
4  foo          1
5  bar          2
</code>```

Body:
I have a DataFrame:

>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar

I need to find all the duplicate groups and label them with sequential dgroup_id's:

>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))

This leads to:

>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

Body:
Use chained operation to first get value_count for each A, calculate the sequence number for each group, and then join back to the original DF.

(
    pd.merge(df,
             df.A.value_counts().apply(lambda x: 1 if x>1 else np.nan)
               .cumsum().rename('dgroup_id').to_frame(),
             left_on='A', right_index=True).sort_index()
)
Out[49]:
     A  dgroup_id
0  foo        1.0
1  bar        2.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        2.0

If you need Nan for unique groups, you can't have int as the datatype which is a pandas limitation at the moment. If you are ok with set 0 for unique groups, you can do something like:

(
    pd.merge(df,
             df.A.value_counts().apply(lambda x: 1 if x>1 else np.nan)
               .cumsum().rename('dgroup_id').to_frame().fillna(0).astype(int),
             left_on='A', right_index=True).sort_index()
)

     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz          0
4  foo          1
5  bar          2


问:
tensorflow contrib.learn save
How do you save your model output with the new contrib.learn functions like contrib.learn.DNNClassifier?

The deprecated functions like skflow.TensorFlowDNNClassifier had methods .save and .restore.  These were supposedly migrated over to the contrib.learn functions, but there are no longer save and restore methods that I can find.

If you create the variables specifically, you can use  tf.train.Saver, but is there any way to save your graph, weights, and biases if you just use the contrib.learn.DNNClassifier or contrib.learn.DNNRegressor functions?

答:
When training

You call DNNClassifier(..., model_dir) and then call the fit() and evaluate() method.

When testing

You call DNNClassifier(..., model_dir) and then can call predict() methods. Your model will find a trained model in the model_dir and will load the trained model params.

Reference

Issue #3340 of TF

Title: tensorflow contrib.learn save


问:
How to separate one column to multiple column (complex column)
I am trying to separate column "Grade" to multiple columns according to their subject and grade

```<code>    grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",sep=";")

# Rename the column names

    names(grade)<-c("Student_ID","Name","Venue","Grade")

    head(grade)

    # Separate `Grade` into `subject` variables and coresponding `Grade`columns
    library(tidyverse)

    df<- grade %>% separate(Grade,paste("V",1:7,sep="_"),sep=":")

    head(df)

    # It still is not separating `subject ` and `grade` independently

    # Here is what I want it to look like

    new_df<-df[c(1:5),c(1:4)]

    new_df<-data.frame(new_df, V2=c(1:5)) # the same for V2,4,5,6,,7 to separate subject and grade

    new_df
</code>```

I am trying to use dplyr and stringr, but could not produce the result as I expected

答:
Here is one attempt using tidyverse package.After converting everything to character (i.e. grade[] <- lapply(grade, as.character)) we create a custom function that returns the sorted subject:grade for each StudentID. We then use unnest to make it long, and use separate to split it into two columns; Subject and Grade. Finally we spread to get one column for each subject.

```<code>library(tidyverse)

#This function could definetely be more elegant or even avoided
#  but this is as far as my regex knowledge allows me to go

mysplit <- function(x){
  y <- strsplit(x, ':\\s+|\\s+')[[1]]
  z <- paste0(y[c(T, F)], ': ', y[c(F, T)])
  return(z[order(sub(':.*', '', z))])
}

grade %>%
  mutate(Grade = lapply(Grade, mysplit)) %>%
  unnest() %>%
  separate(Grade, into = c('Subject', 'Grade'), sep = ': ') %>%
  spread(Subject, Grade)
</code>```

Which will split it as so:

```<code>...     Biology Chemitry English Geography History Literature Math Physics
...   1    6.00     6.00    <NA>      <NA>    <NA>       7.50 4.25    6.80
...   2    5.80     6.00    <NA>      <NA>    <NA>       6.00 5.75    <NA>
...   3    <NA>     <NA>    <NA>      8.00    4.50       7.75 2.25    <NA>
...   4    <NA>     <NA>    <NA>      7.25    7.50       7.75 3.25    <NA>
...   5    <NA>     <NA>    <NA>      7.75    4.50       8.25 1.75    <NA>
...   6    <NA>     6.60    6.78      <NA>    <NA>       7.00 8.75    8.40
.
.
</code>```

To better understand the function you should break it down.
Say tha x is the following:

```<code>x
#[1] "Math:   4.25   Literature:   7.50   Physics:   6.80   Chemitry:   6.00   Biology:   6.00"
</code>```

Split it every space or : space to get the following vector

```<code>y <- strsplit(x, ':\\s+|\\s+')[[1]]
y
 #[1] "Math"       "4.25"       "Literature" "7.50"       "Physics"    "6.80"       "Chemitry"   "6.00"       "Biology"    "6.00"
</code>```

Paste it together, first all the first elements (i.e. the subjects, y[c(TRUE, FALSE)]) and then all the second elements (i.e. the grades y[c(FALSE, TRUE)]), with a : separator

```<code>z <- paste0(y[c(T, F)], ': ', y[c(F, T)])
z
#[1] "Math: 4.25"       "Literature: 7.50" "Physics: 6.80"    "Chemitry: 6.00"   "Biology: 6.00"
</code>```

Finally it outputs a sorted (based on the words sub(':.*', '', z)) vector

```<code>z[order(sub(':.*', '', z))]
#[1] "Biology: 6.00"    "Chemitry: 6.00"   "Literature: 7.50" "Math: 4.25"       "Physics: 6.80"
</code>```

As @rosscova pointed out, strings don't need to be sorted, which simplifies this a lot (function is not needed after all), i.e.

```<code>grade %>%
  mutate(Grade = strsplit(Grade, '[0-9]\\s+')) %>%
  unnest() %>%
  separate(Grade, into = c('Subject', 'Grade'), sep = ': ') %>%
  spread(Subject, Grade)
</code>```

Body:
I am trying to separate column "Grade" to multiple columns according to their subject and grade

    grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",sep=";")

# Rename the column names

    names(grade)<-c("Student_ID","Name","Venue","Grade")

    head(grade)

    # Separate `Grade` into `subject` variables and coresponding `Grade`columns
    library(tidyverse)

    df<- grade %>% separate(Grade,paste("V",1:7,sep="_"),sep=":")

    head(df)

    # It still is not separating `subject ` and `grade` independently

    # Here is what I want it to look like

    new_df<-df[c(1:5),c(1:4)]

    new_df<-data.frame(new_df, V2=c(1:5)) # the same for V2,4,5,6,,7 to separate subject and grade

    new_df

I am trying to use dplyr and stringr, but could not produce the result as I expected

Body:
Here is one attempt using tidyverse package.After converting everything to character (i.e. grade[] <- lapply(grade, as.character)) we create a custom function that returns the sorted subject:grade for each StudentID. We then use unnest to make it long, and use separate to split it into two columns; Subject and Grade. Finally we spread to get one column for each subject.

library(tidyverse)

#This function could definetely be more elegant or even avoided
#  but this is as far as my regex knowledge allows me to go

mysplit <- function(x){
  y <- strsplit(x, ':\\s+|\\s+')[[1]]
  z <- paste0(y[c(T, F)], ': ', y[c(F, T)])
  return(z[order(sub(':.*', '', z))])
}

grade %>%
  mutate(Grade = lapply(Grade, mysplit)) %>%
  unnest() %>%
  separate(Grade, into = c('Subject', 'Grade'), sep = ': ') %>%
  spread(Subject, Grade)

Which will split it as so:

...     Biology Chemitry English Geography History Literature Math Physics
...   1    6.00     6.00    <NA>      <NA>    <NA>       7.50 4.25    6.80
...   2    5.80     6.00    <NA>      <NA>    <NA>       6.00 5.75    <NA>
...   3    <NA>     <NA>    <NA>      8.00    4.50       7.75 2.25    <NA>
...   4    <NA>     <NA>    <NA>      7.25    7.50       7.75 3.25    <NA>
...   5    <NA>     <NA>    <NA>      7.75    4.50       8.25 1.75    <NA>
...   6    <NA>     6.60    6.78      <NA>    <NA>       7.00 8.75    8.40
.
.

To better understand the function you should break it down.
Say tha x is the following:

x
#[1] "Math:   4.25   Literature:   7.50   Physics:   6.80   Chemitry:   6.00   Biology:   6.00"

Split it every space or : space to get the following vector

y <- strsplit(x, ':\\s+|\\s+')[[1]]
y
 #[1] "Math"       "4.25"       "Literature" "7.50"       "Physics"    "6.80"       "Chemitry"   "6.00"       "Biology"    "6.00"

Paste it together, first all the first elements (i.e. the subjects, y[c(TRUE, FALSE)]) and then all the second elements (i.e. the grades y[c(FALSE, TRUE)]), with a : separator

z <- paste0(y[c(T, F)], ': ', y[c(F, T)])
z
#[1] "Math: 4.25"       "Literature: 7.50" "Physics: 6.80"    "Chemitry: 6.00"   "Biology: 6.00"

Finally it outputs a sorted (based on the words sub(':.*', '', z)) vector

z[order(sub(':.*', '', z))]
#[1] "Biology: 6.00"    "Chemitry: 6.00"   "Literature: 7.50" "Math: 4.25"       "Physics: 6.80"

As @rosscova pointed out, strings don't need to be sorted, which simplifies this a lot (function is not needed after all), i.e.

grade %>%
  mutate(Grade = strsplit(Grade, '[0-9]\\s+')) %>%
  unnest() %>%
  separate(Grade, into = c('Subject', 'Grade'), sep = ': ') %>%
  spread(Subject, Grade)


问:
Button inside DrawerLayout is not clickable
I've been searching for a while with this issue and i cant find solution yet.
For my design of DrawerLayout, I will not be using listview but linearlayout as container for my views. I test it first by adding a button inside the linearlayout but i cant click it.
Heres the XML.

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
        android:id="@+id/left_drawer"
        android:background="@color/white"
        android:orientation="vertical"
        android:layout_gravity="start"
        android:layout_width="250dp"
        android:layout_height="match_parent">
    <Button
            android:id="@+id/btn_test"
            android:text="TEST"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    <EditText

            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>

<FrameLayout
        android:id="@+id/container_fragment2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="1dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        >
</FrameLayout>
</code>```

In java, I also tried to put text in the button once it is being loaded and its working.The only thing that is not working is when i click it. the drawer will just close.

```<code>/**Init Drawer*/
private void initDrawer(){

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerContainer = (LinearLayout) findViewById(R.id.left_drawer);

    //mDrawerContainer.setOnClickListener(new DrawerItemClickListener());
    mDrawerContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context,"initDrawer",Toast.LENGTH_SHORT).show();
        }
    });

    btn_test = (Button)mDrawerContainer.findViewById(R.id.btn_test);
    btn_test.setOnClickListener(new View.OnClickListener() { //this is not working,i cant click the button
        @Override
        public void onClick(View v) {
            Log.e("MyActivity","test");
            Toast.makeText(context,"test",Toast.LENGTH_SHORT).show();
        }
    });
    btn_test.setText("hooray"); //this one is working,it change the text to hooray once loaded

}
</code>```

Im looking forward for your input guys,

Thanks a lot.

答:
check it----
cast your button with layout where u keep the button
here is my xml

```<code>    <RelativeLayout
        android:id="@+id/whatYouWantInLeftDrawer"
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#EBF4FA">
        <RelativeLayout
            android:id="@+id/top_view_rel"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@color/blue_color">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_margin="10dp"
                android:visibility="visible">
                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/drawer_driver_name"
                    android:textColor="@color/text_color"
                    android:textSize="16sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/name_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/name"
                    android:layout_marginLeft="135dp"
                    android:text="name"
                    android:textAllCaps="true"
                    android:textColor="@color/text_color"
                    android:textSize="16sp"
                    android:visibility="gone" />
                <Button
                    android:id="@+id/edit"
                    android:layout_width="30dp"
                    android:layout_height="25dp"

                    android:layout_alignParentRight="true"
                    android:background="@color/colorTransparent"
                    android:drawableRight="@drawable/edit1"
                   />
</code>```

in activity--

```<code> leftDrawerRel = (RelativeLayout)findViewById(R.id.whatYouWantInLeftDrawer);
    edit= (Button)leftDrawerRel.findViewById(R.id.edit);
    edit.setOnClickListener(this);
</code>```

Body:
I've been searching for a while with this issue and i cant find solution yet.
For my design of DrawerLayout, I will not be using listview but linearlayout as container for my views. I test it first by adding a button inside the linearlayout but i cant click it.
Heres the XML.

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
        android:id="@+id/left_drawer"
        android:background="@color/white"
        android:orientation="vertical"
        android:layout_gravity="start"
        android:layout_width="250dp"
        android:layout_height="match_parent">
    <Button
            android:id="@+id/btn_test"
            android:text="TEST"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    <EditText

            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>

<FrameLayout
        android:id="@+id/container_fragment2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="1dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        >
</FrameLayout>

In java, I also tried to put text in the button once it is being loaded and its working.The only thing that is not working is when i click it. the drawer will just close.

/**Init Drawer*/
private void initDrawer(){

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerContainer = (LinearLayout) findViewById(R.id.left_drawer);

    //mDrawerContainer.setOnClickListener(new DrawerItemClickListener());
    mDrawerContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context,"initDrawer",Toast.LENGTH_SHORT).show();
        }
    });

    btn_test = (Button)mDrawerContainer.findViewById(R.id.btn_test);
    btn_test.setOnClickListener(new View.OnClickListener() { //this is not working,i cant click the button
        @Override
        public void onClick(View v) {
            Log.e("MyActivity","test");
            Toast.makeText(context,"test",Toast.LENGTH_SHORT).show();
        }
    });
    btn_test.setText("hooray"); //this one is working,it change the text to hooray once loaded

}

Im looking forward for your input guys,

Thanks a lot.

Body:
check it----
cast your button with layout where u keep the button
here is my xml

    <RelativeLayout
        android:id="@+id/whatYouWantInLeftDrawer"
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#EBF4FA">
        <RelativeLayout
            android:id="@+id/top_view_rel"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@color/blue_color">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_margin="10dp"
                android:visibility="visible">
                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/drawer_driver_name"
                    android:textColor="@color/text_color"
                    android:textSize="16sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/name_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/name"
                    android:layout_marginLeft="135dp"
                    android:text="name"
                    android:textAllCaps="true"
                    android:textColor="@color/text_color"
                    android:textSize="16sp"
                    android:visibility="gone" />
                <Button
                    android:id="@+id/edit"
                    android:layout_width="30dp"
                    android:layout_height="25dp"

                    android:layout_alignParentRight="true"
                    android:background="@color/colorTransparent"
                    android:drawableRight="@drawable/edit1"
                   />

in activity--

 leftDrawerRel = (RelativeLayout)findViewById(R.id.whatYouWantInLeftDrawer);
    edit= (Button)leftDrawerRel.findViewById(R.id.edit);
    edit.setOnClickListener(this);


问:
How do i work with two different databases in rails with active records?
I need to use different database connections in different Rails models. Is there a not-so-hacky way to do that?

Any links or search keywords would be great :)

答:
I think that the prettiest way to connect to another database with active model is creating base class for external database, and then inherite from that base in your model.
This method works fine with rails 4.2.6 and 5.0.4

For example:

```<code># in /models/external_db/base.rb
require 'active_record'

class ExternalDb::Base < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "external_db_#{Rails.env}".to_sym
end
</code>```

And in your model class:

```<code># in /models/external_db/some_model.rb
class ExternalDB::SomeModel < ExternalDb::Base
  # your code
end
</code>```

But you must define external database in /config/database.yml

```<code># in /config/database.yml
external_db_development:
  adapter: sqlite3
  pool: 5
  timeout: 5000
  database: db/external_db_development.db

external_db_production:
  adapter: sqlite3
  pool: 5
  timeout: 5000
  database: db/external_db_production.db
</code>```

Body:
I think that the prettiest way to connect to another database with active model is creating base class for external database, and then inherite from that base in your model.
This method works fine with rails 4.2.6 and 5.0.4

For example:

# in /models/external_db/base.rb
require 'active_record'

class ExternalDb::Base < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "external_db_#{Rails.env}".to_sym
end

And in your model class:

# in /models/external_db/some_model.rb
class ExternalDB::SomeModel < ExternalDb::Base
  # your code
end

But you must define external database in /config/database.yml

# in /config/database.yml
external_db_development:
  adapter: sqlite3
  pool: 5
  timeout: 5000
  database: db/external_db_development.db

external_db_production:
  adapter: sqlite3
  pool: 5
  timeout: 5000
  database: db/external_db_production.db


答:
```<code><?php
$username="";
if(isset($_GET['username']))
{
$user=$_GET['username'];
$checkUser = mysqli_query($con,"SELECT user_name FROM user_reg WHERE
user_name='$user'") or die(mysqli_error($con));
$row=mysqli_fetch_assoc($checkUser);
if(mysqli_num_rows($checkUser)>0){
    $username = $row["user_name"];
}else{
    echo "User does not exist";
}
}
?>
</code>```

Title: User Name is not taking from Dataabase


问:
What is the merit of the "function" type (not "pointer to function")
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

```<code>typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above
</code>```

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

```<code>func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}
</code>```

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?

答:
You see it in the new function objects in Boost/TR1/C++0x.

std::function<void()> accepts any object with an operator() that returns void and takes no arguments.

ContentLicense: CC BY-SA 2.5

Body:
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?


问:
Passing JS to PHP
I am trying to pass a string stored in a variable to a mysql table via php.

Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.

I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)

How can I do it?

答:
There are several things you need to do:

You have a form tag and you need to prevent it from submitting, like this:

$("#myformid").submit(function(event) {
    //Do something
    event.preventDefault();
});

If your form is no longer submitted, then you are on the right track.

You need to use $.ajax to send the request, like this:

$("#myformid").submit(function(event) {
    //Here I assume that all variables have been properly initialized
    $.ajax({
        url: "yoururl",
        method: "POST",
        data: yourdata, //yourdata should contain the things you intend to send to the server
    }).done(function(response) {
        //callback
    });
    event.preventDefault();
});

You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //It is a POST request
} else {
    //It is not a POST request
}

Title: Passing JS to PHP


问:
How to change height of text field?
Is there a way to change the height of a text field in IB?  </p>

<p>If not, what is the proper way to do it in code? </p>

答:
Step 1 : Click the Attribute Inspector, Select the Border Styles which is not the rounded one.

Step 2 : Now go to Size Inspector and change the size of the TextField.

Step 3 : Create an @IBOutlet for TextField and then add below code inside the viewWillAppear() or viewDidAppear().

```<code>userTextField.borderStyle = UITextBorderStyle.roundedRect
</code>```

Swift 5.7

```<code>userTextField.borderStyle = UITextField.BorderStyle.roundedRect
</code>```

Now you'll get the cool rounded textfield.

Title: How to change height of text field?

Body:
Is there a way to change the height of a text field in IB?

If not, what is the proper way to do it in code?

Body:
Step 1 : Click the Attribute Inspector, Select the Border Styles which is not the rounded one.

Step 2 : Now go to Size Inspector and change the size of the TextField.

Step 3 : Create an @IBOutlet for TextField and then add below code inside the viewWillAppear() or viewDidAppear().

userTextField.borderStyle = UITextBorderStyle.roundedRect

Swift 5.7

userTextField.borderStyle = UITextField.BorderStyle.roundedRect

Now you'll get the cool rounded textfield.

ContentLicense: CC BY-SA 4.0


问:
Clear all input inside a modal
I have a modal where I can input some data to create and also to update the selected data. What I want to is, whenever the modal closes, it will clear the textbox and set the dropdown to its default display.

I have tried this http://jsfiddle.net/5LCSU/ applying to my project but it doesn't work and there is no error too.

Here is my moda/view:

```<code><div id="productModal" class="modal fade">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Prescription<label id="title"></label></h4>
        </div>
        <div class="modal-body">
            <div class="form-horizontal">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <div class="form-group">
                    @Html.Label("Name", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @ViewBag.name
                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Complaint", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @ViewBag.complaint
                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Medicine", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("MedcineID", null, "--Select Medicine--", htmlAttributes: new { @class = "form-control" })

                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Quantity", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })

                    </div>
                </div>
                <div class="form-group">
                    @Html.Label("Frequency", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.Frequency, frequency, "-- Frequency --", htmlAttributes: new { @class = "form-control" })

                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" id="btn-add" class="btn btn-primary">Add to list</button>
            <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </div>
    </div>
</div>
</code>```

Here is my js:

```<code>$(document).ready(function () {
    //create
    $('#btn-add').click(function () {
        var assessmentID = $('#assessmentID').val();
        var medicineID = $('#MedcineID').val();
        var qty = $('#Quantity').val();
        var freq = $('#Frequency').val();
        var remarks = $('#Remarks').val();
        var data = {
            'assessmentID': assessmentID,
            'medicineID': medicineID,
            'qty': qty,
            'freq': freq,
            'remarks': remarks
        }

        if (medicineID == '') { // check if medicine is null
            alert('Please specify a valid medicine');
        }
        else { //check if duplicate
            $.ajax({//check via controller
                type: "POST",
                dataType: "Json",
                data: data,
                url: '/Prescriptions/CheckData/',
                success: function (f) {
                    if (f == 'Fail') {
                        alert('Specified medicine has already been added');
                    }
                    else {
                        if (qty < 1) {
                            alert('Please specify a valid quantity');
                        }
                        else {
                            if (freq == '') {
                                alert('Please specify a valid frequency');
                            }
                            else {
                                $.ajax({
                                    type: "POST",
                                    dataType: "Json",
                                    data: data,
                                    url: '/Prescriptions/Add/',
                                    success: function (f) {
                                        $('#tbl-prescription').load('/Prescriptions/_PrescriptionList/?assessmentID=' + assessmentID);
                                    }
                                })
                            }
                        }
                    }
                }
            })
        }
    })
});

// clears modal
$('#productModal').on('hidden.bs.modal', function (e) {
    $(this)
      .find("input,textarea,select")
         .val('')
         .end()
})
</code>```

答:
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Modal Example

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <input type="text" value="dgfdhfgjghd">
           <input type="text" value="dgfdhfgjghd">
            <input type="text" value="dgfdhfgjghd">
             <input type="text" value="dgfdhfgjghd">
              <input type="text" value="dgfdhfgjghd">
              <textarea>fgfdhfgjgh</textarea>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

```

Title: Clear all input inside a modal

Body:
I have a modal where I can input some data to create and also to update the selected data. What I want to is, whenever the modal closes, it will clear the textbox and set the dropdown to its default display.

I have tried this http://jsfiddle.net/5LCSU/ applying to my project but it doesn't work and there is no error too.

Here is my moda/view:

            <button type="button" class="close" data-dismiss="modal">×</button>

Prescription

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.Label("Name", new { @class = "control-label col-md-2" })

                        @ViewBag.name

                    @Html.Label("Complaint", new { @class = "control-label col-md-2" })

                        @ViewBag.complaint

                    @Html.Label("Medicine", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.DropDownList("MedcineID", null, "--Select Medicine--", htmlAttributes: new { @class = "form-control" })

                    @Html.Label("Quantity", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.Label("Frequency", htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.DropDownListFor(model => model.Frequency, frequency, "-- Frequency --", htmlAttributes: new { @class = "form-control" })

                    @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })

            <button type="submit" id="btn-add" class="btn btn-primary">Add to list</button>
            <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button>

Here is my js:

$(document).ready(function () {
    //create
    $('#btn-add').click(function () {
        var assessmentID = $('#assessmentID').val();
        var medicineID = $('#MedcineID').val();
        var qty = $('#Quantity').val();
        var freq = $('#Frequency').val();
        var remarks = $('#Remarks').val();
        var data = {
            'assessmentID': assessmentID,
            'medicineID': medicineID,
            'qty': qty,
            'freq': freq,
            'remarks': remarks
        }

        if (medicineID == '') { // check if medicine is null
            alert('Please specify a valid medicine');
        }
        else { //check if duplicate
            $.ajax({//check via controller
                type: "POST",
                dataType: "Json",
                data: data,
                url: '/Prescriptions/CheckData/',
                success: function (f) {
                    if (f == 'Fail') {
                        alert('Specified medicine has already been added');
                    }
                    else {
                        if (qty < 1) {
                            alert('Please specify a valid quantity');
                        }
                        else {
                            if (freq == '') {
                                alert('Please specify a valid frequency');
                            }
                            else {
                                $.ajax({
                                    type: "POST",
                                    dataType: "Json",
                                    data: data,
                                    url: '/Prescriptions/Add/',
                                    success: function (f) {
                                        $('#tbl-prescription').load('/Prescriptions/_PrescriptionList/?assessmentID=' + assessmentID);
                                    }
                                })
                            }
                        }
                    }
                }
            })
        }
    })
});

// clears modal
$('#productModal').on('hidden.bs.modal', function (e) {
    $(this)
      .find("input,textarea,select")
         .val('')
         .end()
})

Body:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
          <input type="text" value="dgfdhfgjghd">
           <input type="text" value="dgfdhfgjghd">
            <input type="text" value="dgfdhfgjghd">
             <input type="text" value="dgfdhfgjghd">
              <input type="text" value="dgfdhfgjghd">
              <textarea>fgfdhfgjgh</textarea>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>
<script>
$(document).on('hidden.bs.modal', function (e) {
  $('.modal-body input,.modal-body textarea').each(function(){
      $(this).val('');
  });
});
</script>

</body>
</html>


问:
Why is my button as a toggle not working when I try to update the state of the button?
When I try to change the state of the button after it is pressed, nothing works. I do this with the line prev = current;

```<code>#include <Servo.h>;

//HIGH not pressed
//LOW pressed

int pushD3 = 3;
int pushD4 = 4;
int pushD5 = 5;
int pushD6 = 6;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;
Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if (current == 1 && prev == 0) {
    checkButtons_slow();
    delay(100);
  }
  if (current == 0 && prev == 1) {
    //ZServo.write(110);
    delay(500); //half a second
  }
  prev = current;
}

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(87);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}
</code>```

答:
I found your implementation and Michael's a bit confusing, why not doing:</p>

```<code>bool state = false;
bool buttonPressed = false;
void loop(){
    if (digitalRead(3) == LOW && !buttonPressed){
        state=!state;
        buttonPressed = true;
    }
    if(digitalRead(3) == HIGH){
        buttonPressed = false;
    }

    // Then your logic
    if (state) {
    checkButtons_slow();
    delay(100);
    } else{
        //ZServo.write(110);
        delay(500); //half a second
    }
}
</code>```

Body:
When I try to change the state of the button after it is pressed, nothing works. I do this with the line prev = current;

#include <Servo.h>;

//HIGH not pressed
//LOW pressed

int pushD3 = 3;
int pushD4 = 4;
int pushD5 = 5;
int pushD6 = 6;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;
Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if (current == 1 && prev == 0) {
    checkButtons_slow();
    delay(100);
  }
  if (current == 0 && prev == 1) {
    //ZServo.write(110);
    delay(500); //half a second
  }
  prev = current;
}

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(87);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}

Body:
I found your implementation and Michael's a bit confusing, why not doing:

bool state = false;
bool buttonPressed = false;
void loop(){
    if (digitalRead(3) == LOW && !buttonPressed){
        state=!state;
        buttonPressed = true;
    }
    if(digitalRead(3) == HIGH){
        buttonPressed = false;
    }

    // Then your logic
    if (state) {
    checkButtons_slow();
    delay(100);
    } else{
        //ZServo.write(110);
        delay(500); //half a second
    }
}


问:
chr values as variable in for loop R
I want to loop over a list of chr values in R.
For ervery value I want to run the next code

```<code>for (locatie in Locaties){ # Locaties is a list of character values ("NL14_20076" "NL14_20077" etc)
  Data_ammoniak <- subset(paste0("Data_",locatie), Parameter == "ammoniak")
  # I want to make a dataset with only ammoniak data out of a dataset called "Data_NL14_20076"
  # So I want to use the value from the list
  ggplot(Data_ammoniak, aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum",
         y = "Meetwaarde",
         title = paste0(locatie, "Ammoniak")) # This one is working I think

  ggsave(paste0("C:/Temp/LTO_Noord/",locatie,"_Ammoniak.png"), #This one is working as well I think
         width = 30,
         height = 20,
         units = "cm")
}
</code>```

When I run this code I get the following error:

```<code>Error in subset.default(paste0("Data_", locatie), Parameter == "ammoniak") :
  object 'Parameter' not found
</code>```

Does somebody know how it will work?

答:
You can do that with lapply. The following code should work:

```<code>lapply(Locaties, function(l) {
  dat <- get(paste0("Data_",l))
  ggplot(dat[dat$Parameter == "ammoniak", ], aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum",
         y = "Meetwaarde",
         title = paste0(l, " Ammoniak")) +
    ggsave(paste0("C:/Temp/LTO_Noord/",l,"_Ammoniak.png"),
           width = 30,
           height = 20,
           units = "cm")
})
</code>```

Title: chr values as variable in for loop R

Body:
I want to loop over a list of chr values in R.
For ervery value I want to run the next code

for (locatie in Locaties){ # Locaties is a list of character values ("NL14_20076" "NL14_20077" etc)
  Data_ammoniak <- subset(paste0("Data_",locatie), Parameter == "ammoniak")
  # I want to make a dataset with only ammoniak data out of a dataset called "Data_NL14_20076"
  # So I want to use the value from the list
  ggplot(Data_ammoniak, aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum",
         y = "Meetwaarde",
         title = paste0(locatie, "Ammoniak")) # This one is working I think

  ggsave(paste0("C:/Temp/LTO_Noord/",locatie,"_Ammoniak.png"), #This one is working as well I think
         width = 30,
         height = 20,
         units = "cm")
}

When I run this code I get the following error:

Error in subset.default(paste0("Data_", locatie), Parameter == "ammoniak") :
  object 'Parameter' not found

Does somebody know how it will work?

Body:
You can do that with lapply. The following code should work:

lapply(Locaties, function(l) {
  dat <- get(paste0("Data_",l))
  ggplot(dat[dat$Parameter == "ammoniak", ], aes(x = Begindatum, y = Meetwaarde_n)) +
    geom_point() +
    geom_line() +
    labs(x = "Datum",
         y = "Meetwaarde",
         title = paste0(l, " Ammoniak")) +
    ggsave(paste0("C:/Temp/LTO_Noord/",l,"_Ammoniak.png"),
           width = 30,
           height = 20,
           units = "cm")
})


问:
How to use sscanf to extract float numbers?
I have one string like:
string line="Name &0.11/-0.11 &0.11/0.11 &0.03/0.03 \\";

And I want to extract name and all float numbers, I tried:

sscanf(line,"%s %*[&]%f%*[/]%f %*[&]%f%*[/]%f %*[&]%f%*[/]%f %*[\\]",systname,&sig_up,&sig_down,&prompt_up,&prompt_down,&Vgam_up,&Vgam_down);

But it didn't work, and got error:Error: sscanf parameter mismatch param[0] C u
Could someone help with this? Thanks.

答:
%f matches a double in printf() and its family, a float in scanf() and its family. Usually you want to work in double precision, so you need %lf for scanf().

However strtod() is more stable and error-resistant.


问:
Copy jagged n-dimensional primitive array to new type in java
I feel I might be missing something really obvious. I need to copy a jagged n-dimensional array in java from one to another primitive (Number) type (e.g., from double[][][][] to int[][][][]). My code below works using Object[]s. How can I (or "Can I even") generate a new type of primitive array of n-dimensions? (By "jagged" I mean some arrays at the same level may have different dimensions as in the example data). Any help appreciated.</p>

```<code>    public class ArrayToNewType {

    public static void main(String... args) {

    Object loNew = arrayAsNewType(
            new double[][][][]
            {
                array1,
                array2,
                array2Nulls,
                array3a
            },
            int.class);

    }

    public static Object arrayAsNewType(Object pArray,
                                        Class<?> pNewType)
    {
      Object[] lNewArray
           = new Object[java.lang.reflect.Array.getLength(pArray)];
      deepCopy(pArray,
               lNewArray,
               pNewType);
      return lNewArray;
    }

    private static void deepCopy(Object pOriginal,
                                 Object pCopy,
                                 Class<?> pNewType) {
    if (pOriginal == null || !pOriginal.getClass().isArray()) {
        return;
    }
    for (int liIndex = 0;
         liIndex < java.lang.reflect.Array.getLength(pOriginal);
         liIndex++) {
        Object lElement = java.lang.reflect.Array.get(pOriginal,
                                                      liIndex);
        if (lElement.getClass().isArray()) {
            int liElementLength =
                    java.lang.reflect.Array.getLength(lElement);
            java.lang.reflect.Array.set(
                    pCopy,
                    liIndex,
                    !lElement.getClass().getComponentType().isArray()
                    ? java.lang.reflect.Array.newInstance(
                                                         pNewType,
                                                         liElementLength)
                    : new Object[liElementLength]);
        }
        else {
            java.lang.reflect.Array.set(pCopy,
                                        liIndex,
                                        castToPrimitive(lElement,
                                                        pNewType));
        }
        deepCopy(lElement,
                 java.lang.reflect.Array.get(pCopy,
                                             liIndex),
                 pNewType);
    }
    }
    // Sample data
    static double[][][] array1 =
        {
            {{3D, 4D, 5D, 2D, 13D}, {8D}, {28D}},
            {{8D}, {4228.2D, 4D, -.29D, 3D}, {228D}},
            {{48D}, {228D}},
            {{48D}, {28D}}
        };
    static double[][][] array2 =
        {
            {{8}, {3, 4, 5, 2, 3}, {28}},
            {{8}, {4228, 4, 29, 3}, {228}},
            {{248}, {228}},
            {{0}, {-2899}, {9}}
        };
    static double[][][] array2Nulls =
        {
            {{8}, {3, 4, 5, 2, 3}, {28}},
            {{8}, {4228, 4, 29, 3}, {228}},
            {},
            {{0}, {-2899}, {9}}
        };
    static double[][][] array3a =
        {
            {{8D}, {554D, 5D, 2D, 3D}, {28D}},
            {{48D}, {228D}},
            {{48D}, {328.65D}}
        };

    static <T extends Number> Object castToPrimitive(Object pElement,
                                                     Class<?> pNewType)
    {
    if (pNewType.equals(byte.class)) {
        return ((Number) pElement).byteValue();
    }
    if (pNewType.equals(short.class)) {
        return ((Number) pElement).shortValue();
    }
    if (pNewType.equals(int.class)) {
        return ((Number) pElement).intValue();
    }
    if (pNewType.equals(long.class)) {
        return ((Number) pElement).longValue();
    }
    if (pNewType.equals(double.class)) {
        return ((Number) pElement).doubleValue();
    }
    if (pNewType.equals(float.class)) {
        return ((Number) pElement).floatValue();
    }

    return (pElement);
    }
    }
</code>```

答:
Another approach using reflection, but working directly with the primitive types:</p>

```<code>import java.lang.reflect.Array;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class NdArrayCaster {
    private final static Map<Class<?>, NumberClassWrapper> TYPES = new HashMap<Class<?>, NumberClassWrapper>() {
        {
            put(byte.class, new ByteClassWrapper());
            put(short.class, new ShortClassWrapper());
            put(int.class, new IntClassWrapper());
            put(long.class, new LongClassWrapper());
            put(float.class, new FloatClassWrapper());
            put(double.class, new DoubleClassWrapper());
        }
    };

    /**
     * Returns a "deep casted" copy of ndArray with the given base type.
     */
    public static Object cast(Object ndArray, Class<?> baseTypeClass) {
        checkThatPrimitiveArray(ndArray);
        int dimension = getDimension(ndArray);
        NumberClassWrapper wrapper = TYPES.get(baseTypeClass);
        return cast(ndArray, wrapper, dimension);
    }

    /**
     * Throws an IllegalArgumentException if ndArray is not a primitive type array.
     */
    private static void checkThatPrimitiveArray(Object ndArray) {
        if (!ndArray.getClass().getName().matches("\\[*[BSIJFD]")) {
            throw new IllegalArgumentException("ndArray is not a primitive array.");
        }
    }

    /**
     * Returns the array's dimension.
     */
    private static int getDimension(Object ndArray) {
        return ndArray.getClass().getName().length() - 1;
    }

    /**
     * Casts an old to an array of the given type and dimension.
     * <p>
     * This is called recursive for each dimension.
     */
    private static Object cast(Object old, NumberClassWrapper wrapper, int dimension) {
        if (dimension == 0) {
            return wrapper.cast((Number) old);
        }

        int size = Array.getLength(old);
        Object newArray = wrapper.createArray(dimension, size);
        for (int i = 0; i < size; i++) {
            Object child = Array.get(old, i);
            Array.set(newArray, i, cast(child, wrapper, dimension - 1));
        }
        return newArray;
    }

    /**
     * Class providing information for a primitive type.
     */
    private static abstract class NumberClassWrapper<N extends Number> {
        private final Class<N> primitiveClass;
        private final String jvmName;

        NumberClassWrapper(Class<N> numberClass, String jvmName) {
            this.primitiveClass = numberClass;
            this.jvmName = jvmName;
        }

        /**
         * Casts a number to the type represented by this Wrapper.
         */
        abstract N cast(Number value);

        /**
         * Creates a primitive array with the given dimension and the given size at the lowest dimension.
         * <p>
         * Example: `IntClassWrapper.createArray(3,4)` returns the same as `new int[4][][]`.
         */
        final Object createArray(int dimension, int size) {
            return Array.newInstance(getBaseClassForArrayCreation(dimension), size);
        }

        Class getBaseClassForArrayCreation(int dimension) {
            if (dimension == 1) {
                return primitiveClass;
            } else {
                try {
                    return Class.forName(getArrayJVMName(dimension - 1));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new Error("Cannot happen.");
                }
            }
        }

        /**
         * Returns the JVM name of the corresponding primitive array with the given dimension.
         */
        private String getArrayJVMName(int dimension) {
            return String.join("", Collections.nCopies(dimension, "[")) + jvmName;
        }
    }

    private final static class ByteClassWrapper extends NumberClassWrapper<Byte> {
        ByteClassWrapper() {
            super(byte.class, "B");
        }

        @Override
        public Byte cast(Number n) {
            return n.byteValue();
        }
    }

    private final static class ShortClassWrapper extends NumberClassWrapper<Short> {
        ShortClassWrapper() {
            super(short.class, "S");
        }

        @Override
        Short cast(Number n) {
            return n.shortValue();
        }
    }

    private final static class IntClassWrapper extends NumberClassWrapper<Integer> {
        IntClassWrapper() {
            super(int.class, "I");
        }

        @Override
        Integer cast(Number n) {
            return n.intValue();
        }
    }

    private final static class LongClassWrapper extends NumberClassWrapper<Long> {
        LongClassWrapper() {
            super(long.class, "J");
        }

        @Override
        Long cast(Number n) {
            return n.longValue();
        }
    }

    private final static class FloatClassWrapper extends NumberClassWrapper<Float> {
        FloatClassWrapper() {
            super(float.class, "F");
        }

        @Override
        Float cast(Number n) {
            return n.floatValue();
        }
    }

    private final static class DoubleClassWrapper extends NumberClassWrapper<Double> {
        DoubleClassWrapper() {
            super(double.class, "D");
        }

        @Override
        Double cast(Number n) {
            return n.doubleValue();
        }
    }

    public static void main(String... args) {
        // Sample data
        double[][][] array1 = {
                {{3D, 4D, 5D, 2D, 13D}, {8D}, {28D}},
                {{8D}, {4228.2D, 4D, -.29D, 3D}, {228D}},
                {{48D}, {228D}},
                {{48D}, {28D}}
        };
        double[][][] array2 = {
                {{8}, {3, 4, 5, 2, 3}, {28}},
                {{8}, {4228, 4, 29, 3}, {228}},
                {{248}, {228}},
                {{0}, {-2899}, {9}}
        };
        double[][][] array2Nulls = {
                {{8}, {3, 4, 5, 2, 3}, {28}},
                {{8}, {4228, 4, 29, 3}, {228}},
                {},
                {{0}, {-2899}, {9}}
        };

        double[][][] array3a = {
                {{8D}, {554D, 5D, 2D, 3D}, {28D}},
                {{48D}, {228D}},
                {{48D}, {328.65D}}
        };

        double[][][][] ndArray = {array1, array2, array2Nulls, array3a};
        System.out.println(cast(ndArray, byte.class).getClass());
        System.out.println(cast(ndArray, short.class).getClass());
        System.out.println(cast(ndArray, int.class).getClass());
        System.out.println(cast(ndArray, long.class).getClass());
        System.out.println(cast(ndArray, float.class).getClass());
        System.out.println(cast(ndArray, double.class).getClass());

        Object[] objectArray = new Object[]{new Object()};
        try {
            System.out.println(cast(objectArray, byte.class).getClass());
        } catch (IllegalArgumentException e) {
            System.out.println("Object array not working: check.");
        }
        try {
            System.out.println(cast(new Object(), byte.class).getClass());
        } catch (IllegalArgumentException e) {
            System.out.println("Object not working: check.");
        }
    }
}
</code>```

Body:
I feel I might be missing something really obvious. I need to copy a jagged n-dimensional array in java from one to another primitive (Number) type (e.g., from double[][][][] to int[][][][]). My code below works using Object[]s. How can I (or "Can I even") generate a new type of primitive array of n-dimensions? (By "jagged" I mean some arrays at the same level may have different dimensions as in the example data). Any help appreciated.

    public class ArrayToNewType {

    public static void main(String... args) {

    Object loNew = arrayAsNewType(
            new double[][][][]
            {
                array1,
                array2,
                array2Nulls,
                array3a
            },
            int.class);

    }

    public static Object arrayAsNewType(Object pArray,
                                        Class<?> pNewType)
    {
      Object[] lNewArray
           = new Object[java.lang.reflect.Array.getLength(pArray)];
      deepCopy(pArray,
               lNewArray,
               pNewType);
      return lNewArray;
    }

    private static void deepCopy(Object pOriginal,
                                 Object pCopy,
                                 Class<?> pNewType) {
    if (pOriginal == null || !pOriginal.getClass().isArray()) {
        return;
    }
    for (int liIndex = 0;
         liIndex < java.lang.reflect.Array.getLength(pOriginal);
         liIndex++) {
        Object lElement = java.lang.reflect.Array.get(pOriginal,
                                                      liIndex);
        if (lElement.getClass().isArray()) {
            int liElementLength =
                    java.lang.reflect.Array.getLength(lElement);
            java.lang.reflect.Array.set(
                    pCopy,
                    liIndex,
                    !lElement.getClass().getComponentType().isArray()
                    ? java.lang.reflect.Array.newInstance(
                                                         pNewType,
                                                         liElementLength)
                    : new Object[liElementLength]);
        }
        else {
            java.lang.reflect.Array.set(pCopy,
                                        liIndex,
                                        castToPrimitive(lElement,
                                                        pNewType));
        }
        deepCopy(lElement,
                 java.lang.reflect.Array.get(pCopy,
                                             liIndex),
                 pNewType);
    }
    }
    // Sample data
    static double[][][] array1 =
        {
            {{3D, 4D, 5D, 2D, 13D}, {8D}, {28D}},
            {{8D}, {4228.2D, 4D, -.29D, 3D}, {228D}},
            {{48D}, {228D}},
            {{48D}, {28D}}
        };
    static double[][][] array2 =
        {
            {{8}, {3, 4, 5, 2, 3}, {28}},
            {{8}, {4228, 4, 29, 3}, {228}},
            {{248}, {228}},
            {{0}, {-2899}, {9}}
        };
    static double[][][] array2Nulls =
        {
            {{8}, {3, 4, 5, 2, 3}, {28}},
            {{8}, {4228, 4, 29, 3}, {228}},
            {},
            {{0}, {-2899}, {9}}
        };
    static double[][][] array3a =
        {
            {{8D}, {554D, 5D, 2D, 3D}, {28D}},
            {{48D}, {228D}},
            {{48D}, {328.65D}}
        };

    static <T extends Number> Object castToPrimitive(Object pElement,
                                                     Class<?> pNewType)
    {
    if (pNewType.equals(byte.class)) {
        return ((Number) pElement).byteValue();
    }
    if (pNewType.equals(short.class)) {
        return ((Number) pElement).shortValue();
    }
    if (pNewType.equals(int.class)) {
        return ((Number) pElement).intValue();
    }
    if (pNewType.equals(long.class)) {
        return ((Number) pElement).longValue();
    }
    if (pNewType.equals(double.class)) {
        return ((Number) pElement).doubleValue();
    }
    if (pNewType.equals(float.class)) {
        return ((Number) pElement).floatValue();
    }

    return (pElement);
    }
    }

Body:
Another approach using reflection, but working directly with the primitive types:

import java.lang.reflect.Array;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class NdArrayCaster {
    private final static Map<Class<?>, NumberClassWrapper> TYPES = new HashMap<Class<?>, NumberClassWrapper>() {
        {
            put(byte.class, new ByteClassWrapper());
            put(short.class, new ShortClassWrapper());
            put(int.class, new IntClassWrapper());
            put(long.class, new LongClassWrapper());
            put(float.class, new FloatClassWrapper());
            put(double.class, new DoubleClassWrapper());
        }
    };

    /**
     * Returns a "deep casted" copy of ndArray with the given base type.
     */
    public static Object cast(Object ndArray, Class<?> baseTypeClass) {
        checkThatPrimitiveArray(ndArray);
        int dimension = getDimension(ndArray);
        NumberClassWrapper wrapper = TYPES.get(baseTypeClass);
        return cast(ndArray, wrapper, dimension);
    }

    /**
     * Throws an IllegalArgumentException if ndArray is not a primitive type array.
     */
    private static void checkThatPrimitiveArray(Object ndArray) {
        if (!ndArray.getClass().getName().matches("\\[*[BSIJFD]")) {
            throw new IllegalArgumentException("ndArray is not a primitive array.");
        }
    }

    /**
     * Returns the array's dimension.
     */
    private static int getDimension(Object ndArray) {
        return ndArray.getClass().getName().length() - 1;
    }

    /**
     * Casts an old to an array of the given type and dimension.
     * <p>
     * This is called recursive for each dimension.
     */
    private static Object cast(Object old, NumberClassWrapper wrapper, int dimension) {
        if (dimension == 0) {
            return wrapper.cast((Number) old);
        }

        int size = Array.getLength(old);
        Object newArray = wrapper.createArray(dimension, size);
        for (int i = 0; i < size; i++) {
            Object child = Array.get(old, i);
            Array.set(newArray, i, cast(child, wrapper, dimension - 1));
        }
        return newArray;
    }

    /**
     * Class providing information for a primitive type.
     */
    private static abstract class NumberClassWrapper<N extends Number> {
        private final Class<N> primitiveClass;
        private final String jvmName;

        NumberClassWrapper(Class<N> numberClass, String jvmName) {
            this.primitiveClass = numberClass;
            this.jvmName = jvmName;
        }

        /**
         * Casts a number to the type represented by this Wrapper.
         */
        abstract N cast(Number value);

        /**
         * Creates a primitive array with the given dimension and the given size at the lowest dimension.
         * <p>
         * Example: `IntClassWrapper.createArray(3,4)` returns the same as `new int[4][][]`.
         */
        final Object createArray(int dimension, int size) {
            return Array.newInstance(getBaseClassForArrayCreation(dimension), size);
        }

        Class getBaseClassForArrayCreation(int dimension) {
            if (dimension == 1) {
                return primitiveClass;
            } else {
                try {
                    return Class.forName(getArrayJVMName(dimension - 1));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new Error("Cannot happen.");
                }
            }
        }

        /**
         * Returns the JVM name of the corresponding primitive array with the given dimension.
         */
        private String getArrayJVMName(int dimension) {
            return String.join("", Collections.nCopies(dimension, "[")) + jvmName;
        }
    }

    private final static class ByteClassWrapper extends NumberClassWrapper<Byte> {
        ByteClassWrapper() {
            super(byte.class, "B");
        }

        @Override
        public Byte cast(Number n) {
            return n.byteValue();
        }
    }

    private final static class ShortClassWrapper extends NumberClassWrapper<Short> {
        ShortClassWrapper() {
            super(short.class, "S");
        }

        @Override
        Short cast(Number n) {
            return n.shortValue();
        }
    }

    private final static class IntClassWrapper extends NumberClassWrapper<Integer> {
        IntClassWrapper() {
            super(int.class, "I");
        }

        @Override
        Integer cast(Number n) {
            return n.intValue();
        }
    }

    private final static class LongClassWrapper extends NumberClassWrapper<Long> {
        LongClassWrapper() {
            super(long.class, "J");
        }

        @Override
        Long cast(Number n) {
            return n.longValue();
        }
    }

    private final static class FloatClassWrapper extends NumberClassWrapper<Float> {
        FloatClassWrapper() {
            super(float.class, "F");
        }

        @Override
        Float cast(Number n) {
            return n.floatValue();
        }
    }

    private final static class DoubleClassWrapper extends NumberClassWrapper<Double> {
        DoubleClassWrapper() {
            super(double.class, "D");
        }

        @Override
        Double cast(Number n) {
            return n.doubleValue();
        }
    }

    public static void main(String... args) {
        // Sample data
        double[][][] array1 = {
                {{3D, 4D, 5D, 2D, 13D}, {8D}, {28D}},
                {{8D}, {4228.2D, 4D, -.29D, 3D}, {228D}},
                {{48D}, {228D}},
                {{48D}, {28D}}
        };
        double[][][] array2 = {
                {{8}, {3, 4, 5, 2, 3}, {28}},
                {{8}, {4228, 4, 29, 3}, {228}},
                {{248}, {228}},
                {{0}, {-2899}, {9}}
        };
        double[][][] array2Nulls = {
                {{8}, {3, 4, 5, 2, 3}, {28}},
                {{8}, {4228, 4, 29, 3}, {228}},
                {},
                {{0}, {-2899}, {9}}
        };

        double[][][] array3a = {
                {{8D}, {554D, 5D, 2D, 3D}, {28D}},
                {{48D}, {228D}},
                {{48D}, {328.65D}}
        };

        double[][][][] ndArray = {array1, array2, array2Nulls, array3a};
        System.out.println(cast(ndArray, byte.class).getClass());
        System.out.println(cast(ndArray, short.class).getClass());
        System.out.println(cast(ndArray, int.class).getClass());
        System.out.println(cast(ndArray, long.class).getClass());
        System.out.println(cast(ndArray, float.class).getClass());
        System.out.println(cast(ndArray, double.class).getClass());

        Object[] objectArray = new Object[]{new Object()};
        try {
            System.out.println(cast(objectArray, byte.class).getClass());
        } catch (IllegalArgumentException e) {
            System.out.println("Object array not working: check.");
        }
        try {
            System.out.println(cast(new Object(), byte.class).getClass());
        } catch (IllegalArgumentException e) {
            System.out.println("Object not working: check.");
        }
    }
}


问:
Create parameterized VIEW in SQL Server 2008
Can we create parameterized VIEW in SQL Server 2008.

Or Any other alternative for this ?

答: no. You can use UDF in which you can pass parameters.</p>


问:
Run-time error, using undeclared variable, C++
Im having this really weird error during run-time.
My program takes two parameters, does some math calculus with them and std::cout's the values in the end.
My program works if i input somevalues, but if i input other values it says that a variable is being used without being initialized, which i think it makes no sence.

Here is the code:

```<code>#include <iostream>
#include <stdio.h>
#include <cmath>

double align_nb(int n) { return { ceil(n / 512.0)*512.0 }; }    // bytes
double align_pt(int k) { return { floor(k / 512.0)*512.0 }; }   // pointer

int main(int argc, char * argv[])
{
    int o_n = std::atoi(argv[1]);       // original number
    int o_p = std::atoi(argv[2]);       // original pointer

    int max_bytes, new_pointer;         // max bytes to read, new pointer to point

    float log = (std::log(o_n) / std::log(2));
    if (log != floor(log))
    {
        max_bytes = align_nb(o_n);      // bytes alinhados para a frente
        new_pointer = align_pt(o_p);    // ponteiro alinhado atrás
    }

    else if (log == floor(log))
    {
        new_pointer = align_pt(o_p);
        if (max_bytes + (o_p - new_pointer) >max_bytes)
        {
            max_bytes += 512;
        }
    }

    std::cout << "Original bytes= " << o_n << std::endl;
    std::cout << "Original pointer= " << o_p << std::endl;
    std::cout << "Max_bytes= " << max_bytes << std::endl;
    std::cout << "new_pointer= " << new_pointer << std::endl;
    return 0;
}
</code>```

Here are the values i tested it and it crashed, giving me that run-time error:

2048 513

1024 500

here is one example of values were the code doesnt give me that error and the program works:

513 520

Here is a print of the error it gives me.

I'd really appreciate someone explaining me why it gives me that error/how to fix it.
Regardless, thanks!

(PS: math tag is included cause it could be the math in the program that is causing it to crash. If annyone thinks it shoudlnt be used in this question, let me know in the comments and ill remove it.)

(PS 2: the variable it complains when it gives me the run time error is 'max_bytes'.)

答:
If your code takes the else path at line 17, then your code doesn't initialize max_bytes, but uses it afterwards. That's the problem.

Notes:

comparing calculated floating point values for equality usually a bad practice

you don't need the additional if at line 23.

Body:
Im having this really weird error during run-time.
My program takes two parameters, does some math calculus with them and std::cout's the values in the end.
My program works if i input somevalues, but if i input other values it says that a variable is being used without being initialized, which i think it makes no sence.

Here is the code:

#include <iostream>
#include <stdio.h>
#include <cmath>

double align_nb(int n) { return { ceil(n / 512.0)*512.0 }; }    // bytes
double align_pt(int k) { return { floor(k / 512.0)*512.0 }; }   // pointer

int main(int argc, char * argv[])
{
    int o_n = std::atoi(argv[1]);       // original number
    int o_p = std::atoi(argv[2]);       // original pointer

    int max_bytes, new_pointer;         // max bytes to read, new pointer to point

    float log = (std::log(o_n) / std::log(2));
    if (log != floor(log))
    {
        max_bytes = align_nb(o_n);      // bytes alinhados para a frente
        new_pointer = align_pt(o_p);    // ponteiro alinhado atrás
    }

    else if (log == floor(log))
    {
        new_pointer = align_pt(o_p);
        if (max_bytes + (o_p - new_pointer) >max_bytes)
        {
            max_bytes += 512;
        }
    }

    std::cout << "Original bytes= " << o_n << std::endl;
    std::cout << "Original pointer= " << o_p << std::endl;
    std::cout << "Max_bytes= " << max_bytes << std::endl;
    std::cout << "new_pointer= " << new_pointer << std::endl;
    return 0;
}

Here are the values i tested it and it crashed, giving me that run-time error:

2048 513

1024 500

here is one example of values were the code doesnt give me that error and the program works:

513 520

Here is a print of the error it gives me.

I'd really appreciate someone explaining me why it gives me that error/how to fix it.
Regardless, thanks!

(PS: math tag is included cause it could be the math in the program that is causing it to crash. If annyone thinks it shoudlnt be used in this question, let me know in the comments and ill remove it.)

(PS 2: the variable it complains when it gives me the run time error is 'max_bytes'.)


问:
Separate strings by word to a separate line in Python
I have a line in my textfile like the line below:

```<code>hi   everyone  this is good
the weather is good     yes
</code>```

I want to write each string in one line like this:

```<code>  hi
  everyone
  this
</code>```

What should i do? I dont know the number of spaces between each string.

Thank you

I used this method but it didn´t work

```<code>text_file = open("1.txt","r")
for line in text_file :
    lline = list(line)
    lline.replace(" ", "")
    line1 = lline.join()
    file.write(line1)
</code>```

答:
You can just use split function.

like:

```<code> text_file = open("1.txt","r").read()
 for i in text_file.strip().split('\n'):
    [print(j) for j in i.split()]
----
hi
everyone
this
is
good
the
weather
is
good
yes
</code>```

it'll print the result.

Body:
I have a line in my textfile like the line below:

hi   everyone  this is good
the weather is good     yes

I want to write each string in one line like this:

  hi
  everyone
  this

What should i do? I dont know the number of spaces between each string.

Thank you

I used this method but it didn´t work

text_file = open("1.txt","r")
for line in text_file :
    lline = list(line)
    lline.replace(" ", "")
    line1 = lline.join()
    file.write(line1)

Body:
You can just use split function.

like:

 text_file = open("1.txt","r").read()
 for i in text_file.strip().split('\n'):
    [print(j) for j in i.split()]
----
hi
everyone
this
is
good
the
weather
is
good
yes

it'll print the result.


问:
Google Auth api: skip asking for user account and grant scopes only
I'm using the Google Auth api in my app to allow users to sign in with their google credentials. Once they access certain parts of my applications, I want to prompt them for the specific permissions / scopes needed.

Looking at the documentation for Google Auth (https://developers.google.com/identity/sign-in/web/reference#googleusergrantoptions), I noticed that there's a grant call which seems to allow me to ask for different permissions / scopes. However, when using this call, it seems to prompt the user to select an account again. Since I'm already logged into the application, this seems redundant. I've played with the different options I can find in the documentation, but nothing seems to skip the account selection step once you're logged in already.

Does anyone have a working solution or a work-around?

答:
It would be dangerous for Google to make an assumption as to which account the user wishes to apply the grant to. Eg. I might have a GDrive app which copies files between two of my accounts. Therefore the app would have grants to both of my accounts. If it wants to extend a grant, let's say upgrade drive.readonly to drive so it can delete the original file, how would Google know which account the new grant relates to.

My only suggestion is to look at the login_hint which will pre-select the appropriate account.


答:
Try this, just make sure file is a file connection open for writing.</p>

```<code>text_file = open("1.txt","r")
for line in text_file :
    lline = line.split()
    line1 = '\n'.join(lline)
    file.write(line1)
</code>```

Title: Separate strings by word to a separate line in Python

Body:
Try this, just make sure file is a file connection open for writing.

text_file = open("1.txt","r")
for line in text_file :
    lline = line.split()
    line1 = '\n'.join(lline)
    file.write(line1)