问:
Javascript Regex setting opposite rules
in a nut shell i need two regular expressions to detect either .css or .scss files.

I need to return true if the following criteria is met:

#1

File name can be anything but must not equal 'global'

File extensions must be either '.css' or '.scss'

#2

File name must equal 'global'

File extensions must be either '.css' or '.scss'

答:
Regex A:

```<code>^global\.s?css$
</code>```

Regex B:

```<code>\.s?css$
</code>```

Your use case #2 is true when Regex A matches. Your use case #1 is true when Regex A does not match, and Regex B matches.

In particular: ^ means "start of the string", which guarantees the first six characters in the matching string are global. \. means "match a period". Without the \, . on its own means "match any character", which we don't want. s? means "match either nothing or an s". $ means "end of the string", which guarantees the last three characters in the matching string are css.

Title: Javascript Regex setting opposite rules

Body:
Regex A:

^global\.s?css$

Regex B:

\.s?css$

Your use case #2 is true when Regex A matches. Your use case #1 is true when Regex A does not match, and Regex B matches.

In particular: ^ means "start of the string", which guarantees the first six characters in the matching string are global. \. means "match a period". Without the \, . on its own means "match any character", which we don't want. s? means "match either nothing or an s". $ means "end of the string", which guarantees the last three characters in the matching string are css.


来源: stackexchange

问:
How do i compare 2 strings in shell?
I want the user to input something at the command line either -l or -e.
so e.g. $./report.sh -e
I want an if statement to split up whatever decision they make so i have tried...

```<code>if [$1=="-e"]; echo "-e"; else; echo "-l"; fi
</code>```

obviously doesn't work though
Thanks

答:
If you just want to print which parameter the user has submitted, you can simply use echo "$1". If you want to fall back to a default value if the user hasn't submitted anything, you can use echo "${1:--l} (:- is the Bash syntax for default values). However, if you want really powerful and flexible argument handling, you could look into getopt:

```<code>params=$(getopt --options f:v --longoptions foo:,verbose --name "my_script.sh" -- "$@")

if [ $? -ne 0 ]
then
    echo "getopt failed"
    exit 1
fi

eval set -- "$params"

while true
do
    case $1 in
        -f|--foo)
            foobar="$2"
            shift 2
            ;;
        -v|--verbose)
            verbose='--verbose'
            shift
            ;;
        --)
            while [ -n "$3" ]
            do
                targets[${#targets[*]}]="$2"
                shift
            done
            source_dir=$(readlink -fn -- "$2")
            shift 2
            break
            ;;
        *)
            echo "Unhandled parameter $1"
            exit 1
            ;;
    esac
done

if [ $# -ne 0 ]
then
    error "Extraneous parameters." "$help_info" $EX_USAGE
fi
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do i compare 2 strings in shell?

Body:
I want the user to input something at the command line either -l or -e.
so e.g. $./report.sh -e
I want an if statement to split up whatever decision they make so i have tried...

if [$1=="-e"]; echo "-e"; else; echo "-l"; fi

obviously doesn't work though
Thanks

Body:
If you just want to print which parameter the user has submitted, you can simply use echo "$1". If you want to fall back to a default value if the user hasn't submitted anything, you can use echo "${1:--l} (:- is the Bash syntax for default values). However, if you want really powerful and flexible argument handling, you could look into getopt:

params=$(getopt --options f:v --longoptions foo:,verbose --name "my_script.sh" -- "$@")

if [ $? -ne 0 ]
then
    echo "getopt failed"
    exit 1
fi

eval set -- "$params"

while true
do
    case $1 in
        -f|--foo)
            foobar="$2"
            shift 2
            ;;
        -v|--verbose)
            verbose='--verbose'
            shift
            ;;
        --)
            while [ -n "$3" ]
            do
                targets[${#targets[*]}]="$2"
                shift
            done
            source_dir=$(readlink -fn -- "$2")
            shift 2
            break
            ;;
        *)
            echo "Unhandled parameter $1"
            exit 1
            ;;
    esac
done

if [ $# -ne 0 ]
then
    error "Extraneous parameters." "$help_info" $EX_USAGE
fi


问:
XML to phpmyadmin
I want to import a XMl file into phpmyadmin.

I have a XML file with 75000 lines so inserting individually the values is a huge no, when I try to import the file as XMl to the database it gave the following message:

```<code>Import has been successfully finished, 0 queries executed.

The following structures have either been created or altered. Here you can:
View a structure's contents by clicking on its name.
Change any of its settings by clicking the corresponding "Options" link.
Edit structure by following the "Structure" link.

wp_db (Options)
(xmlfile.xml)

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

Notice in ./libraries/plugins/import/ImportXml.php#158
Undefined index: pma

Backtrace

./import.php#652: PMA\libraries\plugins\import\ImportXml->doImport(array)
</code>```

The phpmyadmin is behind MAMP, a short version of the xml file looks like this:

```<code><Report>
    <Row1>
        <Reference>123</Reference>
        <Nature>Outside</Nature>
        <Disponibility>Full</Disponibility>
        <State>In progress</State>
        <Person>Jon</Person>
        <Seller></Seller>
    </Row1>
    <Row2>
        <Reference>123</Reference>
        <Nature>Outside</Nature>
        <Disponibility>Full</Disponibility>
        <State>In progress</State>
        <Person>Jon</Person>
        <Seller></Seller>
    </Row2>
</Report>
</code>```

If it's not possible at least what is the easiest way to do it?
Thanks!

答: phpMyAdmin supports importing XML only if it follows a special format. You can see the exact format by exporting in phpMyAdmin a table in XML. You would need to programmatically modify your existing file to adapt to the supported format. </p>

ContentLicense: CC BY-SA 3.0

Title: XML to phpmyadmin

Body:
I want to import a XMl file into phpmyadmin.

I have a XML file with 75000 lines so inserting individually the values is a huge no, when I try to import the file as XMl to the database it gave the following message:

Import has been successfully finished, 0 queries executed.

The following structures have either been created or altered. Here you can:
View a structure's contents by clicking on its name.
Change any of its settings by clicking the corresponding "Options" link.
Edit structure by following the "Structure" link.

wp_db (Options)
(xmlfile.xml)

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

Notice in ./libraries/plugins/import/ImportXml.php#158
Undefined index: pma

Backtrace

./import.php#652: PMA\libraries\plugins\import\ImportXml->doImport(array)

The phpmyadmin is behind MAMP, a short version of the xml file looks like this:

<Report>
    <Row1>
        <Reference>123</Reference>
        <Nature>Outside</Nature>
        <Disponibility>Full</Disponibility>
        <State>In progress</State>
        <Person>Jon</Person>
        <Seller></Seller>
    </Row1>
    <Row2>
        <Reference>123</Reference>
        <Nature>Outside</Nature>
        <Disponibility>Full</Disponibility>
        <State>In progress</State>
        <Person>Jon</Person>
        <Seller></Seller>
    </Row2>
</Report>

If it's not possible at least what is the easiest way to do it?
Thanks!


问:
Ruid2 module configuration with Apache2.4
I try to set up an Ubuntu 16.04 server with Apache2.4 running with the Ruid2 module.

sudo apt-get install apache2 libapache2-mod-ruid2 php7.0-cgi

but when I run php scripts php code is not interpreted.
So what are the configuration steps regarding the ruid2 module, what are the files to edit ?

Thanks

答:
this should work...

```<code>apt-get install libapache2-mod-ruid2
a2enmod libapache2-mod-ruid2
</code>```

...but I also found this answer that says it doesn't...

https://askubuntu.com/questions/769232/apache2-mod-ruid2-doesnt-work

Body:
this should work...

apt-get install libapache2-mod-ruid2
a2enmod libapache2-mod-ruid2

...but I also found this answer that says it doesn't...

https://askubuntu.com/questions/769232/apache2-mod-ruid2-doesnt-work


问:
Angular2 .. Using the same component to show different data on the same page depending on service response / Reusing Component
My main HTML

  <block></block>
  <block></block>

```

<p>My Component </p>

<pre class="lang-js prettyprint-override"><code>import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
    selector : 'block',
    template : `
      <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}}</div>
`,
providers : [HTTP_PROVIDERS,TestService]
})
export class TestComponent implements OnInit{
    _list : any[];
    constructor(private _testDataService : TestService){}
    ngOnInit(){
        this._testDataService.getData()
            .subscribe(list => this._list = list);
    }

}
</code>```

I want to reuse the  component in the same page to show different data for different service calls

答:
We can achieve this by passing data from view to the Component as an attribute.

  <block test="block1"></block>
  <block test="block2"></block>

```

<p>Then in the component get the value of <code>test</code> by using the <code>@Input</code> decorator</p>

