问:
Redux State in Component
trying to figure out how to pull Redux store state into my component from Redux. I've got mapStateToProps and "connect" wired up. However, when I click my button in "App" component, this.props doesn't have my Redux values in it. </p>

```<code>// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;

function tweetReducer(state=[],action) {
    if(action.type === 'ADD_TWEET') {
        return state.concat({ id: Date.now(), tweet: action.payload})
    } else {
        return state;
    }
}

const rootReducer = combineReducers ({
    state: (state = {}) => state,
    tweets: tweetReducer
});

class App extends Component{
    buttonClicked() {
        store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
        console.log(this.props)
    }
    render() {
        return (
            <div>
                <h5>Hello from App</h5>
                <button onClick={this.buttonClicked.bind(this)}>Button</button>

                <div>-------------------</div>
                <Display />
            </div>
         )
     }
}

class Display extends Component {
    render() {
        return (
            <div>
                <h3>Tweets:</h3>
                {this.props.tweets}
            </div>
        )
    }
}

function mapStateToProps(state) {
    console.log('mapping state to props')

    return {
        tweets: state.tweets
    }
}

let store = createStore(rootReducer)

render (
    <Provider store={store}>
        <App />
    </Provider>
    , document.querySelector('#app')
);
connect(mapStateToProps)(App)

console.log(store.getState());
</code>```

答:
This is how you should proceed with getting store state in your component.

1) Create reducers folder and create a new file index.js

```<code>/* reducers/index.js */

import { combineReducers } from "redux";
import tweetReducer from "./tweetReducer";

const rootReducer = combineReducers({
    tweets: tweetReducer
});

export default rootReducer;
</code>```

/* reducers/tweetReducer.js */

```<code>function tweetReducer(state=[],action) {
    switch(action.type) {
        case 'ADD_TWEET':
            return state.concat({ id: Date.now(), tweet: action.payload});
        default:
            return state;
    }
}
</code>```

/* components/App.js */

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
    buttonClicked() {
        this.props.store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
        console.log(this.props)
    }
    render() {
        return (
            <div>
                <h5>Hello from App</h5>
                <button onClick={this.buttonClicked.bind(this)}>Button</button>

                <div>-------------------</div>
                <Display />
            </div>
         )
     }
}
function mapStateToProps(state) {
   console.log('mapping state to props')
   return {
     tweets: state.tweets
   }
}
export default connect(mapStateToProps)(App);
</code>```

/* components/Display.js */

```<code>import React, { Component } from 'react';
  export default class Display extends Component {
     render() {
        return (
            <div>
               <h3>Tweets:</h3>
               {this.props.tweets}
             </div>
        )
     }
  }
</code>```

/*Main.js */

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";

render(
    <Provider store={store}>
        <App store={store} />
    </Provider>,
    document.querySelector('#app')
);
</code>```

/* store/index.js */

```<code>import { createStore, applyMiddleware, compose } from "redux";
import reducers from "../reducers";

const store = createStore(
    reducers,
    composeEnhancers(applyMiddleware())
);

export { store };
</code>```

Title: Redux State in Component

Body:
trying to figure out how to pull Redux store state into my component from Redux. I've got mapStateToProps and "connect" wired up. However, when I click my button in "App" component, this.props doesn't have my Redux values in it.

// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;

function tweetReducer(state=[],action) {
    if(action.type === 'ADD_TWEET') {
        return state.concat({ id: Date.now(), tweet: action.payload})
    } else {
        return state;
    }
}

const rootReducer = combineReducers ({
    state: (state = {}) => state,
    tweets: tweetReducer
});

class App extends Component{
    buttonClicked() {
        store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
        console.log(this.props)
    }
    render() {
        return (

Hello from App

                <button onClick={this.buttonClicked.bind(this)}>Button</button>

-------------------

                <Display />

         )
     }
}

class Display extends Component {
    render() {
        return (

Tweets:

                {this.props.tweets}

        )
    }
}

function mapStateToProps(state) {
    console.log('mapping state to props')

    return {
        tweets: state.tweets
    }
}

let store = createStore(rootReducer)

render (
    <Provider store={store}>
        <App />
    </Provider>
    , document.querySelector('#app')
);
connect(mapStateToProps)(App)

console.log(store.getState());

Body:
This is how you should proceed with getting store state in your component.

1) Create reducers folder and create a new file index.js

/* reducers/index.js */

import { combineReducers } from "redux";
import tweetReducer from "./tweetReducer";

const rootReducer = combineReducers({
    tweets: tweetReducer
});

export default rootReducer;

/* reducers/tweetReducer.js */

function tweetReducer(state=[],action) {
    switch(action.type) {
        case 'ADD_TWEET':
            return state.concat({ id: Date.now(), tweet: action.payload});
        default:
            return state;
    }
}

/* components/App.js */

import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
    buttonClicked() {
        this.props.store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
        console.log(this.props)
    }
    render() {
        return (
            <div>
                <h5>Hello from App</h5>
                <button onClick={this.buttonClicked.bind(this)}>Button</button>

                <div>-------------------</div>
                <Display />
            </div>
         )
     }
}
function mapStateToProps(state) {
   console.log('mapping state to props')
   return {
     tweets: state.tweets
   }
}
export default connect(mapStateToProps)(App);

/* components/Display.js */

import React, { Component } from 'react';
  export default class Display extends Component {
     render() {
        return (
            <div>
               <h3>Tweets:</h3>
               {this.props.tweets}
             </div>
        )
     }
  }

/*Main.js */

import React, { Component } from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";

render(
    <Provider store={store}>
        <App store={store} />
    </Provider>,
    document.querySelector('#app')
);

/* store/index.js */

import { createStore, applyMiddleware, compose } from "redux";
import reducers from "../reducers";

const store = createStore(
    reducers,
    composeEnhancers(applyMiddleware())
);

export { store };


来源: stackexchange

问:
PHP - Do (and echo) operation only when remainder from is 0 - Going into infinite loop
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

```<code>$x = mt_rand(1,10);
$y = mt_rand(1,10);
</code>```

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

```<code><?php

function hello(){
      echo "Hello!";
}

hello();
?>
</code>```

Why not up the ante as I said before and use it, so I mix the up:

```<code><?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>
</code>```

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

答:
It looks to me like you only set $x and $y once.

That means they won't change when you recursively call foo(). I'd start by trying something like this:

```<code><?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        if ($x % $y == 0) {
            echo $x . "/" . $y;
        } else {
            $x = mt_rand(1,10);    # need to recalculate them here.
            $y = mt_rand(1,10);
            foo();
        }
    }
?>
</code>```

I'd check that code though. I know PHP about as well as I know Aramaic :-) My analysis is based more on general language knowledge, so the syntax may be bogus.

Of course, you may want to think about avoiding recursion altogether in this case. There's really no need for it. Recursion is fine when it makes your code more elegant but I don't believe that's the case here. I'd give something like this a shot:

