问:
PHP File Uploading Issue
I'm currently developing a website where users can upload their music. You can set various genres to display. Now, the problem is that sometimes (no idea why) the upload fails for certain files. An error doesnt get displayed. It's definitely not a permission error, since the uploading works for most files.
I've looked around a lot here already and tried many things, but nothing worked for me.
Here's my code:

HTML

```<code><form method="post" action="musicupload.php" enctype="multipart/form-data">
    Choose an MP3 or WAV file<file></file>
    <br /><br />
    <input type="file" name="fileToUpload" id="fileToUpload" required>
    <br /><br />
    <fieldset>
        Genre
        <br />
        <input type="radio" id="db" name="Genre" value="Dubstep" required checked>
        <label for="db"> Dubstep</label>
        <input type="radio" id="trap" name="Genre" value="Trap" required>
        <label for="trap"> Trap</label>
        <input type="radio" id="BB" name="Genre" value="Bass Boosted" required>
        <label for="bb"> Bass Boosted</label>
        <input type="radio" id="other" name="Genre" value="Other" required>
        <label for="other"> Other</label>
    </fieldset>
    <br />
    <input type="submit" value="Upload Song" name="submit">
</form>
</code>```

PHP

```<code><?php
/**
 * Created by IntelliJ IDEA.
 * User: Marc
 * Date: 04.12.2017
 * Time: 20:07
 */
require 'db.php';

$target_dir = "uploadedmusic/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$filename=$_FILES["fileToUpload"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$genre = $_POST["Genre"];
$successfull = false;

if(isset($_POST["submit"])) {
    // Check extensions
    if ($ext != "mp3" && $ext != "wav") {
        echo "Sorry, only MP3 & WAV files are allowed.";
        $uploadOk = 0;
    }

    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $hash = md5_file("uploadedmusic/".$filename);
            //echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
            $sql = "INSERT INTO `music` (`id`, `filename`, `genre`, `uploaded`, `hash`) VALUES (NULL, '$filename', '$genre', CURRENT_TIMESTAMP, '$hash')";
            $conn->query($sql);
            $successfull = true;
        } else {
            $successfull = false;
        }
    }
}

?>

<html>
<head>
    <title>Upload Music</title>
</head>
<body>
<div style="text-align: center;">
     <img src="logo.png">
<h1>Please wait...</h1>
<p style="font-size: 35px;">
    <?php
    if ($successfull == true) {
        echo "Successfully uploaded ". basename($_FILES["fileToUpload"]["name"])."! Use the search to find it!";
    }
    else {
        echo "Sorry, there was an error uploading your file. Check for potential invalid characters like () or - in your filename!";
    }

    ?>
</p>
    <a style="font-size: 35px" href="main.php">Start listening!</a>
</div>
</body>
</html>
</code>```

答:
You need to see file upload errors to find the exact issue.

```<code>echo $_FILES["fileToUpload"]["error"] // this will give you the error code.
</code>```

Possible errors are. check this link http://php.net/manual/en/features.file-upload.errors.php

```<code>$phpFileUploadErrors = array(
    0 => 'There is no error, the file uploaded with success',
    1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
    2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
    3 => 'The uploaded file was only partially uploaded',
    4 => 'No file was uploaded',
    6 => 'Missing a temporary folder',
    7 => 'Failed to write file to disk.',
    8 => 'A PHP extension stopped the file upload.',
);
</code>```

Also in your code apart from checking extension, you need add condition to check upload errors

```<code>if ($uploadOk == 0 || $_FILES["fileToUpload"]["error"]!== UPLOAD_ERR_OK) {
   echo "Sorry, your file was not uploaded.";
   // if everything is ok, try to upload file
}
</code>```

Title: PHP File Uploading Issue

Body:
I'm currently developing a website where users can upload their music. You can set various genres to display. Now, the problem is that sometimes (no idea why) the upload fails for certain files. An error doesnt get displayed. It's definitely not a permission error, since the uploading works for most files.
I've looked around a lot here already and tried many things, but nothing worked for me.
Here's my code:

HTML

<form method="post" action="musicupload.php" enctype="multipart/form-data">
    Choose an MP3 or WAV file<file></file>

    <input type="file" name="fileToUpload" id="fileToUpload" required>

    <fieldset>
        Genre

        <input type="radio" id="db" name="Genre" value="Dubstep" required checked>
         Dubstep
        <input type="radio" id="trap" name="Genre" value="Trap" required>
         Trap
        <input type="radio" id="BB" name="Genre" value="Bass Boosted" required>
         Bass Boosted
        <input type="radio" id="other" name="Genre" value="Other" required>
         Other
    </fieldset>

    <input type="submit" value="Upload Song" name="submit">
</form>

PHP

<?php
/**
 * Created by IntelliJ IDEA.
 * User: Marc
 * Date: 04.12.2017
 * Time: 20:07
 */
require 'db.php';

$target_dir = "uploadedmusic/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$filename=$_FILES["fileToUpload"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$genre = $_POST["Genre"];
$successfull = false;

if(isset($_POST["submit"])) {
    // Check extensions
    if ($ext != "mp3" && $ext != "wav") {
        echo "Sorry, only MP3 & WAV files are allowed.";
        $uploadOk = 0;
    }

    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $hash = md5_file("uploadedmusic/".$filename);
            //echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
            $sql = "INSERT INTO `music` (`id`, `filename`, `genre`, `uploaded`, `hash`) VALUES (NULL, '$filename', '$genre', CURRENT_TIMESTAMP, '$hash')";
            $conn->query($sql);
            $successfull = true;
        } else {
            $successfull = false;
        }
    }
}

?>

    <title>Upload Music</title>

Please wait...

    <?php
    if ($successfull == true) {
        echo "Successfully uploaded ". basename($_FILES["fileToUpload"]["name"])."! Use the search to find it!";
    }
    else {
        echo "Sorry, there was an error uploading your file. Check for potential invalid characters like () or - in your filename!";
    }

    ?>

    Start listening!

Body:
You need to see file upload errors to find the exact issue.

echo $_FILES["fileToUpload"]["error"] // this will give you the error code.

Possible errors are. check this link http://php.net/manual/en/features.file-upload.errors.php

$phpFileUploadErrors = array(
    0 => 'There is no error, the file uploaded with success',
    1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
    2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
    3 => 'The uploaded file was only partially uploaded',
    4 => 'No file was uploaded',
    6 => 'Missing a temporary folder',
    7 => 'Failed to write file to disk.',
    8 => 'A PHP extension stopped the file upload.',
);