<pre class="lang-js prettyprint-override"><code>import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
  selector : 'block',
  template : `
    <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}}
    </div>
    `,
  providers : [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit{

  @Input() test;

  _list : any[];

  constructor(private _testDataService : TestService){}

  ngOnInit(){
    this._testDataService.getData(this.test)
      .subscribe(list => this._list = list);
  }
}
</code>```

After receiving the value from view, pass the same to the service depending on which you get the data.

Wherever angular sees a selector in the view, it will create a new instance of that.

Body:
My main HTML

  <block></block>
  <block></block>

My Component

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
    selector : 'block',
    template : `

{{_list && _list[0].name}}

`,
providers : [HTTP_PROVIDERS,TestService]
})
export class TestComponent implements OnInit{
    _list : any[];
    constructor(private _testDataService : TestService){}
    ngOnInit(){
        this._testDataService.getData()
            .subscribe(list => this._list = list);
    }

}

I want to reuse the  component in the same page to show different data for different service calls

Body:
We can achieve this by passing data from view to the Component as an attribute.

<div>
  <block test="block1"></block>
  <block test="block2"></block>
</div>

Then in the component get the value of test by using the @Input decorator

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
  selector : 'block',
  template : `
    <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}}
    </div>
    `,
  providers : [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit{

  @Input() test;

  _list : any[];

  constructor(private _testDataService : TestService){}

  ngOnInit(){
    this._testDataService.getData(this.test)
      .subscribe(list => this._list = list);
  }
}

After receiving the value from view, pass the same to the service depending on which you get the data.

Wherever angular sees a selector in the view, it will create a new instance of that.

ContentLicense: CC BY-SA 4.0


问:
Rails: destroy_all and update has_many size
I have the following relationship:

```<code>class Match
  has_many :players
end
</code>```

In one example case, I have a match with 2 players, one with the attribute team = 1 and the other team = 2

After I call match.players.where(team: 1).destroy_all, there is code that gets executed below that uses match.players.size
However, instead of the size being 2, the size now is 3. How can I update the size attribute? I can't call match.reload because there were other changes made to this object during this execution

答:
You might consider using counter_cache for this, so your player model gets:

```<code>class Player < ApplicationRecord
  belongs_to :match, dependent: :destroy, counter_cache: true
end
</code>```

You'll have to generate a migration and:

```<code>add_column :matches, :player_count, :integer
</code>```

That way when a player is added/removed from the match the counter cache column will automatically be updated.

More info here http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-counter-cache

Body:
I have the following relationship:

class Match
  has_many :players
end

In one example case, I have a match with 2 players, one with the attribute team = 1 and the other team = 2

After I call match.players.where(team: 1).destroy_all, there is code that gets executed below that uses match.players.size
However, instead of the size being 2, the size now is 3. How can I update the size attribute? I can't call match.reload because there were other changes made to this object during this execution

Body:
You might consider using counter_cache for this, so your player model gets:

class Player < ApplicationRecord
  belongs_to :match, dependent: :destroy, counter_cache: true
end

You'll have to generate a migration and:

add_column :matches, :player_count, :integer

That way when a player is added/removed from the match the counter cache column will automatically be updated.

More info here http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-counter-cache


问:
How to remove index numbers in dropdown list in Codeigniter?
```<code>  <?php
           $query=  $this->db->query('SELECT utility_name FROM utility2');

           $options = $query->result_array();

      //form_dropdown
     echo form_dropdown(array('name' => 'utility_name'), $options,
     set_value('utility_name', isset($utility2->utility_name) ?
     $utility2->utility_name : ''), lang('utility_field_utility_name'));
        ?>
</code>```

Here is my captured image

How do I remove index numbers in dropdown list?

答:
That's happening because of the way the result set you are getting back from codeigniter is structured. Basically you just need to loop through the array and grab the field you want to print instead of the entire array. You can do this easily using the array_column function.

```<code> $options =  array_column($options, 'utility_name');
 echo form_dropdown(array('name' => 'utility_name'),$options,
     set_value('utility_name', isset($utility2->utility_name) ?
     $utility2->utility_name : ''), lang('utility_field_utility_name')); ;
</code>```

Body:
  <?php
           $query=  $this->db->query('SELECT utility_name FROM utility2');

           $options = $query->result_array();

      //form_dropdown
     echo form_dropdown(array('name' => 'utility_name'), $options,
     set_value('utility_name', isset($utility2->utility_name) ?
     $utility2->utility_name : ''), lang('utility_field_utility_name'));
        ?>

Here is my captured image

How do I remove index numbers in dropdown list?

Body:
That's happening because of the way the result set you are getting back from codeigniter is structured. Basically you just need to loop through the array and grab the field you want to print instead of the entire array. You can do this easily using the array_column function.

 $options =  array_column($options, 'utility_name');
 echo form_dropdown(array('name' => 'utility_name'),$options,
     set_value('utility_name', isset($utility2->utility_name) ?
     $utility2->utility_name : ''), lang('utility_field_utility_name')); ;


问:
Azure Storage Table returning empty entities
I have the following Python code:

```<code>def GetData(tableService, tableName, dataFilter):
    keyMarkers = {}
    keyMarkers['nextpartitionkey'] = 0
    keyMarkers['nextrowkey'] = 0
    b=[]
    while True:
        #get a batch of data
        a = tableService.query_entities(table_name=tableName, filter=dataFilter,num_results=1000 ,marker=keyMarkers)
        #copy results to list
        for item in a.items:
            b.append(item.amount.value)
        #check to see if more data is available
        if len(a.next_marker) == 0:
            del a
            break
        #if more data available setup current position
        keyMarkers['nextpartitionkey'] = a.next_marker['nextpartitionkey']
        keyMarkers['nextrowkey'] = a.next_marker['nextrowkey']
        #house keep temp storage
        del a
    #return final list
    return b
</code>```

It is working, however, for the first results, a.items comes empty. After 10 queries, it finally starts returning some data. It is like the table has no rows for the values I queried. I know it has, and it eventually comes. But only after returning too many empty results.

I have a PHP code for the same purpose, but it doesn't get empty entities. So I don't think this is a common behavior from Azure. Maybe the way its SDK for Python works?

答: On the very first request, can you try passing in 'None' for the marker, rather than a dictionary with 0 and 0 for nextpk / nextrk?  I'm not sure, but this might be confusing the service into searching for a table entity with this pk & rk.</p>

Body:
I have the following Python code:

def GetData(tableService, tableName, dataFilter):
    keyMarkers = {}
    keyMarkers['nextpartitionkey'] = 0
    keyMarkers['nextrowkey'] = 0
    b=[]
    while True:
        #get a batch of data
        a = tableService.query_entities(table_name=tableName, filter=dataFilter,num_results=1000 ,marker=keyMarkers)
        #copy results to list
        for item in a.items:
            b.append(item.amount.value)
        #check to see if more data is available
        if len(a.next_marker) == 0:
            del a
            break
        #if more data available setup current position
        keyMarkers['nextpartitionkey'] = a.next_marker['nextpartitionkey']
        keyMarkers['nextrowkey'] = a.next_marker['nextrowkey']
        #house keep temp storage
        del a
    #return final list
    return b

It is working, however, for the first results, a.items comes empty. After 10 queries, it finally starts returning some data. It is like the table has no rows for the values I queried. I know it has, and it eventually comes. But only after returning too many empty results.

I have a PHP code for the same purpose, but it doesn't get empty entities. So I don't think this is a common behavior from Azure. Maybe the way its SDK for Python works?


问:
Ignore JSON field Play Controller Scala
I have a situation where I have an incoming data model as

```<code>case class Person(name: String,
                  age: Int,
                  contact: Int)
</code>```

But, I want to ignore the name property as I would not be receiving it but I need it to persist it in DB which I am injecting in later.

One option could be to make it optional but in that case I need to create another model for DB which is kind of redundant.

Could anybody provide a solution with JSONCombinator READ to avoid reading the field at all?

Thanks

答:
Create a custom Reads and default the name to empty string :

```<code>  import play.api.libs.json._ // JSON library
  import play.api.libs.json.Reads._ // Custom validation helpers
  import play.api.libs.functional.syntax._ // Combinator syntax

  implicit val customReads: Reads[Person] = (
    (JsPath \ "age").read[Int] and
      (JsPath \ "contact").read[Int]
  )((age, contact) => Person(name = "", age = age, contact = contact))
</code>```

Edit

```<code>  implicit val customWrites: Writes[Person] = (
    (JsPath \ "age").write[Int] and
      (JsPath \ "contact").write[Int]
  )((person) => (p.age, p.contact))
