问:
Import css files and react components in a create-react-app application?
I'm just starting with react.js and create-react-app application so excuse me if this is an obvious question.

My 'src' folder structure is like this:

```<code>scr/
....components/
........ComponentA.jsx
........Componentb.jsx
....styles/
........ComponentA.css
....App.css
....App.js
....App.test.js
....index.css
....index.js
...OTHER DEFAULT FILES
</code>```

In App.js I have this:

```<code>import React, { Component } from 'react';
import ComponentA from './components/ComponentA';

class App extends Component {
  render() {
    return (
      <div className="App">
        <ComponentA />
      </div>
    );
  }
}

export default App;
</code>```

In ComponentA I have this:

```<code>import React, { Component } from 'react';
import './styles/ComponentA.css';
import ComponentB from './components/ComponentB';

class ComponentA extends Component {
  render() {
    return (
      <div className="componentAStyle">
        <ComponentB />
      </div>
    );
  }
}

export default ComponentA;
</code>```

In ComponentB I have this:

```<code>import React, { Component } from 'react';

class ComponentB extends Component {
  render() {
    return (
      <div>
        <h1>Hello from ComponentB</h1>
      </div>
    );
  }
}

export default ComponentB;
</code>```

What I'm trying to do is just import ComponentB from ComponentA and also import the style for ComponentA but all this fall showing the following message:

```<code>Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './styles/ComponentA.css' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.
</code>```

And if I remove the css import there is another error message:

```<code>Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './components/ComponentB' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.
</code>```

How can I import another component from another component and its respective css?

Thanks.

答:
You need to make the paths you are importing are relative to the current location of the file doing the import.

The correct imports would be

 Component A

```<code>import React, { Component } from 'react';
import '../styles/ComponentA.css';
import ComponentB from './ComponentB';
</code>```

You can see this working at https://glitch.com/edit/#!/trashy-unicorn.

(Click on Show Live in top left hand corner.)

Currently what is happening with your error is

```<code>import ComponentB from './components/ComponentB';
</code>```

is is looking in the path

```<code>src/components/components/ComponentB
</code>```

which does not exist and so gives you an error. Same thing is happening with your styles.

Hope this helps.

Body:
I'm just starting with react.js and create-react-app application so excuse me if this is an obvious question.

My 'src' folder structure is like this:

scr/
....components/
........ComponentA.jsx
........Componentb.jsx
....styles/
........ComponentA.css
....App.css
....App.js
....App.test.js
....index.css
....index.js
...OTHER DEFAULT FILES

In App.js I have this:

import React, { Component } from 'react';
import ComponentA from './components/ComponentA';

class App extends Component {
  render() {
    return (

        <ComponentA />

    );
  }
}

export default App;

In ComponentA I have this:

import React, { Component } from 'react';
import './styles/ComponentA.css';
import ComponentB from './components/ComponentB';

class ComponentA extends Component {
  render() {
    return (

        <ComponentB />

    );
  }
}

export default ComponentA;

In ComponentB I have this:

import React, { Component } from 'react';

class ComponentB extends Component {
  render() {
    return (

Hello from ComponentB

    );
  }
}

export default ComponentB;

What I'm trying to do is just import ComponentB from ComponentA and also import the style for ComponentA but all this fall showing the following message:

Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './styles/ComponentA.css' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.

And if I remove the css import there is another error message:

Failed to compile
./src/components/ComponentA.jsx
Module not found: Can't resolve './components/ComponentB' in 'C:\xampp\htdocs\custom-k39\src\components'
This error occurred during the build time and cannot be dismissed.

How can I import another component from another component and its respective css?

Thanks.

Body:
You need to make the paths you are importing are relative to the current location of the file doing the import.

The correct imports would be

 Component A

import React, { Component } from 'react';
import '../styles/ComponentA.css';
import ComponentB from './ComponentB';

You can see this working at https://glitch.com/edit/#!/trashy-unicorn.

(Click on Show Live in top left hand corner.)

Currently what is happening with your error is

import ComponentB from './components/ComponentB';

is is looking in the path

src/components/components/ComponentB

which does not exist and so gives you an error. Same thing is happening with your styles.

Hope this helps.


来源: stackexchange

问:
Android Studio Rendering Error xml files
I am getting rendering error with android...Toolbarand android...ConstraintLayout in my xml files. However, in another application I am using exactly the same xml files and no problem occurs.

I am parallelly developing these two applications so not much things differ with each other yet I cannot understand it is doing this. I am using Android Studio 2.3.3.

Error:

```<code>Rendering failed with a known bug. Please try a rebuild.

The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.design.widget.AppBarLayout (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
 Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE.  If this is an unexpected error you can also try to build the project, then manually refresh the layout.

Exception Details

java.lang.NoSuchFieldError: ViewBackgroundHelper
        at android.support.v7.widget.AppCompatBackgroundHelper.loadFromAttributes(AppCompatBackgroundHelper.java:46)
        at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:73)
        at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
        at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:262)
        at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
        at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
        at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
        at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
        at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
        at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
        at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at com.android.layoutlib.bridge.bars.CustomBar.<init>(CustomBar.java:95)
        at com.android.layoutlib.bridge.bars.NavigationBar.<init>(NavigationBar.java:52)
        at com.android.layoutlib.bridge.bars.NavigationBar.<init>(NavigationBar.java:46)
        at com.android.layoutlib.bridge.impl.Layout.createNavBar(Layout.java:284)
        at com.android.layoutlib.bridge.impl.Layout.<init>(Layout.java:140)
        at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:301)
        at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
        at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
        at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
        at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
        at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
        at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
        at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>```

答: Make sure that you are using the library of  ConstraintLayout...check in app:gradle

ContentLicense: CC BY-SA 3.0

Body:
I am getting rendering error with android...Toolbarand android...ConstraintLayout in my xml files. However, in another application I am using exactly the same xml files and no problem occurs.

I am parallelly developing these two applications so not much things differ with each other yet I cannot understand it is doing this. I am using Android Studio 2.3.3.

Error:

Rendering failed with a known bug. Please try a rebuild.

The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.design.widget.AppBarLayout (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
 Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE.  If this is an unexpected error you can also try to build the project, then manually refresh the layout.

Exception Details

java.lang.NoSuchFieldError: ViewBackgroundHelper
        at android.support.v7.widget.AppCompatBackgroundHelper.loadFromAttributes(AppCompatBackgroundHelper.java:46)
        at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:73)
        at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
        at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:262)
        at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
        at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
        at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
        at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
        at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
        at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
        at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at com.android.layoutlib.bridge.bars.CustomBar.<init>(CustomBar.java:95)
        at com.android.layoutlib.bridge.bars.NavigationBar.<init>(NavigationBar.java:52)
        at com.android.layoutlib.bridge.bars.NavigationBar.<init>(NavigationBar.java:46)
        at com.android.layoutlib.bridge.impl.Layout.createNavBar(Layout.java:284)
        at com.android.layoutlib.bridge.impl.Layout.<init>(Layout.java:140)
        at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:301)
        at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
        at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
        at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
        at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
        at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
        at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
        at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)


问:
How to re-structure an Array to an Object based on the value the array elements' property?
I have this array,(which contains all the definition of "love" btw):

```<code>[
    {
        def: "a strong positive emotion of regard and affection",
        exemple: "hildren need a lot of love",
        class_: "noun"
    },
    {
        def: "any object of warm affection or devotion",
        exemple: "the theater was her first love",
        class_: "noun"
    },
    {
        def: "sexual activities (often including sexual intercourse) between two people",
        exemple: "he has a very complicated love life",
        class_: "noun"
    },

    {
        def: "have a great affection or liking for",
        exemple: "She loves her boss and works hard for him",
        class_: "verb"
    },
    {
        def: "get pleasure from",
        exemple: "I love cooking",
        class_: "verb"
    },
]
</code>```

Is it possible to re-structure the Array to an Object with Underscore-PHP or PHP Array function by grouping the array elements based on the value of < class_ > like that:

```<code>{
    noun: [
    {
        def: "a strong positive emotion of regard and affection",
        exemple: "hildren need a lot of love",
        class_: "noun"
    },
    {
        def: "any object of warm affection or devotion",
        exemple: "the theater was her first love",
        class_: "noun"
    },
    {
        def: "sexual activities (often including sexual intercourse) between two people",
        exemple: "he has a very complicated love life",
        class_: "noun"
    },
    ],

    verb: [
    {
        def: "have a great affection or liking for",
        exemple: "She loves her boss and works hard for him",
        class_: "verb"
    },
    {
        def: "get pleasure from",
        exemple: "I love cooking",
        class_: "verb"
    },
    ]
}
</code>```

答:
The algorithm to convert your json string into a grouped one would be like this:

Decode the json string using json_decode() function to get a multidimensional array.

Loop through the array to group the array elements as per your need.

Finally encode the array using json_encode() function to get the desired json string.

So your code should be like this:

(Suppose $json is your original json string)

```<code>// suppose $json is your original json string
$array = json_decode($json, true);

$resultArr = array();
foreach($array as $arr){
    $resultArr[$arr['class_']][] = $arr;
}

// display the resultant json string
echo json_encode($resultArr);
</code>```