Also in your code apart from checking extension, you need add condition to check upload errors

if ($uploadOk == 0 || $_FILES["fileToUpload"]["error"]!== UPLOAD_ERR_OK) {
   echo "Sorry, your file was not uploaded.";
   // if everything is ok, try to upload file
}


来源: stackexchange

问:
containsString: issue
expression contains XXXXXX.DATETIME
array contains {DATE, DATETIME}

On the loop, checking the expression contains DATE.
Both the things are true. But I want only DATE has to go through.

```<code>NSArray *array = [[NSArray alloc] initWithObjects: @"DATE", @"DATETIME", nil]];

for (int i=0; i<[array count]; i++) {
    NSString *formatType = [array objectAtIndex:i];
    if ([expression containsString:formatType]){
        NSLog(@"%@", expression);
    }
}
</code>```

Is there any other options other than containsString ?

答:
I'm not sure exactly what you are asking, this is my guess:

You have a collection (array) containing a number of words some of which are prefixes of others (e.g. DATE is a prefix of DATETIME). This is a dynamic array, i.e. you don't know in advance what the words will be (or else you would trim it at compile time).

You have a string (expression) which may contain one or more of the words in your collection.

For every word in your collection if your string contains one or more occurrences of that word then you wish to do something (in your example represented by NSLog) unless your collection also contains another word which is a prefix of the word, which means your string also contains the shorter word, in which case you only wish to report a match for the shorter word.

If this reading of your question is correct then preprocessing your collection so it does not contain any words which are extensions of others is one way to tackle this. In pseudo code this would be:

```<code>array = original collection, say "ERA", "DATETIME", "DATE"
sortedArray = lexicographic sort of array, e.g. see NSArray's sortedArrayUsingComparator:
   our sample would produce "DATE", "DATETIME", "ERA"

lastWord = first word of sortedArray
trimmedArray = new mutable array containing just lastWord

for each nextWord in sortedArray
   if NOT lastWord is prefix of nextWord (see NSString's hasPrefix:)
      add nextWord to trimmedArray
      lastWord = nextWord
   end if
end for
</code>```

The end result of the above with our sample would be @[ "DATE", "ERA" ]. Use this result in your original code instead of array.

HTH

ContentLicense: CC BY-SA 3.0

Title: containsString: issue

Body:
expression contains XXXXXX.DATETIME
array contains {DATE, DATETIME}

On the loop, checking the expression contains DATE.
Both the things are true. But I want only DATE has to go through.

NSArray *array = [[NSArray alloc] initWithObjects: @"DATE", @"DATETIME", nil]];

for (int i=0; i<[array count]; i++) {
    NSString *formatType = [array objectAtIndex:i];
    if ([expression containsString:formatType]){
        NSLog(@"%@", expression);
    }
}

Is there any other options other than containsString ?

Body:
I'm not sure exactly what you are asking, this is my guess:

You have a collection (array) containing a number of words some of which are prefixes of others (e.g. DATE is a prefix of DATETIME). This is a dynamic array, i.e. you don't know in advance what the words will be (or else you would trim it at compile time).

You have a string (expression) which may contain one or more of the words in your collection.

For every word in your collection if your string contains one or more occurrences of that word then you wish to do something (in your example represented by NSLog) unless your collection also contains another word which is a prefix of the word, which means your string also contains the shorter word, in which case you only wish to report a match for the shorter word.

If this reading of your question is correct then preprocessing your collection so it does not contain any words which are extensions of others is one way to tackle this. In pseudo code this would be:

array = original collection, say "ERA", "DATETIME", "DATE"
sortedArray = lexicographic sort of array, e.g. see NSArray's sortedArrayUsingComparator:
   our sample would produce "DATE", "DATETIME", "ERA"

lastWord = first word of sortedArray
trimmedArray = new mutable array containing just lastWord

for each nextWord in sortedArray
   if NOT lastWord is prefix of nextWord (see NSString's hasPrefix:)
      add nextWord to trimmedArray
      lastWord = nextWord
   end if
end for

The end result of the above with our sample would be @[ "DATE", "ERA" ]. Use this result in your original code instead of array.

HTH


问:
Problem with ad-hoc distribution in iPhone
I am having a problem with ad-hoc distribution in iPhone. I have developed an application in sdk 3.2. I have developer's license (which was expired Today).  but my provisoning profile is valid. I made a build before my developer's licesee expired.

But when I try to install the app on my iPhone, i got an error
"Could not install application on device. Error: A signed resource has been added, modified, or deleted."

Please Help me ...

答:
Did you check this thread? http://www.iphonedevsdk.com/forum/iphone-sdk-development/21988-xcode-issue-signed-resource-has-been-added-modified-deleted.html.

It has many solutions that could be yours.

ContentLicense: CC BY-SA 2.5


问:
mutate case _when error in R
Can someone tell me what is wrong with this chunk of code:

```<code>df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A"
    age %in% 20:40 ~ "B"
    age %in% 40:60 ~ "C"
    age %in% 60:80 ~ "D"
    age %in% 80:100 ~ "E"
     T ~ ""))
</code>```

I get error saying: Error: unexpected symbol in:
"age %in% 0:20 ~ "A" I believe ~ is the problem, but not sure how to solve it.

Thank you

答:
You need commas between the cases (source):

```<code>df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A",
    age %in% 20:40 ~ "B",
    age %in% 40:60 ~ "C",
    age %in% 60:80 ~ "D",
    age %in% 80:100 ~ "E",
     T ~ ""))
</code>```

However, you also might want to think about www's comment in the case that age might take a non-integer value.

Title: mutate case _when error in R

Body:
Can someone tell me what is wrong with this chunk of code:

df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A"
    age %in% 20:40 ~ "B"
    age %in% 40:60 ~ "C"
    age %in% 60:80 ~ "D"
    age %in% 80:100 ~ "E"
     T ~ ""))

I get error saying: Error: unexpected symbol in:
"age %in% 0:20 ~ "A" I believe ~ is the problem, but not sure how to solve it.

Thank you

Body:
You need commas between the cases (source):

df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A",
    age %in% 20:40 ~ "B",
    age %in% 40:60 ~ "C",
    age %in% 60:80 ~ "D",
    age %in% 80:100 ~ "E",
     T ~ ""))

However, you also might want to think about www's comment in the case that age might take a non-integer value.