</code>```

Title: Ignore JSON field Play Controller Scala

Body:
I have a situation where I have an incoming data model as

case class Person(name: String,
                  age: Int,
                  contact: Int)

But, I want to ignore the name property as I would not be receiving it but I need it to persist it in DB which I am injecting in later.

One option could be to make it optional but in that case I need to create another model for DB which is kind of redundant.

Could anybody provide a solution with JSONCombinator READ to avoid reading the field at all?

Thanks

Body:
Create a custom Reads and default the name to empty string :

  import play.api.libs.json._ // JSON library
  import play.api.libs.json.Reads._ // Custom validation helpers
  import play.api.libs.functional.syntax._ // Combinator syntax

  implicit val customReads: Reads[Person] = (
    (JsPath \ "age").read[Int] and
      (JsPath \ "contact").read[Int]
  )((age, contact) => Person(name = "", age = age, contact = contact))

Edit

  implicit val customWrites: Writes[Person] = (
    (JsPath \ "age").write[Int] and
      (JsPath \ "contact").write[Int]
  )((person) => (p.age, p.contact))


问:
Best way to cancel task with functions that don't implement InterruptedException
I would like to cancel the following task

```<code>fooFuture = executor.submit(() ->  {
    bar1();
    bar2();
    bar3();
});
</code>```

The bar functions don't implement InterruptedException.

Is there a way I can catch an interrupt without checking Thread.currentThread().isInterruped(); after every instruction?

答:
I believe that there's no way in Java to just kill off a thread  if during execution not implemented  InterruptedException . If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.

kill the process in which the thread is running. (E.g., call System.exit(int).)

Body:
I would like to cancel the following task

fooFuture = executor.submit(() ->  {
    bar1();
    bar2();
    bar3();
});

The bar functions don't implement InterruptedException.

Is there a way I can catch an interrupt without checking Thread.currentThread().isInterruped(); after every instruction?


问:
How to select content type from HTTP Accept header in PHP
I'm trying to build a standard compliant website framework which serves XHTML 1.1 as application/xhtml+xml or HTML 4.01 as text/html depending on the browser support. Currently it just looks for "application/xhtml+xml" anywhere in the accept header, and uses that if it exists, but that's not flexible - text/html might have a higher score. Also, it will become more complex when other formats (WAP, SVG, XForms etc.) are added. So, does anyone know of a tried and tested piece of PHP code to select, from a string array given by the server, either the one best supported by the client or an ordered list based on the client score?</p>

答:
Client may accept a list of mime-types in the response. In the other hand the order of the response is very important for client side. PHP Pear HTTP2 is the best to deal with language, charset, and mimetypes.

```<code>$http = new HTTP2();
$supportedTypes = array(
    'text/html',
    'application/json'
);

$type = $http->negotiateMimeType($supportedTypes, false);
if ($type === false) {
    header('HTTP/1.1 406 Not Acceptable');
    echo "You don't want any of the content types I have to offer\n";
} else {
    echo 'I\'d give you data of type: ' . $type . "\n";
}
</code>```

Here is a good tutorial: https://cweiske.de/tagebuch/php-http-negotiation.htm

Body:
Client may accept a list of mime-types in the response. In the other hand the order of the response is very important for client side. PHP Pear HTTP2 is the best to deal with language, charset, and mimetypes.

$http = new HTTP2();
$supportedTypes = array(
    'text/html',
    'application/json'
);

$type = $http->negotiateMimeType($supportedTypes, false);
if ($type === false) {
    header('HTTP/1.1 406 Not Acceptable');
    echo "You don't want any of the content types I have to offer\n";
} else {
    echo 'I\'d give you data of type: ' . $type . "\n";
}

Here is a good tutorial: https://cweiske.de/tagebuch/php-http-negotiation.htm


问:
Content in between Header/Footer
I'm building a site where each page has a <TopNav>,  and a <Subfooter>.

As I understand it, the entry point of the app, should include these three components, and an additional component/s should render depending on the route the user is on.

I've built my entry point like so:

App.js

```<code>const App = () => (
  <div>
    <TopNav />
    <Footer />
    <Subfooter />
  </div>
)
</code>```

index.js

```<code>ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

The problem with the way I've structured this is that I can't render anything in between <TopNav> & . Should I do something like this in App.js and somehow inject the proper components into <PageContent> based on the route?

App.js

```<code>const App = () => (
  <div>
    <TopNav />
    <PageContent />
    <Footer />
    <Subfooter />
  </div>
)
</code>```

Also, all each component in app requires a router as they all contain  - where should I be defining the <Router> for all three of these components?

What is the correct approach to adding any necessary component between the three listed in App.js - and where  should the routing code go to dictate the behavior for all three of these components?

答:
One way of doing this could be:-

Routes.js

```<code>import React,{ Component } from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import SomeComponent from './components/some-component';
import AnotherComponent from './components/another-component';

const taskRouter = (
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={SomeComponent} />
            <Route path="/another" component={AnotherComponent} />
        </Route>
    </Router>
);

export default taskRouter;
</code>```

Main.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Router from './Routes';
ReactDOM.render(<Router/>, document.getElementById('root'));
</code>```

Finally inside App.js

```<code>const App = (props) => (
  <div>
    <TopNav />
    {props.children}
    <Footer />
    <Subfooter />
  </div>
)
</code>```

All route components will render themselves inside props.children.

Hope that helps.

Title: Content in between Header/Footer

Body:
I'm building a site where each page has a <TopNav>,  and a <Subfooter>.

As I understand it, the entry point of the app, should include these three components, and an additional component/s should render depending on the route the user is on.

I've built my entry point like so:

App.js

const App = () => (

    <TopNav />

    <Subfooter />

)

index.js

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

The problem with the way I've structured this is that I can't render anything in between <TopNav> & . Should I do something like this in App.js and somehow inject the proper components into <PageContent> based on the route?

App.js

const App = () => (

    <TopNav />
    <PageContent />

    <Subfooter />

)

Also, all each component in app requires a router as they all contain  - where should I be defining the <Router> for all three of these components?

What is the correct approach to adding any necessary component between the three listed in App.js - and where  should the routing code go to dictate the behavior for all three of these components?

Body:
One way of doing this could be:-

Routes.js

import React,{ Component } from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import SomeComponent from './components/some-component';
import AnotherComponent from './components/another-component';

const taskRouter = (
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={SomeComponent} />
            <Route path="/another" component={AnotherComponent} />
        </Route>
    </Router>
);

export default taskRouter;

Main.js

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './Routes';
ReactDOM.render(<Router/>, document.getElementById('root'));

Finally inside App.js

const App = (props) => (
  <div>
    <TopNav />
    {props.children}
    <Footer />
    <Subfooter />
  </div>
)

All route components will render themselves inside props.children.

Hope that helps.


问:
How to format high charts?
I am using highchart  (jquery chart library). I am indicating the axis with tooltip. now i need to display y axis value on top of respective bar. How can i do that

My example graph

Question: To display yaxis values on top of respective bar in highchart.

答:
My Final solution is for my expected graph

```<code>        var chart;

        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'faq_view_graph',
                defaultSeriesType: 'column'
            },
            title: {
                text: 'Category View'
            },
            xAxis: {
                categories: ['Category1', 'Category2', 'Category3', 'Category4', 'Category5', 'Category6', 'Category7', 'Category8', 'Category9', 'Category10'],
                title:{
                    text: 'Views'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Category'
                }
            },
            tooltip: {
                enabled: true,
                formatter: function() {
                    return ''+this.series.name +': '+ this.y;
                }
            },
            point: {
                events: {
                    click: function() {
                        alert('check');
                    }
                }
            },

///////////////////////////////////////////////////////////////////////////////
          plotOptions: {
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function() {
                                alert ('Category: '+ this.x +', value: '+ this.y);
                            }
                        }
                    }
                }
            },

///////////////////////////////////////////////////////////////////////////////

                series: [{
                name: 'Number of visits',
                data: [5, 3, 4, 10, 2, 19, 56, 23, 21, 70],
        //Codes to display value on top of each bar
            dataLabels: {
                enabled: true,
                rotation: 0,
                color: '#FFFFFF',
                align: 'right',
                x: -3,
                y: 10,
                formatter: function() {
                    return this.y;
                },
                style: {
                    font: 'normal 13px Verdana, sans-serif'
                }
            }
            }]
        });
//////////////////////////////Graph/////////////////////////////////////////////

    });
</code>```

Title: How to format high charts?

Body:
My Final solution is for my expected graph

        var chart;

        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'faq_view_graph',
                defaultSeriesType: 'column'
            },
            title: {
                text: 'Category View'
            },
            xAxis: {
                categories: ['Category1', 'Category2', 'Category3', 'Category4', 'Category5', 'Category6', 'Category7', 'Category8', 'Category9', 'Category10'],
                title:{
                    text: 'Views'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Category'
                }
            },
            tooltip: {
                enabled: true,
                formatter: function() {
                    return ''+this.series.name +': '+ this.y;
                }
            },
            point: {
                events: {
                    click: function() {
                        alert('check');
                    }
                }
            },

///////////////////////////////////////////////////////////////////////////////
          plotOptions: {
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function() {
                                alert ('Category: '+ this.x +', value: '+ this.y);
                            }
                        }
                    }
                }
            },

///////////////////////////////////////////////////////////////////////////////

                series: [{
                name: 'Number of visits',
                data: [5, 3, 4, 10, 2, 19, 56, 23, 21, 70],
        //Codes to display value on top of each bar
            dataLabels: {
                enabled: true,
                rotation: 0,
                color: '#FFFFFF',
                align: 'right',
                x: -3,
                y: 10,
                formatter: function() {
                    return this.y;
                },
                style: {
                    font: 'normal 13px Verdana, sans-serif'
                }
            }
            }]
        });
//////////////////////////////Graph/////////////////////////////////////////////

    });


问:
How to be able to connect a AWS lambda to google adx seller
I have a api that i use to get Google Adx seller exchange information. My issue is that i want to put this into a AWS lambda to seed a database everyday automatically, the thing is access tokens expire and once its expired then well i won't have the ability to access the api. I can not make my customers keep having to log back in all the time in order for them to keep getting the adx information. Any suggestions on what I can do would be greatly appreciated. Ill include the script I use but that really shouldn't matter I don't believe.

```<code>import sys

from apiclient import sample_tools
from oauth2client import client

