问:
How to label x-axis if a sequence is used?
I've this R script:

```<code>plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)
</code>```

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

```<code>> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225
</code>```

答:
It's possible to label the axis with the axis function and disable the axis labeling in the plot function with the attribute xaxt="n".

Here is the complete result:

```<code>plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400),
  xaxt = 'n'
)

axis(1, at = seq(1, 5), labels = seq(2011, 2015))

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)
</code>```

This plot is produced:

Body:
I've this R script:

plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225

Body:
It's possible to label the axis with the axis function and disable the axis labeling in the plot function with the attribute xaxt="n".

Here is the complete result:

plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400),
  xaxt = 'n'
)

axis(1, at = seq(1, 5), labels = seq(2011, 2015))

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)

This plot is produced:


来源: stackexchange

问:
YoctoProject: change ownership of all files in a recipe
For the YoctoProject (v2.0, Jethro) the ownership of files inside the image defaults to user and group root unless I do explicitly change them by chown and chgrp in the do_install step for the given recipe.

I have a few recipes for which all files should be owned by another group and user than root. Is there a (cleaner/smarter) way to achieve this without calling chown and chgrp in do_install?

答:
BSP vendors do usually provide example recipes to solve basic tasks.

Usually folder is called "recipes-skeleton"

User/Group add recipe sample path for freescale BSP:

~/yocto/fsl-community-bsp/sources/poky/meta-skeleton/recipes-skeleton/useradd/useradd-example.bb

Same can be found on github:

https://github.com/dirtybit/gumstix-yocto/blob/master/meta-skeleton/recipes-skeleton/useradd/useradd-example.bb

For changing root user info look up EXTRA_USERS_PARAMS flag. Need to inherit "extrausers" class first. Documentation on class is at:

http://www.yoctoproject.org/docs/current/mega-manual/mega-manual.html#ref-classes-extrausers

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Consecutive use of std::list causes crash
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

```<code>class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;
</code>```

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

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

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}
</code>```

答: You can't delete an object that was not allocated with new. MemoryObject foo;is not allocatetd with new.

Body:
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

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

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}


问:
HAML and iterated XML
I'm trying to generate an XML file.  I've got some tags that repeat numerically like so:

```
# necessary XML namespace and metadata stuff...

%img{:src => "Foo002.jpg#full"}/
%img{:src => "Foo003.jpg#full"}/
%img{:src => "Foo004.jpg#full"}/
%img{:src => "Foo005.jpg#full"}/
# and so on for a few hundred lines

%img{:src => "Foo435.jpg#full"}/
```

I'm given "Foo" and the ending number (435 in this case) as parameters.  How do I go about telling HAML to do this?

Thanks

EDIT: Forgot to mention, the leading zeros are important.

答:
```<code>- 2.upto(435) do |n|
  %img{:src => "Foo%03d.jpg#full" % n}
</code>```

or

```<code>- (2..435).each do |n|
  %img{:src => "Foo%03d.jpg#full" % n}
</code>```

Proof:

```<code>phrogz$ haml
!!! XML
%root
  - 2.upto(10) do |n|
    %img{ src:"Foo%03d.jpg" % n }
^D

<?xml version='1.0' encoding='utf-8' ?>
<root>
  <img src='Foo002.jpg' />
  <img src='Foo003.jpg' />
  <img src='Foo004.jpg' />
  <img src='Foo005.jpg' />
  <img src='Foo006.jpg' />
  <img src='Foo007.jpg' />
  <img src='Foo008.jpg' />
  <img src='Foo009.jpg' />
  <img src='Foo010.jpg' />
</root>
</code>```

ContentLicense: CC BY-SA 2.5

Title: HAML and iterated XML

Body:
I'm trying to generate an XML file.  I've got some tags that repeat numerically like so:

# necessary XML namespace and metadata stuff...

%img{:src => "Foo002.jpg#full"}/
%img{:src => "Foo003.jpg#full"}/
%img{:src => "Foo004.jpg#full"}/
%img{:src => "Foo005.jpg#full"}/
# and so on for a few hundred lines

%img{:src => "Foo435.jpg#full"}/

I'm given "Foo" and the ending number (435 in this case) as parameters.  How do I go about telling HAML to do this?

Thanks

EDIT: Forgot to mention, the leading zeros are important.

Body:
- 2.upto(435) do |n|
  %img{:src => "Foo%03d.jpg#full" % n}

or

- (2..435).each do |n|
  %img{:src => "Foo%03d.jpg#full" % n}

Proof:

phrogz$ haml
!!! XML
%root
  - 2.upto(10) do |n|
    %img{ src:"Foo%03d.jpg" % n }
^D

<?xml version='1.0' encoding='utf-8' ?>
<root>
  <img src='Foo002.jpg' />
  <img src='Foo003.jpg' />
  <img src='Foo004.jpg' />
  <img src='Foo005.jpg' />
  <img src='Foo006.jpg' />
  <img src='Foo007.jpg' />
  <img src='Foo008.jpg' />
  <img src='Foo009.jpg' />
  <img src='Foo010.jpg' />
</root>


问:
Karma Testing Angular Seed Project System.JS path error
I'm just getting started with Angular using https://github.com/mgechev/angular-seed as my initial setup.

I'm having some problems getting an initial unit test setup with Jasmine. The OAuth library used in my project seems to be the issue, but I'm not sure whether it can be safely suppressed or what changes I need to make to the config. The base/node_modules path is currently incorrect, but I'm not sure which part of the configuration builds this. I've tried adding the path to the ignored section but the error persists. Any help appreciated.

```<code>// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)
'use strict';

var argv = require('yargs').argv;
var minimatch = require("minimatch");

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // Polyfills.
      'node_modules/core-js/client/shim.min.js',
      'node_modules/intl/dist/Intl.min.js',

      'node_modules/traceur/bin/traceur.js',

      // System.js for module loading
      'node_modules/systemjs/dist/system.src.js',

      // Zone.js dependencies
      'node_modules/zone.js/dist/zone.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/async-test.js',
      'node_modules/zone.js/dist/fake-async-test.js',
      'node_modules/zone.js/dist/sync-test.js',
      'node_modules/zone.js/dist/proxy.js',
      'node_modules/zone.js/dist/jasmine-patch.js',

      // RxJs.
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

      // paths loaded via module imports
      // Angular itself
      { pattern: 'node_modules/@angular/**/*.js', included: false, watched: true },
      { pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false },

      { pattern: 'dist/dev/**/*.js', included: false, watched: true },
      { pattern: 'dist/dev/**/*.html', included: false, watched: true, served: true },
      { pattern: 'dist/dev/**/*.css', included: false, watched: true, served: true },
      { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it

      // suppress annoying 404 warnings for resources, images, etc.
      { pattern: 'dist/dev/assets/**/*', watched: false, included: false, served: true },

      'test-config.js',
      'dist/dev/app/system-config.js',
      'test-main.js'
    ],

    // must go along with above, suppress annoying 404 warnings.
    proxies: {
      '/assets/': '/base/dist/dev/assets/'
    },

    // list of files to exclude
    exclude: [
      'node_modules/**/*spec.js',
      'node_modules/angular-oauth2-oidc/dist/index.js',
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'Chrome'
    ],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Passing command line arguments to tests
    client: {
      files:  argv.files ? minimatch.makeRe(argv.files).source : null
    }
  });

  if (process.env.APPVEYOR) {
    config.browsers = ['IE'];
    config.singleRun = true;
    config.browserNoActivityTimeout = 90000; // Note: default value (10000) is not enough
  }

  if (process.env.TRAVIS || process.env.CIRCLECI) {
    config.browsers = ['Chrome_travis_ci'];
    config.singleRun = true;
    config.browserNoActivityTimeout = 90000;
  }
};
</code>```

The following is the error message :

```<code>06 07 2017 09:27:29.589:INFO [karma]: Karma v1.3.0 server started at http://loca
lhost:9876/
06 07 2017 09:27:29.590:INFO [launcher]: Launching browser Chrome with unlimited
 concurrency