问:
accessing resources within nested react-routes using webpack file-loader
I have recently switched my routing using react-router from hashHistory to browserHistory. There is a problem though. Everytime I access a nested route and try and refresh the page, public resources such as my logo can't be found as it uses the first part of the nested route as the root for the resource.

In my index.js I require the image as follows:

```<code>require('./images/logo-icon.png');
</code>```

I am using a logo in my Navigation Bar component as follows:

```<code>      <Link to="/" className="gc-padding-none">
        <img alt="Get Cooked" className="gc-logo-default" src="images/logo-icon.png" />
      </Link>
</code>```

and here are my routes:

```<code> <Route path="/" component={NavigationBar}>
    <IndexRoute component={Home} />
    <Route path="/chefs" component={ProfileList} />
    <Route exact path="register" component={Register} redirect />
      <Route path="chef">
          <Route path="register" component={RegisterChef} />
      </Route>
</Route>
</code>```

and here is my webpack config:

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
    inline: true,
    contentBase: './client',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};
</code>```

Every time I go to '/' or '/chefs' everything loads fine, however, when I access a nested route such as '/chef/register' and refresh my browser the logo cannot be found in the Navigation Bar component.

The error below is presented:

```<code>logo-icon.png:1 GET http://localhost:8080/chef/images/logo-icon.png 404 (Not Found)
</code>```

As you can see the logo is trying to be fetched from a location which includes the first part of my route '/chef'.

I have tried removing the publicPath configuration in my webpack, however, that affects the rendering of nested components on refresh.

Any ideas on why this is happening?

答:
To explain elmeister's comment,

images/logo-icon.png is a relative path making it dependent upon the current path.

So the request for images/logo-icon.png from url http://localhost:8080/chef/ results in a request for http://localhost:8080/chef/images/logo-icon.png.

/images/logo-icon.png is an absolute path ensuring the path is always based upon the root of the site, no matter what the current path might be.

So a request for /images/logo-icon.png from url http://localhost:8080/chef/ will result in a request for http://localhost:8080/images/logo-icon.png.

Body:
I have recently switched my routing using react-router from hashHistory to browserHistory. There is a problem though. Everytime I access a nested route and try and refresh the page, public resources such as my logo can't be found as it uses the first part of the nested route as the root for the resource.

In my index.js I require the image as follows:

require('./images/logo-icon.png');

I am using a logo in my Navigation Bar component as follows:

      <Link to="/" className="gc-padding-none">

      </Link>

and here are my routes:

 <Route path="/" component={NavigationBar}>
    <IndexRoute component={Home} />
    <Route path="/chefs" component={ProfileList} />
    <Route exact path="register" component={Register} redirect />
      <Route path="chef">
          <Route path="register" component={RegisterChef} />
      </Route>
</Route>

and here is my webpack config:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
    inline: true,
    contentBase: './client',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

Every time I go to '/' or '/chefs' everything loads fine, however, when I access a nested route such as '/chef/register' and refresh my browser the logo cannot be found in the Navigation Bar component.

The error below is presented:

logo-icon.png:1 GET http://localhost:8080/chef/images/logo-icon.png 404 (Not Found)

As you can see the logo is trying to be fetched from a location which includes the first part of my route '/chef'.

I have tried removing the publicPath configuration in my webpack, however, that affects the rendering of nested components on refresh.

Any ideas on why this is happening?


问:
Showing lines with different colors on a Silverlight Toolkit’s LineChart?
Hy,

I have a chart,wich is created in runtime,this could be Line,
Bar or Pie type.

Basically what i want is to have more contrast on the lines on the chart,this means i should use different colors on the lines.

For Bar chart i use the StylePalette property to set wich colors will used in the chart,and it's working fine,but for Line it has no effect.

As a Line chart i tried this:
For the line i want to use  lets say 2 colors.

```<code>    Style style = new Style(typeof(Control));
     Setter st = new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Red));
     style.Setters.Add(st);
     Style style2 = new Style(typeof(Control));
Setter st2 = new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Green));
                style2.Setters.Add(st2);

                StylePalette palette = new StylePalette();
                palette.Add(style);
                palette.Add(style2);

                m_oChart.StylePalette = palette;
</code>```

And this in the xaml file:

```<code><chartingToolkit:Chart x:Name="m_oChart" Style="{StaticResource ChartStyleLegendBottom}" d:IsHidden="True">
                    <chartingToolkit:Chart.StylePalette>
                        <visualizationToolkit:StylePalette>
                            <Style TargetType="Control">
                                <Setter Property="Background" Value="Gray"/>
                            </Style>
                            <Style TargetType="Control">
                                <Setter Property="Background" Value="Black"/>
                            </Style>
                        </visualizationToolkit:StylePalette>
                    </chartingToolkit:Chart.StylePalette>
                </chartingToolkit:Chart>