```<code><?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        while ($x % $y != 0) {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        echo $x . "/" . $y;
    }
?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php

function hello(){
      echo "Hello!";
}

hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

Body:
It looks to me like you only set $x and $y once.

That means they won't change when you recursively call foo(). I'd start by trying something like this:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        if ($x % $y == 0) {
            echo $x . "/" . $y;
        } else {
            $x = mt_rand(1,10);    # need to recalculate them here.
            $y = mt_rand(1,10);
            foo();
        }
    }
?>

I'd check that code though. I know PHP about as well as I know Aramaic :-) My analysis is based more on general language knowledge, so the syntax may be bogus.

Of course, you may want to think about avoiding recursion altogether in this case. There's really no need for it. Recursion is fine when it makes your code more elegant but I don't believe that's the case here. I'd give something like this a shot:

<?php
    function foo() {
        $x = mt_rand(1,10);
        $y = mt_rand(1,10);
        while ($x % $y != 0) {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        echo $x . "/" . $y;
    }
?>


问:
What this is doing to the require statement?
I'm exploring with NodeJS and I've stumble upon the following syntax using the express debug module:

```<code>require('debug')(express:server);
</code>```

What is it? I've never see this form before and doesn't really find a way to google it to retrieve information on it.

Does this form allow a sort of argument passing to the load module statement ?

答:
Putting (some, arguments) after something that evaluates as a value does the same thing it does everywhere else. It calls that value as a function.

This is a function expression:

```<code>(function () { })
</code>```

It evaluates as a function and you can call it:

```<code>(function () { })()
</code>```

This is a function that returns a function:

```<code>function foo () {
    return function () { };
}
</code>```

You can call it to get a function:

```<code>foo();
</code>```

and that evaluates as a function so you can call that function immediately:

```<code>foo()();
</code>```

This is a module that returns a function:

```<code>module.exports = function () {}
</code>```

You can require it to get a function:

```<code>require("myModule")
</code>```

And you can call that function immediately:

```<code>require("myModule")()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm exploring with NodeJS and I've stumble upon the following syntax using the express debug module:

require('debug')(express:server);

What is it? I've never see this form before and doesn't really find a way to google it to retrieve information on it.

Does this form allow a sort of argument passing to the load module statement ?

Body:
Putting (some, arguments) after something that evaluates as a value does the same thing it does everywhere else. It calls that value as a function.

This is a function expression:

(function () { })

It evaluates as a function and you can call it:

(function () { })()

This is a function that returns a function:

function foo () {
    return function () { };
}

You can call it to get a function:

foo();

and that evaluates as a function so you can call that function immediately:

foo()();

This is a module that returns a function:

module.exports = function () {}

You can require it to get a function:

require("myModule")

And you can call that function immediately:

require("myModule")()


问:
C program Reading from a text file and writing the sorted list into the same text file. What modifications can i do?
The below program giving the following error when compiling:

./vpl_test: line 2: 18699 Segmentation fault      (core dumped) ./solution

What could be the problem with the below C program ?

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

void sort(long *sorted, int count,long value){
    int i=0;
    sorted[count] = value;
    if(count == 0)return;
    for(i=count;i>=0;i--){
        if(value<sorted[i-1])
        sorted[i] = sorted[i-1];
        else break;
    }
    sorted[i]=value;
}