def main(argv):
 # Authenticate and construct service.
 service, _ = sample_tools.init(
  argv, 'adexchangeseller', 'v2.0', __doc__, __file__,
  scope='https://www.googleapis.com/auth/adexchange.seller.readonly')

try:
# Retrieve report.
result = service.accounts().reports().generate(
    accountId='myaccount',
    startDate='today-6d', endDate='today',
    metric=['AD_REQUESTS', 'CLICKS'],
    dimension=['DATE', 'WINNING_BID_RULE_NAME'],
    sort=['+DATE']).execute()

# Display headers.
for header in result['headers']:
  print '%25s' % header['name'],
print

# Display results.
for row in result['rows']:
  for column in row:
    print '%25s' % column,
  print

# Display totals
for total in result['totals']:
  print '%25s' % total,
print

except client.AccessTokenRefreshError:
  print ('The credentials have been revoked or expired, please re-run
 the '
       'application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)
</code>```

I'm also totally new to python. So this seems like how we want it too. but  I'm waiting on client Adx credentials, so not 100 percent sure. I just wanted to find out about how to get around the token expiring all the time or if someone had suggestions.

答:
Use the google-api-python-client.

When performing server to server interactions with Google's APIs, use  Service Account Authentication, this means you don't have to refresh your tokens.

Here is a guide on how to set it up properly.

Body:
I have a api that i use to get Google Adx seller exchange information. My issue is that i want to put this into a AWS lambda to seed a database everyday automatically, the thing is access tokens expire and once its expired then well i won't have the ability to access the api. I can not make my customers keep having to log back in all the time in order for them to keep getting the adx information. Any suggestions on what I can do would be greatly appreciated. Ill include the script I use but that really shouldn't matter I don't believe.

import sys

from apiclient import sample_tools
from oauth2client import client

def main(argv):
 # Authenticate and construct service.
 service, _ = sample_tools.init(
  argv, 'adexchangeseller', 'v2.0', __doc__, __file__,
  scope='https://www.googleapis.com/auth/adexchange.seller.readonly')

try:
# Retrieve report.
result = service.accounts().reports().generate(
    accountId='myaccount',
    startDate='today-6d', endDate='today',
    metric=['AD_REQUESTS', 'CLICKS'],
    dimension=['DATE', 'WINNING_BID_RULE_NAME'],
    sort=['+DATE']).execute()

# Display headers.
for header in result['headers']:
  print '%25s' % header['name'],
print

# Display results.
for row in result['rows']:
  for column in row:
    print '%25s' % column,
  print

# Display totals
for total in result['totals']:
  print '%25s' % total,
print

except client.AccessTokenRefreshError:
  print ('The credentials have been revoked or expired, please re-run
 the '
       'application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)

I'm also totally new to python. So this seems like how we want it too. but  I'm waiting on client Adx credentials, so not 100 percent sure. I just wanted to find out about how to get around the token expiring all the time or if someone had suggestions.


问:
Parsing json in kusto query
How can I extract individual values from a JSON using KUSTO query.

I want to be able to read the value for SourceSystemId, Message and project these values.  I also want to use date in the following JSON as a filter. And project only those records where date greater than a date supplied as an external parameter.

```<code>{{
  "Status": 2,
  "SourceSystemId": "4",
  "RequisitionId": null,
  "Errors": [
    {
      "Code": "8002",
      "Message": "some message",
      "FieldName": "VendorNumber",
      "PartNumber": null
    },
    {
      "Code": "8003",
      "Message": "",
      "FieldName": "PartNumber",
      "PartNumber": ""
    }
  ],
  "SuppName": "SomeSupp",
 "Date":"22/2/2017"
}}
</code>```

答:
Let's assume you have a table named T, with a column named MyString, which stores your JSON values and is typed as string (such a table is defined below for the example).

You'll first need to invoke parse_json() on your column (unless it's already typed as dynamic and not as string, in which case you can skip this step).

Then you can access the Date property in your JSON value and use todatetime() to cast it to type datetime.

Afterwards, you can filter by your external parameter (dateTimeLowerBound in the example below).

Lastly - you can project the relevant properties you're interested in (Message is in the first element in the Errors array, and SourceSystemId), and you can cast them to their expected types (e.g. long and string using tolong() and tostring() respectively).

Here's the example:

```<code>let dateTimeLowerBound = datetime(2017-01-21);
let T = datatable(MyString:string) // this table is just for the example
[
'{"Status": 2, "SourceSystemId": "4", "RequisitionId": null, "Errors": [ { "Code": "8002", "Message": "some message", "FieldName": "VendorNumber", "PartNumber": null }, { "Code": "8003", "Message": "", "FieldName": "PartNumber", "PartNumber": "" } ], "SuppName": "SomeSupp", "Date":"2017-02-22"}'
];
T
| project MyJson = parse_json(MyString)
| where todatetime(MyJson.Date) > dateTimeLowerBound
| project SourceSystemId = tolong(MyJson.SourceSystemId), Message = tostring(MyJson.Errors[0].Message)
</code>```

The output of this example should be a table with 2 columns, named SourceSystemId and Message, of types long and string, and with the values 4 an some message, respectively.

Title: Parsing json in kusto query

Body:
How can I extract individual values from a JSON using KUSTO query.

I want to be able to read the value for SourceSystemId, Message and project these values.  I also want to use date in the following JSON as a filter. And project only those records where date greater than a date supplied as an external parameter.

{{
  "Status": 2,
  "SourceSystemId": "4",
  "RequisitionId": null,
  "Errors": [
    {
      "Code": "8002",
      "Message": "some message",
      "FieldName": "VendorNumber",
      "PartNumber": null
    },
    {
      "Code": "8003",
      "Message": "",
      "FieldName": "PartNumber",
      "PartNumber": ""
    }
  ],
  "SuppName": "SomeSupp",
 "Date":"22/2/2017"
}}

Body:
Let's assume you have a table named T, with a column named MyString, which stores your JSON values and is typed as string (such a table is defined below for the example).

You'll first need to invoke parse_json() on your column (unless it's already typed as dynamic and not as string, in which case you can skip this step).

Then you can access the Date property in your JSON value and use todatetime() to cast it to type datetime.

Afterwards, you can filter by your external parameter (dateTimeLowerBound in the example below).

Lastly - you can project the relevant properties you're interested in (Message is in the first element in the Errors array, and SourceSystemId), and you can cast them to their expected types (e.g. long and string using tolong() and tostring() respectively).

Here's the example:

let dateTimeLowerBound = datetime(2017-01-21);
let T = datatable(MyString:string) // this table is just for the example
[
'{"Status": 2, "SourceSystemId": "4", "RequisitionId": null, "Errors": [ { "Code": "8002", "Message": "some message", "FieldName": "VendorNumber", "PartNumber": null }, { "Code": "8003", "Message": "", "FieldName": "PartNumber", "PartNumber": "" } ], "SuppName": "SomeSupp", "Date":"2017-02-22"}'
];
T
| project MyJson = parse_json(MyString)
| where todatetime(MyJson.Date) > dateTimeLowerBound
| project SourceSystemId = tolong(MyJson.SourceSystemId), Message = tostring(MyJson.Errors[0].Message)

The output of this example should be a table with 2 columns, named SourceSystemId and Message, of types long and string, and with the values 4 an some message, respectively.


问:
Linux One Liner to return eth name, ip, mac and subnet
I have been trying to combine two queries I have into one. I am trying to get an output of IP info which will get compared to another query against the host file and eventually dumped into a database. My commands have to be simple one liners due to how they are deployed.  I can get what I need with these two, but is there a way to combined them.  The ip show puts out a multiline output and not sure how to combined the lines.

```<code>ip -o addr show | awk '/inet/ {print $9, $4}' | grep -v '127.0.0.1'
ip -o addr show | awk '/link/ {print $2, $13}' | grep -v lo
</code>```

Top gives most of the info and bottom gets the mac. This gives both but it is multi line so not sure how to awk out the values I need.  Any good thoughts or tricks?  Still new on the linux/bash.

```<code> ip -o addr show | grep -i 'ether\|inet'
</code>```

Example of an ip -o addr show command

```<code>1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \            link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
2: eth0    inet x.x.x.x/24 brd x.x.x.x scope global eth0
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
3: eth1    inet x.x.x.x/24 brd x.x.x.x scope global eth1
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
4: eth2    inet x.x.x.x/27 brd x.x.x.x scope global eth2
5: eth3: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4    inet x.x.x.x/24 brd x.x.x.x scope global eth4
7: eth5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
7: eth5    inet x.x.x.x/24 brd x.x.x.x scope global eth5
8: eth6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
8: eth6    inet x.x.x.x/28 brd x.x.x.x scope global eth6
9: eth7: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
</code>```

答:
Try egrep instead of grep</p>

```<code>ip -o addr show | egrep -i "ether|inet"
</code>```

Body:
I have been trying to combine two queries I have into one. I am trying to get an output of IP info which will get compared to another query against the host file and eventually dumped into a database. My commands have to be simple one liners due to how they are deployed.  I can get what I need with these two, but is there a way to combined them.  The ip show puts out a multiline output and not sure how to combined the lines.

ip -o addr show | awk '/inet/ {print $9, $4}' | grep -v '127.0.0.1'
ip -o addr show | awk '/link/ {print $2, $13}' | grep -v lo

Top gives most of the info and bottom gets the mac. This gives both but it is multi line so not sure how to awk out the values I need.  Any good thoughts or tricks?  Still new on the linux/bash.

 ip -o addr show | grep -i 'ether\|inet'

Example of an ip -o addr show command

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \            link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
2: eth0    inet x.x.x.x/24 brd x.x.x.x scope global eth0
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
3: eth1    inet x.x.x.x/24 brd x.x.x.x scope global eth1
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
4: eth2    inet x.x.x.x/27 brd x.x.x.x scope global eth2
5: eth3: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4    inet x.x.x.x/24 brd x.x.x.x scope global eth4
7: eth5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
7: eth5    inet x.x.x.x/24 brd x.x.x.x scope global eth5
8: eth6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
8: eth6    inet x.x.x.x/28 brd x.x.x.x scope global eth6
9: eth7: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff

Body:
Try egrep instead of grep

ip -o addr show | egrep -i "ether|inet"


问:
How can I use the display() function in Microsoft Azure Notebook
I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.

When I reproduce the problem on my local computer it works fine.

This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.

Following is the code used to create the file:

```<code>from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')
</code>```

答:
It appears you are missing an import statement, try :

```<code>from Ipython.display import Image
display(Image("xx.png"))
</code>```

Body:
I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.

When I reproduce the problem on my local computer it works fine.

This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.

Following is the code used to create the file:

from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')

Body:
It appears you are missing an import statement, try :

from Ipython.display import Image
display(Image("xx.png"))


问:
Handling of two forms in one webpage
I have a webpage with a div area. In this area, there can be two different forms.
It looks like this:

Form 1:

```<code><div id="data" ...>
    <form action="/action1" method="post">
        <label for="label1">ID</label>
        <input type="text" name="id" id="label1" value="" />
        <label for="label2">Name</label>
        <input type="text" name="name" id="label2" value="" />
        <label for="label3">Description</label>
        <input type="text" name="desc" id="label3" value="" />
        <label for="label4">Address</label>
        <input type="text" name="address" id="label4" value="" />
     </form>
</div>
</code>```

Form 2:

```<code><div id="data" ...>
    <form action="/action2" method="post">
        <label for="label1">ID</label>
        <input type="text" name="id" id="label1" value="" />
        <label for="label2">Firstname</label>
        <input type="text" name="first" id="label2" value="" />
        <label for="label3">Lastname</label>
        <input type="text" name="last" id="label3" value="" />
        <label for="label4">Address</label>
        <input type="text" name="address" id="label4" value="" />
        <label for="label5">eMail</label>
        <input type="text" name="mail" id="label5" value="" />
     </form>
</div>
</code>```

So there are two different forms. The values will be set with jQuery (Ajax call to the backend).

What is the best way to handle these two forms? Should I create two files with only the form and the load the form when they are needed? (Form 1 is needed if some clicks on button 1, form 2 is needed if someoe clicks on button 2 - the events are handled on client-side).
Or should I place both form into the single HTML file and enable or disable the form?

答: There's nothing stopping you have both forms in the HTML and conditionally hiding/showing the one that you want active. You're best bet is to give each form (or its containing div) a unique ID, and using this to show/hide using jQuery.</p>

Title: Handling of two forms in one webpage

Body:
I have a webpage with a div area. In this area, there can be two different forms.
It looks like this:

Form 1:

    <form action="/action1" method="post">
        ID
        <input type="text" name="id" id="label1" value="" />
        Name
        <input type="text" name="name" id="label2" value="" />
        Description
        <input type="text" name="desc" id="label3" value="" />
        Address
        <input type="text" name="address" id="label4" value="" />
     </form>

Form 2:

    <form action="/action2" method="post">
        ID
        <input type="text" name="id" id="label1" value="" />
        Firstname
        <input type="text" name="first" id="label2" value="" />
        Lastname
        <input type="text" name="last" id="label3" value="" />
        Address
        <input type="text" name="address" id="label4" value="" />
        eMail
        <input type="text" name="mail" id="label5" value="" />
     </form>

So there are two different forms. The values will be set with jQuery (Ajax call to the backend).

What is the best way to handle these two forms? Should I create two files with only the form and the load the form when they are needed? (Form 1 is needed if some clicks on button 1, form 2 is needed if someoe clicks on button 2 - the events are handled on client-side).
Or should I place both form into the single HTML file and enable or disable the form?


问:
change the ndb.StringProperty()
I am new to Python. I am writing an online application form, which users can enter their name, phone, email and select a class. The question is that once user enter the data of name, phone , email, it will present the result on the next page, and systematically at the main page. However, when users select the class option from the HTML select option, the result cannot be presented at the next page and the main page. How can I adjust the ndb.StringProperty() to get the value from the select option?

```<code>class Contact(ndb.Model):
name = ndb.StringProperty()
phone = ndb.StringProperty()
email = ndb.StringProperty()
classselect = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)