06 07 2017 09:27:29.595:INFO [launcher]: Starting browser Chrome
06 07 2017 09:27:31.064:INFO [Chrome 59.0.3071 (Windows 8.1 0.0.0)]: Connected o
n socket /#4mhCO5mVkEwzD0EfAAAA with id 14947625
06 07 2017 09:27:32.242:WARN [web-server]: 404: /base/node_modules/angular-oauth
2-oidc/dist/index.js
Chrome 59.0.3071 (Windows 8.1 0.0.0) ERROR: '(SystemJS) XHR error (404 Not Found
) loading http://localhost:9876/base/node_modules/angular-oauth2-oidc/dist/index
.js
        Error: XHR error (404 Not Found) loading http://localhost:9876/base/node
_modules/angular-oauth2-oidc/dist/index.js
            at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (ht
tp://localhost:9876/base/node_modules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b6
52319d281eef1d450d5:1056:39)
            at ZoneDelegate.invokeTask (http://localhost:9876/base/node_modules/
zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:424:31)
            at Zone.runTask (http://localhost:9876/base/node_modules/zone.js/dis
t/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:191:47)
            at XMLHttpRequest.ZoneTask.invoke (http://localhost:9876/base/node_m
odules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:486:38)
        Error loading http://localhost:9876/base/node_modules/angular-oauth2-oid
c/dist/index.js as "angular-oauth2-oidc" from http://localhost:9876/base/dist/de
v/app/shared/login/login-service.js'
Chrome 59.0.3071 (Windows 8.1 0.0.0) ERROR: '(SystemJS) XHR error (404 Not Found
) loading http://localhost:9876/base/node_modules/angular-oauth2-oidc/dist/index
.js
        Error: XHR error (404 Not Found) loading http://localhost:9876/base/node
_modules/angular-oauth2-oidc/dist/index.js
            at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (ht
tp://localhost:9876/base/node_modules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b6
52319d281eef1d450d5:1056:39)
            at ZoneDelegate.invokeTask (http://localhost:9876/base/node_modules/
zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:424:31)
            at Zone.runTask (http://localhost:9876/base/node_modules/zone.js/dis
t/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:191:47)
            at XMLHttpRequest.ZoneTask.invoke (http://localhost:9876/base/node_m
odules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:486:38)
        Error loading http://localhost:9876/base/node_modules/angular-oauth2-oid
c/dist/index.js as "angular-oauth2-oidc" from http://localhost:9876/base/dist/de
v/app/shared/login/login-service.js'
06 07 2017 09:27:32.274:WARN [web-server]: 404: /base/node_modules/angular-oauth
2-oidc/dist/index.js
</code>```

Update:

After removing the list of files to exclude:

答:
I think you need to proxy node_module too</p>

```<code> proxies: {
            '/node_modules/': "/base/node_modules/",
            '/assets/': '/base/dist/dev/assets/'
        },