Body:
I have this array,(which contains all the definition of "love" btw):

[
    {
        def: "a strong positive emotion of regard and affection",
        exemple: "hildren need a lot of love",
        class_: "noun"
    },
    {
        def: "any object of warm affection or devotion",
        exemple: "the theater was her first love",
        class_: "noun"
    },
    {
        def: "sexual activities (often including sexual intercourse) between two people",
        exemple: "he has a very complicated love life",
        class_: "noun"
    },

    {
        def: "have a great affection or liking for",
        exemple: "She loves her boss and works hard for him",
        class_: "verb"
    },
    {
        def: "get pleasure from",
        exemple: "I love cooking",
        class_: "verb"
    },
]

Is it possible to re-structure the Array to an Object with Underscore-PHP or PHP Array function by grouping the array elements based on the value of < class_ > like that:

{
    noun: [
    {
        def: "a strong positive emotion of regard and affection",
        exemple: "hildren need a lot of love",
        class_: "noun"
    },
    {
        def: "any object of warm affection or devotion",
        exemple: "the theater was her first love",
        class_: "noun"
    },
    {
        def: "sexual activities (often including sexual intercourse) between two people",
        exemple: "he has a very complicated love life",
        class_: "noun"
    },
    ],

    verb: [
    {
        def: "have a great affection or liking for",
        exemple: "She loves her boss and works hard for him",
        class_: "verb"
    },
    {
        def: "get pleasure from",
        exemple: "I love cooking",
        class_: "verb"
    },
    ]
}

Body:
The algorithm to convert your json string into a grouped one would be like this:

Decode the json string using json_decode() function to get a multidimensional array.

Loop through the array to group the array elements as per your need.

Finally encode the array using json_encode() function to get the desired json string.

So your code should be like this:

(Suppose $json is your original json string)

// suppose $json is your original json string
$array = json_decode($json, true);

$resultArr = array();
foreach($array as $arr){
    $resultArr[$arr['class_']][] = $arr;
}

// display the resultant json string
echo json_encode($resultArr);


问:
How to inject a class in the app/console/Kernel in Laravel?
I'm trying to inject a class (a repository) in my app/Console/Kernel:

```<code>public function __construct(LocaleRepository $localeRepository)
{
    $this->_localeRepository = $localeRepository;
}
</code>```

Unfortunately this doesn't work as I receive the following error:
PHP Fatal error:  Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [App\Repositories\Interfaces\LocaleRepository] is not instantiable while building [App\Console\Kernel]. in /home/cv/cus/vendor/laravel/framework/src/Illuminate/Container/Container.php:895

I can inject the repository in  controllers without any problem. The repository is also registered in the service provider:

```<code>public function register()
{
    $this->app->bind('App\Repositories\Interfaces\LocaleRepository', 'App\Repositories\Implementations\EloquentLocaleRepository');
}
</code>```

Is it possible to inject a class in the app/console/Kernel class?

答:
class app/console/Kernel is instantiated before the app service provider is loaded.

So, I don't think it's possible to inject the class into the constructor.

However, you could use method injection. Just inject the repository into the method in which you need it.

Body:
I'm trying to inject a class (a repository) in my app/Console/Kernel:

public function __construct(LocaleRepository $localeRepository)
{
    $this->_localeRepository = $localeRepository;
}

Unfortunately this doesn't work as I receive the following error:
PHP Fatal error:  Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [App\Repositories\Interfaces\LocaleRepository] is not instantiable while building [App\Console\Kernel]. in /home/cv/cus/vendor/laravel/framework/src/Illuminate/Container/Container.php:895

I can inject the repository in  controllers without any problem. The repository is also registered in the service provider:

public function register()
{
    $this->app->bind('App\Repositories\Interfaces\LocaleRepository', 'App\Repositories\Implementations\EloquentLocaleRepository');
}

Is it possible to inject a class in the app/console/Kernel class?


问:
Symfony 2. Migration project to php 7 from php5.5. Performance issues
I have one project ~4y old, I started with 5.3 and Symfony 2.0, migrated to 5.5 and S2.3. At the moment I migrated to S2.8 and I want to migrate to php 7.

As there was so much heap around PHP 7 performance I was eager to test my project performance in dev env.

So running benchmark in dev env; service is on vagrant host having both php5-fpm and php7.0-fpm, shutting one down and setting another up.

I would expect that php7 would outperform php5, but basically it seems that php7 is 1.5-2 times slower on my local dev env.

What am I doing wrong? Or should I rewrite my app somehow?

phpinfo:
php 7 http://pastebin.com/a6a76vE2
php 5 http://pastebin.com/4GBXNmBB

P.S. Yes, I understand that running benchmarks in local dev env is not 100% valid and pure, but I need only to understand if php7 faster than php5, as it said.

U1

Funniest thing is that blackfire shows clearly that php 7 is ~45% faster than php 5. But when I am sieging, than I see that performance degrades.

U2

Here is more or less my custom configuration for dev env. It is the same for php5.5 and php7:

```<code>[Date]
date.timezone = Europe/Tallinn

[PHP]
memory_limit = 512M
expose_php = Off
cgi.fix_pathinfo = 0
post_max_size = 10M
upload_max_filesize = 10M
max_execution_time = 60
realpath_cache_size = 4096k
realpath_cache_ttl = 7200

error_reporting = E_ALL | E_STRICT
log_errors = On
error_log = /var/log/php.errors.log

display_errors = On
display_startup_errors = On
html_errors = On

; xdebug
xdebug.remote_enable = On
xdebug.remote_port = 9001
xdebug.max_nesting_level = 200
xdebug.remote_log = /tmp/xdebug.log
xdebug.remote_connect_back = on
xdebug.idekey = "vagrant"

[opcache]
opcache.enable_cli=0
opcache.save_comments=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=66000
opcache.fast_shutdown=1
opcache.enable=1
opcache.revalidate_freq=5
opcache.validate_timestamps=1
</code>```

答:
Few steps to optimize PHP code globally and for PHP7 :

composer selfupdate

composer update

composer dumpautoload -a

activate zend opcache (or any other installed php opcache)

in php.ini :

opcache.max_accelerated_files=20000 (or more)

opcache.validate_timestamps=1

opcache.revalidate_freq=10 (or more)

xdebug.default_enable=0

restart php-fpm7 service

If performance issues still persist, profile your typical test page with blackfire.

Body:
I have one project ~4y old, I started with 5.3 and Symfony 2.0, migrated to 5.5 and S2.3. At the moment I migrated to S2.8 and I want to migrate to php 7.

As there was so much heap around PHP 7 performance I was eager to test my project performance in dev env.

So running benchmark in dev env; service is on vagrant host having both php5-fpm and php7.0-fpm, shutting one down and setting another up.

I would expect that php7 would outperform php5, but basically it seems that php7 is 1.5-2 times slower on my local dev env.

What am I doing wrong? Or should I rewrite my app somehow?

phpinfo:
php 7 http://pastebin.com/a6a76vE2
php 5 http://pastebin.com/4GBXNmBB

P.S. Yes, I understand that running benchmarks in local dev env is not 100% valid and pure, but I need only to understand if php7 faster than php5, as it said.

U1

Funniest thing is that blackfire shows clearly that php 7 is ~45% faster than php 5. But when I am sieging, than I see that performance degrades.

U2

Here is more or less my custom configuration for dev env. It is the same for php5.5 and php7:

[Date]
date.timezone = Europe/Tallinn

[PHP]
memory_limit = 512M
expose_php = Off
cgi.fix_pathinfo = 0
post_max_size = 10M
upload_max_filesize = 10M
max_execution_time = 60
realpath_cache_size = 4096k
realpath_cache_ttl = 7200

error_reporting = E_ALL | E_STRICT
log_errors = On
error_log = /var/log/php.errors.log

display_errors = On
display_startup_errors = On
html_errors = On

; xdebug
xdebug.remote_enable = On
xdebug.remote_port = 9001
xdebug.max_nesting_level = 200
xdebug.remote_log = /tmp/xdebug.log
xdebug.remote_connect_back = on
xdebug.idekey = "vagrant"

[opcache]
opcache.enable_cli=0
opcache.save_comments=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=66000
opcache.fast_shutdown=1
opcache.enable=1
opcache.revalidate_freq=5
opcache.validate_timestamps=1


问:
How to use function to call button instead of pressing it (swift3)
I want to be able to call function start within function use without hitting the action button for start. I know simple thing to do is just put print("a") in use. But I am using this as a simple example because I have a more complex problem in mind. </p>

```<code>   @IBAction func start(_ sender: Any) {
print("a")}

fun use() {
}

viewdidload() {
use()
}
</code>```

答:
Consider refactoring your functions. Instead of putting the button action code directly inside of the @IBAction function, put it in a separate function. This way, you can call this code from multiple places.

Here is one solution:

```<code>@IBAction func start(_ sender: Any) {
    startAction()
}

func startAction() {
    print("a")
}

func use() {
    startAction()
    // anything else
}

override func viewDidLoad() {
    use()
}
</code>```

Body:
I want to be able to call function start within function use without hitting the action button for start. I know simple thing to do is just put print("a") in use. But I am using this as a simple example because I have a more complex problem in mind.

   @IBAction func start(_ sender: Any) {
print("a")}