@classmethod
def query_contact(cls, ancestor_key):
    return cls.query(ancestor=ancestor_key).order(-cls.date)
`class MainHandler(Handler):
def get(self):

    email = "abc@def.com"

    ancestor_key = ndb.Key("Email", email or "*nocell*")
    contacts = Contact.query_contact(ancestor_key).fetch(20)

    self.render('mainPage.html', contacts = contacts)

    class Newcontact(webapp2.RequestHandler):
    def post(self):
    email = "abc@def.com"
    new_name = self.request.get('name')
    new_phone = self.request.get('phone')
    new_email = self.request.get('email')
    new_classselect = self.request.get('classselect')
    newcontactitem = Contact(parent=ndb.Key("Email", email or "*nocell*"),
    name = new_name, phone = new_phone, email = new_email,classselect =
    new_classselect)
    newcontactitem.put()

    self.response.out.write('<html><body>New Contact has been added```')
    self.response.out.write('
'+cgi.escape("Name: " + new_name))
    self.response.out.write('
'+cgi.escape("Phone: " + new_phone))
    self.response.out.write('
'+cgi.escape("Email: " + new_email))
    self.response.out.write('
'+cgi.escape("classselect:+"new_classselect))
    self.response.out.write('
<input type ="button" onclick="location.href
    = document.referrer" value="回到上一頁"></input>')
    self.response.out.write('```</body></html>')

   app = webapp2.WSGIApplication([
   ('/', MainHandler),
   ('/insertcontact', Newcontact),], debug=True)`
</code>```

HTML select option, these are typed in the template:

```<code><body>
    <form  action="/insertcontact" method="post" enctype="multipart/form-data">
        <div>Name:</div>
        <input type="text" name="name" value="{{name}}">
        <div>Phone number:</div>
        <input type="text" name="phone" value="{{phone}}">
        <div>Email address:</div>
        <input type="text" name="email" value="{{email}}">

        <div>classselect:</div>
        <select name="YourClass"value="">
        <option value="A">CLASS A</option>
        <option value="B">CLASS B</option>
        <option value="C">CLASS C</option>
        </select>
        <div>gender:</div>
        <input type="radio" name="gender" value="male" checked>male
        <input type="radio" name="gender" value="female">female

        <div>
        <input type="submit" name="newcontact">
    </div>
    </form>
    <hr>
    {% for contact in contacts %}
    <div>
        <div>{{contact.name}} - {{contact.phone}} - {{contact.email}-
   {{contact.classselect}}</div>
    </div>
    {% endfor %}
   </body>
   </html>
</code>```

Results:

答:
I think in your HTML body

```<code><select name="YourClass" value="">
</code>```

should be

```<code><select name="classselect" value="">
</code>```

Title: change the ndb.StringProperty()

Body:
I am new to Python. I am writing an online application form, which users can enter their name, phone, email and select a class. The question is that once user enter the data of name, phone , email, it will present the result on the next page, and systematically at the main page. However, when users select the class option from the HTML select option, the result cannot be presented at the next page and the main page. How can I adjust the ndb.StringProperty() to get the value from the select option?

class Contact(ndb.Model):
name = ndb.StringProperty()
phone = ndb.StringProperty()
email = ndb.StringProperty()
classselect = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)

@classmethod
def query_contact(cls, ancestor_key):
    return cls.query(ancestor=ancestor_key).order(-cls.date)
`class MainHandler(Handler):
def get(self):

    email = "abc@def.com"

    ancestor_key = ndb.Key("Email", email or "*nocell*")
    contacts = Contact.query_contact(ancestor_key).fetch(20)

    self.render('mainPage.html', contacts = contacts)

    class Newcontact(webapp2.RequestHandler):
    def post(self):
    email = "abc@def.com"
    new_name = self.request.get('name')
    new_phone = self.request.get('phone')
    new_email = self.request.get('email')
    new_classselect = self.request.get('classselect')
    newcontactitem = Contact(parent=ndb.Key("Email", email or "*nocell*"),
    name = new_name, phone = new_phone, email = new_email,classselect =
    new_classselect)
    newcontactitem.put()

    self.response.out.write('New Contact has been added
')
    self.response.out.write('
'+cgi.escape("Name: " + new_name))
    self.response.out.write('
'+cgi.escape("Phone: " + new_phone))
    self.response.out.write('
'+cgi.escape("Email: " + new_email))
    self.response.out.write('
'+cgi.escape("classselect:+"new_classselect))
    self.response.out.write('
<input type ="button" onclick="location.href
    = document.referrer" value="回到上一頁"></input>')
    self.response.out.write('
')

   app = webapp2.WSGIApplication([
   ('/', MainHandler),
   ('/insertcontact', Newcontact),], debug=True)`

HTML select option, these are typed in the template:

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

Name:

        <input type="text" name="name" value="{{name}}">

Phone number:

        <input type="text" name="phone" value="{{phone}}">

Email address:

        <input type="text" name="email" value="{{email}}">

classselect:

        <select name="YourClass"value="">
        <option value="A">CLASS A</option>
        <option value="B">CLASS B</option>
        <option value="C">CLASS C</option>
        </select>

gender:

        <input type="radio" name="gender" value="male" checked>male
        <input type="radio" name="gender" value="female">female

        <input type="submit" name="newcontact">

    </form>

    {% for contact in contacts %}

{{contact.name}} - {{contact.phone}} - {{contact.email}-
   {{contact.classselect}}

    {% endfor %}

Results:

Body:
I think in your HTML body

<select name="YourClass" value="">

should be

<select name="classselect" value="">


问:
Could not find or load main class jar intelij
After i finished my spring-boot server i want to make it a jar so i can deploy it on a remote server. I choose to do this with maven

After .jar-with-dependecies.jar is created i upload it on server and try to run

```<code>java -jar buyme-0.0.1-SNAPSHOT-jar-with-dependencies.jar
</code>```

Like everybody else i get

```<code>Error: Could not find or load main class com.buyme.BuymeApplication
</code>```

I tried answers from here:

Link 1

Link 2

Link 3

Link 4

Nothing seems to work.
This is my

pom.xml

```<code><build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                       <mainClass>com.buyme.BuymeApplication</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

Manifest

```<code>Manifest-Version: 1.0
Main-Class: com.buyme.BuymeApplication
</code>```

This is the project structure

mvn commands:

```<code>mvnc clean install (sometimes i tried assembly:assembly with the other two)
</code>```

This doesn't work either:

```<code>java -cp <name>.jar com.buyme.BuymeApplication
</code>```

答:
I managed to solve it :

I used this answer:

```<code><build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.2.RELEASE</version>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>
</code>```

Body:
After i finished my spring-boot server i want to make it a jar so i can deploy it on a remote server. I choose to do this with maven

After .jar-with-dependecies.jar is created i upload it on server and try to run

java -jar buyme-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Like everybody else i get

Error: Could not find or load main class com.buyme.BuymeApplication

I tried answers from here:

Link 1

Link 2

Link 3

Link 4

Nothing seems to work.
This is my

pom.xml

<build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                       <mainClass>com.buyme.BuymeApplication</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Manifest

Manifest-Version: 1.0
Main-Class: com.buyme.BuymeApplication

This is the project structure

mvn commands:

mvnc clean install (sometimes i tried assembly:assembly with the other two)

This doesn't work either:

java -cp <name>.jar com.buyme.BuymeApplication

Body:
I managed to solve it :

I used this answer:

<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.2.RELEASE</version>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>


问:
Weak symbols and weakrefs
I'm trying to explore how these features of gcc work.

I've created a library with a function that should call either sigprocmask or pthread_sigmask depending on whether or not libpthread is linked.

My weakref version of the code works as expected, but my weak-symbol based version doesn't seem to get overridden by the real pthread_sigmask symbol as I would expect it to.

Could you please point what I'm doing wrong?

Weakref version:

```<code>#!/bin/sh
cat > lib.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

__attribute__((weakref("pthread_sigmask")))
static int pthread_sigmask_ref(int How,  sigset_t const *Set, sigset_t *Oldset);

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("calling pthread_sigmask");
    if(pthread_sigmask_ref){
        return pthread_sigmask_ref(How, Set, Oldset);
    }else{
        puts("SIGPROCMASK");
        return sigprocmask(How, Set, Oldset);
    }
}
EOF

cat > main.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset);

int main()
{
    sigset_t all_sigs, old_mask;
    sigemptyset(&all_sigs);
    sigaddset(&all_sigs, SIGTERM);
    call_pthread_sigmask(SIG_SETMASK, &all_sigs, &old_mask);

#if 0
    pthread_mutex_t mx;
    pthread_mutex_init(&mx,0);
#endif
}

EOF

gcc -c -fpic lib.c
gcc lib.o -o lib.so -shared

gcc main.c $PWD/lib.so -lpthread -o wrap
gcc main.c $PWD/lib.so -Wl,--no-as-needed  -lpthread -o real

echo wrap
ldd ./wrap
./wrap

echo real
ldd ./real
./real
</code>```

Example output:

```<code>wrap
    linux-vdso.so.1 =>  (0x00007ffd5dda0000)
    /home/user/tmp/lib.so (0x00007faa4f8cf000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007faa4f507000)
    /lib64/ld-linux-x86-64.so.2 (0x00007faa4fad1000)
calling pthread_sigmask
SIGPROCMASK
real
    linux-vdso.so.1 =>  (0x00007ffc7f51e000)
    /home/user/tmp/lib.so (0x00007f6ff23b2000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f6ff2194000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6ff1dcc000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f6ff25b4000)
calling pthread_sigmask
</code>```

Weak-symbol version:

```<code>#!/bin/sh
cat > lib.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

__attribute__((weak,noinline))
int pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("SIGPROCMASK");
    return sigprocmask(How, Set, Oldset);
}

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("calling pthread_sigmask");
    return pthread_sigmask(How, Set, Oldset);
}
EOF

cat > main.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset);