int main(int argc,char *argv[]){
    FILE *fp = NULL;
    long sorted[1024];
    long value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    while(!feof(fp)){
        fscanf(fp,"%ld\n",&sorted[i]);
        sort(sorted,count,value);
        ++count;
    }
    for(i=0;i<count;i++){
        fprintf(fp,"%ld\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }
}
</code>```

答:
I could not reproduce the segfault (probably because of being "lucky" or maybe because of having wrong input).

The problem I did have was wrong sorting and strange values in sorted output, I believe that the same problem causes all misbehaviours, including the segfault in your case.

Here is a commented version of your code, picking up from the excellent comments and adding the (many) necessary changes to work on strings instead of integers.

(Allow me this little rant: It would really have saved a lot of time to provide actual sample input from start.)

It does have no segfault (at least not for me), no missorting and no strange values.
Output (i.e. new content of input file):

```<code>Damro
Duriyan
Evoks
Godrej
Luxxe
Nilkamal
Wipro
Zuari
</code>```

Code:

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

typedef char brandname[20];

void sort(brandname *sorted, int count, brandname *value){
    int i=0;
    strncpy((char*)sorted[count], (char*)value, sizeof(brandname));
    if(count == 0) return;

    // picking up input by BLUEPIXY;
    // this probably prevents the segfault,
    // it definitly prevents strange values
    // appearing in the sorted result
    for(i=count;i>0;i--)
    {
        if(0>strncmp((char*)value, (char*)sorted[i-1],sizeof(brandname)))
            strncpy( (char*)sorted[i], (char*)sorted[i-1], sizeof(brandname));
            else break;
    }
    strncpy((char*)sorted[i], (char*)value, sizeof(brandname));
}
int main(int argc,char *argv[]){
    FILE *fp = NULL;
    brandname sorted[1024];
    brandname value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    // picking up input from cooments on feof
    // but also use the increasing "count"
    // instead of unchanging "i"
    while(1==fscanf(fp,"%s", value))
    {
        // use the read value inside "sorted[count]"
        sort(sorted, count, &value);
        ++count;
    }
    // do not append sorted to input
    rewind(fp);
    for(i=0;i<count;i++){
        fprintf(fp,"%s\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }

    // avoid a warning
    return 0;
}
</code>```

Body:
The below program giving the following error when compiling:

./vpl_test: line 2: 18699 Segmentation fault      (core dumped) ./solution

What could be the problem with the below C program ?

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

void sort(long *sorted, int count,long value){
    int i=0;
    sorted[count] = value;
    if(count == 0)return;
    for(i=count;i>=0;i--){
        if(value<sorted[i-1])
        sorted[i] = sorted[i-1];
        else break;
    }
    sorted[i]=value;
}

int main(int argc,char *argv[]){
    FILE *fp = NULL;
    long sorted[1024];
    long value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    while(!feof(fp)){
        fscanf(fp,"%ld\n",&sorted[i]);
        sort(sorted,count,value);
        ++count;
    }
    for(i=0;i<count;i++){
        fprintf(fp,"%ld\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }
}

Body:
I could not reproduce the segfault (probably because of being "lucky" or maybe because of having wrong input).

The problem I did have was wrong sorting and strange values in sorted output, I believe that the same problem causes all misbehaviours, including the segfault in your case.

Here is a commented version of your code, picking up from the excellent comments and adding the (many) necessary changes to work on strings instead of integers.

(Allow me this little rant: It would really have saved a lot of time to provide actual sample input from start.)

It does have no segfault (at least not for me), no missorting and no strange values.
Output (i.e. new content of input file):

Damro
Duriyan
Evoks
Godrej
Luxxe
Nilkamal
Wipro
Zuari

Code:

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

typedef char brandname[20];

void sort(brandname *sorted, int count, brandname *value){
    int i=0;
    strncpy((char*)sorted[count], (char*)value, sizeof(brandname));
    if(count == 0) return;

    // picking up input by BLUEPIXY;
    // this probably prevents the segfault,
    // it definitly prevents strange values
    // appearing in the sorted result
    for(i=count;i>0;i--)
    {
        if(0>strncmp((char*)value, (char*)sorted[i-1],sizeof(brandname)))
            strncpy( (char*)sorted[i], (char*)sorted[i-1], sizeof(brandname));
            else break;
    }
    strncpy((char*)sorted[i], (char*)value, sizeof(brandname));
}
int main(int argc,char *argv[]){
    FILE *fp = NULL;
    brandname sorted[1024];
    brandname value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    // picking up input from cooments on feof
    // but also use the increasing "count"
    // instead of unchanging "i"
    while(1==fscanf(fp,"%s", value))
    {
        // use the read value inside "sorted[count]"
        sort(sorted, count, &value);
        ++count;
    }
    // do not append sorted to input
    rewind(fp);
    for(i=0;i<count;i++){
        fprintf(fp,"%s\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }

    // avoid a warning
    return 0;
}


问:
python fabric multiple commands
I'm trying to understand how fabric is working with multiple commands on one machine.
I need to run several commands on each host (thousands of hosts) and would like to know what would be best.

Using multiple runs:

```<code>res_1 = run(command_1)
res_2 = run(command_2)
...
...
res_n = run(command_n)
</code>```

Or:

```<code>res = run(command_1 && command_2 && ... command_n)
res.splitlines()
res_1 = res[0]
res_2 = res[1]
...
...
res_n = res[n-1]
</code>```

What I want to know is how fabric handles multiple runs, will it open multiple sessions or do all commands in the same session?

答: The important difference between those two approaches is that the first one will run all commands regardless of the exit status of former commands; the second one, however, will only execute commmand_2 if command_1 returned no error, etc. So it is up to you if you want this behaviour or the other.</p>

Title: python fabric multiple commands

Body:
I'm trying to understand how fabric is working with multiple commands on one machine.
I need to run several commands on each host (thousands of hosts) and would like to know what would be best.

Using multiple runs:

res_1 = run(command_1)
res_2 = run(command_2)
...
...
res_n = run(command_n)

Or:

res = run(command_1 && command_2 && ... command_n)
res.splitlines()
res_1 = res[0]
res_2 = res[1]
...
...
res_n = res[n-1]

What I want to know is how fabric handles multiple runs, will it open multiple sessions or do all commands in the same session?


问:
Can't register Mediatr automatically trough structuremap IoC
I have a web application with multilayer architecture and the classes of handlers and queries in the separate layer from a structuremap configuration. I tried to register all handlers and queries dynamically but I couldn't.When I try to run the application I receive the runtime error:

No default Instance is registered and cannot be automatically determined for type 'IRequestHandler'
There is no configuration specified for IRequestHandler

```<code>        public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.AssemblyContainingType<IMediator>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.With(new ControllerConvention());
            });
        //For<IExample>().Use<Example
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
        For<IMediator>().Use<Mediator>();
        For<IUnitOfWork>().Use<UnitOfWork>().LifecycleIs<TransientLifecycle>();
        For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(Business.Pipeline.MediatorPipeline<,>));
    }
</code>```

controller
var query = new GetUserQuery(id);var user = _mediator.Send(query);

query

```<code>    public class GetUserQuery : IRequest<User>
{
    public GetUserQuery() { }
    public GetUserQuery(int id)
    {
        Id = id;
    }

    public int Id { get; set; }
}
</code>```

handler

```<code> public class GetUserHandler : IRequestHandler<GetUserQuery, User>
{
    private readonly IUnitOfWork _uow;
    public GetUserHandler(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public User Handle(GetUserQuery message)
    {
        return _uow.UserRepository.Get(message.Id);
    }
}
</code>```

答:
ANSWER
I've added to Scan method few commands for scanning other projects from the solution, after that, I called method LookForRegistries. If you want scan types and implementations in other projects you need to set the rule of scanning specific dlls in Scan method.

```<code>                    scan.Assembly("NameOfProj.Business");
                scan.Assembly("NameOfProj.Persistence");
                scan.TheCallingAssembly();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.LookForRegistries();
                scan.WithDefaultConventions();
</code>```

Body:
I have a web application with multilayer architecture and the classes of handlers and queries in the separate layer from a structuremap configuration. I tried to register all handlers and queries dynamically but I couldn't.When I try to run the application I receive the runtime error:

No default Instance is registered and cannot be automatically determined for type 'IRequestHandler'
There is no configuration specified for IRequestHandler

        public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.AssemblyContainingType<IMediator>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.With(new ControllerConvention());
            });
        //For<IExample>().Use<Example
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
        For<IMediator>().Use<Mediator>();
        For<IUnitOfWork>().Use<UnitOfWork>().LifecycleIs<TransientLifecycle>();
        For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(Business.Pipeline.MediatorPipeline<,>));
    }

controller
var query = new GetUserQuery(id);var user = _mediator.Send(query);

query

    public class GetUserQuery : IRequest<User>
{
    public GetUserQuery() { }
    public GetUserQuery(int id)
    {
        Id = id;
    }

    public int Id { get; set; }
}

handler

 public class GetUserHandler : IRequestHandler<GetUserQuery, User>
{
    private readonly IUnitOfWork _uow;
    public GetUserHandler(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public User Handle(GetUserQuery message)
    {
        return _uow.UserRepository.Get(message.Id);
    }
}

Body:
ANSWER
I've added to Scan method few commands for scanning other projects from the solution, after that, I called method LookForRegistries. If you want scan types and implementations in other projects you need to set the rule of scanning specific dlls in Scan method.

                    scan.Assembly("NameOfProj.Business");
                scan.Assembly("NameOfProj.Persistence");
                scan.TheCallingAssembly();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.LookForRegistries();
                scan.WithDefaultConventions();


问:
Node - how to run app.js?
I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?

I followed few instructions here to run a project.

Error logs below:

```<code>Junryls-Mac-mini:app junrylmaraviles$ node app.js

/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
</code>```

答:
To run app.js file check "main": "app.js" in your package.json file.

Then run command $ node app.js That should run your app.

Title: Node - how to run app.js?

Body:
I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?

I followed few instructions here to run a project.

Error logs below:

Junryls-Mac-mini:app junrylmaraviles$ node app.js

/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

ContentLicense: CC BY-SA 4.0


问:
Clustering a sparse co-occurrence matrix
I have two N x N co-occurrence matrices (484x484 and 1060x1060) that I have to analyze. The matrices are symmetrical along the diagonal and contain lots of zero values. The non-zero values are integers.

I want to group together the positions that are non-zero. In other words, what I want to do is the algorithm on this link. When order by cluster is selected, the matrix gets re-arranged in rows and columns to group the non-zero values together.

Since I am using Python for this task, I looked into SciPy Sparse Linear Algebra library, but couldn't find what I am looking for.

Any help is much appreciated. Thanks in advance.

答:
Because your data is sparse, treat it as a graph, not a matrix.

Then try the various graph clustering methods. For example cliques are interesting on such data.

Note that not everything may cluster.


问:
array_flip with an array in the value
Simple one (but not solved yet): this is my array

```<code>[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]
</code>```

And I would love to see this result:

```<code>[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]
</code>```

I've already tried array_flip

答:
try this DEMO</p>

```<code>$original = [
     [
       "role" => "admin",
       "name" => [
         "Felipy",
         "Ivan",
       ],
     ],
     [
       "role" => "user",
       "name" => [
         "Michel",
         "Paul",
         "Tay",
        ],
      ]
    ];
    $arr = [];

    foreach ($original as $value)
    {
       foreach($value['name'] as $name)
       {
           $arr[$name] = $value['role'];
       }
    }
</code>```

Title: array_flip with an array in the value

Body:
Simple one (but not solved yet): this is my array

[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]

And I would love to see this result:

[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]

I've already tried array_flip

Body:
try this DEMO

$original = [
     [
       "role" => "admin",
       "name" => [
         "Felipy",
         "Ivan",
       ],
     ],
     [
       "role" => "user",
       "name" => [
         "Michel",
         "Paul",
         "Tay",
        ],
      ]
    ];
    $arr = [];

    foreach ($original as $value)
    {
       foreach($value['name'] as $name)
       {
           $arr[$name] = $value['role'];
       }
    }


问:
How to train a constant model (regression) in Python?
I'm trying to train a linear regression model in Python (with sklearn), but with slopes equal to zero, i.e., a constant model h(x) = b (h: model, b: intercept).

Do you know any method in sklearn to accomplish this? (I'm familiar with LinearRegression but I couldn't find an answer there).

Thanks!

答:
Hi I don't think you need sklearn for that. Algebraically speaking and assuming your X matrix univariate that is solved by the mean of Y minus the mean of your X.</p>

```<code>    b = y_train.mean() - X_train.mean()
</code>```

Body:
Hi I don't think you need sklearn for that. Algebraically speaking and assuming your X matrix univariate that is solved by the mean of Y minus the mean of your X.

    b = y_train.mean() - X_train.mean()


问:
rendering alternate components under the same flow:router URL
How can I render two different views in a one page app without changing URLs. I'm using meteor with the default blaze as well as the flow:router package. Right now I have it set up like this:
routes.js..

```<code>FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "calendar"
    });
  }
});

FlowRouter.route("/list", {
  name: "App.list",
  action() {
    BlazeLayout.render("App_body", { main: "App_home", mainContent: "list" });
  }
});
</code>```

but this way I'm using the url /list and i dont want that. I would like to simply render an alternate component template in the same url. I'm very new to coding so forgive me if this is obvious. Essentially I just want two different view styles: a list and a calendar. So I would like a way to set it up so that a spacebars template can be rendered if a certain button is clicked, and a different one can be rendered instead if another button is clicked.

Thanks so much for any help, i've been at this for a couple of days :)

答:
Create another template, which renders particular view conditionally. Something like this:

FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "listOrCal"
    });
  }
});
```

<pre class="lang-html prettyprint-override"><code><template name="listOrCal">
  {{#if showList}}
    {{> list}}
  {{else}}
    {{> calendar}}
  {{/if}}
  <button id="switchView">Switch view</button>
</template>
</code>```