</code>```

Body:
I'm just getting started with Angular using https://github.com/mgechev/angular-seed as my initial setup.

I'm having some problems getting an initial unit test setup with Jasmine. The OAuth library used in my project seems to be the issue, but I'm not sure whether it can be safely suppressed or what changes I need to make to the config. The base/node_modules path is currently incorrect, but I'm not sure which part of the configuration builds this. I've tried adding the path to the ignored section but the error persists. Any help appreciated.

// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)
'use strict';

var argv = require('yargs').argv;
var minimatch = require("minimatch");

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // Polyfills.
      'node_modules/core-js/client/shim.min.js',
      'node_modules/intl/dist/Intl.min.js',

      'node_modules/traceur/bin/traceur.js',

      // System.js for module loading
      'node_modules/systemjs/dist/system.src.js',

      // Zone.js dependencies
      'node_modules/zone.js/dist/zone.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/async-test.js',
      'node_modules/zone.js/dist/fake-async-test.js',
      'node_modules/zone.js/dist/sync-test.js',
      'node_modules/zone.js/dist/proxy.js',
      'node_modules/zone.js/dist/jasmine-patch.js',

      // RxJs.
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

      // paths loaded via module imports
      // Angular itself
      { pattern: 'node_modules/@angular/**/*.js', included: false, watched: true },
      { pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false },

      { pattern: 'dist/dev/**/*.js', included: false, watched: true },
      { pattern: 'dist/dev/**/*.html', included: false, watched: true, served: true },
      { pattern: 'dist/dev/**/*.css', included: false, watched: true, served: true },
      { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it

      // suppress annoying 404 warnings for resources, images, etc.
      { pattern: 'dist/dev/assets/**/*', watched: false, included: false, served: true },

      'test-config.js',
      'dist/dev/app/system-config.js',
      'test-main.js'
    ],

    // must go along with above, suppress annoying 404 warnings.
    proxies: {
      '/assets/': '/base/dist/dev/assets/'
    },

    // list of files to exclude
    exclude: [
      'node_modules/**/*spec.js',
      'node_modules/angular-oauth2-oidc/dist/index.js',
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      'Chrome'
    ],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Passing command line arguments to tests
    client: {
      files:  argv.files ? minimatch.makeRe(argv.files).source : null
    }
  });

  if (process.env.APPVEYOR) {
    config.browsers = ['IE'];
    config.singleRun = true;
    config.browserNoActivityTimeout = 90000; // Note: default value (10000) is not enough
  }

  if (process.env.TRAVIS || process.env.CIRCLECI) {
    config.browsers = ['Chrome_travis_ci'];
    config.singleRun = true;
    config.browserNoActivityTimeout = 90000;
  }
};

The following is the error message :

06 07 2017 09:27:29.589:INFO [karma]: Karma v1.3.0 server started at http://loca
lhost:9876/
06 07 2017 09:27:29.590:INFO [launcher]: Launching browser Chrome with unlimited
 concurrency
06 07 2017 09:27:29.595:INFO [launcher]: Starting browser Chrome
06 07 2017 09:27:31.064:INFO [Chrome 59.0.3071 (Windows 8.1 0.0.0)]: Connected o
n socket /#4mhCO5mVkEwzD0EfAAAA with id 14947625
06 07 2017 09:27:32.242:WARN [web-server]: 404: /base/node_modules/angular-oauth
2-oidc/dist/index.js
Chrome 59.0.3071 (Windows 8.1 0.0.0) ERROR: '(SystemJS) XHR error (404 Not Found
) loading http://localhost:9876/base/node_modules/angular-oauth2-oidc/dist/index
.js
        Error: XHR error (404 Not Found) loading http://localhost:9876/base/node
_modules/angular-oauth2-oidc/dist/index.js
            at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (ht
tp://localhost:9876/base/node_modules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b6
52319d281eef1d450d5:1056:39)
            at ZoneDelegate.invokeTask (http://localhost:9876/base/node_modules/
zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:424:31)
            at Zone.runTask (http://localhost:9876/base/node_modules/zone.js/dis
t/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:191:47)
            at XMLHttpRequest.ZoneTask.invoke (http://localhost:9876/base/node_m
odules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:486:38)
        Error loading http://localhost:9876/base/node_modules/angular-oauth2-oid
c/dist/index.js as "angular-oauth2-oidc" from http://localhost:9876/base/dist/de
v/app/shared/login/login-service.js'
Chrome 59.0.3071 (Windows 8.1 0.0.0) ERROR: '(SystemJS) XHR error (404 Not Found
) loading http://localhost:9876/base/node_modules/angular-oauth2-oidc/dist/index
.js
        Error: XHR error (404 Not Found) loading http://localhost:9876/base/node
_modules/angular-oauth2-oidc/dist/index.js
            at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (ht
tp://localhost:9876/base/node_modules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b6
52319d281eef1d450d5:1056:39)
            at ZoneDelegate.invokeTask (http://localhost:9876/base/node_modules/
zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:424:31)
            at Zone.runTask (http://localhost:9876/base/node_modules/zone.js/dis
t/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:191:47)
            at XMLHttpRequest.ZoneTask.invoke (http://localhost:9876/base/node_m
odules/zone.js/dist/zone.js?082dc1d83c7a42ddda9b652319d281eef1d450d5:486:38)
        Error loading http://localhost:9876/base/node_modules/angular-oauth2-oid
c/dist/index.js as "angular-oauth2-oidc" from http://localhost:9876/base/dist/de
v/app/shared/login/login-service.js'
06 07 2017 09:27:32.274:WARN [web-server]: 404: /base/node_modules/angular-oauth
2-oidc/dist/index.js

Update:

After removing the list of files to exclude:

Body:
I think you need to proxy node_module too

 proxies: {
            '/node_modules/': "/base/node_modules/",
            '/assets/': '/base/dist/dev/assets/'
        },


问:
Rest-client POST without a payload
I am trying to POST using Rest-Client gem in Ruby, and I keep getting a return from the web service as Error 414 Unsupported Media Type, because I am setting the payload argument as ''

Example

```<code>RestClient.post 'https://username:password@remotesystem/api/v1/applications/44204093/publishUpdates','' ,:accept =>  'json'
</code>```

The issue is that the web service does not want or need a payload for this resource, but the RestClient feels the need to have one specified.

Anyone know how to do a post with rest client and not have to specify a payload argument?

thanks

答:
This started happening for me in ruby 2.4. Ruby 1.9 didn't have this problem, for the same version of rest-client. If no payload is specified in the call, the content-type header was being set to 'application/x-www-form-urlencoded' which caused the server to say 'No operation matching request path ...' and return '415 Unsupported Media Type'. The solution was to explicitly set content-type to nil in the call:</p>

```<code>RestClient::Request.execute(:url => query, :ssl_version => 'TLSv1', :method => 'post', :headers => {'Content-Type' => nil})
</code>```

Title: Rest-client POST without a payload

Body:
I am trying to POST using Rest-Client gem in Ruby, and I keep getting a return from the web service as Error 414 Unsupported Media Type, because I am setting the payload argument as ''

Example

RestClient.post 'https://username:password@remotesystem/api/v1/applications/44204093/publishUpdates','' ,:accept =>  'json'

The issue is that the web service does not want or need a payload for this resource, but the RestClient feels the need to have one specified.

Anyone know how to do a post with rest client and not have to specify a payload argument?

thanks

Body:
This started happening for me in ruby 2.4. Ruby 1.9 didn't have this problem, for the same version of rest-client. If no payload is specified in the call, the content-type header was being set to 'application/x-www-form-urlencoded' which caused the server to say 'No operation matching request path ...' and return '415 Unsupported Media Type'. The solution was to explicitly set content-type to nil in the call:

RestClient::Request.execute(:url => query, :ssl_version => 'TLSv1', :method => 'post', :headers => {'Content-Type' => nil})


问:
ionic 2 headers not being set before the http request
I have the following request to my backend:

```<code>loggedIn() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.getToken().then((val) => {
        headers.append('X-Auth-Token', val);
    });
    const options = new RequestOptions({headers: headers});
    let seq = this.api.post('/login', null, options).share();
    seq.map((res: Response) => res.json())
        .subscribe(res => {

        }, err => {
            console.log("HEADERS ------- ", options.headers);
        });
    return seq;
};
</code>```

Sometimes 'X-Auth-Token' isn't being set. How's it possible to make sure that the header is being set?

getToken() looks like this:

```<code>getToken() {
    return this.storage.get('token').then((value) => {
        return value;
    });
}
</code>```

The method that calls loggedIn() looks like this:

```<code>checkIfLoggedIn() {
    this.user.loggedIn()
        .subscribe((res) => {
            console.log("LoginPage RETURN VALUE --------------- ", res);
        }, (err) => {
            console.log("LoginPage RETURN ERROR --------------- ", err);
        });
}
</code>```

答:
Update your code to ensure the api post after header had data</p>

```<code>loggedIn() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.getToken().then((val) => {
        headers.append('X-Auth-Token', val);
         const options = new RequestOptions({headers: headers});
         let seq = this.api.post('/login', null, options).share();
         seq.map((res: Response) => res.json())
            .subscribe(res => {

            }, err => {
                console.log("HEADERS ------- ", options.headers);
            });
        return seq;
    });

};
</code>```

Body:
I have the following request to my backend:

loggedIn() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.getToken().then((val) => {
        headers.append('X-Auth-Token', val);
    });
    const options = new RequestOptions({headers: headers});
    let seq = this.api.post('/login', null, options).share();
    seq.map((res: Response) => res.json())
        .subscribe(res => {

        }, err => {
            console.log("HEADERS ------- ", options.headers);
        });
    return seq;
};

Sometimes 'X-Auth-Token' isn't being set. How's it possible to make sure that the header is being set?

getToken() looks like this:

getToken() {
    return this.storage.get('token').then((value) => {
        return value;
    });
}

The method that calls loggedIn() looks like this:

checkIfLoggedIn() {
    this.user.loggedIn()
        .subscribe((res) => {
            console.log("LoginPage RETURN VALUE --------------- ", res);
        }, (err) => {
            console.log("LoginPage RETURN ERROR --------------- ", err);
        });
}

Body:
Update your code to ensure the api post after header had data

loggedIn() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.getToken().then((val) => {
        headers.append('X-Auth-Token', val);
         const options = new RequestOptions({headers: headers});
         let seq = this.api.post('/login', null, options).share();
         seq.map((res: Response) => res.json())
            .subscribe(res => {

            }, err => {
                console.log("HEADERS ------- ", options.headers);
            });
        return seq;
    });

};


问:
Remove Text Between Parentheses PHP
I'm just wondering how I could remove the text between a set of parentheses and the parentheses themselves in php.

Example :

ABC (Test1)

I would like it to delete (Test1) and only leave ABC

Thanks

Title: Remove Text Between Parentheses PHP

Body:
$str ="ABC (Test1)";
echo preg_replace( '~\(.*\)~' , "", $str );


问:
Retrieving rows based on another column's aggregate values in MS SQL
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

```<code>Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1
</code>```

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

```<code>SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0
</code>```

resulting in:

```<code>3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

```<code>8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

I.e. every container_parent_id that which has only records with quantity = 0.

答:
```<code>SELECT T.*
FROM Container  t
    INNER JOIN (
            SELECT container_parent_id,SUM(quantity) Tot
            FROM Container
            GROUP BY container_parent_id) g ON T.container_parent_id = G.container_parent_id
WHERE G.Tot=0
</code>```

Body:
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0

resulting in:

3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

I.e. every container_parent_id that which has only records with quantity = 0.


问:
FFmpeg keep same video dimension if video height is less than x480
The following code im using for video converting:

```<code>ffmpeg -i input.mkv -c:v libx264 -crf 23 -preset medium -c:a aac -b:a 128k -movflags +faststart -s hd480 output.mp4
</code>```

I want to keep same video dimension for smaller videos. For example keep 640x360 dimension if video height is less than x480.

Is ffmpeg such option?

答:
Use</p>

```<code>ffmpeg -i input.mkv
   -vf "scale=w='if(gt(ih,480),2*trunc(oh*a/2),iw)':h='if(gt(ih,480),480,ih)'"
   -c:v libx264 -crf 23 -preset medium -c:a aac -b:a 128k -movflags +faststart output.mp4