</code>```

Note that i tried for Background and Foreground propertys too both on the xaml and codebehind side.

I've done this according to this link:

http://forums.silverlight.net/forums/t/58894.aspx

Basically what i want is to have more contrast on the lines on the chart,this means i should use different colors on the lines.
I use this example to demonstrate the problem i'm facing in this particular situation.

Does somebody have this problem?
Did somebody have any solution for that?

答:
All this Silverlight Charting is poorly/randomly documented.

Beware StylePalette has been dropped in Silverlight4 and new mechanism & chart types released which is/are more consistent with other objects

Body:
Hy,

I have a chart,wich is created in runtime,this could be Line,
Bar or Pie type.

Basically what i want is to have more contrast on the lines on the chart,this means i should use different colors on the lines.

For Bar chart i use the StylePalette property to set wich colors will used in the chart,and it's working fine,but for Line it has no effect.

As a Line chart i tried this:
For the line i want to use  lets say 2 colors.

    Style style = new Style(typeof(Control));
     Setter st = new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Red));
     style.Setters.Add(st);
     Style style2 = new Style(typeof(Control));
Setter st2 = new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Green));
                style2.Setters.Add(st2);

                StylePalette palette = new StylePalette();
                palette.Add(style);
                palette.Add(style2);

                m_oChart.StylePalette = palette;

And this in the xaml file:

<chartingToolkit:Chart x:Name="m_oChart" Style="{StaticResource ChartStyleLegendBottom}" d:IsHidden="True">
                    <chartingToolkit:Chart.StylePalette>
                        <visualizationToolkit:StylePalette>

                        </visualizationToolkit:StylePalette>
                    </chartingToolkit:Chart.StylePalette>
                </chartingToolkit:Chart>

Note that i tried for Background and Foreground propertys too both on the xaml and codebehind side.

I've done this according to this link:

http://forums.silverlight.net/forums/t/58894.aspx

Basically what i want is to have more contrast on the lines on the chart,this means i should use different colors on the lines.
I use this example to demonstrate the problem i'm facing in this particular situation.

Does somebody have this problem?
Did somebody have any solution for that?


问:
Can not upload Unity WebGL in ASP.Net with an error of "The error was: SyntaxError: expected expression, got '<"
I built some sample game in Unity in WebGL and it worked well locally. However, when I tried to put it on my ASP.net MVC, it did not work.

I simply created my ASP.NET MVC project and copied my Unity WebGl Build into the project.

My ASP.NET MVC

But when I ran the web project and opened my Unity WebGL Build, I got an error of "An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was: SyntaxError: expected expression, got '<"

Error

If anyone knows how to solve this problem, please kindly help me.

Thank you in advance.

答:
Sorry for my unclear question.

First, I did not write any code. The code in the first picture is from the html file built by Unity

I navigated further into JavaScript console. I got the following error:

Error for Console

SyntaxError: expected expression, got '<'

TypeError:UnityLoader[r] is not a function in UnityLoader.js

Note: It works properly locally.

Thank you.


问:
Is there a shorter way to provide an Observable onComplete handler?

I'm working with an Observable chain and I'm not interested in the next or error values, only when the chain has fully complete.  It feels wrong to tap into the subscribe method and supply 2 noops for next and error just so I can provide an onComplete callback.

For Example:

```<code>let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .subscribe(
    () => {},
    () => {},
    () => isRunning = false;
  );
</code>```

What I'd like is something that looks like this

```<code>let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .onComplete(() => isRunning = false);
</code>```

答:
Shortest form would be use observer object.

obs.subscribe({ complete: () => isRunning = false });

Body:
I'm working with an Observable chain and I'm not interested in the next or error values, only when the chain has fully complete.  It feels wrong to tap into the subscribe method and supply 2 noops for next and error just so I can provide an onComplete callback.

For Example:

let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .subscribe(
    () => {},
    () => {},
    () => isRunning = false;
  );

What I'd like is something that looks like this

let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .onComplete(() => isRunning = false);


问:
Hiding master for nested UISplitViewControlles's details
Apple is encouraging us to use UISplitViewController for Universal apps, but anytime I try it I face a brick wall.

I've created my app based on UINavigationController as it was iPhone only so far, but now with switching to Universal we want to have a Master-Details for one screen, so it was natural for me to reach for UISplitViewController. I've started simple with Master-Detail App Template and I just wanted to check whether it resizes correctly for different devices and screen sizes.

Template is clear and everything works smooth, but as I've mentioned - I want this Master-Detail to be visible only for one screen at the moment (maybe more in the future), so... I've added new View Controller to the Storyboard and now it look like:

Everything works great on iPhones, but when it comes to iPads I can see a Master View Controller all the time. What I want to achieve is to hide it once we get deeper in the Details View Controller hierarchy. Is it actually possible?

Since it's only for one view I was also thinking about creating separate Storyboard for iPad and have this one screen being represented as UIViewController with two UIContainerViews, but I'm not sure whether it's worth an overhead with maintaining 2 Storyboards just for this...

答:
At launch did you set the preferredDisplayMode to .primaryHidden? For example, if your reference to the split view controller is splitviewctlr, try this at launch:

```<code>splitviewctlr.preferredDisplayMode = .primaryHidden
</code>```

That should hide the primary when on the iPad.

You should also assign a delegate for the split view controller and implement the targetDisplayModeForAction(in:) method in the delegate to control which controller appears when the user clicks the back button.

Another useful property of the split view controller is isCollapsed, a boolean to test whether the interface is collapsed to the detail controller or not.

Body:
At launch did you set the preferredDisplayMode to .primaryHidden? For example, if your reference to the split view controller is splitviewctlr, try this at launch:

splitviewctlr.preferredDisplayMode = .primaryHidden

That should hide the primary when on the iPad.

You should also assign a delegate for the split view controller and implement the targetDisplayModeForAction(in:) method in the delegate to control which controller appears when the user clicks the back button.

Another useful property of the split view controller is isCollapsed, a boolean to test whether the interface is collapsed to the detail controller or not.


问:
How to use Where operator in Linq
```<code>SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported
</code>```

but why when I use number instead of parameter it works fine ?

```<code>SomeObject.Where(p => FunctionOn(1));
</code>```

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

答:
As others have mentioned, your FunctionOn method isn't directly translatable by your data source.

However, there may be a way around it - depending upon what sort of comparison you need to do, and how big of a comparison you're making.

If instead, you create an extension method which takes an IQueryable<T> and returns IQueryable<T> you can write your expression directly.

This allows you to re-use complex expressions. You should also be able to compare against a list of reference data - however you'll need to take care that this comparison list doesn't exceed the parameters permitted for your datasource.

Example:

```<code>static void Main(string[] args)
{

    var data = new List<Customer>
                {
                    new Customer {Id = 1, Name = "Anna"},
                    new Customer {Id = 2, Name = "Bob"},
                    new Customer {Id = 3, Name = "Claire"}
                };

    var result = data.AsQueryable().TestCustomer();

}