Template.listOrCal.onCreated(function listOrCalOnCreated() {
  this.showList = new ReactiveVar(true);
})

Template.listOrCal.helpers({
  showList() {
    return Template.instance().showList.get();
  }
})

Template.listOrCal.events({
  'click #switchView' {
    let showList = Template.instance().showList.get();
    Template.instance().showList.set(!showList);
  }
})
```

Body:
How can I render two different views in a one page app without changing URLs. I'm using meteor with the default blaze as well as the flow:router package. Right now I have it set up like this:
routes.js..

FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "calendar"
    });
  }
});

FlowRouter.route("/list", {
  name: "App.list",
  action() {
    BlazeLayout.render("App_body", { main: "App_home", mainContent: "list" });
  }
});

but this way I'm using the url /list and i dont want that. I would like to simply render an alternate component template in the same url. I'm very new to coding so forgive me if this is obvious. Essentially I just want two different view styles: a list and a calendar. So I would like a way to set it up so that a spacebars template can be rendered if a certain button is clicked, and a different one can be rendered instead if another button is clicked.

Thanks so much for any help, i've been at this for a couple of days :)

Body:
Create another template, which renders particular view conditionally. Something like this:

FlowRouter.route("/", {
  name: "App.home",
  action() {
    BlazeLayout.render("App_body", {
      main: "App_home",
      mainContent: "listOrCal"
    });
  }
});

<template name="listOrCal">
  {{#if showList}}
    {{> list}}
  {{else}}
    {{> calendar}}
  {{/if}}
  <button id="switchView">Switch view</button>
</template>

Template.listOrCal.onCreated(function listOrCalOnCreated() {
  this.showList = new ReactiveVar(true);
})

Template.listOrCal.helpers({
  showList() {
    return Template.instance().showList.get();
  }
})

Template.listOrCal.events({
  'click #switchView' {
    let showList = Template.instance().showList.get();
    Template.instance().showList.set(!showList);
  }
})


问:
histogram on pandas columns by grouping cells
l have a column in pandas dataframe called  Column_values. l want to make a histogram on these values as follow :

Grouping  the cells of  alphabetic characters

Grouping the cells of  alpha numeric chacaters

Grouping the cells that contains only digits and  special chars , ; / .

Here is my column

```<code>Column_values
hello
goodmorning
6,35
11,68
Yours
ok
2292
Question
number
those
937,99
and
1
620
amounts
ROB21
Pieces
designation
these
rates
13s
2
with
the
</code>```

Thank you

答:
First, you need to create the group using a mapping function and then plot the histogram. The function is mapping by condition - in your case:

```<code>def find_group(val):
    val = str(val)
    if val.isalpha():
        return 'Alpha'
    elif val.isalnum and any(c.isalpha() for c in val):
        return 'Alphanumeric'
    else:
        return 'Special'
</code>```

the transformation is by using pandas apply method:

```<code>df.Column_values.apply(find_group)
</code>```

and the plotting is by adding value_counts and plot methods:

```<code>df.Column_values.apply(find_group).value_counts().plot(kind='bar')
</code>```

Body:
l have a column in pandas dataframe called  Column_values. l want to make a histogram on these values as follow :

Grouping  the cells of  alphabetic characters

Grouping the cells of  alpha numeric chacaters

Grouping the cells that contains only digits and  special chars , ; / .

Here is my column

Column_values
hello
goodmorning
6,35
11,68
Yours
ok
2292
Question
number
those
937,99
and
1
620
amounts
ROB21
Pieces
designation
these
rates
13s
2
with
the

Thank you

Body:
First, you need to create the group using a mapping function and then plot the histogram. The function is mapping by condition - in your case:

def find_group(val):
    val = str(val)
    if val.isalpha():
        return 'Alpha'
    elif val.isalnum and any(c.isalpha() for c in val):
        return 'Alphanumeric'
    else:
        return 'Special'

the transformation is by using pandas apply method:

df.Column_values.apply(find_group)

and the plotting is by adding value_counts and plot methods:

df.Column_values.apply(find_group).value_counts().plot(kind='bar')


问:
How do i make random letter from a string?
In python I want to know how to get random letter from string.

eg.

```<code>randomize("HELLO")
</code>```

```<code>returns "L"
</code>```

Body:
In python I want to know how to get random letter from string.

eg.

randomize("HELLO")

returns "L"

Body: return (random.choice(string))


问:
Azure CLI: unable to update NIC parameters
So i need to script detaching Load Balancer's backend pool from NIC to update our live machines, but i have a strange problem while updating NIC from CLI.

I can set whole 'loadBalancerBackendAddressPools' group to null with --set or remove key, but when this is a last property in a group - i can't update it.

```<code>az network nic update --resource-group MyPreciousGroup -n machineNetworkInt01020 --set ipConfigurations.[0].loadBalancerBackendAddressPools.[0].backendIpConfigurations=null
</code>```

this throws an error:

```<code>Operation failed with status: 'Not Found'. Details: 404 Client Error: Not Found for url: https://management.azure.com/subscriptions/00000000-1234-1234-1234-0000000000/providers/Microsoft.Network/locations/australiaeast/operations/1111111-1234-1234-1234-1111111111?api-version=2017-03-01
</code>```

Btw, is there a way to update whole property group with JSON or something? All that i want to setup after machine updates with parameters below:

```<code>loadBalancerBackendAddressPools": [
    {
      "backendIpConfigurations": null,
      "etag": null,
      "id": "/subscriptions/111111111-1111-1111-1111-111111111111/resourceGroups/MyEnvironment-AustraliaEast/providers/Microsoft.Network/loadBalancers/MyLoadBalancer/backendAddressPools/MyBackendPool",
      "loadBalancingRules": null,
      "name": null,
      "outboundNatRule": null,
      "provisioningState": null,
      "resourceGroup": "MyEnvironment-AustraliaEast"
    }
  ],