</code>```

Body:
The following code im using for video converting:

ffmpeg -i input.mkv -c:v libx264 -crf 23 -preset medium -c:a aac -b:a 128k -movflags +faststart -s hd480 output.mp4

I want to keep same video dimension for smaller videos. For example keep 640x360 dimension if video height is less than x480.

Is ffmpeg such option?

Body:
Use

ffmpeg -i input.mkv
   -vf "scale=w='if(gt(ih,480),2*trunc(oh*a/2),iw)':h='if(gt(ih,480),480,ih)'"
   -c:v libx264 -crf 23 -preset medium -c:a aac -b:a 128k -movflags +faststart output.mp4


问:
How to archive a directory in master and copy to minions using salt
I know I can use cp.get_dir to download a directory from master to minions, but when the directory contains a lot of files, it's very slow. If I can tar up the directory and then download to minion, it will be much faster.  But I can't find out how to archive a directory at master prior to downloading it to minions. Any ideas?</p>

答:
What we do is tar the files manually, then extract them on the minion, as you said. We then either replace or modify any files that should be different from what is in the tar-file. This is a good approach for a configuration file that resides in the .tar file, for example.

To archive the file, we just ssh on the salt master and then use something like tar -cvzf files.tar.gz <yourfiles>.

You could also consider having the files on the machines from the start, with a rsync afterwards (via salt.states.rsync for example). This would just push over the changes in the files, not all the files.


问:
Python csv input and output algorithm
I am building an algorithm without using a module.
My algorithm is calculate each line's value from 111.txt, which have

```<code>2,2,2,2
4,4,0,4
2,3,3,3
</code>```

to 222.txt. So the result what i want is

```<code>Column, Sum, Mean, STD, Median, Mode, Min, Max
1,8,2,0,2,2,2,2
2,12,3,2,4,4,0,4
3,11,2.75,0.5,3,3,2,3
</code>```

My algorithm is

```<code>infile = open("111.txt", "r")
outfile = open("222.txt", "w")

outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")

for line in infile:
    infileline = line.rstrip().split(",")
    infileline.sort()
    while line != "":
        total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
        mean = total / 4
        std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
        median = (float(infileline[1]) + float(infileline[2])) / 2
        mode = 2
        minimum = float(infileline[0])
        maximum = float(infileline[3])
        line = infile.readline()

outfile.write("1")
outfile.write(",")
outfile.write("%1.0f" % total)
outfile.write(",")
outfile.write("%1.0f" % mean)
outfile.write(",")
outfile.write("%1.0f" % std)
outfile.write(",")
outfile.write("%1.0f" % median)
outfile.write(",")
outfile.write("%1.0f" % mode)
outfile.write(",")
outfile.write("%1.0f" % minimum)
outfile.write(",")
outfile.write("%1.0f\n" % maximum)

infile.close()
outfile.close()
</code>```

but the problem is my algorithm read only first line on the 111.txt
Therefore, the result is like this on 222.txt

```<code>Column,Sum,Mean,STD,Median,Mode,Min,Max
1,8,2,0,2,2,2,2
</code>```

Also,I've been thinking a lot, but I don't know how to write the algorithm of the column and the algorithm of the mode.

答:
You result file open on 'w' mode (rewrite file by last value), just use 'a' (append) mode.

Script write only last operation at the loop, you must add write block to the loop.

You don't need this line line = infile.readline().

This code must be look like this:

```<code>infile = open("111.txt", "r")
outfile = open("222.txt", "a")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
column = 0

for line in infile:
    if line:
        column += 1
        infileline = line.rstrip().split(",")
        infileline.sort()
        total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
        mean = total / 4
        std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
        median = (float(infileline[1]) + float(infileline[2])) / 2
        mode = 2
        minimum = float(infileline[0])
        maximum = float(infileline[3])

        outfile.write(str(column)+',')
        outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,
                                                   mode, minimum, maximum)))
        outfile.write('\n')

infile.close()
outfile.close()
</code>```

Title: Python csv input and output algorithm

Body:
I am building an algorithm without using a module.
My algorithm is calculate each line's value from 111.txt, which have

2,2,2,2
4,4,0,4
2,3,3,3

to 222.txt. So the result what i want is

Column, Sum, Mean, STD, Median, Mode, Min, Max
1,8,2,0,2,2,2,2
2,12,3,2,4,4,0,4
3,11,2.75,0.5,3,3,2,3

My algorithm is

infile = open("111.txt", "r")
outfile = open("222.txt", "w")

outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")

for line in infile:
    infileline = line.rstrip().split(",")
    infileline.sort()
    while line != "":
        total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
        mean = total / 4
        std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
        median = (float(infileline[1]) + float(infileline[2])) / 2
        mode = 2
        minimum = float(infileline[0])
        maximum = float(infileline[3])
        line = infile.readline()

outfile.write("1")
outfile.write(",")
outfile.write("%1.0f" % total)
outfile.write(",")
outfile.write("%1.0f" % mean)
outfile.write(",")
outfile.write("%1.0f" % std)
outfile.write(",")
outfile.write("%1.0f" % median)
outfile.write(",")
outfile.write("%1.0f" % mode)
outfile.write(",")
outfile.write("%1.0f" % minimum)
outfile.write(",")
outfile.write("%1.0f\n" % maximum)

infile.close()
outfile.close()

but the problem is my algorithm read only first line on the 111.txt
Therefore, the result is like this on 222.txt

Column,Sum,Mean,STD,Median,Mode,Min,Max
1,8,2,0,2,2,2,2

Also,I've been thinking a lot, but I don't know how to write the algorithm of the column and the algorithm of the mode.

Body:
You result file open on 'w' mode (rewrite file by last value), just use 'a' (append) mode.

Script write only last operation at the loop, you must add write block to the loop.

You don't need this line line = infile.readline().

This code must be look like this:

infile = open("111.txt", "r")
outfile = open("222.txt", "a")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
column = 0

for line in infile:
    if line:
        column += 1
        infileline = line.rstrip().split(",")
        infileline.sort()
        total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
        mean = total / 4
        std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
        median = (float(infileline[1]) + float(infileline[2])) / 2
        mode = 2
        minimum = float(infileline[0])
        maximum = float(infileline[3])

        outfile.write(str(column)+',')
        outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,
                                                   mode, minimum, maximum)))
        outfile.write('\n')

infile.close()
outfile.close()


问:
Split 2-3 tree into less-than and greater-than given value X
I need to write function, which receives some key x and split 2-3 tree into 2 2-3 trees. In first tree there are all nodes which are bigger than x, and in second which are less. I need to make it with complexity O(logn). thanks in advance for any idea.

edited
I thought about finding key x in the tree. And after split its two sub-trees(bigger or lesser if they exist) into 2 trees, and after begin to go up and every time to check sub-trees which I've not checked yet and to join to one of the trees. My problem is that all leaves must be at the same level.

答: Assuming you have covered 2-3-4 trees in the lecture already, here is a hint: see whether you can apply the same insertion algorithm for 2-3 trees also. In particular, make insertions always start in the leaf, and then restructure the tree appropriately. When done, determine the complexity of the algorithm you got.</p>


问:
How to set fixed view position across different locals?
I'm currently working on an app and set up another local in strings.xml

I have a list view with three elements two text views and an image view

when I change the language to something like Arabic the items positions change and they appear from right to left.

that messes up the whole layout.

My question is how to set the position to fixed value so they don't change

 I tried searching for solutions for this problem but didn't get any.

答:
You can also make some views in a layout always in LTR, or RTL or whatever, regardless of their parent:</p>

```<code><LinearLayout
...
    android:layoutDirection="ltr"