private static IQueryable<Customer> TestCustomer(this IQueryable<Customer> source)
{
    return source.Where(x => x.Id > 1);
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

Title: How to use Where operator in Linq

Body:
SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported

but why when I use number instead of parameter it works fine ?

SomeObject.Where(p => FunctionOn(1));

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

Body:
As others have mentioned, your FunctionOn method isn't directly translatable by your data source.

However, there may be a way around it - depending upon what sort of comparison you need to do, and how big of a comparison you're making.

If instead, you create an extension method which takes an IQueryable<T> and returns IQueryable<T> you can write your expression directly.

This allows you to re-use complex expressions. You should also be able to compare against a list of reference data - however you'll need to take care that this comparison list doesn't exceed the parameters permitted for your datasource.

Example:

static void Main(string[] args)
{

    var data = new List<Customer>
                {
                    new Customer {Id = 1, Name = "Anna"},
                    new Customer {Id = 2, Name = "Bob"},
                    new Customer {Id = 3, Name = "Claire"}
                };

    var result = data.AsQueryable().TestCustomer();

}

private static IQueryable<Customer> TestCustomer(this IQueryable<Customer> source)
{
    return source.Where(x => x.Id > 1);
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}


问:
Communication between angular 2 and pure javascript
I am building an angular application and i am in a situation where i have to communicate with an external javascript.

Scenario
During app initialization, i inject two iframes into index.html using

```<code>document.body.appendChild(iframe);
</code>```

I have script running in index.html and has a multiple functions among which one is getData();  I have to send data to this function from the angular app component when the app initialises. How to go about this ? I know how to communicate from javascript to angular but not the other way round. Please help me. I am struck.

答:
The basic communication can be performed via callbacks.

A callback can be defined either by Angular or non-Angular application. depending on the direction of communication.

```<code>@Injectable()
class GlobalService {
  constructor() {
    window.vanillaToAngularCallback = data => {
      // communicate with other Angular providers
    }
  }
}
</code>```

And/or

```<code>window.angularToVanillaCallback = data => {
  // communicate with other vanilla JS code
}
</code>```

Where angularToVanillaCallback is supposed to be called inside Angular, and vanillaToAngularCallback is called outside Angular. The time of first callback calls should be chosen correctly; callbacks shouldn't be called by one side until they will be defined by another side.

It's still preferable to keep non-Angular part as a Webpack bundle. This way the reference to window can be avoided, and common classes can be used for communication with Angular part, either via callbacks or RxJS subjects.

Body:
I am building an angular application and i am in a situation where i have to communicate with an external javascript.

Scenario
During app initialization, i inject two iframes into index.html using

document.body.appendChild(iframe);

I have script running in index.html and has a multiple functions among which one is getData();  I have to send data to this function from the angular app component when the app initialises. How to go about this ? I know how to communicate from javascript to angular but not the other way round. Please help me. I am struck.

Body:
The basic communication can be performed via callbacks.

A callback can be defined either by Angular or non-Angular application. depending on the direction of communication.

@Injectable()
class GlobalService {
  constructor() {
    window.vanillaToAngularCallback = data => {
      // communicate with other Angular providers
    }
  }
}

And/or

window.angularToVanillaCallback = data => {
  // communicate with other vanilla JS code
}

Where angularToVanillaCallback is supposed to be called inside Angular, and vanillaToAngularCallback is called outside Angular. The time of first callback calls should be chosen correctly; callbacks shouldn't be called by one side until they will be defined by another side.

It's still preferable to keep non-Angular part as a Webpack bundle. This way the reference to window can be avoided, and common classes can be used for communication with Angular part, either via callbacks or RxJS subjects.


问:
Unable to change to another activity
I want to change from main activity to login activity through button log in. i followed all the steps but it still doesn't work when i test it on my device.

this is main.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

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

    View v = findViewById(R.id.buttonlog);
    v.setOnClickListener((View.OnClickListener) this);

}

@Override
public void onClick(View v) {
    if(v.getId()==R.id.buttonlog)
    {
        Intent intent = new Intent(this,LoginActivity.class);
        this.startActivity(intent);
    }
}}
</code>```

Login activity is:

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

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

  }
}
</code>```

The Logcat:

```<code>12-06 19:57:03.960 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd V/BoostFramework: BoostFramework() : mPerf = null
12-06 19:57:04.046 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.435 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:04.522 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.791 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
12-06 19:57:04.837 6374-6374/com.example.ancaalexandra.proiectandroidd D/AndroidRuntime: Shutting down VM
12-06 19:57:04.838 6374-6374/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 6374
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ancaalexandra.proiectandroidd/com.example.ancaalexandra.proiectandroidd.LoginActivity}: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
                                                                                Caused by: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
                                                                                at com.example.ancaalexandra.proiectandroidd.LoginActivity.onCreate(LoginActivity.java:19)
                                                                                at android.app.Activity.performCreate(Activity.java:6956)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

I declared both activities in the manifest file. What i did wrong? thank you!

答:
Your error is on this line:

```<code>v.setOnClickListener((View.OnClickListener) this);
</code>```

which is explained in your stacktrace:

```<code>LoginActivity cannot be cast to android.view.View$OnClickListener
</code>```

You are trying to cast your Activity LoginActivityto an OnClickListener, which won't work.

If your Activity implements an OnClickListener you just need to pass this :

```<code>class LoginActivity extends Activity implements OnClickListener {

    protected void onCreate(Bundle savedValues) {
        ...
        v.setOnClickListener(this)
    }

}
</code>```

Title: Unable to change to another activity

Body:
I want to change from main activity to login activity through button log in. i followed all the steps but it still doesn't work when i test it on my device.

this is main.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

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

    View v = findViewById(R.id.buttonlog);
    v.setOnClickListener((View.OnClickListener) this);

}

@Override
public void onClick(View v) {
    if(v.getId()==R.id.buttonlog)
    {
        Intent intent = new Intent(this,LoginActivity.class);
        this.startActivity(intent);
    }
}}

Login activity is:

 public class LoginActivity extends AppCompatActivity {

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

  }
}

The Logcat:

12-06 19:57:03.960 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd V/BoostFramework: BoostFramework() : mPerf = null
12-06 19:57:04.046 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.435 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:04.522 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.791 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl@c94e23f[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
12-06 19:57:04.837 6374-6374/com.example.ancaalexandra.proiectandroidd D/AndroidRuntime: Shutting down VM
12-06 19:57:04.838 6374-6374/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 6374
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ancaalexandra.proiectandroidd/com.example.ancaalexandra.proiectandroidd.LoginActivity}: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
                                                                                Caused by: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
                                                                                at com.example.ancaalexandra.proiectandroidd.LoginActivity.onCreate(LoginActivity.java:19)
                                                                                at android.app.Activity.performCreate(Activity.java:6956)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

I declared both activities in the manifest file. What i did wrong? thank you!

Body:
Your error is on this line:

v.setOnClickListener((View.OnClickListener) this);

which is explained in your stacktrace:

LoginActivity cannot be cast to android.view.View$OnClickListener

You are trying to cast your Activity LoginActivityto an OnClickListener, which won't work.

If your Activity implements an OnClickListener you just need to pass this :

class LoginActivity extends Activity implements OnClickListener {

    protected void onCreate(Bundle savedValues) {
        ...
        v.setOnClickListener(this)
    }

}


问:
Unexpected error message while joining data.table with rbindlist() using mget()
While preparing this answer, I've got the error message

Error: value for ‘spine_hlfs’ not found

from running

```<code>setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]
</code>```

while

```<code>df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]
</code>```

works as expected.

Before reporting an issue on github, I want to verify with the community that this indeed is a bug or if there is a simple explanation for the error message which I'm unaware of.

Reproducible example

```<code>set.seed(123L)
giraffe <- data.frame(runkey = 1:500,
                      X2 = sample.int(99L, 500L, TRUE),
                      X3 = sample.int(99L, 500L, TRUE),
                      X4 = sample.int(99L, 500L, TRUE),
                      project = "",
                      stringsAsFactors = FALSE)