int main()
{
    sigset_t all_sigs, old_mask;
    sigemptyset(&all_sigs);
    sigaddset(&all_sigs, SIGTERM);
    call_pthread_sigmask(SIG_SETMASK, &all_sigs, &old_mask);

#if 0
    pthread_mutex_t mx;
    pthread_mutex_init(&mx,0);
#endif
}

EOF

gcc -c -fpic lib.c
gcc lib.o -o lib.so -shared

gcc main.c $PWD/lib.so -lpthread -o wrap
gcc main.c $PWD/lib.so -Wl,--no-as-needed  -lpthread -o real

echo wrap
ldd ./wrap
./wrap

echo real
ldd ./real
./real
</code>```

Example output:

```<code>wrap
    linux-vdso.so.1 =>  (0x00007ffd19d23000)
    /home/user/tmp/lib.so (0x00007fdd24b46000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fdd2477e000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fdd24d48000)
calling pthread_sigmask
SIGPROCMASK
real
    linux-vdso.so.1 =>  (0x00007fff115f6000)
    /home/user/tmp/lib.so (0x00007fb22be95000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fb22bc77000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb22b8af000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fb22c097000)
calling pthread_sigmask
SIGPROCMASK
</code>```

答:
Just swap library order:</p>

```<code>gcc main.c -lpthread $PWD/lib.so -o real
</code>```

Title: Weak symbols and weakrefs

Body:
I'm trying to explore how these features of gcc work.

I've created a library with a function that should call either sigprocmask or pthread_sigmask depending on whether or not libpthread is linked.

My weakref version of the code works as expected, but my weak-symbol based version doesn't seem to get overridden by the real pthread_sigmask symbol as I would expect it to.

Could you please point what I'm doing wrong?

Weakref version:

#!/bin/sh
cat > lib.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

__attribute__((weakref("pthread_sigmask")))
static int pthread_sigmask_ref(int How,  sigset_t const *Set, sigset_t *Oldset);

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("calling pthread_sigmask");
    if(pthread_sigmask_ref){
        return pthread_sigmask_ref(How, Set, Oldset);
    }else{
        puts("SIGPROCMASK");
        return sigprocmask(How, Set, Oldset);
    }
}
EOF

cat > main.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset);

int main()
{
    sigset_t all_sigs, old_mask;
    sigemptyset(&all_sigs);
    sigaddset(&all_sigs, SIGTERM);
    call_pthread_sigmask(SIG_SETMASK, &all_sigs, &old_mask);

#if 0
    pthread_mutex_t mx;
    pthread_mutex_init(&mx,0);
#endif
}

EOF

gcc -c -fpic lib.c
gcc lib.o -o lib.so -shared

gcc main.c $PWD/lib.so -lpthread -o wrap
gcc main.c $PWD/lib.so -Wl,--no-as-needed  -lpthread -o real

echo wrap
ldd ./wrap
./wrap

echo real
ldd ./real
./real

Example output:

wrap
    linux-vdso.so.1 =>  (0x00007ffd5dda0000)
    /home/user/tmp/lib.so (0x00007faa4f8cf000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007faa4f507000)
    /lib64/ld-linux-x86-64.so.2 (0x00007faa4fad1000)
calling pthread_sigmask
SIGPROCMASK
real
    linux-vdso.so.1 =>  (0x00007ffc7f51e000)
    /home/user/tmp/lib.so (0x00007f6ff23b2000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f6ff2194000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6ff1dcc000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f6ff25b4000)
calling pthread_sigmask

Weak-symbol version:

#!/bin/sh
cat > lib.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

__attribute__((weak,noinline))
int pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("SIGPROCMASK");
    return sigprocmask(How, Set, Oldset);
}

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset)
{
    puts("calling pthread_sigmask");
    return pthread_sigmask(How, Set, Oldset);
}
EOF

cat > main.c <<EOF
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>

int call_pthread_sigmask(int How,  sigset_t const *Set, sigset_t *Oldset);

int main()
{
    sigset_t all_sigs, old_mask;
    sigemptyset(&all_sigs);
    sigaddset(&all_sigs, SIGTERM);
    call_pthread_sigmask(SIG_SETMASK, &all_sigs, &old_mask);

#if 0
    pthread_mutex_t mx;
    pthread_mutex_init(&mx,0);
#endif
}

EOF

gcc -c -fpic lib.c
gcc lib.o -o lib.so -shared

gcc main.c $PWD/lib.so -lpthread -o wrap
gcc main.c $PWD/lib.so -Wl,--no-as-needed  -lpthread -o real

echo wrap
ldd ./wrap
./wrap

echo real
ldd ./real
./real

Example output:

wrap
    linux-vdso.so.1 =>  (0x00007ffd19d23000)
    /home/user/tmp/lib.so (0x00007fdd24b46000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fdd2477e000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fdd24d48000)
calling pthread_sigmask
SIGPROCMASK
real
    linux-vdso.so.1 =>  (0x00007fff115f6000)
    /home/user/tmp/lib.so (0x00007fb22be95000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fb22bc77000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb22b8af000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fb22c097000)
calling pthread_sigmask
SIGPROCMASK

Body:
Just swap library order:

gcc main.c -lpthread $PWD/lib.so -o real


问:
How can I access an existing AWS database via .PEM file in R?
To make a long story short, a former developer have setup a database(MongoDB) at Amazon Web Services(AWS), through EC2. Now to the problem, all I have got thus far is the information in the previous sentence as well as a .PEM file, and I would like to access the database through R, is that possible?

Sorry that I don’t have more information at the moment, but I just have no idea where to start.

答:
If you have the PEM file you can follow the directions to access the instance here. Now this assumes the instance has a public ip address that is internet reachable with port 22 open.
 If it does not you'll need a vpn setup to reach the private instances.

If you do not have the PEM file you'll need to re-create instance by snapshotting it and creating a new instances based off of that snapshot, with a PEM key you do have access to. Here is the AWS documentation on that process


问:
Spring Boot JPA with not a well known database
I am trying to write Spring Boot application to connect to a Teiid database, I want to use JPA layer on it. I have configured the JDBC Data Source, but since this not well-known database in Spring JPA libraries do not autodetect this source. I have manually setup "spring.jpa.*" properties too. I do have a Hibernate dialect for this database, and it is on the classpath.

So, how does one need to configure JPA layer for a not well-known database in Spring Boot? Thank you for your time.

Ramesh..

答:
This is fairly well defined in the Spring Boot documentation.

You can set this explicitly in the application.properties file

```<code>spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