.../>
</code>```

Body:
You can also make some views in a layout always in LTR, or RTL or whatever, regardless of their parent:

<LinearLayout
...
    android:layoutDirection="ltr"
.../>


问:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table
I defined table name users_table and run db.create_all() to create the table, but get error "no such table user_table" on commit for updating user info.

How I test :

```<code>(under /project) python3 manage.py shell
>>> u = User(email='foo@bar.com', username='foobar', password='player')
>>> db.create_all()
>>> db.session.add(u)
>>> db.session.commit()  # with following error message
Traceback (most recent call last):
  File "C:\...\Python\Python36-32\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context
  context)
  File "C:\...\Python\Python36-32\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute
  cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: users_table
...
...
  sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users_table
</code>```

/project/app/_init_.py:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config

db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    db.init_app(app)
    return app
</code>```

/project/app/models.py:

```<code>import os
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
from flask import Flask

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'users_table'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User %r>' % self.username

    @property
    def password(self):
        raise AttributeError('Password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)
</code>```

project/config.py:

```<code>import os
basedir = os.path.abspath(os.path.dirname(\__file__))

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'fhuaioe7832of67^&*T#oy93'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True

    @staticmethod
    def init_app(app):
        pass

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')

config = {
    'development': DevelopmentConfig,
    'default': DevelopmentConfig,
}
</code>```

project/manage.py:

```<code>import os
from app import create_app, db
from app.models import User
from flask_script import Manager, Shell

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)

def make_shell_context():
    return dict(app=app, db=db, User=User)

manager.add_command("shell", Shell(make_context=make_shell_context))

if __name__ == '__main__':
    manager.run()
</code>```

答:
I just got done setting up a Flask app and I dealt with this kind of problem.

I strongly suspect the problem here is that the instance of db that you are creating in __init__.py is unaware of the contents of models.py, including the User class. The db object in __init__.py is a totally separate object from the db you are creating in models.py. So when you run db.create_all() in __init__.py, it is checking the list of tables that it knows about and isn't finding any. I ran into this exact issue.

What I discovered is that the models (like User) are registered with the particular db object that is listed in the model's class definition (e.g. class User(db.Model):).

So basically my understanding is that the way to fix this is to run db.create_all() using the same instance of db that is being used to define the models. In other words, run db.create_all() from within models.py.

Here's my code so you can see how I have it set up:

app.py:

```<code>#!flask/bin/python
import os

from flask import Flask

class CustomFlask(Flask):
    jinja_options = Flask.jinja_options.copy()
    jinja_options.update(dict(
        variable_start_string='%%',  # Default is '{{', I'm changing this because Vue.js uses '{{' / '}}'
        variable_end_string='%%',
    ))
app = CustomFlask(__name__)

app.config['SECRET_KEY'] = 'hard to guess string'

import yaml
if os.environ['SERVER_ENVIRONMENT'] == 'PRODUCTION':
    config_filename = "production.yaml"
elif os.environ['SERVER_ENVIRONMENT'] == 'LOCAL':
    config_filename = "local.yaml"
else:
    config_filename = "local.yaml"

base_directory = path = os.path.dirname(os.path.realpath(__file__))

with open(base_directory + "/config/" + config_filename) as config_file:
    config = yaml.load(config_file)

db_config = config['database']
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username=db_config['username'],
    password=db_config['password'],
    hostname=db_config['hostname'],
    databasename=db_config['databasename'],
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
db.app = app

def clear_the_template_cache():
    app.jinja_env.cache = {}

app.before_request(clear_the_template_cache)

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(email):
    from models import User
    return User.query.filter_by(email=email).first()

if __name__ == '__main__':
    from routes import web_routes
    app.register_blueprint(web_routes)

    from api import api
    app.register_blueprint(api)

    # To get PyCharm's debugger to work, you need to have "debug=False, threaded=True"
    #app.run(debug=False, threaded=True)
    app.run(debug=True)
</code>```

models.py:

```<code>from app import db

import datetime
from werkzeug.security import generate_password_hash, \
     check_password_hash

class Song(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80))
    datetime_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    lines = db.relationship('Line', cascade="all,delete", backref=db.backref('song', lazy='joined'), lazy='dynamic')
    is_deleted = db.Column(db.Boolean, default=False)

class Line(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    song_id = db.Column(db.Integer, db.ForeignKey('song.id'))
    spans_of_time = db.relationship('SpanOfTime', cascade="all,delete", backref=db.backref('line', lazy='joined'), lazy='dynamic')

class SpanOfTime(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    line_id = db.Column(db.Integer, db.ForeignKey('line.id'))
    starting_64th = db.Column(db.Integer)  # I'm assuming the highest-granularity desired will be a 1/64th note-length.
    length = db.Column(db.Integer)  # I guess this'll be in 1/64th notes, so a 1/16th note will be '4'.
    content = db.Column(db.String(80))

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(80), primary_key=True, unique=True)
    display_name = db.Column(db.String(80), default="A Rhymecraft User")
    password_hash = db.Column(db.String(200))
    datetime_subscription_valid_until = db.Column(db.DateTime, default=datetime.datetime.utcnow() - datetime.timedelta(days=1))
    datetime_joined = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    songs = db.relationship('Song', cascade="all,delete", backref=db.backref('user', lazy='joined'), lazy='dynamic')

    def __init__(self, email, password):
        self.email = email
        self.set_password(password)

    def __repr__(self):
        return '<User %r>' % self.email

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.email)

def init_db():
    db.create_all()

    # Create a test user
    new_user = User('a@a.com', 'aaaaaaaa')
    new_user.display_name = 'Nathan'
    db.session.add(new_user)
    db.session.commit()

    new_user.datetime_subscription_valid_until = datetime.datetime(2019, 1, 1)
    db.session.commit()

if __name__ == '__main__':
    init_db()
</code>```

Body:
I defined table name users_table and run db.create_all() to create the table, but get error "no such table user_table" on commit for updating user info.

How I test :

(under /project) python3 manage.py shell
>>> u = User(email='foo@bar.com', username='foobar', password='player')
>>> db.create_all()
>>> db.session.add(u)
>>> db.session.commit()  # with following error message
Traceback (most recent call last):
  File "C:\...\Python\Python36-32\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context
  context)
  File "C:\...\Python\Python36-32\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute
  cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: users_table
...
...
  sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users_table

/project/app/_init_.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config

db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    db.init_app(app)
    return app

/project/app/models.py:

import os
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
from flask import Flask

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'users_table'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User %r>' % self.username

    @property
    def password(self):
        raise AttributeError('Password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

project/config.py:

import os
basedir = os.path.abspath(os.path.dirname(\__file__))

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'fhuaioe7832of67^&*T#oy93'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True

    @staticmethod
    def init_app(app):
        pass

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')

config = {
    'development': DevelopmentConfig,
    'default': DevelopmentConfig,
}

project/manage.py:

import os
from app import create_app, db
from app.models import User
from flask_script import Manager, Shell

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)

def make_shell_context():
    return dict(app=app, db=db, User=User)

manager.add_command("shell", Shell(make_context=make_shell_context))

if __name__ == '__main__':
    manager.run()

Body:
I just got done setting up a Flask app and I dealt with this kind of problem.