fun use() {
}

viewdidload() {
use()
}

Body:
Consider refactoring your functions. Instead of putting the button action code directly inside of the @IBAction function, put it in a separate function. This way, you can call this code from multiple places.

Here is one solution:

@IBAction func start(_ sender: Any) {
    startAction()
}

func startAction() {
    print("a")
}

func use() {
    startAction()
    // anything else
}

override func viewDidLoad() {
    use()
}


问:
array value by jQuery
I have an javascript array that has the following values,

```<code>let arr = ["2","4","6","8","10"];
</code>```

I have a second array that has three integers,

```<code>let index = [1,5,9];
</code>```

How would I use jQuery (or Javascript) to use the array to get the index from arr, and add it to a new array. I want to add these strings to a new array.

```<code>indexArr = ["1","3","5"]
</code>```

Thanks

答:
```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    $(document).ready(function(){
    var arr = ["2","4","6","8","10"];
    var index =  ["1","5","9"];
    var arrIndex = index.map(function(value){
             return arr.indexOf(value);
    })

    console.log(arrIndex);
    })</code>```

    ```
</div>
</div>

</code>```

Title: array value by jQuery

Body:
I have an javascript array that has the following values,

let arr = ["2","4","6","8","10"];

I have a second array that has three integers,

let index = [1,5,9];

How would I use jQuery (or Javascript) to use the array to get the index from arr, and add it to a new array. I want to add these strings to a new array.

indexArr = ["1","3","5"]

Thanks

Body:
    $(document).ready(function(){
    var arr = ["2","4","6","8","10"];
    var index =  ["1","5","9"];
    var arrIndex = index.map(function(value){
             return arr.indexOf(value);
    })

    console.log(arrIndex);
    })

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
execute stored procedure from SqlQuery data reader issue
so i am trying to execute my stored procedure as folowing

```<code>            String sql =
        "SET NOCOUNT ON; " +
        "DECLARE @id INT, @itemnumber nvarchar(20); " +
        "SELECT @id= '" + car.ID + "'" +
        "EXEC [file].[usp_iudCar] " +
        "@p_ID=@id OUTPUT," +
        "@p_Location= '" + location + "', " +
        "@p_ItemNumber=@itemnumber OUTPUT, " +
        "@p_DoerTicket= '" + userToken + "' " +
        "SELECT @id AS id, @itemnumber AS itemNumber; ";

            QueryParamCollection queryParams = new QueryParamCollection();
            queryParams.AddInt32Param(QueryParamName.CarID, (object)car.ID);
            queryParams.AddStringParam(QueryParamName.Location, (object)location);
            queryParams.AddStringParam(QueryParamName.DoerTicket, (object)userToken);

            var update = context.Database.SqlQuery<Int32>(sql).FirstOrDefault<Int32>();

            return update;
</code>```

similar to when i doing it from query on the server as

```<code>   DECLARE @return_value int,
            @p_ID int,
            @p_ItemNumber nvarchar(20)

    SELECT  @p_ID = 1783999

    EXEC    @return_value = [file].[usp_iudCar]
            @p_ID = @p_ID OUTPUT,
            @p_ItemNumber = @p_ItemNumber OUTPUT,
            @p_Location = N'test',
            @p_DoerTicket = N'0x0100000057065fc3a91f34c3f1f9cad41e2f5889bac6a68d3eab408dddc1cd54e57ce240565294f481f4f248bca4fb772d38fd737a6448dcbbfd9d58'

    SELECT  @p_ID as N'@p_ID',
            @p_ItemNumber as N'@p_ItemNumber'

    SELECT  'Return Value' = @return_value

    GO
</code>```

result set

but i gets an execption

"ExceptionMessage": "The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.",

so how do i fix that or what is the correct way to do this?

答:
This error:

"ExceptionMessage": "The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.",

means that your stored procedure returns more than just one field. This is what you are telling EF:

```<code>var update = context.Database.SqlQuery<Int32>(sql).FirstOrDefault<Int32>();
</code>```

that the query returns a single field but clearly that is not the case or you would not get that error.

Also that is not how to call a stored procedure using EF database first approach. Please refer this question and accepted answer for how to do what you want the proper way.

Body:
so i am trying to execute my stored procedure as folowing

            String sql =
        "SET NOCOUNT ON; " +
        "DECLARE @id INT, @itemnumber nvarchar(20); " +
        "SELECT @id= '" + car.ID + "'" +
        "EXEC [file].[usp_iudCar] " +
        "@p_ID=@id OUTPUT," +
        "@p_Location= '" + location + "', " +
        "@p_ItemNumber=@itemnumber OUTPUT, " +
        "@p_DoerTicket= '" + userToken + "' " +
        "SELECT @id AS id, @itemnumber AS itemNumber; ";

            QueryParamCollection queryParams = new QueryParamCollection();
            queryParams.AddInt32Param(QueryParamName.CarID, (object)car.ID);
            queryParams.AddStringParam(QueryParamName.Location, (object)location);
            queryParams.AddStringParam(QueryParamName.DoerTicket, (object)userToken);

            var update = context.Database.SqlQuery<Int32>(sql).FirstOrDefault<Int32>();

            return update;

similar to when i doing it from query on the server as

   DECLARE @return_value int,
            @p_ID int,
            @p_ItemNumber nvarchar(20)

    SELECT  @p_ID = 1783999

    EXEC    @return_value = [file].[usp_iudCar]
            @p_ID = @p_ID OUTPUT,
            @p_ItemNumber = @p_ItemNumber OUTPUT,
            @p_Location = N'test',
            @p_DoerTicket = N'0x0100000057065fc3a91f34c3f1f9cad41e2f5889bac6a68d3eab408dddc1cd54e57ce240565294f481f4f248bca4fb772d38fd737a6448dcbbfd9d58'

    SELECT  @p_ID as N'@p_ID',
            @p_ItemNumber as N'@p_ItemNumber'

    SELECT  'Return Value' = @return_value

    GO

result set

but i gets an execption

"ExceptionMessage": "The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.",

so how do i fix that or what is the correct way to do this?

Body:
This error:

"ExceptionMessage": "The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.",

means that your stored procedure returns more than just one field. This is what you are telling EF:

var update = context.Database.SqlQuery<Int32>(sql).FirstOrDefault<Int32>();

that the query returns a single field but clearly that is not the case or you would not get that error.

Also that is not how to call a stored procedure using EF database first approach. Please refer this question and accepted answer for how to do what you want the proper way.


问:
How can i store token value into my local javascript file
Hi am a beginner to Nodejs i have used passportjs token based authentication if the user logins it provides a token for each user i want to perform some operations based for the users who has token values for example if the user want to see the list of registered users they can view it if he has the token value. Now it provides me the token value perfectly in Postman but i don't know how to store it in a variable and call it via FRONT-END. I want do it via Front End(If he clicks the get users button) it should display the list of users.I have done that in POSTMAN it works finely i don't have an idea how to do it via frontend.
My user Code(Login/Logout)

```<code>var express = require('express');
var router = express.Router();
var User = require('../models/user');
var passport = require('passport');
var Verify    = require('./verify');
/* GET users listing. */
router.route('/')
.get(Verify.verifyOrdinaryUser, function(req, res, next) {
    User.find({}, function (err, users) {
            if (err) throw err;
            res.json(users);
        });
});
router.post('/register', function(req, res, next) {
    User.register(new User({ username : req.body.username }),req.body.password, function(err, user) {
        if (err) {
            return res.status(500).json({err: err});
        }
        user.save(function(err,user) {
            passport.authenticate('local')(req, res, function () {
                return res.status(200).json({status: 'Registration Successful!'});
            });
        });
    });
});
router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return res.status(401).json({
                err: info
            });
        }
        req.logIn(user, function(err) {
            if (err) {
                return res.status(500).json({
                    err: 'Could not log in user'
                });
            }
            var token = Verify.getToken(user);
            res.status(200).json({
                status: 'Login successful!',
                success: true,
                token: token
            });
        });
    })(req,res,next);
});
router.get('/logout', function(req, res) {
        req.logout();
    res.status(200).json({
        status: 'Bye!'
    });
});
module.exports = router;
</code>```

Main.js File. In this main.js file i want to send that token in this get method any idea?

```<code>$(".get-users-button").click(function() {
  $.ajax({
      method: "GET",
      url: " http://localhost:3000/users"
    })
    .done(function(msg) {
      console.log(msg);
      template(msg);
    });
});
</code>```

答:
As per the documentation for Passport:

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

Now if I'm understanding your question correctly, you want to pass the token value you obtain from:

```<code>var token = Verify.getToken(user)
</code>```

to the view in which your front-end can do something with. You can pass variables to the view using the following middleware:

```<code>app.use((req, res, next) => {
  res.locals.token = Verify.getToken(req.user)
  next()
}
</code>```

See the documentation for res.locals for more details.

Example usage:

app.js

```<code>const express = require('express')
const app = express()

app.set('view engine', 'pug')

app.use((req, res, next) => {
  res.locals.text = 'asdf'
  res.locals.token = 'abc'
  next()
})

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

app.listen(3000, () => {
  console.log('listening on 3000')
})
</code>```