spine_hlfs <- data.frame(runkey = c(1L, 498L, 5L))
ir_dia     <- data.frame(runkey = c(3L, 499L, 47L, 327L))
df_names <- c("spine_hlfs", "ir_dia")
library(data.table)

# this creates the error message
setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]
## Error: value for ‘spine_hlfs’ not found

# this works as expected
df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]
</code>```

答:
This is basically because (unlike get) mget has inherits = FALSE as default. Hence it only looks in the local environment. Changing to mget(df_names, inherits = TRUE) (or, if you want to be explicit to mget(df_names, envir = .GlobalEnv)) should fix this.

This was independently reported by @Arun on GH a while ago and he intends to change the default behavior of mget (while used within a data.table) to be consistent with get in the future, so stay tuned.

Body:
While preparing this answer, I've got the error message

Error: value for ‘spine_hlfs’ not found

from running

setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]

while

df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]

works as expected.

Before reporting an issue on github, I want to verify with the community that this indeed is a bug or if there is a simple explanation for the error message which I'm unaware of.

Reproducible example

set.seed(123L)
giraffe <- data.frame(runkey = 1:500,
                      X2 = sample.int(99L, 500L, TRUE),
                      X3 = sample.int(99L, 500L, TRUE),
                      X4 = sample.int(99L, 500L, TRUE),
                      project = "",
                      stringsAsFactors = FALSE)
spine_hlfs <- data.frame(runkey = c(1L, 498L, 5L))
ir_dia     <- data.frame(runkey = c(3L, 499L, 47L, 327L))
df_names <- c("spine_hlfs", "ir_dia")
library(data.table)

# this creates the error message
setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]
## Error: value for ‘spine_hlfs’ not found

# this works as expected
df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]


答:
Your way of handling findViewById() and setting onClick listener is quite unusual.

Change this code :

```<code>View v = findViewById(R.id.buttonlog);
v.setOnClickListener((View.OnClickListener) this);
</code>```

to this code :

```<code> Button loginButton = (Button)findViewById(R.id.buttonlog);
    loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
            }
        });
</code>```

And it should work just fine.

Title: Unable to change to another activity

Body:
Your way of handling findViewById() and setting onClick listener is quite unusual.

Change this code :

View v = findViewById(R.id.buttonlog);
v.setOnClickListener((View.OnClickListener) this);

to this code :

 Button loginButton = (Button)findViewById(R.id.buttonlog);
    loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
            }
        });

And it should work just fine.


问:
R: Fast multiply selected rows in data.frame (or other data structure)
I have an object of type data.frame like this, but much bigger:

```<code>> head(mydf)
   id1     id2   n
1    0 1032142   3
2    0 1072163   1
3    0  119323   2
</code>```

I need to print to a file columns a1 and a1, each of them n times. So that I could get a file like that:

```<code>0 1032142
0 1032142
0 1032142
0 1072163
0  119323
0  119323
</code>```

I tried the following solutions, but they make use of explicit for loops and are incredibly slow (it take few days to finish them with my data...):

```<code>for (j in 1:(nrow(mydf))) for (i in 1:(mydf[j,"n"])) write.table( mydf[j,c("id1","id2")], file="trials", append=T, row.names= F, col.names=F )
</code>```

The other tries to build a new data.frame with multiplied rows, but it is even slower to run.

```<code>towrite=data.frame(); for (j in 1:(nrow(mydf))) for (i in 1:(mydf[j,"n"])) towrite=rbind(towrite,mydf[j,c("id1","id2")])
</code>```

What is the simplest and fastest way of resolving this under R?

答:
Try subsetting  your data and save in one batch:

```<code>mydf[rep(1:nrow(mydf), mydf$n), ]
</code>```

If your data is numeric, then manipulating the matrix is much faster:

```<code>mymat <- as.matrix(mydf)
reps <- as.integer(mydf$n)
mymat[rep(1:nrow(mymat), reps), ]

  id1     id2 n
1   0 1032142 3
1   0 1032142 3
1   0 1032142 3
2   0 1072163 1
3   0  119323 2
3   0  119323 2
</code>```

If you managed to manipulate your original data.frame, then you will probably be able to handle the above matrix.

Body:
I have an object of type data.frame like this, but much bigger:

> head(mydf)
   id1     id2   n
1    0 1032142   3
2    0 1072163   1
3    0  119323   2

I need to print to a file columns a1 and a1, each of them n times. So that I could get a file like that:

0 1032142
0 1032142
0 1032142
0 1072163
0  119323
0  119323

I tried the following solutions, but they make use of explicit for loops and are incredibly slow (it take few days to finish them with my data...):

for (j in 1:(nrow(mydf))) for (i in 1:(mydf[j,"n"])) write.table( mydf[j,c("id1","id2")], file="trials", append=T, row.names= F, col.names=F )

The other tries to build a new data.frame with multiplied rows, but it is even slower to run.

towrite=data.frame(); for (j in 1:(nrow(mydf))) for (i in 1:(mydf[j,"n"])) towrite=rbind(towrite,mydf[j,c("id1","id2")])

What is the simplest and fastest way of resolving this under R?

Body:
Try subsetting  your data and save in one batch:

mydf[rep(1:nrow(mydf), mydf$n), ]

If your data is numeric, then manipulating the matrix is much faster:

mymat <- as.matrix(mydf)
reps <- as.integer(mydf$n)
mymat[rep(1:nrow(mymat), reps), ]

  id1     id2 n
1   0 1032142 3
1   0 1032142 3
1   0 1032142 3
2   0 1072163 1
3   0  119323 2
3   0  119323 2

If you managed to manipulate your original data.frame, then you will probably be able to handle the above matrix.


问:
Sticky text in a table cell
I've got this basic table inside a wrapper

Let's say the wrapper is 1000px wide, and the table is 10000px wide.

The table has 100 columns, and the top row is 10 columns with a colspan of 10.

All this is made by angularjs and some ng-repeat

```<code><div class="wrapper">
    <table>
        <tbody>
        <tr> <!-- Just 1 -->
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
        </tr>
        </tbody>
        <tbody>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        </tbody>
    </table>