I strongly suspect the problem here is that the instance of db that you are creating in __init__.py is unaware of the contents of models.py, including the User class. The db object in __init__.py is a totally separate object from the db you are creating in models.py. So when you run db.create_all() in __init__.py, it is checking the list of tables that it knows about and isn't finding any. I ran into this exact issue.

What I discovered is that the models (like User) are registered with the particular db object that is listed in the model's class definition (e.g. class User(db.Model):).

So basically my understanding is that the way to fix this is to run db.create_all() using the same instance of db that is being used to define the models. In other words, run db.create_all() from within models.py.

Here's my code so you can see how I have it set up:

app.py:

#!flask/bin/python
import os

from flask import Flask

class CustomFlask(Flask):
    jinja_options = Flask.jinja_options.copy()
    jinja_options.update(dict(
        variable_start_string='%%',  # Default is '{{', I'm changing this because Vue.js uses '{{' / '}}'
        variable_end_string='%%',
    ))
app = CustomFlask(__name__)

app.config['SECRET_KEY'] = 'hard to guess string'

import yaml
if os.environ['SERVER_ENVIRONMENT'] == 'PRODUCTION':
    config_filename = "production.yaml"
elif os.environ['SERVER_ENVIRONMENT'] == 'LOCAL':
    config_filename = "local.yaml"
else:
    config_filename = "local.yaml"

base_directory = path = os.path.dirname(os.path.realpath(__file__))

with open(base_directory + "/config/" + config_filename) as config_file:
    config = yaml.load(config_file)

db_config = config['database']
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username=db_config['username'],
    password=db_config['password'],
    hostname=db_config['hostname'],
    databasename=db_config['databasename'],
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
db.app = app

def clear_the_template_cache():
    app.jinja_env.cache = {}

app.before_request(clear_the_template_cache)

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(email):
    from models import User
    return User.query.filter_by(email=email).first()

if __name__ == '__main__':
    from routes import web_routes
    app.register_blueprint(web_routes)

    from api import api
    app.register_blueprint(api)

    # To get PyCharm's debugger to work, you need to have "debug=False, threaded=True"
    #app.run(debug=False, threaded=True)
    app.run(debug=True)

models.py:

from app import db

import datetime
from werkzeug.security import generate_password_hash, \
     check_password_hash

class Song(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80))
    datetime_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    lines = db.relationship('Line', cascade="all,delete", backref=db.backref('song', lazy='joined'), lazy='dynamic')
    is_deleted = db.Column(db.Boolean, default=False)

class Line(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    song_id = db.Column(db.Integer, db.ForeignKey('song.id'))
    spans_of_time = db.relationship('SpanOfTime', cascade="all,delete", backref=db.backref('line', lazy='joined'), lazy='dynamic')

class SpanOfTime(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    line_id = db.Column(db.Integer, db.ForeignKey('line.id'))
    starting_64th = db.Column(db.Integer)  # I'm assuming the highest-granularity desired will be a 1/64th note-length.
    length = db.Column(db.Integer)  # I guess this'll be in 1/64th notes, so a 1/16th note will be '4'.
    content = db.Column(db.String(80))

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(80), primary_key=True, unique=True)
    display_name = db.Column(db.String(80), default="A Rhymecraft User")
    password_hash = db.Column(db.String(200))
    datetime_subscription_valid_until = db.Column(db.DateTime, default=datetime.datetime.utcnow() - datetime.timedelta(days=1))
    datetime_joined = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    songs = db.relationship('Song', cascade="all,delete", backref=db.backref('user', lazy='joined'), lazy='dynamic')

    def __init__(self, email, password):
        self.email = email
        self.set_password(password)

    def __repr__(self):
        return '<User %r>' % self.email

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.email)

def init_db():
    db.create_all()

    # Create a test user
    new_user = User('a@a.com', 'aaaaaaaa')
    new_user.display_name = 'Nathan'
    db.session.add(new_user)
    db.session.commit()

    new_user.datetime_subscription_valid_until = datetime.datetime(2019, 1, 1)
    db.session.commit()

if __name__ == '__main__':
    init_db()


问:
Is there a possibility to redirect from my ionic2 app to an external app?
I want to create a button, which when is clicked, an external application is opened. For example: https://play.google.com/store/apps/details?id=com.fitbit.FitbitMobile&hl=fr

Is there a way to do that?

答:
Have you tried this one?

https://github.com/nchutchind/cordova-plugin-app-launcher

I found the plugin during some googling. Hope it works.

Alternatively you can write your own plugin or make some native development.


问:
variable point to another variable by ref
I have a problem that I create a variable with value that not exist yet (other variable)

example:

```<code>var a=b;
var b=5;
console.log(a)
//I want result to be 5
</code>```

I need it to be without wrapping with function or object (unless I can still call "a" as is and not "a()" )

if 'a' can point to 'b' by ref I will do:

```<code>var b="temp"
var a=b
b=5
</code>```

so, is there any way that 'b' will point on same location as 'a' ?

答:
Maybe the Promises API could work for you? Docs here

A trivial example;

var bPromise = new Promise(function(resolve, reject) {
   resolve(5);
});

bPromise.then(function(result) {
   var a = result;
   console.log('a = ' + a);
});```

Body:
I have a problem that I create a variable with value that not exist yet (other variable)

example:

var a=b;
var b=5;
console.log(a)
//I want result to be 5

I need it to be without wrapping with function or object (unless I can still call "a" as is and not "a()" )

if 'a' can point to 'b' by ref I will do:

var b="temp"
var a=b
b=5

so, is there any way that 'b' will point on same location as 'a' ?


问:
MYSQL need to remove random values and add values in sequence
i have this table and i have column called order it has random values like
1
2
5
7
8
12
11
9

i want to remove that and get values in a sequence
1
2
3
4
5
6
7
8

is there a way to do that?

答:
welcome to this forum..I must say that you haven't searched well for solution ..but still I would like to help you.

You can use given command to get the data according to your question

```<code>SELECT * FROM your_table_name
ORDER BY order ;
</code>```

Or use identity on order column at the time of creation of your table as

```<code>CREATE TABLE your_table_name(
    order int identity(1, 1),
    other_columns ur_choice_datatype
);
</code>```

Body:
welcome to this forum..I must say that you haven't searched well for solution ..but still I would like to help you.

You can use given command to get the data according to your question

SELECT * FROM your_table_name
ORDER BY order ;

Or use identity on order column at the time of creation of your table as

CREATE TABLE your_table_name(
    order int identity(1, 1),
    other_columns ur_choice_datatype
);


问:
Remove input file button and style the files chosen
I am trying to create an upload form which takes multiple images. I want to be able to remove the "Choose Files" button but keep the "No file chosen" to inform the user what files they are going to be uploading.

I understand that I can set the opacity to 0 on the input type file styling, but this removes both the "Choose Files" and "No file chosen" text.

Here is the codepen of the image uploader so far.

To summarise:

I want to remove the Choose Files button

Keep the No file chosen text.

Here is the HTML:

```<code><div class="upload">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>Would you like to <span style='color: lightgreen;'>Upload</span> or <span style='color: orangered;'>Delete</span> a file?</h1>
                <div style="position: relative; height: 275px;">
                    <form action="" method="post" enctype="multipart/form-data" class="formUp">

                        <input type="file" name="fileToUpload[]" id="fileToUpload" accept="image/*" multiple="multiple"><p>Click here to upload images.</p></input>
                        <input type="submit" value="Upload Images" name="submitUpload" />
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Here is the CSS:

```<code>.up {
    border: none;
}

.upload {
    padding-top: 6%;
}

.upload input[type='file'] {
    outline: none;

    width: 100%;
    height: 100%;
    position: absolute;
}

.formUp {
    border: 4px dashed black;
    width: 400px;
    height: 200px;
    position: absolute;
}

.formUp p {
    text-align: center;
    width: 100%;
    height: 100%;
    line-height: 170px;
    font-weight: bold;
    font-size: 1.5em;
}

.upload input[type='submit'] {
    margin-top: 2%;
    width: 100%;
    height: 20%;
}

.upload input[type='submit'] {
  background: #0AC986;
  dispaly: inline-block;
  width: 100%;
  font-size: 16px;
  height: 50px;
  color: #fff;
  text-decoration: none;
  border: none;
  border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
}

.upload input[type='submit']:hover {
    color: #F37272;
    background-color: palegreen;
}

.upload input[type='submit'] {
    -o-transition: all .3s;
    -moz-transition: all .3s;
    -webkit-transition: all .3s;
    -ms-transition: all .3s;
}

.upload input[type='submit']:hover {
    color: red;
}
</code>```

答:
The text-indent property will manipulate the position of the Choose Files button but leave the No file chosen text.

```

    .upload input[type='file']
    {
        text-indent: -999em;
        outline: none;
        width: 100%;
        height: 100%;
        position: absolute;
    }

```

Body:
I am trying to create an upload form which takes multiple images. I want to be able to remove the "Choose Files" button but keep the "No file chosen" to inform the user what files they are going to be uploading.

I understand that I can set the opacity to 0 on the input type file styling, but this removes both the "Choose Files" and "No file chosen" text.

Here is the codepen of the image uploader so far.

To summarise:

I want to remove the Choose Files button

Keep the No file chosen text.

Here is the HTML:

Would you like to Upload or Delete a file?

                    <form action="" method="post" enctype="multipart/form-data" class="formUp">

                        <input type="file" name="fileToUpload[]" id="fileToUpload" accept="image/*" multiple="multiple">
Click here to upload images.
</input>
                        <input type="submit" value="Upload Images" name="submitUpload" />
                    </form>

Here is the CSS:

.up {
    border: none;
}

.upload {
    padding-top: 6%;
}

.upload input[type='file'] {
    outline: none;

    width: 100%;
    height: 100%;
    position: absolute;
}

.formUp {
    border: 4px dashed black;
    width: 400px;
    height: 200px;
    position: absolute;
}

.formUp p {
    text-align: center;
    width: 100%;
    height: 100%;
    line-height: 170px;
    font-weight: bold;
    font-size: 1.5em;
}

.upload input[type='submit'] {
    margin-top: 2%;
    width: 100%;
    height: 20%;
}

.upload input[type='submit'] {
  background: #0AC986;
  dispaly: inline-block;
  width: 100%;
  font-size: 16px;
  height: 50px;
  color: #fff;
  text-decoration: none;
  border: none;
  border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
}

.upload input[type='submit']:hover {
    color: #F37272;
    background-color: palegreen;
}

.upload input[type='submit'] {
    -o-transition: all .3s;
    -moz-transition: all .3s;
    -webkit-transition: all .3s;
    -ms-transition: all .3s;
}

.upload input[type='submit']:hover {
    color: red;
}

Body:
The text-indent property will manipulate the position of the Choose Files button but leave the No file chosen text.

    .upload input[type='file']
    {
        text-indent: -999em;
        outline: none;
        width: 100%;
        height: 100%;
        position: absolute;
    }


问:
Android Tabbed Activity Searchview not opening in Toolbar
the problem

I've used the Setting Up The Search interface doc from the official Android documentation but I'm not getting far for some strange reason as the SearchView refuses to open in the Toolbar
cfr. Android docs

the code

I've added the menu item as such:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="...">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView"/>
</menu>
```

<p>(Sidenote, I've also tried the v7 <code>SearchView</code> view class, but result is no different)
<br /><br /><br />
This is how the toolbar is laid out</p>

<pre class="lang-xml prettyprint-override"><code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        app:theme="@style/AppTheme.Toolbar"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>
</code>```

I have also added the SEARCH intent in the manifest and the menu gets properly inflated in the onCreateOptionsMenu method.

edit, manifest.xml and searchable.xml
Added these by request although I don't believe they are relevant to the issue.

<activity
    android:name=".HomeActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.SEND" />
        <action android:name="android.intent.action.SEARCH" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
```

<p>Searchable.xml
</p>

```<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="" />
```

Now according to the Android doc the SearchView is supposed to show up but when I press the search icon in the Toolbar nothing happens.

Any ideas what could be wrong?

答:
i got the solution my friend try this add your meta tag outside activity tag like this

replace your menu with

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_search"
    android:title="Search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
</code>```

now in your activity write this line of code

```<code>    Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
    setSupportActionBar(toolbar);

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pkgname">
<application
    android:name=".Utils.Application"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />
<activity
android:name=".HomeActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.SEND" />
    <action android:name="android.intent.action.SEARCH" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code>```

Body:
the problem

I've used the Setting Up The Search interface doc from the official Android documentation but I'm not getting far for some strange reason as the SearchView refuses to open in the Toolbar
cfr. Android docs

the code

I've added the menu item as such:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="...">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView"/>
</menu>