views/index.pug

```<code>doctype html
html
  head
    title= title
  body
    h1= text
  script.
    console.log('#{token}')
</code>```

Body:
Hi am a beginner to Nodejs i have used passportjs token based authentication if the user logins it provides a token for each user i want to perform some operations based for the users who has token values for example if the user want to see the list of registered users they can view it if he has the token value. Now it provides me the token value perfectly in Postman but i don't know how to store it in a variable and call it via FRONT-END. I want do it via Front End(If he clicks the get users button) it should display the list of users.I have done that in POSTMAN it works finely i don't have an idea how to do it via frontend.
My user Code(Login/Logout)

var express = require('express');
var router = express.Router();
var User = require('../models/user');
var passport = require('passport');
var Verify    = require('./verify');
/* GET users listing. */
router.route('/')
.get(Verify.verifyOrdinaryUser, function(req, res, next) {
    User.find({}, function (err, users) {
            if (err) throw err;
            res.json(users);
        });
});
router.post('/register', function(req, res, next) {
    User.register(new User({ username : req.body.username }),req.body.password, function(err, user) {
        if (err) {
            return res.status(500).json({err: err});
        }
        user.save(function(err,user) {
            passport.authenticate('local')(req, res, function () {
                return res.status(200).json({status: 'Registration Successful!'});
            });
        });
    });
});
router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return res.status(401).json({
                err: info
            });
        }
        req.logIn(user, function(err) {
            if (err) {
                return res.status(500).json({
                    err: 'Could not log in user'
                });
            }
            var token = Verify.getToken(user);
            res.status(200).json({
                status: 'Login successful!',
                success: true,
                token: token
            });
        });
    })(req,res,next);
});
router.get('/logout', function(req, res) {
        req.logout();
    res.status(200).json({
        status: 'Bye!'
    });
});
module.exports = router;

Main.js File. In this main.js file i want to send that token in this get method any idea?

$(".get-users-button").click(function() {
  $.ajax({
      method: "GET",
      url: " http://localhost:3000/users"
    })
    .done(function(msg) {
      console.log(msg);
      template(msg);
    });
});

Body:
As per the documentation for Passport:

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

Now if I'm understanding your question correctly, you want to pass the token value you obtain from:

var token = Verify.getToken(user)

to the view in which your front-end can do something with. You can pass variables to the view using the following middleware:

app.use((req, res, next) => {
  res.locals.token = Verify.getToken(req.user)
  next()
}

See the documentation for res.locals for more details.

Example usage:

app.js

const express = require('express')
const app = express()

app.set('view engine', 'pug')

app.use((req, res, next) => {
  res.locals.text = 'asdf'
  res.locals.token = 'abc'
  next()
})

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

app.listen(3000, () => {
  console.log('listening on 3000')
})

views/index.pug

doctype html
html
  head
    title= title
  body
    h1= text
  script.
    console.log('#{token}')


问:
Read & split multiple column text file into arrays
For a project I'm working on a fairly big animal dataset with up to 14 parameters of data. I was able to read it in and display it as strings using this:

```<code>public static void readIn(String file) throws IOException {

    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        System.out.println(data);
    }
}
</code>```

and displaying something like this:

```<code>04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01    0.32    -0.03   -0.07   1047505 977.34  92.91
04:00:01    0.49    -0.03   -0.08   1047493 978.66  92.17
</code>```

But I'm currently having trouble trying to split each column into separate arrays so that I can process the data (e.g. calculating means). Any idea of how I can do this? Any help would be much appreciated.

Edit: thanks, I've found out a solution that works and also lets me choose which channel it reads specifically. I've also decided to store the data as arrays within the class, here's what I have now:

```<code>public static void readChannel(String file, int channel) throws IOException
{
    List<Double> dataArr = new ArrayList<>();
    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("\t");

        for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
            dataArr.add(Double.parseDouble(columns[i]));
            dataArr.toArray();
        }
    }
}
</code>```

答:
Following snippet will list down all values for a given index</p>

```<code>public static void readIn(String file) throws Exception {

Scanner scanner = new Scanner(new File(file));
  final Map<Integer,List<String>> resultMap = new HashMap<>();
  while (scanner.hasNext()) {
    String[] columns = scanner.nextLine().split("/t");
    for(int i=0;i<columns.length;i++){
      resultMap.computeIfAbsent(i, k -> new ArrayList<>()).add(columns[i]);
    }
  }   resultMap.keySet().forEach(index -> System.out.println(resultMap.get(index).toString()));}
</code>```

Body:
For a project I'm working on a fairly big animal dataset with up to 14 parameters of data. I was able to read it in and display it as strings using this:

public static void readIn(String file) throws IOException {

    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        System.out.println(data);
    }
}

and displaying something like this:

04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01    0.32    -0.03   -0.07   1047505 977.34  92.91
04:00:01    0.49    -0.03   -0.08   1047493 978.66  92.17

But I'm currently having trouble trying to split each column into separate arrays so that I can process the data (e.g. calculating means). Any idea of how I can do this? Any help would be much appreciated.

Edit: thanks, I've found out a solution that works and also lets me choose which channel it reads specifically. I've also decided to store the data as arrays within the class, here's what I have now:

public static void readChannel(String file, int channel) throws IOException
{
    List<Double> dataArr = new ArrayList<>();
    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("\t");

        for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
            dataArr.add(Double.parseDouble(columns[i]));
            dataArr.toArray();
        }
    }
}

Body:
Following snippet will list down all values for a given index

public static void readIn(String file) throws Exception {

Scanner scanner = new Scanner(new File(file));
  final Map<Integer,List<String>> resultMap = new HashMap<>();
  while (scanner.hasNext()) {
    String[] columns = scanner.nextLine().split("/t");
    for(int i=0;i<columns.length;i++){
      resultMap.computeIfAbsent(i, k -> new ArrayList<>()).add(columns[i]);
    }
  }   resultMap.keySet().forEach(index -> System.out.println(resultMap.get(index).toString()));}


问:
date problem while adding Event to iPhone calendar
while adding an event to the calendar of an iphone, the date is going to be reseted to 1.1.2001 and i have no idea why.

```<code>id arg1 = [args objectAtIndex:0];  // start
id arg2 = [args objectAtIndex:1];  // end
id arg3 = [args objectAtIndex:2];  // title
id arg4 = [args objectAtIndex:3];  // location
id arg5 = [args objectAtIndex:4];  // text

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startdate = [df dateFromString: arg1];
NSDate *enddate = [df dateFromString: arg2];

EKEventStore *eventStore = [[[EKEventStore alloc] init] autorelease];

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];

event.title     = arg3;
event.location  = arg4;
event.notes     = arg5;
event.startDate = startdate;
event.endDate   = enddate;

[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
</code>```

the input seems to be fine since

```<code>NSLog([args objectAtIndex:0]);
</code>```

writes the correct date. i have no real idea :(

答:
Your input maybe correct but the formatter is not. Please, review these 2 lines. I believe the bug is there</p>

```<code>[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startdate = [df dateFromString: arg1];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
while adding an event to the calendar of an iphone, the date is going to be reseted to 1.1.2001 and i have no idea why.

id arg1 = [args objectAtIndex:0];  // start
id arg2 = [args objectAtIndex:1];  // end
id arg3 = [args objectAtIndex:2];  // title
id arg4 = [args objectAtIndex:3];  // location
id arg5 = [args objectAtIndex:4];  // text

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startdate = [df dateFromString: arg1];
NSDate *enddate = [df dateFromString: arg2];

EKEventStore *eventStore = [[[EKEventStore alloc] init] autorelease];

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];

event.title     = arg3;
event.location  = arg4;
event.notes     = arg5;
event.startDate = startdate;
event.endDate   = enddate;

[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];

the input seems to be fine since

NSLog([args objectAtIndex:0]);

writes the correct date. i have no real idea :(

Body:
Your input maybe correct but the formatter is not. Please, review these 2 lines. I believe the bug is there

[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startdate = [df dateFromString: arg1];


问:
standalone Shell script working fine but not working with crontab
I have a shell script which has the below statements. It works fine while executing stand alone.

```<code>$ORACLEHOME/bin/sqlplus -s $BDBUSER@$LINKNAME/$BDBPASSWORD <<EOF
  DECLARE
  COUNT1 NUMBER:=0;
  BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE TABLE1';
    EXECUTE IMMEDIATE 'CREATE TABLE TABLE1 AS SELECT * FROM $SCHEMA_NAME.TABLE2@DBLINKNAME';
  END;
  /

EOF
</code>```

But when I call this ffrom crontab, it fails. My crontab looks like

```<code>*/1 * * * * /bin/sh /home/mig/Test.sh > /home/mig/Test.txt
</code>```

I am getting the following error in log.

```<code>Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
</code>```

Any help is appreciated.

答:
Try adding the this line on the top of your shell script.

```<code>export ORACLE_HOME=/path/to/oracle/home/directory
</code>```

Get the value of ORACLE_HOME environment variable using  echo command on your shell

Body:
I have a shell script which has the below statements. It works fine while executing stand alone.

$ORACLEHOME/bin/sqlplus -s $BDBUSER@$LINKNAME/$BDBPASSWORD <<EOF
  DECLARE
  COUNT1 NUMBER:=0;
  BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE TABLE1';
    EXECUTE IMMEDIATE 'CREATE TABLE TABLE1 AS SELECT * FROM $SCHEMA_NAME.TABLE2@DBLINKNAME';
  END;
  /

EOF

But when I call this ffrom crontab, it fails. My crontab looks like

*/1 * * * * /bin/sh /home/mig/Test.sh > /home/mig/Test.txt

I am getting the following error in log.

Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory

Any help is appreciated.

Body:
Try adding the this line on the top of your shell script.

export ORACLE_HOME=/path/to/oracle/home/directory

Get the value of ORACLE_HOME environment variable using  echo command on your shell


问:
With a SVG circle, how to position the starting point?
I'm working to create an SVG circle progress indicator in react... Here is my output:

CODEPEN

The problem is I need the red stroke to start at the top, not at the current 90% angle... Is there some CSS I can add to reposition the red stroke to start at the top?

FYI, I'm using the following component in react to render this HTML: https://github.com/wmartins/react-circular-progress/blob/gh-pages/src/js/components/CircularProgress.jsx.js

codepen source below

html

```<code><svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">
   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg>
</code>```

css

```<code>.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0 50%);
}
</code>```

答:
You could use transform, add transform="rotate(-90 25 25)" and it will start at the top

.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">

   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle transform="rotate(-90 25 25)" class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-startOffest: 50%;stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg></code>```