</code>```

Python 2.7.12

azure-cli 2.0.7

答:
You could try to use the following commands to detach NIC from Load Balancer backend pools.

```<code>az network nic update -g <your group name> -n <nic name> --set ipConfigurations[name=<ip-config-name>].loadBalancerBackendAddressPools=[]
</code>```

Following script is an example, it works for me.

```<code>az network nic update -g shuiload -n shui0 --set ipConfigurations[name=ipconfig1].loadBalancerBackendAddressPools=[]
</code>```

Also, you could use Azure CLI to add NICs to backend pools.

```<code>az network nic update -g ${resource-group} --name ${nic-name} --add ipConfigurations[name=${ip-config}].loadBalancerBackendAddressPools id=${backend-address-pool-id}
</code>```

Body:
So i need to script detaching Load Balancer's backend pool from NIC to update our live machines, but i have a strange problem while updating NIC from CLI.

I can set whole 'loadBalancerBackendAddressPools' group to null with --set or remove key, but when this is a last property in a group - i can't update it.

az network nic update --resource-group MyPreciousGroup -n machineNetworkInt01020 --set ipConfigurations.[0].loadBalancerBackendAddressPools.[0].backendIpConfigurations=null

this throws an error:

Operation failed with status: 'Not Found'. Details: 404 Client Error: Not Found for url: https://management.azure.com/subscriptions/00000000-1234-1234-1234-0000000000/providers/Microsoft.Network/locations/australiaeast/operations/1111111-1234-1234-1234-1111111111?api-version=2017-03-01

Btw, is there a way to update whole property group with JSON or something? All that i want to setup after machine updates with parameters below:

loadBalancerBackendAddressPools": [
    {
      "backendIpConfigurations": null,
      "etag": null,
      "id": "/subscriptions/111111111-1111-1111-1111-111111111111/resourceGroups/MyEnvironment-AustraliaEast/providers/Microsoft.Network/loadBalancers/MyLoadBalancer/backendAddressPools/MyBackendPool",
      "loadBalancingRules": null,
      "name": null,
      "outboundNatRule": null,
      "provisioningState": null,
      "resourceGroup": "MyEnvironment-AustraliaEast"
    }
  ],

Python 2.7.12

azure-cli 2.0.7

Body:
You could try to use the following commands to detach NIC from Load Balancer backend pools.

az network nic update -g <your group name> -n <nic name> --set ipConfigurations[name=<ip-config-name>].loadBalancerBackendAddressPools=[]

Following script is an example, it works for me.

az network nic update -g shuiload -n shui0 --set ipConfigurations[name=ipconfig1].loadBalancerBackendAddressPools=[]

Also, you could use Azure CLI to add NICs to backend pools.

az network nic update -g ${resource-group} --name ${nic-name} --add ipConfigurations[name=${ip-config}].loadBalancerBackendAddressPools id=${backend-address-pool-id}


问:
Pros and Cons of table name having spaces
In one of my project, it was required to have a table with space in between. Some suggest me not to include spaces because it is not a good technique.

we can still implement it using single-double quotes for table name in queries. But i need a solid backing for not opting spaces. Please help.

答:
It makes it harder to read, creates complexity if you ever want to do dynamic SQL.  Spaces in the tables names on the other hand add no value whatsoever.

Mr. Anderson points out that its tedious. This is true enough, but more importantly it adds unnecessary tediousness.


问:
Get latitude and longitude at 50 miles radius with reference to particular latitude and longitude
I have latitude and longitude value and want to find another lat long value at 50 miles of it. How to do that? Any formula or custom function to get that in php?</p>

答:
This query method is base on the google map store locator api.

Please refer this website:

https://developers.google.com/maps/solutions/store-locator/clothing-store-locator

Let say you have a variable of lat and lang
$lat;
$lng;

Let us assume that those variable has its coordinates.

In your query do this:

SELECT id, lat, lng ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance <= 50 ORDER BY distance;

The result will return the id, lat, and lng coordinates that is less than or equal to 50 miles.

P.S The 3959 is the unit to return the miles.


问:
NoSuchMethod error sometimes

Sometimes after deploy of my application on tomcat 8 i get :

```<code>2017 06 05 10:34:47#+0300#ERROR#org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/]##anonymous#localhost-startStop-1#na###web##StandardWrapper.Throwablejava.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:331)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:390)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:172)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:364)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4931)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5241)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
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:805)
</code>```

I guess sometimes it gets different dependency that doesn`t have the .getProperties() method ,but how i do choose which one to be used everytime

答: Which version of JAX-RS jar you have in your classpath or your classpath contain both JAX-RS 1(jsr311-api.jar) and JAX-RS 2(javax.ws.rs-api-2.0.1.jar) jar.If in your classpath you have jsr311-api.jar which is JAX-RS 1.jsr311-api.jar doesn't have the method getProperties() hence you are getting NoSuchMethodError.Use the javax.ws.rs-api-2.0.1.jar in your classpath it will fix your problem.

Title: NoSuchMethod error sometimes

Body:
Sometimes after deploy of my application on tomcat 8 i get :

2017 06 05 10:34:47#+0300#ERROR#org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/]##anonymous#localhost-startStop-1#na###web##StandardWrapper.Throwablejava.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:331)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:390)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:172)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:364)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4931)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5241)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
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:805)

I guess sometimes it gets different dependency that doesn`t have the .getProperties() method ,but how i do choose which one to be used everytime


问:
Logging daily check results with changing requirements
I apologize for the title, but I couldn't think of a better way to ask this question.

Basically, I need to create a database model for logging daily checks and parameters on various pieces of equipment. Every day the user will open up a form, it will list a number of tasks to check as well ask for operating parameters to be recorded (for example, temperature). The user then enters the parameters and flags any item that has an issue.

The issue I have with modeling this is the fact that the items to check can change as operational requirements change. We may need to add or remove things to check to keep things relevant.

I don't really have much example data to show as I am stumped about which way to go. One thing I can think of is keeping some sort of version number but I'm not sure how that would look in a database. The only other thing I could think to do is generate a hard copy PDF of the results and save that, rather than saving the results in the database. That way I don't have to worry about adding/removing items because previous daily checks will not be stored in the database and therefore won't be impacted. This would probably work fine for our needs as we don't have to go back and change anything after it's done, but I can't help to think there is a better way.

Let me know if you need any clarification and thanks for any help you can provide.

Edit (More Information)

Right now we have a blank excel sheet for each device, it's got a list of checks... one is say "General cleanup of hydraulic fluid", or "Check for abnormal noise/vibration" then there are a couple that wily say "Hydraulic Pressure (psi)" and you have to enter the pressure you recorded... there's probably about 20 tasks on average. You then put your name on the sheet, date it, print it and sign it.. it gets filled probably to never be seen again....

答:
What I would suggest is maybe breaking it down into components...so each device has a list of "tasks" and then each one of these tasks can be created and even reused across multiple devices if you have commonalities. That way if the requirements change you can just create new tasks. It might take a bit of fiddling to develop a UI that looks nice as far as editing and displaying the end result but for modeling purposes i'd say that's the way to go.

I would create a table to store instances of devices, a table to store instances of tasks, and then you would have one other table that connected dates,devices, and tasks. And if a particular task changes itself you have the option of designing it so that way it would be editable.


问:
Linq to SQL anonymous types return null
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

```<code>from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u
}
</code>```

and

```<code>from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }
</code>```

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

答:
Personally I would say not to do what you are trying to do and go with Enigmativity's answer

To someone maintaining this code is is not clear what the intention is.
Also it may not result in the data structure you intended. For each Unit found it will select all of the AgreementType and OptionRightsType data. This could be a lot of duplication of the same data.

```<code>from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

Splitting the code into two separate queries as per your Update 2 makes it clearer what you are trying to achieve.