</div>
</code>```

I want the span with some text to stick to the edge of the container

left: 0

But it won't

Is it possible to make the content inside a td to stick?

答:
Looking for something like this?

.wrapper {position:relative;}

.wrapper tr:first-child td {height:1.2em}

.wrapper tr:first-child span {position:fixed}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
    <table>
        <tbody>
        <tr> <!-- Just 1 -->
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
        </tr>
        </tbody>
        <tbody>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        </tbody>
    </table>
</div></code>```

The styles are really straightforward; the only trick I had to use was to give the top td elements a certain height, because otherwise they would collapse and the second row would appear in the same position as the first.

If this is NOT what you mean, please edit the question and clarify!

Title: Sticky text in a table cell

Body:
I've got this basic table inside a wrapper

Let's say the wrapper is 1000px wide, and the table is 10000px wide.

The table has 100 columns, and the top row is 10 columns with a colspan of 10.

All this is made by angularjs and some ng-repeat

                Some text

            content X

I want the span with some text to stick to the edge of the container

left: 0

But it won't

Is it possible to make the content inside a td to stick?

Body:
Looking for something like this?

.wrapper {position:relative;}

.wrapper tr:first-child td {height:1.2em}

.wrapper tr:first-child span {position:fixed}

<div class="wrapper">
    <table>
        <tbody>
        <tr> <!-- Just 1 -->
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
            <td colspan="10"> <!-- Repeat for 10 -->
                <span>Some text</span>
            </td>
        </tr>
        </tbody>
        <tbody>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        <tr> <!-- Repeat for 7 -->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
            <td>content X</td> <!-- Repeat for 100-->
        </tr>
        </tbody>
    </table>
</div>

The styles are really straightforward; the only trick I had to use was to give the top td elements a certain height, because otherwise they would collapse and the second row would appear in the same position as the first.

If this is NOT what you mean, please edit the question and clarify!


问:
String replace Hash using regex with special condition (lookahead / lookbehind)
Lets stay I have the following list of string, in JavaScript (NodeJS) I want to apply a regex one at a time and replace the hash between . and ., but I don't want to replace the word, .style. or .bundle. or .chunk. and it should also work to replace the hash in the case where there is no preceding dots.

```<code>// hash starts with number
/css/app.style.7fef363d5a8c4ef2458c.css
/css/app.bundle.7fef363d5a8c4ef2458c.css
/css/app.chunk.7fef363d5a8c4ef2458c.css
/css/app.7fef363d5a8c4ef2458c.css
/css/loading-animation.7fef363d5a8c4ef2458c.css

// hash starts with letter
/css/app.style.b3bcb606396f0c96623a.css
/css/app.bundle.b3bcb606396f0c96623a.css
/css/app.chunk.b3bcb606396f0c96623a.css
/css/app.b3bcb606396f0c96623a.css

// no preceeding dot separated name before the hash
/css/loading-animation.b3bcb606396f0c96623a.css
/css/app.b3bcb606396f0c96623a.js

// It should not affect items without a hash
/fonts/MaterialIcons-Regular.eot
/fonts/MaterialIcons-Regular.svg
</code>```

The result should be

```<code>// hash starts with number
/css/app.style.css
/css/app.bundle.css
/css/app.chunk.css
/css/app.css
/css/loading-animation.css

// hash starts with letter
/css/app.style.css
/css/app.bundle.css
/css/app.chunk.css
/css/app.css

// no preceeding dot separated name before the hash
/css/loading-animation.css
/css/app.js

// It should not affect items without a hash
/fonts/MaterialIcons-Regular.eot
/fonts/MaterialIcons-Regular.svg
</code>```

I tried hard and the closest I got was this

```<code> const manifest = {};
 stats.assets.map(asset => asset.name)
    .sort()
    .forEach((file) => {
       let regEx = /\.(?!(?:[A-Za-z]))(([^.]*))\./gi
       let passTest = regEx.test(file);
       let key = file.replace(regEx, '.');
       console.log(file, passTest, key);
       manifest[key] = file;
    });
</code>```

But that only replaces the hash starting with the number, and ignores all the rest.

I also tried /\.(?!(?:[A-Za-z]))(([^.]*))\./gi; but that just replaced the first occurrence of .something.

I also had no luck with negative lookbehinds (it is a new feature in JS according to here and here)

What is the proper regex for this?

答:
How about this?

```<code>[^.]+\.(?=[^.]+$)
</code>```

It looks for any non-period characters followed by a period ([^.]+\.) followed by (using a lookahead) a series of non-period characters ([^.]+) and an end-of-line ($).

https://regex101.com/r/5QfED2/1

Body:
Lets stay I have the following list of string, in JavaScript (NodeJS) I want to apply a regex one at a time and replace the hash between . and ., but I don't want to replace the word, .style. or .bundle. or .chunk. and it should also work to replace the hash in the case where there is no preceding dots.

// hash starts with number
/css/app.style.7fef363d5a8c4ef2458c.css
/css/app.bundle.7fef363d5a8c4ef2458c.css
/css/app.chunk.7fef363d5a8c4ef2458c.css
/css/app.7fef363d5a8c4ef2458c.css
/css/loading-animation.7fef363d5a8c4ef2458c.css

// hash starts with letter
/css/app.style.b3bcb606396f0c96623a.css
/css/app.bundle.b3bcb606396f0c96623a.css
/css/app.chunk.b3bcb606396f0c96623a.css
/css/app.b3bcb606396f0c96623a.css

// no preceeding dot separated name before the hash
/css/loading-animation.b3bcb606396f0c96623a.css
/css/app.b3bcb606396f0c96623a.js

// It should not affect items without a hash
/fonts/MaterialIcons-Regular.eot
/fonts/MaterialIcons-Regular.svg

The result should be

// hash starts with number
/css/app.style.css
/css/app.bundle.css
/css/app.chunk.css
/css/app.css
/css/loading-animation.css

// hash starts with letter
/css/app.style.css
/css/app.bundle.css
/css/app.chunk.css
/css/app.css

// no preceeding dot separated name before the hash
/css/loading-animation.css
/css/app.js

// It should not affect items without a hash
/fonts/MaterialIcons-Regular.eot
/fonts/MaterialIcons-Regular.svg