If to use CSS, you can rotate the svg element instead of the circle (which might or might not be possible based on its shape)

.CircularProgress {
    transform: rotate(-90deg);
}

.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0, 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">
   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg></code>```

Body:
I'm working to create an SVG circle progress indicator in react... Here is my output:

CODEPEN

The problem is I need the red stroke to start at the top, not at the current 90% angle... Is there some CSS I can add to reposition the red stroke to start at the top?

FYI, I'm using the following component in react to render this HTML: https://github.com/wmartins/react-circular-progress/blob/gh-pages/src/js/components/CircularProgress.jsx.js

codepen source below

html

<svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">
   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg>

css

.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0 50%);
}

Body:
You could use transform, add transform="rotate(-90 25 25)" and it will start at the top

.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0 50%);
}

<svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">

   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle transform="rotate(-90 25 25)" class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-startOffest: 50%;stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg>

If to use CSS, you can rotate the svg element instead of the circle (which might or might not be possible based on its shape)

.CircularProgress {
    transform: rotate(-90deg);
}

.CircularProgress-Bg,
.CircularProgress-Fg {
    fill: none;
}

.CircularProgress-Bg {
    stroke: #CCC;
}

.CircularProgress-Fg {
    transition: stroke-dashoffset .5s ease-in-out;
    stroke: red;
}

.CircularProgress-Text {
    font-size: 15px;
    font-weight: 600;
    fill: rgba(255,255,255,0.9);
    transform: translate(0, 50%);
}

<svg class="CircularProgress" width="50" height="50" viewBox="0 0 50 50">
   <circle class="CircularProgress-Bg" cx="25" cy="25" r="24" stroke-width="2px"></circle>
   <circle class="CircularProgress-Fg" cx="25" cy="25" r="24" stroke-width="2px" style="stroke-dasharray: 150.796; stroke-dashoffset: 125.161;"></circle>
   <text class="CircularProgress-Text" x="25" y="25" dy=".4em" text-anchor="middle">17%</text>
</svg>


问:
Can't delete from a table with two conditions using PHP
I am trying to delete a row from a table using two conditions. this is my current code :

```<code><?php
require 'database.php';
$id=0;
$od=0;
if(!empty($_GET['id_espece'])){
    $id=$_REQUEST['id_espece'];
}
if(!empty($_GET['id_valor'])){
    $od=$_REQUEST['id_valor'];
}
if(!empty($_POST)){
    $id= $_POST['id_espece'];
    $od= $_POST ['id_valor'];
    $pdo=Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         $sql = 'DELETE FROM mode_valorisation WHERE "id_espece" = ? and "id_valor" = ? ';
            $q = $pdo->prepare($sql);
            $q->execute(array($id,$od));
            Database::disconnect();

             header("Location: page-valo.php");
        }
    ?>

<form class="form-horizontal" action="page-supprimervalo.php" method="post" style="background: #89e29a; border-color: black; border-radius: 20px; padding: 5px;width: 500px; position: relative;right: -480px;" >
      <input type="hidden" name="id_espece" value="<?php echo $id;?>"/>
      <input type="hidden" name="id_valor" value="<?php echo $od;?>"/>