You are getting the Units you want.

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u
}
</code>```

You are getting all the AgreementTypes and OptionRightsTypes but not duplicating the data for each unit found.

```<code>from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }
</code>```

May be you can ask another question as to why you wanted to do this in the first place. It sounds like you are trying to optimise your database calls. This could possible achieved another way. e.g. caching the static data.

If you still want to try and reduce these to one query then I will advise you try and write the code in SQL first and then look to see if that code can be converted into Linq.

Title: Linq to SQL anonymous types return null

Body:
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

from u in Units
where u.Id == 1000
select new
{
    Unit = u
}

and

from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

Body:
Personally I would say not to do what you are trying to do and go with Enigmativity's answer

To someone maintaining this code is is not clear what the intention is.
Also it may not result in the data structure you intended. For each Unit found it will select all of the AgreementType and OptionRightsType data. This could be a lot of duplication of the same data.

from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

Splitting the code into two separate queries as per your Update 2 makes it clearer what you are trying to achieve.

You are getting the Units you want.

from u in Units
where u.Id == 1000
select new
{
    Unit = u
}

You are getting all the AgreementTypes and OptionRightsTypes but not duplicating the data for each unit found.

from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }

May be you can ask another question as to why you wanted to do this in the first place. It sounds like you are trying to optimise your database calls. This could possible achieved another way. e.g. caching the static data.

If you still want to try and reduce these to one query then I will advise you try and write the code in SQL first and then look to see if that code can be converted into Linq.


问:
How to use kernel header <linux/gfp.h>
Hi i am developing a small program that allocates physical pages dynamically using Alloc_pages function declared in gfp.h but when i am trying to compile it encounters an error with message linux/gfp.h no such file or directory. How can i use this header to develop memory management programs. Any suggestions are heartly welcomed.

答:
Hi i am developing a small program that allocates physical pages dynamically using Alloc_pages function declared in gfp.h…

That won't work.

The linux/gfp.h header file declares functions that are available within the kernel. These functions cannot be called directly by userspace applications; the header file can only be used for building kernel modules.

Title: How to use kernel header <linux/gfp.h>


问:
How to stop index count increment using Array.map iteration based on certain condition inside loop?
like for e.g.

```<code>Array.map((obj, index) => (
    condition === true ?
    default index counter increment
    : do not increase index count
))
</code>```

I want my counter to increase only if my condition is true, is there any work around for this? I am facing problems when I like adding alternate colors to rows based on object and in case I want to reject certain objects and don't create any rows, even though the row doesn't create, still my counter increases, colors apply on the row which is actually not there and produces UI flaw.

答:
You could use Array.prototype.forEach() and increment the counter variable based on the "condition" that is applied to all elements of the array one by one:

```<code>let counter = 0;
Array.forEach((o, i) => condition && counter++);
</code>```

Body:
like for e.g.

Array.map((obj, index) => (
    condition === true ?
    default index counter increment
    : do not increase index count
))

I want my counter to increase only if my condition is true, is there any work around for this? I am facing problems when I like adding alternate colors to rows based on object and in case I want to reject certain objects and don't create any rows, even though the row doesn't create, still my counter increases, colors apply on the row which is actually not there and produces UI flaw.

Body:
You could use Array.prototype.forEach() and increment the counter variable based on the "condition" that is applied to all elements of the array one by one:

let counter = 0;
Array.forEach((o, i) => condition && counter++);


问:
mongoDB, express, webpack-dev-middleware, console.log db collection won't work
I try to setting up together mongoDB, express and webpack-dev-middleware. I want to do it the simplest way as it's possible, using as little adding modules as it's possible. I'm basing on several tutorials (I haven't found one simply). Everything worked to moment when I tred console log collection from mongoDB. I have nothing print in my consola.

I'm sure that connection to mongoDB is ok. I think it's something with webpac-dev-middleware and routing, but I can't find some helpfull information or tutorial.

server.js

```<code>const path = require('path');
const express = require('express');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const config = require('./webpack.config.js');

const app = express();

const compiler = webpack(config);

app.use(bodyParser.urlencoded({extended: true}));

const MongoClient = require('mongodb').MongoClient;

var db;

MongoClient.connect('mongodb://USER:PASSWORD@HOST:PORT/testit' (err, database) => {
  if (err) return console.log('Connection error: ',err);
  db = database;
  app.listen(3000, () => {
    console.log('MongoDB listening on 3000');
 });
});

const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
  noInfo: true,
      stats: {
        colors: true,
      }
  });
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, {
     log: console.log
});

app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);

app.use(express.static(__dirname + '/'));
app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);  //according to tutorial this line should to display console log, but I have nothing, even if I try console log error. Or whatever...
    });
});

app.post('/quotes', (req, res) => {
  console.log(req.body);
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err);

    console.log('saved to database');
    res.redirect('/');
  });
});

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port + ' mode: ' +
app.settings.env);
});
</code>```

webpack.confing.js

```<code>'use strict';

var Webpack = require('webpack');
var path = require('path');

var config = {
    entry: [
        'webpack-hot-middleware/client',
        './public/index.js'
    ],
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
        },
    devServer: {
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id, Content-Length, X-Requested-With",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        inline: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015','react']
                }
            }
        ]
    },
    plugins: [new Webpack.HotModuleReplacementPlugin()]
};

module.exports = config;
</code>```

Please, help me find where exactly problem is. I'm sure I missunderstand something, but I don't know what.

答:
Exactly, if someone want to use it, this part of code should looks like:

```<code>app.get('/', (req, res, next) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);
    });
    next();
});

app.use(express.static(__dirname + '/'));
</code>```

Add next.

Body:
I try to setting up together mongoDB, express and webpack-dev-middleware. I want to do it the simplest way as it's possible, using as little adding modules as it's possible. I'm basing on several tutorials (I haven't found one simply). Everything worked to moment when I tred console log collection from mongoDB. I have nothing print in my consola.

I'm sure that connection to mongoDB is ok. I think it's something with webpac-dev-middleware and routing, but I can't find some helpfull information or tutorial.

server.js

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const config = require('./webpack.config.js');

const app = express();

const compiler = webpack(config);

app.use(bodyParser.urlencoded({extended: true}));

const MongoClient = require('mongodb').MongoClient;

var db;

MongoClient.connect('mongodb://USER:PASSWORD@HOST:PORT/testit' (err, database) => {
  if (err) return console.log('Connection error: ',err);
  db = database;
  app.listen(3000, () => {
    console.log('MongoDB listening on 3000');
 });
});

const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
  noInfo: true,
      stats: {
        colors: true,
      }
  });
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, {
     log: console.log
});

app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);

app.use(express.static(__dirname + '/'));
app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);  //according to tutorial this line should to display console log, but I have nothing, even if I try console log error. Or whatever...
    });
});

app.post('/quotes', (req, res) => {
  console.log(req.body);
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err);

    console.log('saved to database');
    res.redirect('/');
  });
});

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port + ' mode: ' +
app.settings.env);
});

webpack.confing.js

'use strict';

var Webpack = require('webpack');
var path = require('path');

var config = {
    entry: [
        'webpack-hot-middleware/client',
        './public/index.js'
    ],
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
        },
    devServer: {
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id, Content-Length, X-Requested-With",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        inline: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015','react']
                }
            }
        ]
    },
    plugins: [new Webpack.HotModuleReplacementPlugin()]
};

module.exports = config;

Please, help me find where exactly problem is. I'm sure I missunderstand something, but I don't know what.

Body:
Exactly, if someone want to use it, this part of code should looks like:

app.get('/', (req, res, next) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);
    });
    next();
});

app.use(express.static(__dirname + '/'));

Add next.


问:
iOS app transition by custom url scheme takes too much time
I am testing inter app communication like this.
App A -(1)-> App B -(2)-> App A

The transition (1) takes more than 10 seconds. (2) is fast. App B is almost empty app, handling URL from App A and openURL for reverting back to App A is added. Strange thing is that launching App B from the home screen does not have any problem. It launches about 1 seconds. It happens only when it is launched by URL scheme.

I tried async call by GCD but it does not help. I think there is something wrong with launching App B rather than something in App A. Because the most time consuming point is in the state of showing splash image. It takes almost 10 seconds.

I am testing in Xcode 8 and iOS 10.

Any advice is welcomed!

EDIT

App A ViewController: transit to App B

```<code>func call() {
    let url = URL(string: "AppB://" + "?type=aa&data=" + testData)
    if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.openURL(url!)
        print("OK")
    }
    else {
        print("NOK")
    }
}
</code>```

App B AppDelegate: return to App A

```<code>func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    let url = URL(string: "AppA://")
    if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.openURL(url!)
        print("OK")
    }
    else {
        print("NOK")
    }

    return true;
}
</code>```

答:
I thought this issue is about calling openURL in AppAloading AppB. But I found out that it is happening during AppB->AppA transition. I could resolve the issue by asynchronous openURL function call in AppB.

Thank you for the comments pnizzle, Nirmalsinh and Vladislav Kovalyov.

Body:
I am testing inter app communication like this.
App A -(1)-> App B -(2)-> App A

The transition (1) takes more than 10 seconds. (2) is fast. App B is almost empty app, handling URL from App A and openURL for reverting back to App A is added. Strange thing is that launching App B from the home screen does not have any problem. It launches about 1 seconds. It happens only when it is launched by URL scheme.

I tried async call by GCD but it does not help. I think there is something wrong with launching App B rather than something in App A. Because the most time consuming point is in the state of showing splash image. It takes almost 10 seconds.

I am testing in Xcode 8 and iOS 10.

Any advice is welcomed!

EDIT

App A ViewController: transit to App B

func call() {
    let url = URL(string: "AppB://" + "?type=aa&data=" + testData)
    if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.openURL(url!)
        print("OK")
    }
    else {
        print("NOK")
    }
}

App B AppDelegate: return to App A

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    let url = URL(string: "AppA://")
    if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.openURL(url!)
        print("OK")
    }
    else {
        print("NOK")
    }

    return true;
}


问:
Angular 2 Routing ERROR in Cannot use "in" operator to search for "providers" in null
I am testing the Lazy Router version with Angular.

I implemented for every component with the following parts:

```<code>in componentone.component.ts
@Component({...})
export class ComponentOne ...