I tried hard and the closest I got was this

 const manifest = {};
 stats.assets.map(asset => asset.name)
    .sort()
    .forEach((file) => {
       let regEx = /\.(?!(?:[A-Za-z]))(([^.]*))\./gi
       let passTest = regEx.test(file);
       let key = file.replace(regEx, '.');
       console.log(file, passTest, key);
       manifest[key] = file;
    });

But that only replaces the hash starting with the number, and ignores all the rest.

I also tried /\.(?!(?:[A-Za-z]))(([^.]*))\./gi; but that just replaced the first occurrence of .something.

I also had no luck with negative lookbehinds (it is a new feature in JS according to here and here)

What is the proper regex for this?

Body:
How about this?

[^.]+\.(?=[^.]+$)

It looks for any non-period characters followed by a period ([^.]+\.) followed by (using a lookahead) a series of non-period characters ([^.]+) and an end-of-line ($).

https://regex101.com/r/5QfED2/1


问:
Pandas - how do you create a new data frame based on another dataframe?
I have a dataframe that contains school types and their locations. One of the columns is "Institude_Type" and the two school types are "Secondary (non-grammar) School" and "Secondary (grammar) School". I want to take all of the Secondary (non-grammar) School's information and put it into another dataframe - but I'm not sure how to do this.

I want it to be an exact copy of the current DF, with all the same 8 columns. Just one with the grammar and the other with non grammar schools.

Thanks in advance.

答:
use the built-in copy function:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html

For example:

```<code>schoolCopy = schoolDataFrame[allTheColumnsRequired].copy(deep=True)
</code>```

Body:
use the built-in copy function:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html

For example:

schoolCopy = schoolDataFrame[allTheColumnsRequired].copy(deep=True)


问:
increment value outside of function for every use in python
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

```<code>def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)
</code>```

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

答:
You could create a function attribute to hold the counter. Here is a decorator that does this:

```<code>import functools as ft

def I_can_count(f):
    @ft.wraps(f)
    def wrapper(*args, **kwds):
        wrapper.times_called += 1
        return f(*args, **kwds)
    wrapper.times_called = 0
    return wrapper

@I_can_count
def f(x):
    print x

print(f.times_called)
f(100)
print(f.times_called)
f(100)
print(f.times_called)

# 0
# 100
# 1
# 100
# 2
</code>```

Please note that the purpose of the decorator here is twofold: (1) it adds convenience; but more importantly (2) it protects the namespace where the function or rather its wrapper finds itself. Without that the following accident can happen:

```<code>def f(x)
    f.times_called += 1
    print(x)
f.times_called = 0

f(100)
# 100
f.times_called
# 1
g = f
del f
g(100)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 2, in f
# NameError: name 'f' is not defined
</code>```

Body:
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

Body:
You could create a function attribute to hold the counter. Here is a decorator that does this:

import functools as ft

def I_can_count(f):
    @ft.wraps(f)
    def wrapper(*args, **kwds):
        wrapper.times_called += 1
        return f(*args, **kwds)
    wrapper.times_called = 0
    return wrapper

@I_can_count
def f(x):
    print x

print(f.times_called)
f(100)
print(f.times_called)
f(100)
print(f.times_called)

# 0
# 100
# 1
# 100
# 2

Please note that the purpose of the decorator here is twofold: (1) it adds convenience; but more importantly (2) it protects the namespace where the function or rather its wrapper finds itself. Without that the following accident can happen:

def f(x)
    f.times_called += 1
    print(x)
f.times_called = 0

f(100)
# 100
f.times_called
# 1
g = f
del f
g(100)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 2, in f
# NameError: name 'f' is not defined


问:
How to plot a histogram from existing counts with uneven bin widths using ggplot
I want to create an histogram from already existing classes. I have this dataset:

```<code>interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})
</code>```

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

```<code>DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})
</code>```

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

答:
I think what you need is not a histogram, but a barplot. Here I showed how to use geom_col to create a barplot. Notice that I used factor to sort the bar of each class before plotting the data.

```<code>library(ggplot2)

# Order the bar
dt$interval <- factor(dt$interval, levels = dt$interval)
# Create the bar plot
ggplot(dt, aes(x=interval, y = counts)) + geom_col()
</code>```

DATA

```<code>dt <- read.table(text = "interval        counts
'0 - 8.50'        2577
                 '8.51 - 10.00'    1199
                 '10.01 - 12.00'   1878
                 '12.01 - 14.00'   637
                 '14.01 - 16.00'   369
                 '16.01 - 18.00'   98
                 '18.00 - 20.00'   308",
                 header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I want to create an histogram from already existing classes. I have this dataset:

interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

Body:
I think what you need is not a histogram, but a barplot. Here I showed how to use geom_col to create a barplot. Notice that I used factor to sort the bar of each class before plotting the data.

library(ggplot2)

# Order the bar
dt$interval <- factor(dt$interval, levels = dt$interval)
# Create the bar plot
ggplot(dt, aes(x=interval, y = counts)) + geom_col()

DATA

dt <- read.table(text = "interval        counts
'0 - 8.50'        2577
                 '8.51 - 10.00'    1199
                 '10.01 - 12.00'   1878
                 '12.01 - 14.00'   637
                 '14.01 - 16.00'   369
                 '16.01 - 18.00'   98
                 '18.00 - 20.00'   308",
                 header = TRUE, stringsAsFactors = FALSE)


问:
Cannot resolve method setText(java.lang.String) in Fragment
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

```<code>@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }
</code>```

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

```<code>public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
</code>```

This is the XML file associated with this class:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>
</code>```

答:
Bring "count" out of "onCreateView", so it will be accessiable in "onSensorChanged"  </p>

```<code>public class Tab3 extends Fragment implements SensorEventListener {
 private SensorManager sensorManager;
 private TextView textView;
 boolean activityRunning;
 private Button buttonReturn;

private TextView count ;//<-- add this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    //define count global
    count = (TextView)rootView.findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
</code>```

Body:
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

This is the XML file associated with this class:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>

Body:
Bring "count" out of "onCreateView", so it will be accessiable in "onSensorChanged"

public class Tab3 extends Fragment implements SensorEventListener {
 private SensorManager sensorManager;
 private TextView textView;
 boolean activityRunning;
 private Button buttonReturn;

private TextView count ;//<-- add this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    //define count global
    count = (TextView)rootView.findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}