(Sidenote, I've also tried the v7 SearchView view class, but result is no different)

This is how the toolbar is laid out

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        app:theme="@style/AppTheme.Toolbar"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

I have also added the SEARCH intent in the manifest and the menu gets properly inflated in the onCreateOptionsMenu method.

edit, manifest.xml and searchable.xml
Added these by request although I don't believe they are relevant to the issue.

<activity
    android:name=".HomeActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.SEND" />
        <action android:name="android.intent.action.SEARCH" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Searchable.xml

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="" />

Now according to the Android doc the SearchView is supposed to show up but when I press the search icon in the Toolbar nothing happens.

Any ideas what could be wrong?

Body:
i got the solution my friend try this add your meta tag outside activity tag like this

replace your menu with

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_search"
    android:title="Search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

now in your activity write this line of code

    Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
    setSupportActionBar(toolbar);

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pkgname">
<application
    android:name=".Utils.Application"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />
<activity
android:name=".HomeActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.SEND" />
    <action android:name="android.intent.action.SEARCH" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


问:
Block command history access in shell
I don't want to access the shell command history in shell. It has to block for temporary purpose and after that I am able to release that block.

e.g. when I press up arrow in shell it shows the last command present in history, But i don't want to access history when I press up arrow on shell

Can we block history from accessing it?

i have tried set +o history  but its for different purpose.

```<code>shell:> ifconfig
shell:> #some shell.py
Login: #when I press up arrow, "ifconfig" comes here as that was last command
Password:
</code>```

for Login: it only has to access input, don't access history here.
After accepting Login and Password then i can able to access history again.

答:
You can disable the Up Arrow Key by editing your ~/.bashrc and adding :

bind '"\e[A": '

Meaning : Bind Up Arrow Key to nothing

(You will need to reload it or re-open your session)

To re-enable it, simply remove the line and reload the .bashrc file

Title: Block command history access in shell

Body:
I don't want to access the shell command history in shell. It has to block for temporary purpose and after that I am able to release that block.

e.g. when I press up arrow in shell it shows the last command present in history, But i don't want to access history when I press up arrow on shell

Can we block history from accessing it?

i have tried set +o history  but its for different purpose.

shell:> ifconfig
shell:> #some shell.py
Login: #when I press up arrow, "ifconfig" comes here as that was last command
Password:

for Login: it only has to access input, don't access history here.
After accepting Login and Password then i can able to access history again.


答:
To remove up-arrow binding

```<code>bind -r '\e[A'
</code>```

To restore

```<code>bind '"\e[A": previous-history'
</code>```

To retrieve all bindings to previous-history

```<code>bind -p | grep previous-history
</code>```

or

```<code>bind -q previous-history
</code>```

see also

```<code>help bind
</code>```

Title: Block command history access in shell

Body:
To remove up-arrow binding

bind -r '\e[A'

To restore

bind '"\e[A": previous-history'

To retrieve all bindings to previous-history

bind -p | grep previous-history

or

bind -q previous-history

see also

help bind


问:
React native - Change screen after x seconds
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

```<code>import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}
</code>```

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

答:
Not Using any navigator this can solve your problem</p>

```<code>import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
constructor(props){
 super(props)
 this.state = {
  component : <Quote />
 }
}

componentDidMount(){

     // Start counting when the page is loaded
     this.timeoutHandle = setTimeout(()=>{
          // Add your logic for the transition
          this.setState({ component: <Defis /> })
     }, 5000);
}

componentWillUnmount(){
     clearTimeout(this.timeoutHandle);
}

render() {
return (
  this.state.component
);
</code>```

Body:
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

Body:
Not Using any navigator this can solve your problem

import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
constructor(props){
 super(props)
 this.state = {
  component : <Quote />
 }
}

componentDidMount(){

     // Start counting when the page is loaded
     this.timeoutHandle = setTimeout(()=>{
          // Add your logic for the transition
          this.setState({ component: <Defis /> })
     }, 5000);
}

componentWillUnmount(){
     clearTimeout(this.timeoutHandle);
}

render() {
return (
  this.state.component
);


问:
SNS handle more than 10 million subscriptions per topic
how to SNS Topic handle  more than 10 million subscriptions.

Request increase the limit.
is any other option to handle this scenario.

Topic: MyAPPNOTIFICATION
Reached 9.9 Million subscriptions.

答:
The 2014 Amazon SNS Update – Large Topics and MPNS Authenticated Mode blog post from AWS says:

Today we are lifting the limit of 10,000 subscriptions per SNS topic; you can now create as many as you need and no longer need to partition large subscription lists across multiple topics. This has been a frequent request from AWS customers that use SNS to build news and media sharing applications.

There is an administrative limit of 10 million subscriptions per topic, but we’ll happily raise it if you expect to have more subscribers for a single topic. Fill out the Contact Us form, select SNS, and we’ll take good care of you!


问:
Elastic elements on scroll with javascript and or CSS
Is there anyone who knows if there is a javascript library or some functions which allow me to add a elastic/rubber band effect for specific elements on scroll? So in example, when I scroll very fast and suddenly stop, those elements will move out of place for a bit and then move back to their original position like they are attached to a rubber band.

I tried to search for this but couldn't find it.

Anyone who knows anything about this?

答:
You may want to use both ScrollMagic.js to control the scroll functionality and Animate.css to create the elastic effect.

Using ScrollMagic you can set a trigger at a specific screen location class/id/div etc. Upon which you can give the element a class from the Animate.css library e.g. Bounce.

ScrollMagic.js

Animate.css


问:
Toggle bootstrap value
How to find toggle value when using toggle in bootstrap.

```<code><input id="toggle-event" type="checkbox" data-toggle="toggle" data-on="Enabled" data-off="Disabled">

$(document).ready(function(){
    $('#toggle-event').change(function() {
        //Enabled means it will enter into if loop, here we sort machine list by green
        if('toggle is Enable'){
           //do something
        }
        //if toggle is disable
       else{
            //do something
        }
    })
  });
</code>```

In the above example, when i toggle to Enable or Disable, how to find the value of toggle checkbox.

答:
You mean that?

https://fiddle.jshell.net/MAXXALANDER/nrh6pq2n/1/

```<code>// HTML
<input type="checkbox" id="toggle-event" checked>
<div id="console-event"> </div>

// Jquery
$(document).ready(function(){

    $('#toggle-event').change(function() {

        if($(this).is(":checked")){
           //do something
           $('#console-event').html('on');
        } else{
           $('#console-event').html('off');
        }

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

Title: Toggle bootstrap value

Body:
How to find toggle value when using toggle in bootstrap.

<input id="toggle-event" type="checkbox" data-toggle="toggle" data-on="Enabled" data-off="Disabled">

$(document).ready(function(){
    $('#toggle-event').change(function() {
        //Enabled means it will enter into if loop, here we sort machine list by green
        if('toggle is Enable'){
           //do something
        }
        //if toggle is disable
       else{
            //do something
        }
    })
  });

In the above example, when i toggle to Enable or Disable, how to find the value of toggle checkbox.

Body:
You mean that?

https://fiddle.jshell.net/MAXXALANDER/nrh6pq2n/1/

// HTML
<input type="checkbox" id="toggle-event" checked>
<div id="console-event"> </div>

// Jquery
$(document).ready(function(){

    $('#toggle-event').change(function() {

        if($(this).is(":checked")){
           //do something
           $('#console-event').html('on');
        } else{
           $('#console-event').html('off');
        }

    })
  });


问:
GET https://127.0.0.1:9000/peerjs/peerjs/id?ts=14993271469660.591159722513086 net::ERR_CONNECTION_REFUSED
I have created a simple video chat app using javascript's webRTC library peerjs.
And now I am trying to deploy the site on zeit.co. But I get the error when a peerjs instance gets created
Below is the code where I have mentioned ports and host to run the server

Server side code

```<code>const express = require('express')
const app = express()
const path = require('path')
const server = require('http').createServer(app)
const io = require('socket.io').listen(server)

const srv = server.listen(3000)

app.use('/peerjs', require('peer').ExpressPeerServer(srv, {
    debug: true
}))

const users = []
const connections = []

server.listen(3000, () => {
  console.log('server running')
})

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', (req, res) => {

})
</code>```

Client side code

```<code>const peerObj = {
  host: '127.0.0.1',
  path: '/peerjs',
  debug: 3,
  config: {icerServers: [
    { url: 'stun:stun1.l.google.com:19302' },
    { url: 'turn:numb.viagenie.ca',
      credential: 'muazkh',
      username: 'webrtc@live.com' }
  ]}
}

peer = new Peer(peerObj)
</code>```

List item

答:
PeerJS's default port is 9000, which is also what the error suggests: it's trying to connect to port 9000 of 127.0.0.1, but your server is running on port 3000.

Try adding the port number explicitly:

```<code>const peerObj = {
  host : '127.0.0.1',
  port : 3000,
  ...
}
</code>```

You may also need to set secure : false, because your server doesn't support TLS.

Body:
I have created a simple video chat app using javascript's webRTC library peerjs.
And now I am trying to deploy the site on zeit.co. But I get the error when a peerjs instance gets created
Below is the code where I have mentioned ports and host to run the server

Server side code

const express = require('express')
const app = express()
const path = require('path')
const server = require('http').createServer(app)
const io = require('socket.io').listen(server)

const srv = server.listen(3000)

app.use('/peerjs', require('peer').ExpressPeerServer(srv, {
    debug: true
}))

const users = []
const connections = []

server.listen(3000, () => {
  console.log('server running')
})

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', (req, res) => {

})

Client side code

const peerObj = {
  host: '127.0.0.1',
  path: '/peerjs',
  debug: 3,
  config: {icerServers: [
    { url: 'stun:stun1.l.google.com:19302' },
    { url: 'turn:numb.viagenie.ca',
      credential: 'muazkh',
      username: 'webrtc@live.com' }
  ]}
}

peer = new Peer(peerObj)

List item

Body:
PeerJS's default port is 9000, which is also what the error suggests: it's trying to connect to port 9000 of 127.0.0.1, but your server is running on port 3000.

Try adding the port number explicitly:

const peerObj = {
  host : '127.0.0.1',
  port : 3000,
  ...
}

You may also need to set secure : false, because your server doesn't support TLS.