in componentone.module.ts
@NgModule({..., imports: [componentOneRoutes]})
export default class ComponentOneModule

in componentone.routes.ts
const routes = [ {path: '', component: ComponentOne} ]
export default RouterModule.forChild(routes);
</code>```

In my appcomponent.ts

```<code>@Component({})
export class AppComponent {
   // for displaying the content in url in the app.component.html
   navs = [ {url: '', content: 'Component 1'},... ]
}
</code>```

In app.routes.ts

```<code>const routes = [ {path: "", loadChildren:
"app/componentone/componentone.module"} ]

export default RouterModule.forRoot(routes);
</code>```

Then in app.module.ts import the app.routes.ts

```<code>@NgModule({imports:[appRoutes,...]})
</code>```

I receive the following Error:
    ERROR in Cannot use "in" operator to search for "providers" in null.

My providers section is empty because i have no services only the routing part in the import array.

I am using angular 4 and angular-cli 1.0.0

答:
A possible reason for this is described here: https://github.com/angular/angular-cli/issues/3826

First, remove the default annotation from your code (componens and others places).
Second, where are the definitions of componentOneRoutes and appRoutes?

Body:
I am testing the Lazy Router version with Angular.

I implemented for every component with the following parts:

in componentone.component.ts
@Component({...})
export class ComponentOne ...

in componentone.module.ts
@NgModule({..., imports: [componentOneRoutes]})
export default class ComponentOneModule

in componentone.routes.ts
const routes = [ {path: '', component: ComponentOne} ]
export default RouterModule.forChild(routes);

In my appcomponent.ts

@Component({})
export class AppComponent {
   // for displaying the content in url in the app.component.html
   navs = [ {url: '', content: 'Component 1'},... ]
}

In app.routes.ts

const routes = [ {path: "", loadChildren:
"app/componentone/componentone.module"} ]

export default RouterModule.forRoot(routes);

Then in app.module.ts import the app.routes.ts

@NgModule({imports:[appRoutes,...]})

I receive the following Error:
    ERROR in Cannot use "in" operator to search for "providers" in null.

My providers section is empty because i have no services only the routing part in the import array.

I am using angular 4 and angular-cli 1.0.0


问:
Connecting an .xib-File to a Custom Class
I have created a custom .xib-file and a custom subclass of UIView.
What is the procedure to connect the two?

Meaning that when I set MyCustomClass in the custom class attribute, it turns into my custom .xib-file and acts according to MyCustomClass.swift.

答: Click on your Xib file and go here and set your custom Class here


问:
Is there a way to get count of elements with the same accessibilityID?
Is there a way to get the count of elements having same accessibilityID/label etc in Swift?</p>

答: I think that there is much better solution that google provides right in EarlGrey repo. Follow this link.</p>


问:
Show only nth tick LINE on x-axis for Chart.js diagram
I've been searching for a solution to this for a while but am getting no nearer to a solution due to the mass of deleted documentation and hacky answers for previous versions of the library.

I'm working on a chart with ChartJS v2 with quarterly-month names along the x-axis, and I've set my labels so that only every 4th label is shown (i.e. one per year). The result is this:

However, I would like to have it such that the tick lines also only appear on every 4th x-axis entry at the same point as the labels. Is this possible?

My current script tag is as follows:

```<code><script>
    var ctx = document.getElementById("myChart").getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 420;
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {

          < snipped for brevity >

        },
        options: {
            tooltips: {
              mode: 'index',
              intersect: false
            },
            scales: {
                xAxes: [{
                    ticks: {
                        userCallback: function(item, index) {
                            if (index%4) return "";
                            return item;
                        },
                        autoSkip: false
                    },
                    display: true
                }],
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
    </script>
</code>```

Is this possible to achieve? Thanks in advance.

答:
Replace your tick's userCallback function with the following ...

```<code>userCallback: function(item, index) {
   if (!(index % 4)) return item;
}
</code>```

Basically, you don't need to return any empty string for the label that you wish to hide. If you do not return anything (for the label you don't want), it won't draw any tick (as well as gridline) for that label.

ᴅᴇᴍᴏ

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
      datasets: [{
         label: 'Standard Rating',
         data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
         backgroundColor: 'rgba(209, 230, 245, 0.5)',
         borderColor: 'rgba(56, 163, 236, 1)',
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      tooltips: {
         mode: 'label',
         intersect: false
      },
      scales: {
         xAxes: [{
            ticks: {
               userCallback: function(item, index) {
                  if (!(index % 4)) return item;
               },
               autoSkip: false
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas></code>```

Body:
I've been searching for a solution to this for a while but am getting no nearer to a solution due to the mass of deleted documentation and hacky answers for previous versions of the library.

I'm working on a chart with ChartJS v2 with quarterly-month names along the x-axis, and I've set my labels so that only every 4th label is shown (i.e. one per year). The result is this:

However, I would like to have it such that the tick lines also only appear on every 4th x-axis entry at the same point as the labels. Is this possible?

My current script tag is as follows:

Is this possible to achieve? Thanks in advance.

Body:
Replace your tick's userCallback function with the following ...

userCallback: function(item, index) {
   if (!(index % 4)) return item;
}

Basically, you don't need to return any empty string for the label that you wish to hide. If you do not return anything (for the label you don't want), it won't draw any tick (as well as gridline) for that label.

ᴅᴇᴍᴏ

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
      datasets: [{
         label: 'Standard Rating',
         data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
         backgroundColor: 'rgba(209, 230, 245, 0.5)',
         borderColor: 'rgba(56, 163, 236, 1)',
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      tooltips: {
         mode: 'label',
         intersect: false
      },
      scales: {
         xAxes: [{
            ticks: {
               userCallback: function(item, index) {
                  if (!(index % 4)) return item;
               },
               autoSkip: false
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>


问:
How to parse or read CSV separated comma ignoring empty and selected value using C#?
I got some issue in parsing or reading the CSV. I want to achieve to pick the selected value in CSV file because it doesn't have a header. Then I want to store the selected item into the database.

Example Data:

```<code>Row 1: "","",John,"",28,"","",
Row 2: "",Doe,"","USA",
Row 3: Devoper,"","","ABC Company",
Row 4: "","",10,000,"2 Years",
Row 5: "C#","LINQ","ASP.NET MVC",
</code>```

I want to select like this:

```<code>Row 1: John,28
Row 2: Doe, USA
Row 3: Developer, ABC Company
Row 4: 10,000, 2 Years
Row 5: C#, LINQ, ASP.NET MVC
</code>```

We assume class structured is like this:

```<code>public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Position { get; set; }
public double Salary { get; set; }
public string YearWorked { get; set; }
public string Skills { get; set; }
</code>```

答:
LINQ is a wonderfull quick tool. But like all quick tools, it has limits. I generally consider parsing CSV to be way beyond those limits.

You should be using a proper CSV parser. There is just to many special cases (like Multiline fields, escaped commas) for LINQ to ever realiably deal with. And even if you could, the performance and memory usage would still be bad.

Here is a CSV Parser I often link. Could it be the droid you are looking for?
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

Body:
I got some issue in parsing or reading the CSV. I want to achieve to pick the selected value in CSV file because it doesn't have a header. Then I want to store the selected item into the database.

Example Data:

Row 1: "","",John,"",28,"","",
Row 2: "",Doe,"","USA",
Row 3: Devoper,"","","ABC Company",
Row 4: "","",10,000,"2 Years",
Row 5: "C#","LINQ","ASP.NET MVC",

I want to select like this:

Row 1: John,28
Row 2: Doe, USA
Row 3: Developer, ABC Company
Row 4: 10,000, 2 Years
Row 5: C#, LINQ, ASP.NET MVC

We assume class structured is like this:

public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Position { get; set; }
public double Salary { get; set; }
public string YearWorked { get; set; }
public string Skills { get; set; }


问:
Is WCF ready for real world?
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

```<code>Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to
</code>```

install some extension files. so it's
  lot of work for a new product.

```<code>2. I found it very hard to configure security settings. when i
</code>```

tried to configure for the first time
  it threw all kind of errors.

```<code>3. After installing WCF in IIS, sometimes it's trowing an exception
</code>```

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

```<code>and a lot more...
</code>```

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.

答:
Yes, definitely, WCF is ready for real world use, and is being used by lots of large and small corporations around the world.

Yes, hosting in IIS sucks - but that's not WCF's fault, it's IIS which is really just a web server - not an application host.

Therefore, for any serious, production-grade WCF services, I would recommend to always self-host. Skips all the IIS related messiness, gives you full control over your service and your endpoints - all sounding pretty good to me!

Title: Is WCF ready for real world?

Body:
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to

install some extension files. so it's
  lot of work for a new product.

2. I found it very hard to configure security settings. when i

tried to configure for the first time
  it threw all kind of errors.

3. After installing WCF in IIS, sometimes it's trowing an exception

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

and a lot more...

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.


问:
Swift: Using Int in UILabel inside View Controller
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

```<code>   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!
</code>```

Any suggestions for better ways to handle this would be amazing.

Thanks

答:
You should separate your data and logic from the view. It is absurd to put a value into a label and try to interpret it. Please consider reading up on the MVC (model view controller) pattern which is the underpinning of iOS.

Your view controller should have a variable, say number to keep track of the value that determines which image to show.

```<code>var number: Int = 0 {
    didSet {
        imageView.image = number <= 2 ? pic1 : pic2
        label.text = "\(number)"
    }
}
</code>```

On naming

Your variable names are also a mess. By convention variables are lowerCamelCase. If you are naming an UIImageView, the name picture is too generic and could be misleading. Also avoid names like pic1, pic2, better is something like activeImage, inactiveImage.

Body:
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!

Any suggestions for better ways to handle this would be amazing.

Thanks

Body:
You should separate your data and logic from the view. It is absurd to put a value into a label and try to interpret it. Please consider reading up on the MVC (model view controller) pattern which is the underpinning of iOS.

Your view controller should have a variable, say number to keep track of the value that determines which image to show.

var number: Int = 0 {
    didSet {
        imageView.image = number <= 2 ? pic1 : pic2
        label.text = "\(number)"
    }
}

On naming

Your variable names are also a mess. By convention variables are lowerCamelCase. If you are naming an UIImageView, the name picture is too generic and could be misleading. Also avoid names like pic1, pic2, better is something like activeImage, inactiveImage.


问:
Programmatically add an application to Windows Firewall
I have an application that is installed and updated via ClickOnce.  The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall.  Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also.  What would be the best way to have the changes made to the firewall so that it's invisible to the end user?

(The application is written in C#)

答:
Assuming we're using a Visual Studio Installer->Setup Project - You need an installer class like this inside an assembly that's being installed, and then make sure you add a custom action for the "Primary output" in the install phase.</p>

```<code>using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Diagnostics;

namespace YourNamespace
{
    [RunInstaller(true)]
    public class AddFirewallExceptionInstaller : Installer
    {
        protected override void OnAfterInstall(IDictionary savedState)
        {
            base.OnAfterInstall(savedState);

            var path = Path.GetDirectoryName(Context.Parameters["assemblypath"]);
            OpenFirewallForProgram(Path.Combine(path, "YourExe.exe"),
                                   "Your program name for display");
        }

        private static void OpenFirewallForProgram(string exeFileName, string displayName)
        {
            var proc = Process.Start(
                new ProcessStartInfo
                    {
                        FileName = "netsh",
                        Arguments =
                            string.Format(
                                "firewall add allowedprogram program=\"{0}\" name=\"{1}\" profile=\"ALL\"",
                                exeFileName, displayName),
                        WindowStyle = ProcessWindowStyle.Hidden
                    });
            proc.WaitForExit();
        }
    }
}
</code>```

OwnerDisplayName: RichieACC

Body:
Assuming we're using a Visual Studio Installer->Setup Project - You need an installer class like this inside an assembly that's being installed, and then make sure you add a custom action for the "Primary output" in the install phase.

using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Diagnostics;

namespace YourNamespace
{
    [RunInstaller(true)]
    public class AddFirewallExceptionInstaller : Installer
    {
        protected override void OnAfterInstall(IDictionary savedState)
        {
            base.OnAfterInstall(savedState);

            var path = Path.GetDirectoryName(Context.Parameters["assemblypath"]);
            OpenFirewallForProgram(Path.Combine(path, "YourExe.exe"),
                                   "Your program name for display");
        }

        private static void OpenFirewallForProgram(string exeFileName, string displayName)
        {
            var proc = Process.Start(
                new ProcessStartInfo
                    {
                        FileName = "netsh",
                        Arguments =
                            string.Format(
                                "firewall add allowedprogram program=\"{0}\" name=\"{1}\" profile=\"ALL\"",
                                exeFileName, displayName),
                        WindowStyle = ProcessWindowStyle.Hidden
                    });
            proc.WaitForExit();
        }
    }
}


问:
array_flip with an array in the value
Simple one (but not solved yet): this is my array

```<code>[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]
</code>```

And I would love to see this result:

```<code>[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]
</code>```

I've already tried array_flip

答:
Try this:</p>

```<code>foreach ($yourArr as $role) {
 foreach ($role['name'] as $user) {
    $arr[$user] = $role['role'];
 }
}
</code>```

Title: array_flip with an array in the value

Body:
Simple one (but not solved yet): this is my array

[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]

And I would love to see this result:

[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]

I've already tried array_flip

Body:
Try this:

foreach ($yourArr as $role) {
 foreach ($role['name'] as $user) {
    $arr[$user] = $role['role'];
 }
}


问:
mysqlimport cannot read trademark symbol
I have a large CSV data file. One of the fields in the file contains ™ symbol. I have created the table using

```<code>CREATE TABLE scraped_data(
.....) ENGINE=MyISAM DEFAULT CHARSET=latin1;
</code>```

Then I have imported the data into the DB using mysqlimport command.

```<code>mysqlimport --ignore-lines=1 --fields-terminated-by=',' --fields-enclosed-by='"' --local -u root -p scraping scraped_data.csv
</code>```

then, after processing I have exported the file back to csv. But the exported file contains â„¢ symbol instead of ™. How do I retain this symbol in the exported csv ?

答:
I have changed the charset to utf8 by creating table by using

```<code>CREATE TABLE scaped_data(
....)ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

This solved the problem.

Body:
I have a large CSV data file. One of the fields in the file contains ™ symbol. I have created the table using

CREATE TABLE scraped_data(
.....) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Then I have imported the data into the DB using mysqlimport command.

mysqlimport --ignore-lines=1 --fields-terminated-by=',' --fields-enclosed-by='"' --local -u root -p scraping scraped_data.csv

then, after processing I have exported the file back to csv. But the exported file contains â„¢ symbol instead of ™. How do I retain this symbol in the exported csv ?

Body:
I have changed the charset to utf8 by creating table by using

CREATE TABLE scaped_data(
....)ENGINE=MyISAM DEFAULT CHARSET=utf8;

This solved the problem.