Body:
This is fairly well defined in the Spring Boot documentation.

You can set this explicitly in the application.properties file

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


问:
Installation of ffmpeg and others on UWAMP
i try to install clip bucket for making a youtube clone site  but the  script ask to install ffmpeg and others compression tools on the server and i dont know how to do it .
Lots of online host dont allow those libs for free.
I use UWAMP but dont know how to install ffmpeg on UWAMP ...
Anyone know ?</p>

答:
It seems like you are using Windows, if yes then you can install FFMPEG using following link.

https://github.com/adaptlearning/adapt_authoring/wiki/Installing-FFmpeg

Yes, you need SSH access for install FFMPEG and other tool on server. Free web-hosting does allow you to install FFMPEG and other Libraries. You need Atleast VPS for this.


问:
Html.DropDownList - Disabled/Readonly
What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?

I've tried things like....

```<code>Html.DropDownList("Types", Model.Types, new { _Enabled = "false" })
</code>```

...and many different things along this line; alas no joy!

I thought this would be an easy.....and it probably is!

答:
I had to disable the dropdownlist and hide the primary ID</p>

```<code><div class="form-group">
        @Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("OBJ_ID", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled"})
            @Html.HiddenFor(m => m.OBJ_ID)
            @Html.ValidationMessageFor(model => model.OBJ_ID, "", new { @class = "text-danger" })
        </div>
    </div>
</code>```

Title: Html.DropDownList - Disabled/Readonly

Body:
What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?

I've tried things like....

Html.DropDownList("Types", Model.Types, new { _Enabled = "false" })

...and many different things along this line; alas no joy!

I thought this would be an easy.....and it probably is!

Body:
I had to disable the dropdownlist and hide the primary ID

<div class="form-group">
        @Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("OBJ_ID", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled"})
            @Html.HiddenFor(m => m.OBJ_ID)
            @Html.ValidationMessageFor(model => model.OBJ_ID, "", new { @class = "text-danger" })
        </div>
    </div>


问:
Search and Replace in PHPMyAdmin database for Wordpress (absolute beginner)
I apologise in advance for I know that this question has been asked several times already, but being a complete beginner at wordpress coding and database handling, I am still not sure about what those answers really meant.
So having just coded a website and converted it into WordPress, I now find myself having to change all of the localhost strings to the accurate ones, but with hundreds to go through, I just wanted to know if any of you were able to recommend a program or technique within PHPMyAdmin (that I may not be aware of) to avoid having to change them one at a time.
Thank you all in advance for your time and attention.</p>

答: In phpMyAdmin open your table, choose Search > Find and replace. Then specify in which column you want to find and replace, and the original and replacement texts.</p>


问:
Spring Rest API with WebApp
I just followed this tutorial
https://spring.io/guides/tutorials/react-and-spring-data-rest/

And it's really interesting but I am wondering how can I create the same app without using spring boot, I want to deploy it in a tomcat web container.

In addiction I want also to add a context path to that the app will run on localhost:8080/appName/app and the api will run on localhost:8080/appName/web

thank you!

答:
You can you Spring mvc

```<code>@Configuration
@EnableWebMvc
public class WebConfig{
   //
}
</code>```

@EnableWebMvc annotation does a number of useful things – specifically, in the case of REST, it detects the existence of Jackson and JAXB 2 on the classpath
 and automatically creates and registers default JSON and XML converters.

The @Controller is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – Foo:

```<code>    @Controller
     @RequestMapping( value = "/foos" )
        class FooController{
           @Autowired
           IFooService service;

           @RequestMapping( method = RequestMethod.GET )
           @ResponseBody
           public List< Foo > findAll(){
              return service.findAll();
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.GET )
           @ResponseBody
           public Foo findOne( @PathVariable( "id" ) Long id ){
              return RestPreconditions.checkFound( service.findOne( id ) );
           }

           @RequestMapping( method = RequestMethod.POST )
           @ResponseStatus( HttpStatus.CREATED )
           @ResponseBody
           public Long create( @RequestBody Foo resource ){
              Preconditions.checkNotNull( resource );
              return service.save( resource );
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.PUT )
           @ResponseStatus( HttpStatus.OK )
           public void update( @PathVariable( "id" ) Long id, @RequestBody Foo resource ){
              Preconditions.checkNotNull( resource );
              RestPreconditions.checkNotNull( service.findOne( resource.getId() ) );
//update logic
              service.save( resource );
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
           @ResponseStatus( HttpStatus.OK )
           public void delete( @PathVariable( "id" ) Long id ){
              service.delete( id );
           }

        }
</code>```

The Controller implementation is non-public – this is because it doesn’t need to be. Usually, the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the DispathcerServlet) and simply delegates them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public.

The request mappings are straightforward – as with any controller, the actual value of the mapping as well as the HTTP method are used to determine the target method for the request. @RequestBody will bind the parameters of the method to the body of the HTTP request, whereas @ResponseBody does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. Content negotiation will take place to choose which one of the active converters will be used, based mostly on the Accept header, although other HTTP headers may be used to determine the representation as well.
Here is helpful tutorial

Spring Data
Lets see IFooService, it is used in our controller for basic curd operation

IFooService.java

```<code>public interface IFooService extends CrudRepository<Foo, Long> {
}
</code>```

Spring data save our life, Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.

Here IFooService extends the CrudRepository, where we passing the Foo as a entity and Long as a Foo id type in generic argument.
If you will see in FooController IFooService is autowire and we are using there  following methods :

findAll,findOne,save, delete

We dont have provided the implementation of these methods in  IFooService
, actually, these method is come from CrudRepository means curd operation is handling by spring data which save out lot of the time here is CrudRepository doc also you can learn lot about spring data from here

Title: Spring Rest API with WebApp

Body:
You can you Spring mvc

@Configuration
@EnableWebMvc
public class WebConfig{
   //
}

@EnableWebMvc annotation does a number of useful things – specifically, in the case of REST, it detects the existence of Jackson and JAXB 2 on the classpath
 and automatically creates and registers default JSON and XML converters.