</form>
</code>```

I Tried the solution proposed here:
How to Delete a Record in php that has composite (multi-column) primary key

```<code>$sql = "DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ? limit 1";
</code>```

but it gives me the following error :

syntax error at or near "limit" LINE 1: ..._valorisation WHERE
  id_espece = $1 and id_valor = $2 limit 1 ^

Thank you ;

答:
You cannot use LIMIT in DELETE statement.

So the correct SQL with placeholders is:

```<code>DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ?;
</code>```

-- this will delete all rows (if any) with specified id_espece and id_valor.

If you need to delete only single row, use DELETE with SELECT sub-query (I suppose mode_valorisation has PK id; if not, edit the query to use the correct PK name):

```<code>delete from mode_valorisation where id in (
  select id from mode_valorisation
  where id_espece = ? and id_valor = ?
  order by id desc
  limit 1
);
</code>```

-- here you can control, which single row among several (if any) you will delete, using ORDER BY statement; I used order by id desc to delete "the latest" row.

Body:
I am trying to delete a row from a table using two conditions. this is my current code :

<?php
require 'database.php';
$id=0;
$od=0;
if(!empty($_GET['id_espece'])){
    $id=$_REQUEST['id_espece'];
}
if(!empty($_GET['id_valor'])){
    $od=$_REQUEST['id_valor'];
}
if(!empty($_POST)){
    $id= $_POST['id_espece'];
    $od= $_POST ['id_valor'];
    $pdo=Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         $sql = 'DELETE FROM mode_valorisation WHERE "id_espece" = ? and "id_valor" = ? ';
            $q = $pdo->prepare($sql);
            $q->execute(array($id,$od));
            Database::disconnect();

             header("Location: page-valo.php");
        }
    ?>

<form class="form-horizontal" action="page-supprimervalo.php" method="post" style="background: #89e29a; border-color: black; border-radius: 20px; padding: 5px;width: 500px; position: relative;right: -480px;" >
      <input type="hidden" name="id_espece" value="<?php echo $id;?>"/>
      <input type="hidden" name="id_valor" value="<?php echo $od;?>"/>
</form>

I Tried the solution proposed here:
How to Delete a Record in php that has composite (multi-column) primary key

$sql = "DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ? limit 1";

but it gives me the following error :

syntax error at or near "limit" LINE 1: ..._valorisation WHERE
  id_espece = $1 and id_valor = $2 limit 1 ^

Thank you ;

Body:
You cannot use LIMIT in DELETE statement.

So the correct SQL with placeholders is:

DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ?;

-- this will delete all rows (if any) with specified id_espece and id_valor.

If you need to delete only single row, use DELETE with SELECT sub-query (I suppose mode_valorisation has PK id; if not, edit the query to use the correct PK name):

delete from mode_valorisation where id in (
  select id from mode_valorisation
  where id_espece = ? and id_valor = ?
  order by id desc
  limit 1
);

-- here you can control, which single row among several (if any) you will delete, using ORDER BY statement; I used order by id desc to delete "the latest" row.


问:
run spark on AWS EMR by passing credentials
I am new to EMR and tried to launch Spark job as a step using something like command-runner.jar spark-submit --deploy-mode cluster --class com.xx.xx.className s3n://mybuckets/spark-jobs.jar

However, the spark job needs credentials as environment variables, my question is what is the best way to pass the credentials as environment variables to the spark jobs.

Thanks!

答:
Have a look here: AWS EMR 4.0 - How can I add a custom JAR step to run shell commands and here: http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-hadoop-script.html
try running step like this(arguments): /usr/bin/spark-submit  --deploy-mode cluster --class  </p>


问:
Inserting unknown number of rows into a MySQL database
I'm writing an online application form and one of the pieces of data I'm trying to collect is the users education history; school name, school city, years they were there and achievements while there.  This data could be collected for anywhere between zero to about four different schools and the user will be dynamically adding more fields if required.

My question is how would this be captured within the database since I don't know how many schools the user will be adding?  Can it be done in one table, or do I need to create multiple tables and capture the education data in a separate table?

Any help or pointers would be greatly appreciated.

Thanks.

答: Make a separate table for education, and model an "education" in php as a separate class.</p>


问:
Chain vim yank and paste?
Is it possible to chain yank move and paste? Something like :10,20y | 30 | p? Goal is to yank line 10 to 20 and paste at line 30 and the cursor is at line 25 (preferably without the move part to avoid moving the cursor)?

答:
Why don't you simply use :help :t?

```<code>:10,20t30
</code>```

Title: Chain vim yank and paste?

Body:
Why don't you simply use :help :t?

:10,20t30


问:
Datanode process not running in Hadoop
I set up and configured a multi-node Hadoop cluster using this tutorial.

When I type in the start-all.sh command, it shows all the processes initializing properly as follows:

```<code>starting namenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-namenode-jawwadtest1.out
jawwadtest1: starting datanode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-datanode-jawwadtest1.out
jawwadtest2: starting datanode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-datanode-jawwadtest2.out
jawwadtest1: starting secondarynamenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-secondarynamenode-jawwadtest1.out
starting jobtracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-jobtracker-jawwadtest1.out
jawwadtest1: starting tasktracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-tasktracker-jawwadtest1.out
jawwadtest2: starting tasktracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-tasktracker-jawwadtest2.out
</code>```

However, when I type the jps command, I get the following output:

```<code>31057 NameNode
4001 RunJar
6182 RunJar
31328 SecondaryNameNode
31411 JobTracker
32119 Jps
31560 TaskTracker
</code>```

As you can see, there's no datanode process running. I tried configuring a single-node cluster but got the same problem. Would anyone have any idea what could be going wrong here? Are there any configuration files that are not mentioned in the tutorial or I may have looked over? I am new to Hadoop and am kinda lost and any help would be greatly appreciated.

EDIT:
hadoop-root-datanode-jawwadtest1.log:

```<code>STARTUP_MSG:   args = []
STARTUP_MSG:   version = 1.0.3
STARTUP_MSG:   build = https://svn.apache.org/repos/asf/hadoop/common/branches/$
************************************************************/
2012-08-09 23:07:30,717 INFO org.apache.hadoop.metrics2.impl.MetricsConfig: loa$
2012-08-09 23:07:30,734 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapt$
2012-08-09 23:07:30,735 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:30,736 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:31,018 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapt$
2012-08-09 23:07:31,024 WARN org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:32,366 INFO org.apache.hadoop.ipc.Client: Retrying connect to $
2012-08-09 23:07:37,949 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: $
        at org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(Data$
        at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransition$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.startDataNode(DataNo$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.<init>(DataNode.java$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.makeInstance(DataNod$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.instantiateDataNode($
        at org.apache.hadoop.hdfs.server.datanode.DataNode.createDataNode(DataN$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.secureMain(DataNode.$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.main(DataNode.java:1$

2012-08-09 23:07:37,951 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: S$
/************************************************************
SHUTDOWN_MSG: Shutting down DataNode at jawwadtest1/198.101.220.90
************************************************************/
</code>```

答:
Need to follow 3 steps.

(1) Need to go to the logs and check the most recent log (In hadoop-
   2.6.0/logs/hadoop-user-datanode-ubuntu.log)

If the error is as

java.io.IOException: Incompatible clusterIDs in /home/kutty/work/hadoop2data/dfs/data: namenode clusterID = CID-c41df580-e197-4db6-a02a-a62b71463089; datanode clusterID = CID-a5f4ba24-3a56-4125-9137-fa77c5bb07b1

i.e. namenode cluster id and datanode cluster id's are not identical.

(2) Now copy the namenode clusterID which is CID-c41df580-e197-4db6-a02a-a62b71463089 in above error

(3) Replace the Datanode cluster ID  with Namenode cluster ID in hadoopdata/dfs/data/current/version

clusterID=CID-c41df580-e197-4db6-a02a-a62b71463089

Restart Hadoop. Will run DataNode

Title: Datanode process not running in Hadoop

Body:
I set up and configured a multi-node Hadoop cluster using this tutorial.

When I type in the start-all.sh command, it shows all the processes initializing properly as follows:

starting namenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-namenode-jawwadtest1.out
jawwadtest1: starting datanode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-datanode-jawwadtest1.out
jawwadtest2: starting datanode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-datanode-jawwadtest2.out
jawwadtest1: starting secondarynamenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-secondarynamenode-jawwadtest1.out
starting jobtracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-jobtracker-jawwadtest1.out
jawwadtest1: starting tasktracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-tasktracker-jawwadtest1.out
jawwadtest2: starting tasktracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-root-tasktracker-jawwadtest2.out

However, when I type the jps command, I get the following output:

31057 NameNode
4001 RunJar
6182 RunJar
31328 SecondaryNameNode
31411 JobTracker
32119 Jps
31560 TaskTracker

As you can see, there's no datanode process running. I tried configuring a single-node cluster but got the same problem. Would anyone have any idea what could be going wrong here? Are there any configuration files that are not mentioned in the tutorial or I may have looked over? I am new to Hadoop and am kinda lost and any help would be greatly appreciated.

EDIT:
hadoop-root-datanode-jawwadtest1.log:

STARTUP_MSG:   args = []
STARTUP_MSG:   version = 1.0.3
STARTUP_MSG:   build = https://svn.apache.org/repos/asf/hadoop/common/branches/$
************************************************************/
2012-08-09 23:07:30,717 INFO org.apache.hadoop.metrics2.impl.MetricsConfig: loa$
2012-08-09 23:07:30,734 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapt$
2012-08-09 23:07:30,735 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:30,736 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:31,018 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapt$
2012-08-09 23:07:31,024 WARN org.apache.hadoop.metrics2.impl.MetricsSystemImpl:$
2012-08-09 23:07:32,366 INFO org.apache.hadoop.ipc.Client: Retrying connect to $
2012-08-09 23:07:37,949 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: $
        at org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(Data$
        at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransition$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.startDataNode(DataNo$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.<init>(DataNode.java$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.makeInstance(DataNod$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.instantiateDataNode($
        at org.apache.hadoop.hdfs.server.datanode.DataNode.createDataNode(DataN$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.secureMain(DataNode.$
        at org.apache.hadoop.hdfs.server.datanode.DataNode.main(DataNode.java:1$

2012-08-09 23:07:37,951 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: S$
/************************************************************
SHUTDOWN_MSG: Shutting down DataNode at jawwadtest1/198.101.220.90
************************************************************/


问:
Offline XML Validation with Java
I need to figure out how to validate my XML files with schema's offline. After looking around for a couple of days, what I was able to find was basically that I needed to have an internal reference to the schema. I needed to find them, download them, and change the reference to a local system path. What I was unable to find was exactly how to do that. Where and how can I change the reference to point internally instead of externally? What is the best way to download the schemas?</p>

答:
XmlValidate is a simple but powerful command-line tool that can perform offline validation of single or multiple XML files against target schemas. It can scan local xml files by file name, directory, or URL.

XmlValidate automatically adds the schemaLocation based on the schema namespace and a config file that mapping to a local file. The tool will validate against whatever XML Schema is referenced in the config file.

Here are example mappings of namespace to target Schema in config file:

```<code>http://www.opengis.net/kml/2.2=${XV_HOME}/schemas/kml22.xsd
http://appengine.google.com/ns/1.0=C:/xml/appengine-web.xsd
urn:oasis:names:tc:ciq:xsdschema:xAL:2.0=C:/xml/xAL.xsd
</code>```

Note that ${XV_HOME} token above is simply an alias for the top-level directory that XmlValidate is running from. The location can likewise be a full file path.

XmlValidate is an open-source project (source code available) that runs with the Java Runtime Environment (JRE). The bundled application (Java jars, examples, etc.) can be downloaded here.

If XmlValidate is run in batch mode against multiple XML files, it will provide a summary of validation results.

```<code>Errors: 17  Warnings: 0  Files: 11  Time: 1506 ms
Valid files 8/11 (73%)
</code>```

Title: Offline XML Validation with Java

Body:
XmlValidate is a simple but powerful command-line tool that can perform offline validation of single or multiple XML files against target schemas. It can scan local xml files by file name, directory, or URL.

XmlValidate automatically adds the schemaLocation based on the schema namespace and a config file that mapping to a local file. The tool will validate against whatever XML Schema is referenced in the config file.

Here are example mappings of namespace to target Schema in config file:

http://www.opengis.net/kml/2.2=${XV_HOME}/schemas/kml22.xsd
http://appengine.google.com/ns/1.0=C:/xml/appengine-web.xsd
urn:oasis:names:tc:ciq:xsdschema:xAL:2.0=C:/xml/xAL.xsd

Note that ${XV_HOME} token above is simply an alias for the top-level directory that XmlValidate is running from. The location can likewise be a full file path.

XmlValidate is an open-source project (source code available) that runs with the Java Runtime Environment (JRE). The bundled application (Java jars, examples, etc.) can be downloaded here.

If XmlValidate is run in batch mode against multiple XML files, it will provide a summary of validation results.

Errors: 17  Warnings: 0  Files: 11  Time: 1506 ms
Valid files 8/11 (73%)


问:
How to merge two lines in a CSV file
I have a CSV file that has the following issue.

```<code>line 1:  "x","y","z","
line 2:
line 3:  "," ",": "
</code>```

This is a single line but has been written as multiple lines. Unfortunately, I cannot ask the provider to fix it. Is there a way we can fix it?

答:
Read the file. Go trough every line and append your output to a variable. Then you have all lines after each other.

```<code>$output = '';

foreach($lines as $line) {
    $output .= $line;
}
</code>```

to read the csv file you can use fgetcsv. If line 1: is part of your csv file then split your output on the : and use the second part.

Title: How to merge two lines in a CSV file

Body:
I have a CSV file that has the following issue.

line 1:  "x","y","z","
line 2:
line 3:  "," ",": "

This is a single line but has been written as multiple lines. Unfortunately, I cannot ask the provider to fix it. Is there a way we can fix it?

Body:
Read the file. Go trough every line and append your output to a variable. Then you have all lines after each other.

$output = '';

foreach($lines as $line) {
    $output .= $line;
}

to read the csv file you can use fgetcsv. If line 1: is part of your csv file then split your output on the : and use the second part.


问:
Is there a C# library that allows you to query mp3 duration and bitrate
I'm looking for an open source library (BSD/MIT style license) that allows me to extract the bitrate and duration of a MP3 audio file in dot net.

Any takers?

答:
NAudio

MS-PL license

Body:
NAudio

MS-PL license


问:
How to get form control validation errors in template in Angular
I have a form which changes its validation based on some value from the dropdown. If college A is selected then min percentage required in 60, if college B is selected then min percentage drops down to 55.
Although I have figured out a way to get the min error in the template in so that I didn't have to hard code the percentage value in my template. Although I am not sure if this is the correct way or not.

```<code><div formGroupName="marks">
  <div class="form-group">
    <label for="email" class="col-lg-3 control-label">Semester 1</label>
    <div class="col-lg-3">
      <input autocomplete="off"
             #sem1
             type="text"
             min="0"
             max="99"
             maxlength="1"
             maxlength="2"
             class="form-control"
             id="email"
             placeholder="Sem 1 (%)"
             (keypress)="onlyNumberKey($event)"
             formControlName="sem1">
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Sem 1 percentage required
      </span>
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
                   registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
      </span>
    </div>
  </div>
</div>
</code>```

Component

```<code>registrationForm = new FormGroup({
  college: new FormControl('', [
    Validators.required, dropDrownValidator
  ]),
  marks: new FormGroup({
    sem1: new FormControl('',
      [
        Validators.required,
        Validators.min(60),
        Validators.max(99),
        Validators.minLength(1),
        Validators.maxLength(2)
      ]
    )
  })
});
</code>```

答:
To achieve what you want, you have to watch the changes in your college control.

You can do this using (change) in template:

```<code><select formControlName="college" (change)="handleChange($event.target.value)">
  ...
</select>
</code>```

or even using valueChanges in component:

```<code>this.registrationForm.get('college').valueChanges.subscribe(college => this.handleChange(college));
</code>```

And in your function, based on what college user selects, you can set the min value to your validator using AbstractControl#setValidators + AbstractControl#updateValueAndValidity (to apply ), as below:

```<code>handleChange(selectedCollege: string): void {
  const min = selectedCollege === 'CollegeA' ? 60 : 55;
  const control = this.registrationForm.get('marks.sem1');
  control.setValidators([Validators.required, customMin(min)]);
  control.updateValueAndValidity();
}
</code>```

Tips:

1 - Since, you're using model-driven forms you shouldn't put validations in your HTML, keep it clean and put everything in component.

2 - You can use FormBuilder in order to simplify the construction of form (see the demo at the bottom).

3 - You should never access private properties like this:

```<code>{{ registrationForm.get('marks.sem1')._errors.min.min }}
</code>```

Just use errors instead of _errors if you need to.

4 - You can simplify even more your markup:

Instead of:

```<code><span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
             registrationForm.controls['marks'].controls['sem1'].touched"
             class="text-danger">
  Sem 1 percentage required
</span>
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
             registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
             registrationForm.controls['marks'].controls['sem1'].touched"
             class="text-danger">
  Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
</span>
</code>```

You can have:

```<code><div class="text-danger" *ngIf="registrationForm.get('marks.sem1').touched">
  <span *ngIf="registrationForm.hasError('required', 'marks.sem1')">
    Sem 1 percentage required
  </span>
  <span *ngIf="registrationForm.getError('customMin', 'marks.sem1') as error">
    Percentage must be greater than or equal to {{ error.min }}.
  </span>
</div>
</code>```

WORKING DEMO

Body:
I have a form which changes its validation based on some value from the dropdown. If college A is selected then min percentage required in 60, if college B is selected then min percentage drops down to 55.
Although I have figured out a way to get the min error in the template in so that I didn't have to hard code the percentage value in my template. Although I am not sure if this is the correct way or not.

    Semester 1

      <input autocomplete="off"
             #sem1
             type="text"
             min="0"
             max="99"
             maxlength="1"
             maxlength="2"
             class="form-control"
             id="email"
             placeholder="Sem 1 (%)"
             (keypress)="onlyNumberKey($event)"
             formControlName="sem1">

        Sem 1 percentage required

        Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.

Component

registrationForm = new FormGroup({
  college: new FormControl('', [
    Validators.required, dropDrownValidator
  ]),
  marks: new FormGroup({
    sem1: new FormControl('',
      [
        Validators.required,
        Validators.min(60),
        Validators.max(99),
        Validators.minLength(1),
        Validators.maxLength(2)
      ]
    )
  })
});

Body:
To achieve what you want, you have to watch the changes in your college control.

You can do this using (change) in template:

<select formControlName="college" (change)="handleChange($event.target.value)">
  ...
</select>

or even using valueChanges in component:

this.registrationForm.get('college').valueChanges.subscribe(college => this.handleChange(college));

And in your function, based on what college user selects, you can set the min value to your validator using AbstractControl#setValidators + AbstractControl#updateValueAndValidity (to apply ), as below:

handleChange(selectedCollege: string): void {
  const min = selectedCollege === 'CollegeA' ? 60 : 55;
  const control = this.registrationForm.get('marks.sem1');
  control.setValidators([Validators.required, customMin(min)]);
  control.updateValueAndValidity();
}

Tips:

1 - Since, you're using model-driven forms you shouldn't put validations in your HTML, keep it clean and put everything in component.

2 - You can use FormBuilder in order to simplify the construction of form (see the demo at the bottom).

3 - You should never access private properties like this:

{{ registrationForm.get('marks.sem1')._errors.min.min }}

Just use errors instead of _errors if you need to.

4 - You can simplify even more your markup:

Instead of:

<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
             registrationForm.controls['marks'].controls['sem1'].touched"
             class="text-danger">
  Sem 1 percentage required
</span>
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
             registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
             registrationForm.controls['marks'].controls['sem1'].touched"
             class="text-danger">
  Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
</span>

You can have:

<div class="text-danger" *ngIf="registrationForm.get('marks.sem1').touched">
  <span *ngIf="registrationForm.hasError('required', 'marks.sem1')">
    Sem 1 percentage required
  </span>
  <span *ngIf="registrationForm.getError('customMin', 'marks.sem1') as error">
    Percentage must be greater than or equal to {{ error.min }}.
  </span>
</div>

WORKING DEMO

ContentLicense: CC BY-SA 4.0


问:
webgl replace program shader
I'm trying to swap the fragement-shader used in a program. The fragment-shaders all have the same variables, just different calculations. I am trying to provide alternative shaders for lower level hardware.

I end up getting single color outputs (instead of a texture), does anyone have an idea what I could be doing wrong? I know the shaders are being used, due to the color changing accordingly.

```<code>     //if I don't do this:
     //WebGL: INVALID_OPERATION: attachShader: shader attachment already has shader
gl.detachShader(program, _.attachedFS);
     //select a random shader, all using the same parameters
attachedFS = fragmentShaders[~~(Math.qrand()*fragmentShaders.length)];
     //attach the new shader
gl.attachShader(program, attachedFS);
     //if I don't do this nothing happens
gl.linkProgram(program);
     //if I don't add this line:
     //globject.js:313 WebGL: INVALID_OPERATION: uniform2f:
     //location not for current program
updateLocations();
</code>```

答:
I am assuming you have called gl.compileShader(fragmentShader);

Have you tried to test the code on a different browser and see if you get the same behavior? (it could be standards implementation specific)

Have you tried to delete the fragment shader (gl.deleteShader(attachedFS); ) right after detaching it. The
previous shader may still have a pointer in memory.

If this does not let you move forward, you may have to detach both shaders (vertex & frag) and reattach them or even recreate the program from scratch

Title: webgl replace program shader

Body:
I'm trying to swap the fragement-shader used in a program. The fragment-shaders all have the same variables, just different calculations. I am trying to provide alternative shaders for lower level hardware.

I end up getting single color outputs (instead of a texture), does anyone have an idea what I could be doing wrong? I know the shaders are being used, due to the color changing accordingly.

     //if I don't do this:
     //WebGL: INVALID_OPERATION: attachShader: shader attachment already has shader
gl.detachShader(program, _.attachedFS);
     //select a random shader, all using the same parameters
attachedFS = fragmentShaders[~~(Math.qrand()*fragmentShaders.length)];
     //attach the new shader
gl.attachShader(program, attachedFS);
     //if I don't do this nothing happens
gl.linkProgram(program);
     //if I don't add this line:
     //globject.js:313 WebGL: INVALID_OPERATION: uniform2f:
     //location not for current program
updateLocations();


问:
How can I get redux-saga to wait for two actions to happen at least once in any order?
Redux saga noob here.

I need to create a saga that loads the initial state for the redux store from my API server.

This involves using two async sagas: getCurrentUser and getGroups.

I need to issue these ajax requests in parallel and wait for the GET_CURRENT_USER_SUCCESS and GET_GROUPS_SUCCESS actions before issuing the pageReady action which tells the UI it's time to render the react components.

I came up with a hacky solution:

```<code>function * loadInitialState () {
  yield fork(getCurrentUser)
  yield fork(getGroups)

  while (true) {
    yield take([
      actions.GET_GROUPS_SUCCESS,
      actions.GET_CURRENT_USER_SUCCESS
    ])
    yield take([
      actions.GET_GROUPS_SUCCESS,
      actions.GET_CURRENT_USER_SUCCESS
    ])
    yield put(actions.pageReady())
  }
}
</code>```

The problem with this code is that if for some reason GET_GROUPS_SUCCESS is issued twice, the pageReady action will be called to early.

How can I get redux saga to wait for GET_GROUPS_SUCCESS and GET_CURRENT_USER_SUCCESS to happen at least once in any order?

答:
I think you want the all effect

```<code>function * loadInitialState () {
  // start loading state...

  yield all([
    take(actions.GET_GROUPS_SUCCESS)
    take(actions.GET_CURRENT_USER_SUCCESS)
  ]);

  yield put(actions.pageReady())
}
</code>```

Body:
Redux saga noob here.

I need to create a saga that loads the initial state for the redux store from my API server.

This involves using two async sagas: getCurrentUser and getGroups.

I need to issue these ajax requests in parallel and wait for the GET_CURRENT_USER_SUCCESS and GET_GROUPS_SUCCESS actions before issuing the pageReady action which tells the UI it's time to render the react components.

I came up with a hacky solution:

function * loadInitialState () {
  yield fork(getCurrentUser)
  yield fork(getGroups)

  while (true) {
    yield take([
      actions.GET_GROUPS_SUCCESS,
      actions.GET_CURRENT_USER_SUCCESS
    ])
    yield take([
      actions.GET_GROUPS_SUCCESS,
      actions.GET_CURRENT_USER_SUCCESS
    ])
    yield put(actions.pageReady())
  }
}

The problem with this code is that if for some reason GET_GROUPS_SUCCESS is issued twice, the pageReady action will be called to early.

How can I get redux saga to wait for GET_GROUPS_SUCCESS and GET_CURRENT_USER_SUCCESS to happen at least once in any order?

Body:
I think you want the all effect

function * loadInitialState () {
  // start loading state...

  yield all([
    take(actions.GET_GROUPS_SUCCESS)
    take(actions.GET_CURRENT_USER_SUCCESS)
  ]);

  yield put(actions.pageReady())
}


问:
Connecting to Access database through HTML on PC
So I'm trying to figure out how to connect to an access database that is on my  desktop through html. Everything I've found so far involves the DB being server side and people mentioning ASP.net or just using SQL or mySQL instead. I just need to know how to get the connection up and running. Any help would be appreciated.</p>

答:
You need some kind of web programming language. That can be PHP or ASP.NET or Java or whatever, but you need something else -- HTML can't connect to a database on its own.

I'd highly advise that you take this opportunity to switch to another database server (like SQL Server or MySQL, like you mentioned). Microsoft Access is not well suited to use in web applications.


问:
rspec test to submit json data
I'm trying to make a test to submit JSON data to my API endpoint, however it's not working.  After trying various suggestions from blogs and the rspec documentation I'm still failing.

specs/controller/v1/devices_controller_spec.rb

```<code>require 'rails_helper'

RSpec.describe V1::DevicesController, type: :controller do

  it "updates device info" do
    @data = {}
    @device = FactoryGirl.create(:device)
    @data[:diagnostic_dns] = false
    @data[:diagnostic_ping] = false
    put :update, @data.to_json
    @data.reload
    response.should be_successful
  end

end
</code>```

I've also tried this in my test:

```<code>  it "updates device info" do
    device = FactoryGirl.create(:device)
    device.diagnostic_dns = false
    device.diagnostic_ping = false
    put :update, :device, :format => :json
    response.should be_successful
  end
</code>```

Which results in this rspec failure:

```<code>Failures:

  1) V1::DevicesController updates device info
     Failure/Error: put :update, @data.to_json

     ArgumentError:
       wrong number of arguments (given 2, expected 1)
</code>```

app/controllers/v1/devices_controller.rb

```<code>class V1::DevicesController < ApplicationController
  skip_before_action :authenticate_user!, only: [:show, :update], :if => Proc.new { |c| c.request.format == 'application/json' }
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def update
    if @device.update(device_params)
      render json: @device, status: :ok
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
    )
  end

end
</code>```

And my routes.rb file

```<code>       v1_device GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                 PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                 PUT    /v1/devices/:serial_number(.:format)              v1/devices#update
</code>```

UPDATE
After changing my test submit to:

```<code>patch :update, params: {serial_number: device.serial_number, device: @data }, :format => :json
</code>```

I'm now getting:

```<code>Failures:

  1) V1::DevicesController updates device info
     Failure/Error: response.should be_successful
       expected `#<ActionDispatch::TestResponse:0x005592458af9d0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mu...:Headers:0x00559245826d10 @req=#<ActionController::TestRequest:0x005592458afcc8 ...>>, @variant=[]>>.successful?` to return true, got false
</code>```

UPDATE
I added byebug to the controller and this is what @device.errors has it in:

```<code>@messages={:diagnostic_ping=>["can't be blank"], :diagnostic_dns=>["can't be blank"]}, @details={:diagnostic_ping=>[{:error=>:blank}], :diagnostic_dns=>[{:error=>:blank}]}>
</code>```

So, the variables are not being set?

答:
I wouldn't stress too much about getting RSpec to submit an actual JSON string to your code. Rails is in charge of turning that JSON into a params hash for you, so Rails should have the tests verifying they handle JSON properly. I would just do a normal test passing params with a format: :json verifying that you return the JSON you're expecting.

I believe that would look like

```<code>put :update, serial_number: @device.serial_number, device: @data, format: :json
</code>```

Title: rspec test to submit json data

Body:
I'm trying to make a test to submit JSON data to my API endpoint, however it's not working.  After trying various suggestions from blogs and the rspec documentation I'm still failing.

specs/controller/v1/devices_controller_spec.rb

require 'rails_helper'

RSpec.describe V1::DevicesController, type: :controller do

  it "updates device info" do
    @data = {}
    @device = FactoryGirl.create(:device)
    @data[:diagnostic_dns] = false
    @data[:diagnostic_ping] = false
    put :update, @data.to_json
    @data.reload
    response.should be_successful
  end

end

I've also tried this in my test:

  it "updates device info" do
    device = FactoryGirl.create(:device)
    device.diagnostic_dns = false
    device.diagnostic_ping = false
    put :update, :device, :format => :json
    response.should be_successful
  end

Which results in this rspec failure:

Failures:

  1) V1::DevicesController updates device info
     Failure/Error: put :update, @data.to_json

     ArgumentError:
       wrong number of arguments (given 2, expected 1)

app/controllers/v1/devices_controller.rb

class V1::DevicesController < ApplicationController
  skip_before_action :authenticate_user!, only: [:show, :update], :if => Proc.new { |c| c.request.format == 'application/json' }
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def update
    if @device.update(device_params)
      render json: @device, status: :ok
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
    )
  end

end

And my routes.rb file

       v1_device GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                 PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                 PUT    /v1/devices/:serial_number(.:format)              v1/devices#update

UPDATE
After changing my test submit to:

patch :update, params: {serial_number: device.serial_number, device: @data }, :format => :json

I'm now getting:

Failures:

  1) V1::DevicesController updates device info
     Failure/Error: response.should be_successful
       expected `#<ActionDispatch::TestResponse:0x005592458af9d0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mu...:Headers:0x00559245826d10 @req=#<ActionController::TestRequest:0x005592458afcc8 ...>>, @variant=[]>>.successful?` to return true, got false

UPDATE
I added byebug to the controller and this is what @device.errors has it in:

@messages={:diagnostic_ping=>["can't be blank"], :diagnostic_dns=>["can't be blank"]}, @details={:diagnostic_ping=>[{:error=>:blank}], :diagnostic_dns=>[{:error=>:blank}]}>

So, the variables are not being set?

Body:
I wouldn't stress too much about getting RSpec to submit an actual JSON string to your code. Rails is in charge of turning that JSON into a params hash for you, so Rails should have the tests verifying they handle JSON properly. I would just do a normal test passing params with a format: :json verifying that you return the JSON you're expecting.

I believe that would look like

put :update, serial_number: @device.serial_number, device: @data, format: :json


问:
How can I play a local video in my IPython notebook?
I've got a local video file (an .avi, but could be converted) that I would like to show a client (ie it is private and can't be published to the web), but I can't figure out how to play it in IPython notebook.

After a little Googling it seems that maybe the HTML5 video tag is the way to go, but I don't know any html and can't get it to play.

Any thoughts on how I can embed this?

答:
Use a markdown cell:

<video controls src="path/to/video.mp4" />

Citation: Jupyter Notebook » Docs » Examples » Markdown Cells