The @Controller is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – Foo:

    @Controller
     @RequestMapping( value = "/foos" )
        class FooController{
           @Autowired
           IFooService service;

           @RequestMapping( method = RequestMethod.GET )
           @ResponseBody
           public List< Foo > findAll(){
              return service.findAll();
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.GET )
           @ResponseBody
           public Foo findOne( @PathVariable( "id" ) Long id ){
              return RestPreconditions.checkFound( service.findOne( id ) );
           }

           @RequestMapping( method = RequestMethod.POST )
           @ResponseStatus( HttpStatus.CREATED )
           @ResponseBody
           public Long create( @RequestBody Foo resource ){
              Preconditions.checkNotNull( resource );
              return service.save( resource );
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.PUT )
           @ResponseStatus( HttpStatus.OK )
           public void update( @PathVariable( "id" ) Long id, @RequestBody Foo resource ){
              Preconditions.checkNotNull( resource );
              RestPreconditions.checkNotNull( service.findOne( resource.getId() ) );
//update logic
              service.save( resource );
           }

           @RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
           @ResponseStatus( HttpStatus.OK )
           public void delete( @PathVariable( "id" ) Long id ){
              service.delete( id );
           }

        }

The Controller implementation is non-public – this is because it doesn’t need to be. Usually, the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the DispathcerServlet) and simply delegates them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public.

The request mappings are straightforward – as with any controller, the actual value of the mapping as well as the HTTP method are used to determine the target method for the request. @RequestBody will bind the parameters of the method to the body of the HTTP request, whereas @ResponseBody does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. Content negotiation will take place to choose which one of the active converters will be used, based mostly on the Accept header, although other HTTP headers may be used to determine the representation as well.
Here is helpful tutorial

Spring Data
Lets see IFooService, it is used in our controller for basic curd operation

IFooService.java

public interface IFooService extends CrudRepository<Foo, Long> {
}

Spring data save our life, Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.

Here IFooService extends the CrudRepository, where we passing the Foo as a entity and Long as a Foo id type in generic argument.
If you will see in FooController IFooService is autowire and we are using there  following methods :

findAll,findOne,save, delete

We dont have provided the implementation of these methods in  IFooService
, actually, these method is come from CrudRepository means curd operation is handling by spring data which save out lot of the time here is CrudRepository doc also you can learn lot about spring data from here


问:
Declaring Method with generic type
I was using generic types in C# and I am new to using generic types. So, right now I am stuck with a problem. I have some classes like these:

```<code>public class MyModel1
{
}

public class MyModel2
{
}

public class BaseClass<T>
{
}

public class ChildClass1 : BaseClass<MyModel1>
{
}

public class ChildClass2 : BaseClass<MyModel2>
{
}

public class AnotherClass
{
    //What will be the syntax of declaring this method
    //The syntax of the following method is wrong and incomplete.
    //It's there just to give an idea about whai i want to do.
    public void MyMethod<T>()
      where T : BaseClass<..what to write..>
    {

    }
}
</code>```

My question is what will be the correct syntax of declaring MyMethod if I want to call MyMethod like this:

```<code>MyMethod<ChildClass1>();
</code>```

答:
If I understood correctly, you try to filter "MyMethod" so that T is a class of type "ChildClass ...".

You can add a generic parameter to your function like this:

```<code>public void MyMethod<T, U>()
where T : BaseClass<U>
{

}
</code>```

But then you have to call MyMethod in that way.

```<code>MyMethod<ChildClass1, MyModel1>();
</code>```

So it's quite complicated to use.

Another solution is to create a new "blank" class :

```<code>public abstract class  Base // mark it as abstract if you don't need to use it in your code
{
}

public class MyModel1
{
}

public class MyModel2
{
}

public class BaseClass<T> : Base //The class inherits the new class
{
}

public class ChildClass1 : BaseClass<MyModel1>
{
}

public class ChildClass2 : BaseClass<MyModel2>
{
}

public class AnotherClass
{
    public void MyMethod<T>()
    where T : Base
    {
    }
}
</code>```

Title: Declaring Method with generic type

Body:
I was using generic types in C# and I am new to using generic types. So, right now I am stuck with a problem. I have some classes like these:

public class MyModel1
{
}

public class MyModel2
{
}

public class BaseClass<T>
{
}

public class ChildClass1 : BaseClass<MyModel1>
{
}

public class ChildClass2 : BaseClass<MyModel2>
{
}

public class AnotherClass
{
    //What will be the syntax of declaring this method
    //The syntax of the following method is wrong and incomplete.
    //It's there just to give an idea about whai i want to do.
    public void MyMethod<T>()
      where T : BaseClass<..what to write..>
    {

    }
}

My question is what will be the correct syntax of declaring MyMethod if I want to call MyMethod like this:

MyMethod<ChildClass1>();

Body:
If I understood correctly, you try to filter "MyMethod" so that T is a class of type "ChildClass ...".

You can add a generic parameter to your function like this:

public void MyMethod<T, U>()
where T : BaseClass<U>
{

}

But then you have to call MyMethod in that way.

MyMethod<ChildClass1, MyModel1>();

So it's quite complicated to use.

Another solution is to create a new "blank" class :

public abstract class  Base // mark it as abstract if you don't need to use it in your code
{
}

public class MyModel1
{
}

public class MyModel2
{
}

public class BaseClass<T> : Base //The class inherits the new class
{
}

public class ChildClass1 : BaseClass<MyModel1>
{
}

public class ChildClass2 : BaseClass<MyModel2>
{
}

public class AnotherClass
{
    public void MyMethod<T>()
    where T : Base
    {
    }
}


问:
java web page reader
I want to retrieve all the links in web page ,but the web page use javascript and each page contain number of links

how can i go to the next page and read its contain in java program

答:
Getting this info from a Javascript'ed page can be a hard job. Your program must interpret the whole page and understand what the JS is doing. Not all web spiders doing this.

Most modern JS libraries (jquery, etc) are mostly manipulate CSS and attributes of HTML elements. So first you have to generate the "flat" HTML from HTML source and JS and then maybe run a classical web spider over the flat HTML code.

(For example the FF webdeveloper plugin allows to see the original source code of a page and the generated code of the page, when all JS is done).

Title: java web page reader


问:
Xamarin.Forms app to fit screen ratio of Samsung Galaxy S8
How do I configure a Xamarin.Forms app to fill out phones with newer aspect ratios like the Samsung Galaxy S8?

Currently my Xamarin.Forms app looks like the one on the left below. What configuration do I need to change?

答:
Initially, I thought this might have been an issue with Xamarin. However, after further research I found it to be a new configuration for Android apps in general to support the 18:9 aspect ratio.

Here is the Android Developers Blog post describing the updates:

In order to take full advantage of the larger display formats on these
  devices, you should consider increasing your app's maximum supported
  aspect ratio. To do so, simply declare an android.max_aspect
  <meta-data> element in the app's <application> element:

```<code><meta-data android:name="android.max_aspect" android:value="2.1" />
</code>```

This resolved the issue for me. Related answer here.

Body:
Initially, I thought this might have been an issue with Xamarin. However, after further research I found it to be a new configuration for Android apps in general to support the 18:9 aspect ratio.

Here is the Android Developers Blog post describing the updates:

In order to take full advantage of the larger display formats on these
  devices, you should consider increasing your app's maximum supported
  aspect ratio. To do so, simply declare an android.max_aspect
  <meta-data> element in the app's <application> element:

<meta-data android:name="android.max_aspect" android:value="2.1" />

This resolved the issue for me. Related answer here.


问:
restful query to search on directory.io
I'm trying to use the query restful on the site directory.io to go back to a certain address

Can you give me some advice because with GET and any key and value always returns me the first page

答:
I suggest you start by reading this http://directory.io/faq

You may then find you don't wish to use the 'api'

Q: Should I search by private key?
  A: No. I log and steal everything.

Title: restful query to search on directory.io


问:
Pause a script till a certain time and start again at another certain time
I made a RGB LED color changing script on my raspberry pi 3 for my setup but i want it to make it so at 11PM the lights stop and start again at 9AM. How can i make this possible ?
Thank you,
PhantomX</p>

答:
Using the time library in python, there is a time.localtime() function that will return the current time as a structure.

You can check for the hour to be 23 (11PM), then turn the lights off, then have it sleep for 36000 seconds (10 hours) and then turn the lights back on.

Alternatively, check for the hour to be 9 (9AM) every few minutes, and turn the lights on in the event that the script may restart during the night

Example:

```<code>import time

while True:
    if time.localtime().tm_hour == 23:
        lights_off()
        time.sleep(3600) # No need to check for at least 1 hour
    elif time.localtime().tm_hour == 9:
        lights_on()
        time.sleep(3600)
    time.sleep(60) # Checks every  minute
</code>```

Time Docs: https://docs.python.org/3.6/library/time.html#time.localtime

Body:
Using the time library in python, there is a time.localtime() function that will return the current time as a structure.

You can check for the hour to be 23 (11PM), then turn the lights off, then have it sleep for 36000 seconds (10 hours) and then turn the lights back on.

Alternatively, check for the hour to be 9 (9AM) every few minutes, and turn the lights on in the event that the script may restart during the night

Example:

import time

while True:
    if time.localtime().tm_hour == 23:
        lights_off()
        time.sleep(3600) # No need to check for at least 1 hour
    elif time.localtime().tm_hour == 9:
        lights_on()
        time.sleep(3600)
    time.sleep(60) # Checks every  minute

Time Docs: https://docs.python.org/3.6/library/time.html#time.localtime