问:
Simple react native app(with react-native-navigation) crash after splash screen
I'm trying to use react-native-navigation as navigation system in my react-native. I've wrote a very simple app for test it, but this app crashes(without giving me any error or info) after the splash screen.

my index.ios.js:

```<code>/* eslint-disable no-unused-vars */
import App from './src/app';
</code>```

my app.ios.js:

```<code>import {
  Platform
} from 'react-native';
import {Navigation} from 'react-native-navigation';

import { registerScreens } from './screens';
registerScreens(); // this is where you register all of your app's screens

// this will start our app
Navigation.startTabBasedApp({
  tabs: [{
    label: 'One',
    screen: 'AwesomeProject.Home', // this is a registered name for a screen
    icon: require('../img/one.png'),
    selectedIcon: require('../img/one_selected.png'), // iOS only
    title: 'Screen One'
  }]
});
</code>```

my screens.js

```<code>import { Navigation } from 'react-native-navigation';

import Home from './containers/Home';
import About from './containers/About';

// register all screens of the app (including internal ones)
export function registerScreens() {
  Navigation.registerComponent('AwesomeProject.Home', () => Home);
  Navigation.registerComponent('AwesomeProject.About', () => About);
}
</code>```

my Home.js:

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

class Home extends Component {
  render() {
    return (
      <Text>Home!</Text>
    );
  }
}

export default Home;
</code>```

my About.js:

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

class About extends Component {
  render() {
    return (
      <Text>About!</Text>
    );
  }
}

export default About;
</code>```

You can see a full gist here: https://gist.github.com/inchr/d0184f4ae91abd6036a2fa61725744c9

I've done very test on how loads the tabs in startTabBasedApp() and I've tried to load only a screen too.

Any idea on the reason of the crash/close after the splash screen ?

Thanks.

答:
Ok the problem was that after I've run: react-native link

I've forgot to edit the AppDelete.m file as explained here:
https://github.com/wix/react-native-navigation/wiki/Installation---iOS#installation---ios

https://github.com/wix/react-native-navigation/blob/master/example/ios/example/AppDelegate.m

Body:
I'm trying to use react-native-navigation as navigation system in my react-native. I've wrote a very simple app for test it, but this app crashes(without giving me any error or info) after the splash screen.

my index.ios.js:

/* eslint-disable no-unused-vars */
import App from './src/app';

my app.ios.js:

import {
  Platform
} from 'react-native';
import {Navigation} from 'react-native-navigation';

import { registerScreens } from './screens';
registerScreens(); // this is where you register all of your app's screens

// this will start our app
Navigation.startTabBasedApp({
  tabs: [{
    label: 'One',
    screen: 'AwesomeProject.Home', // this is a registered name for a screen
    icon: require('../img/one.png'),
    selectedIcon: require('../img/one_selected.png'), // iOS only
    title: 'Screen One'
  }]
});

my screens.js

import { Navigation } from 'react-native-navigation';

import Home from './containers/Home';
import About from './containers/About';

// register all screens of the app (including internal ones)
export function registerScreens() {
  Navigation.registerComponent('AwesomeProject.Home', () => Home);
  Navigation.registerComponent('AwesomeProject.About', () => About);
}

my Home.js:

import React, { Component } from 'react';
import { Text } from 'react-native';

class Home extends Component {
  render() {
    return (
      <Text>Home!</Text>
    );
  }
}

export default Home;

my About.js:

import React, { Component } from 'react';
import { Text } from 'react-native';

class About extends Component {
  render() {
    return (
      <Text>About!</Text>
    );
  }
}

export default About;

You can see a full gist here: https://gist.github.com/inchr/d0184f4ae91abd6036a2fa61725744c9

I've done very test on how loads the tabs in startTabBasedApp() and I've tried to load only a screen too.

Any idea on the reason of the crash/close after the splash screen ?

Thanks.


来源: stackexchange

问:
Font awesome - change icon inside color on hover
I'm trying to change the inside color of an icon when hovering it, I've tried this css code:

.fa-star-o:hover {
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<i class="fa fa-star-o fa-2x"></i></code>```

With this code, only the outline of the icon is changed, not the inside, I want to change the inside color

答:
Use stacked icons:

.fa-star{
  color: white /* your background color */
}

.fa-stack:hover .fa-star{
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet"/>
<span class="fa-stack fa-lg">
  <i class="fa fa-star fa-stack-2x"></i>
  <i class="fa fa-star-o fa-stack-2x"></i>
</span></code>```

JSFiddle

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to change the inside color of an icon when hovering it, I've tried this css code:

.fa-star-o:hover {
  color: black;
}

<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet" />

With this code, only the outline of the icon is changed, not the inside, I want to change the inside color

Body:
Use stacked icons:

.fa-star{
  color: white /* your background color */
}

.fa-stack:hover .fa-star{
  color: black;
}

<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet"/>
<span class="fa-stack fa-lg">
  <i class="fa fa-star fa-stack-2x"></i>
  <i class="fa fa-star-o fa-stack-2x"></i>
</span>

JSFiddle

ContentLicense: CC BY-SA 3.0


问:
How to connect to telegram api from telegram.link module?
I am using telegram.link for implementing telegram methods in node.js and working with my telegram account by sending and receiving messages.
but when I want to connect to telegram server as follow:

  1 app = require("telegram.link")()
  2 client = app.createClient({
  3   id: 48820
  4   hash: '0028ba7cd67b8e9e487f7700cc4760e9'
  5   version: '1.0.0'
  6   lang: 'en'
  7 }, app.TEST_PRIMARY_DC, (ex) ->
  8   if !ex
  9     console.log 'ok'
 10     client.contacts.getContacts (err, result) ->
 11       console.log result
 12   else
 13     console.log 'Not ok'
 14 )
 15
 16 dc = client.getDataCenters()
 17
 18 cosole.log dc```

but when I want run this this error appear in my console
[ERROR] Thu, 05 May 2016 16:19:41 GMT  telegram-link Client is not yet ready!
What do you think about this error?

答: You cannot call getDataCenters()method before the connection has been stablished, i.e. you must make your call inside the callback of createClient, just before the call to client.contacts.getContacts

Body:
I am using telegram.link for implementing telegram methods in node.js and working with my telegram account by sending and receiving messages.
but when I want to connect to telegram server as follow:

  1 app = require("telegram.link")()
  2 client = app.createClient({
  3   id: 48820
  4   hash: '0028ba7cd67b8e9e487f7700cc4760e9'
  5   version: '1.0.0'
  6   lang: 'en'
  7 }, app.TEST_PRIMARY_DC, (ex) ->
  8   if !ex
  9     console.log 'ok'
 10     client.contacts.getContacts (err, result) ->
 11       console.log result
 12   else
 13     console.log 'Not ok'
 14 )
 15
 16 dc = client.getDataCenters()
 17
 18 cosole.log dc

but when I want run this this error appear in my console
[ERROR] Thu, 05 May 2016 16:19:41 GMT  telegram-link Client is not yet ready!
What do you think about this error?


问:
TinyXML2/C++ - create empty element
I'm trying to create XML file with TinyXML2.

```<code>string _text = "<body><foo><foo2>text</foo2></foo></body>";
XMLElement *body = xmlDoc->NewElement("body");
body->SetText(_text.c_str());
</code>```

Give me:

```<code><body>
    <body><foo><foo2>text<foo2/><foo/><body/>
<body>
</code>```

Is any way how to create empty element without top "body" and replace escape characters with <,>?

答:
You've created a top level element  then added another  element, with child elements, below it. You can't create an 'empty' element but you can add your string directly into an empty document:

```<code>XMLDocument doc;
doc .Parse ("<body><foo><foo2>text</foo2></foo></body>");
</code>```

Title: TinyXML2/C++ - create empty element

Body:
I'm trying to create XML file with TinyXML2.

string _text = "<foo><foo2>text</foo2></foo>";
XMLElement *body = xmlDoc->NewElement("body");
body->SetText(_text.c_str());

Give me:

    <foo><foo2>text<foo2/><foo/>

Is any way how to create empty element without top "body" and replace escape characters with <,>?

Body:
You've created a top level element <body> then added another <body> element, with child elements, below it. You can't create an 'empty' element but you can add your string directly into an empty document:

XMLDocument doc;
doc .Parse ("<body><foo><foo2>text</foo2></foo></body>");


问:
Polynomial time and exponential time
Could someone explain the difference between polynomial-time, non-polynomial-time, and exponential-time algorithms?

For example, if an algorithm takes O(n^2) time, then which category is it in?

答:
Polynomial time.

A polynomial is a sum of terms that look like Constant * x^k
Exponential means something like Constant * k^x

(in both cases, k is a constant and x is a variable).

The execution time of exponential algorithms grows much faster than that of polynomial ones.

Title: Polynomial time and exponential time


问:
TYPO3 6.2 DB Error: "exec_SELECTquery" while browsing in backend
Every time I click on any page in the backend I get 6 DB Errors, that look very similar to this one, in total 3 different SELECT errors for the table lawyer and 3 for the table student:

```<code>caller  TYPO3\CMS\Core\Database\DatabaseConnection::exec_SELECTquery
ERROR   Table 'db_lawclinic47.tx_lcapp_domain_model_lawyer' doesn't exist
lastBuiltQuery  SELECT uid FROM tx_lcapp_domain_model_lawyer
WHERE pid=24 AND tx_lcapp_domain_model_lawyer.deleted=0
AND (tx_lcapp_domain_model_lawyer.t3ver_state <= 0 OR
tx_lcapp_domain_model_lawyer.t3ver_wsid = 0) LIMIT 1

debug_backtrace     require(25/typo3/sysext/recordlist/mod1/index.php),25/typo3/mod.php#32 //
TYPO3\CMS\Recordlist\RecordList->main#31 //
TYPO3\CMS\Recordlist\RecordList\AbstractDatabaseRecordList->generateList#332 //
TYPO3\CMS\Core\Database\DatabaseConnection->exec_SELECTgetSingleRow#410 //
TYPO3\CMS\Core\Database\DatabaseConnection->exec_SELECTquery#406 //
TYPO3\CMS\Core\Database\DatabaseConnection->debug#305
</code>```

Those tables really don't exist because I renamed some and deleted some...and my webpage is working fine, so somehow those new tables are used, but there seems to be something old that is trying to select from the old tables and I have no idea what it could be and how to find it and get rid of it. Any clues?

答:
You have an extension installed (probably with key lcapp) that requires these tables. If you don't need that functionality any longer, you should uninstall that extension in the Extension Manager.

Also, if the database was manipulated by some other tool than TYPO3 itself, you should check the database structure in the Install Tool. It can tell you about missing tables, fields that are not as specified and so on.

The database definitions for an extension are stored in the file ext_tables.sql in root of the extensions install directory, the Install Tool compares against these definitions.

Body:
Every time I click on any page in the backend I get 6 DB Errors, that look very similar to this one, in total 3 different SELECT errors for the table lawyer and 3 for the table student:

caller  TYPO3\CMS\Core\Database\DatabaseConnection::exec_SELECTquery
ERROR   Table 'db_lawclinic47.tx_lcapp_domain_model_lawyer' doesn't exist
lastBuiltQuery  SELECT uid FROM tx_lcapp_domain_model_lawyer
WHERE pid=24 AND tx_lcapp_domain_model_lawyer.deleted=0
AND (tx_lcapp_domain_model_lawyer.t3ver_state <= 0 OR
tx_lcapp_domain_model_lawyer.t3ver_wsid = 0) LIMIT 1

debug_backtrace     require(25/typo3/sysext/recordlist/mod1/index.php),25/typo3/mod.php#32 //
TYPO3\CMS\Recordlist\RecordList->main#31 //
TYPO3\CMS\Recordlist\RecordList\AbstractDatabaseRecordList->generateList#332 //
TYPO3\CMS\Core\Database\DatabaseConnection->exec_SELECTgetSingleRow#410 //
TYPO3\CMS\Core\Database\DatabaseConnection->exec_SELECTquery#406 //
TYPO3\CMS\Core\Database\DatabaseConnection->debug#305

Those tables really don't exist because I renamed some and deleted some...and my webpage is working fine, so somehow those new tables are used, but there seems to be something old that is trying to select from the old tables and I have no idea what it could be and how to find it and get rid of it. Any clues?


问:
Calling javascript function from C++ Addon
I need some help to solve my problem.
Basically, I want to "call" javascript function from C++ addon, I've googled about it and found something like this.

Here is my .js file

```<code>const myaddon = process.binding('myaddon');

function Foo() {
    console.log("wooo");
}
myaddon.getfoo(Foo);
myaddon.callfoo(); // just to test if C++ Call js function work
</code>```

Here is my .cpp

```<code>Local<Function> pfOnScriptInit;
Local<Object> globel;
void test(const FunctionCallbackInfo<Value>& args)
{
    pfOnScriptInit = Local<Function>::Cast(args[0]);
}
void call(const FunctionCallbackInfo<Value>& args)
{
    pfOnScriptInit->Call(globel, 0, nullptr);
}
void initAll(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv)
{
    node::Environment* env = node::Environment::GetCurrent(context);

    globel = env->context()->Global();
    env->SetMethod(target, "getfoo", test);
    env->SetMethod(target, "callfoo", call);
}
NODE_MODULE_CONTEXT_AWARE_BUILTIN(fivemp, node::fivemp::initAll)
</code>```

I got this error when calling myaddon.callfoo(); function:

TypeError: Illegal Invocation

答:
This question is kinda old, but it's a common question, which has been asked a couple times. These answers don't have a proper answer in my opinion. Hence, here I go!

Before I answer your question, let me say that you should use Native Abstractions for Node.js to write a Node.js addon. This will make your addon portable across Node.js versions.

Also, you should take a look at the official addon documentation here, and to the repo with Nan examples.

That said, your code has a big and common mistake: you are confusingly using a local object as persistent. In other words, declaring a Local<Function> out of a function scope is plain wrong. These two cannot be declared anywhere but in function scope:

```<code>Local<Function> pfOnScriptInit;
Local<Object> globel;
</code>```

And of course, you cannot assign a Local<Function> like this:

```<code>pfOnScriptInit = Local<Function>::Cast(args[0]);
</code>```

This local object is going to be reclaimed by v8's garbage collector - it won't exist anymore. So, instead you need to use a persistent type. Here is an example, written using Nan, which might show you how it's done:

```<code>#include <nan.h>

static Nan::CopyablePersistentTraits<v8::Function>::CopyablePersistent _cb;

static void SetCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  _cb = Nan::Persistent<v8::Function>(info[0].As<v8::Function>());
}

static void RunCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(_cb), 0, 0);
  _cb.Reset();
}

void RunThisCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Function> cb = info[0].As<v8::Function>();
  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, 0, 0);
}

static void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
  Nan::SetMethod(exports, "setCallback", SetCallback);
  Nan::SetMethod(exports, "call", RunCallback);
  Nan::SetMethod(exports, "callThis", RunThisCallback);
}

NODE_MODULE(addon, Init)
</code>```

And here's the JS side:

```<code>var addon = require('bindings')('addon');

function foo() {
        console.log("woohoo!");
}

addon.setCallback(foo);
addon.call();
addon.callThis(() => console.log("this too!"));
</code>```

For more information about v8's local vs persistent, you should take a look at v8's documentation. There is a also a good book about Node.js addons by Scott Frees, here https://scottfrees.com/ebooks/nodecpp/.

Body:
I need some help to solve my problem.
Basically, I want to "call" javascript function from C++ addon, I've googled about it and found something like this.

Here is my .js file

const myaddon = process.binding('myaddon');

function Foo() {
    console.log("wooo");
}
myaddon.getfoo(Foo);
myaddon.callfoo(); // just to test if C++ Call js function work

Here is my .cpp

Local<Function> pfOnScriptInit;
Local<Object> globel;
void test(const FunctionCallbackInfo<Value>& args)
{
    pfOnScriptInit = Local<Function>::Cast(args[0]);
}
void call(const FunctionCallbackInfo<Value>& args)
{
    pfOnScriptInit->Call(globel, 0, nullptr);
}
void initAll(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv)
{
    node::Environment* env = node::Environment::GetCurrent(context);

    globel = env->context()->Global();
    env->SetMethod(target, "getfoo", test);
    env->SetMethod(target, "callfoo", call);
}
NODE_MODULE_CONTEXT_AWARE_BUILTIN(fivemp, node::fivemp::initAll)

I got this error when calling myaddon.callfoo(); function:

TypeError: Illegal Invocation

Body:
This question is kinda old, but it's a common question, which has been asked a couple times. These answers don't have a proper answer in my opinion. Hence, here I go!

Before I answer your question, let me say that you should use Native Abstractions for Node.js to write a Node.js addon. This will make your addon portable across Node.js versions.

Also, you should take a look at the official addon documentation here, and to the repo with Nan examples.

That said, your code has a big and common mistake: you are confusingly using a local object as persistent. In other words, declaring a Local<Function> out of a function scope is plain wrong. These two cannot be declared anywhere but in function scope:

Local<Function> pfOnScriptInit;
Local<Object> globel;

And of course, you cannot assign a Local<Function> like this:

pfOnScriptInit = Local<Function>::Cast(args[0]);

This local object is going to be reclaimed by v8's garbage collector - it won't exist anymore. So, instead you need to use a persistent type. Here is an example, written using Nan, which might show you how it's done:

#include <nan.h>

static Nan::CopyablePersistentTraits<v8::Function>::CopyablePersistent _cb;

static void SetCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  _cb = Nan::Persistent<v8::Function>(info[0].As<v8::Function>());
}

static void RunCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(_cb), 0, 0);
  _cb.Reset();
}

void RunThisCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Function> cb = info[0].As<v8::Function>();
  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, 0, 0);
}

static void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
  Nan::SetMethod(exports, "setCallback", SetCallback);
  Nan::SetMethod(exports, "call", RunCallback);
  Nan::SetMethod(exports, "callThis", RunThisCallback);
}

NODE_MODULE(addon, Init)

And here's the JS side:

var addon = require('bindings')('addon');

function foo() {
        console.log("woohoo!");
}

addon.setCallback(foo);
addon.call();
addon.callThis(() => console.log("this too!"));

For more information about v8's local vs persistent, you should take a look at v8's documentation. There is a also a good book about Node.js addons by Scott Frees, here https://scottfrees.com/ebooks/nodecpp/.


问:
How do I instantiate a class given its string name?
I have an abstract class and I want to initalize it to a class that extends it.

I have the child classes name as a string.

Besides this...

```<code>String childClassString;
MyAbstractClass myObject;

if (childClassString = "myExtenedObjectA")
    myObject = new ExtenedObjectA();
if (childClassString = "myExtenedObjectB")
    myObject = new ExtenedObjectB();
</code>```

How can I do this? Basically how do I get rid of the if statements here?

答:
I had some difficulty implementing some of the answers here because I was trying to instantiate an object from a different assembly (but in the same solution).  So I thought I'd post what I found to work.

First, the Activator.CreateInstance method has several overloads.  If you just call Activator.CreateInstance(Type.GetType("MyObj")), that assumes the object is defined in the current assembly, and it returns a MyObj.

If you call it as recommended in the answers here: Activator.CreateInstance(string AssemblyName, string FullyQualifiedObjectName), then it instead returns an ObjectHandle, and you need to call Unwrap() on it to get your object.  This overload is useful when trying to call a method defined in a different assembly (BTW, you can use this overload in the current assembly, just leave the AssemblyName parameter null).

Now, I found that the suggestion above to use typeof(ParentNamespace.ChildNamespace.MyObject).AssemblyQualifiedName  for AssemblyName actually gave me errors, and I could not get that to work.  I'd get System.IO.FileLoadException (could not load file or assembly...).

What I did get to work is as follows:

```<code>var container = Activator.CreateInstance(@"AssemblyName",@"ParentNamespace.ChildNamespace.MyObject");
MyObject obj = (MyObject)container.Unwrap();
obj.DoStuff();
</code>```

Body:
I have an abstract class and I want to initalize it to a class that extends it.

I have the child classes name as a string.

Besides this...

String childClassString;
MyAbstractClass myObject;

if (childClassString = "myExtenedObjectA")
    myObject = new ExtenedObjectA();
if (childClassString = "myExtenedObjectB")
    myObject = new ExtenedObjectB();

How can I do this? Basically how do I get rid of the if statements here?

Body:
I had some difficulty implementing some of the answers here because I was trying to instantiate an object from a different assembly (but in the same solution).  So I thought I'd post what I found to work.

First, the Activator.CreateInstance method has several overloads.  If you just call Activator.CreateInstance(Type.GetType("MyObj")), that assumes the object is defined in the current assembly, and it returns a MyObj.

If you call it as recommended in the answers here: Activator.CreateInstance(string AssemblyName, string FullyQualifiedObjectName), then it instead returns an ObjectHandle, and you need to call Unwrap() on it to get your object.  This overload is useful when trying to call a method defined in a different assembly (BTW, you can use this overload in the current assembly, just leave the AssemblyName parameter null).

Now, I found that the suggestion above to use typeof(ParentNamespace.ChildNamespace.MyObject).AssemblyQualifiedName  for AssemblyName actually gave me errors, and I could not get that to work.  I'd get System.IO.FileLoadException (could not load file or assembly...).

What I did get to work is as follows:

var container = Activator.CreateInstance(@"AssemblyName",@"ParentNamespace.ChildNamespace.MyObject");
MyObject obj = (MyObject)container.Unwrap();
obj.DoStuff();


问:
Laravel: Where selection for Eloquent Eager Loading relationship
I got two DB tables:

Posts

```<code>$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
</code>```

Countries

```<code>$table->increments('id');
$table->string('name', 70);
</code>```

I use laravel as back-end. Now I want to implement filtering data for my front-end. So the user can select a country name and laravel should answer the request only with posts that have a country with the specified name.

How could I add this condition to my existing pagination query? I tried this:

```<code>$query = app(Post::class)->with('country')->newQuery();
// ...
if ($request->exists('country')) {
        $query->where('country.name', $request->country);
}
// ...
</code>```

... resulting in the following error:

```<code>Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)
</code>```

答:
```<code>$query = ""

if ($request->has('country'){
    $query = Post::with("country")->whereHas("country", function($q) use($request){
        $q->where("name","=",$request->country);
   })->get()
}else{
    $query = Post::with("country")->get();
}
</code>```

Body:
I got two DB tables:

Posts

$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');

Countries

$table->increments('id');
$table->string('name', 70);

I use laravel as back-end. Now I want to implement filtering data for my front-end. So the user can select a country name and laravel should answer the request only with posts that have a country with the specified name.

How could I add this condition to my existing pagination query? I tried this:

$query = app(Post::class)->with('country')->newQuery();
// ...
if ($request->exists('country')) {
        $query->where('country.name', $request->country);
}
// ...

... resulting in the following error:

Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)


答:
You don't need the icon fa-star-o. Use only fa-star:

.fa-star:hover {
    color: black;
    cursor:pointer
}
.fa-star {
    color:white;
    transition:color 0.5s
}
body {
    background-color:red !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="http://fontawesome.io/assets/css/site.css">

<div style="font-size: 24px; line-height: 1.5em;" id="parent">
    <div style="font-size: 24px; line-height: 1.5em;">
        <i class="fa fa-star" aria-hidden="true"></i>
    </div>
</div> </code>```

Title: Font awesome - change icon inside color on hover

Body:
You don't need the icon fa-star-o. Use only fa-star:

.fa-star:hover {
    color: black;
    cursor:pointer
}
.fa-star {
    color:white;
    transition:color 0.5s
}
body {
    background-color:red !important;
}

<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="http://fontawesome.io/assets/css/site.css">

<div style="font-size: 24px; line-height: 1.5em;" id="parent">
    <div style="font-size: 24px; line-height: 1.5em;">
        <i class="fa fa-star" aria-hidden="true"></i>
    </div>
</div>


答:
O(n^2) is polynomial time.  The polynomial is f(n) = n^2.  On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n.  The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.

Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.

Title: Polynomial time and exponential time

Body:
Could someone explain the difference between polynomial-time, non-polynomial-time, and exponential-time algorithms?

For example, if an algorithm takes O(n^2) time, then which category is it in?

ContentLicense: CC BY-SA 2.5


问:
How to draw the triangle symbol?
I am trying to implement the triangle example yet it fails with d3 v4 for me

```<code>triangles = [];
triangles.push({x : 250});
triangles.push({x : 350});

var group = svgContainer.append('g').attr('transform','translate('+ xOffset +','+ 30 +')');
var arc = d3.symbol().type('triangle');

var line = group.selectAll('path')
            .data(triangles)
            .enter()
            .append('path')
            .attr('d',arc)
            .attr('fill','red')
            .attr('stroke','#000')
            .attr('stroke-width',1)
            .attr('transform',function(d){ return "translate("+(d.x)+",0)"; });
</code>```

The error:

Uncaught TypeError: type.apply(...).draw is not a function

答:
Instead of...

```<code>type("triangle")
</code>```

... it has to be:

```<code>type(d3.symbolTriangle)
</code>```

Here is the list of the symbols in D3 v4.x.

And here is the demo:

var svg = d3.select("svg");

triangles = [];
triangles.push({
  x: 150
});
triangles.push({
  x: 50
});

var arc = d3.symbol().type(d3.symbolTriangle);

var line = svg.selectAll('path')
  .data(triangles)
  .enter()
  .append('path')
  .attr('d', arc)
  .attr('fill', 'red')
  .attr('stroke', '#000')
  .attr('stroke-width', 1)
  .attr('transform', function(d) {
    return "translate(" + d.x + ",30)";
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg></code>```

The same code, rotating the triangles (as you asked in your comment):

var svg = d3.select("svg");

triangles = [];
triangles.push({
  x: 150
});
triangles.push({
  x: 50
});

var arc = d3.symbol().type(d3.symbolTriangle);

var line = svg.selectAll('path')
  .data(triangles)
  .enter()
  .append('path')
  .attr('d', arc)
  .attr('fill', 'red')
  .attr('stroke', '#000')
  .attr('stroke-width', 1)
  .attr('transform', function(d) {
    return "translate(" + d.x + ",30) rotate(180)";
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg></code>```

Title: How to draw the triangle symbol?

Body:
I am trying to implement the triangle example yet it fails with d3 v4 for me

triangles = [];
triangles.push({x : 250});
triangles.push({x : 350});

var group = svgContainer.append('g').attr('transform','translate('+ xOffset +','+ 30 +')');
var arc = d3.symbol().type('triangle');

var line = group.selectAll('path')
            .data(triangles)
            .enter()
            .append('path')
            .attr('d',arc)
            .attr('fill','red')
            .attr('stroke','#000')
            .attr('stroke-width',1)
            .attr('transform',function(d){ return "translate("+(d.x)+",0)"; });

The error:

Uncaught TypeError: type.apply(...).draw is not a function

Body:
Instead of...

type("triangle")

... it has to be:

type(d3.symbolTriangle)

Here is the list of the symbols in D3 v4.x.

And here is the demo:

var svg = d3.select("svg");

triangles = [];
triangles.push({
  x: 150
});
triangles.push({
  x: 50
});

var arc = d3.symbol().type(d3.symbolTriangle);

var line = svg.selectAll('path')
  .data(triangles)
  .enter()
  .append('path')
  .attr('d', arc)
  .attr('fill', 'red')
  .attr('stroke', '#000')
  .attr('stroke-width', 1)
  .attr('transform', function(d) {
    return "translate(" + d.x + ",30)";
  });

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

The same code, rotating the triangles (as you asked in your comment):

var svg = d3.select("svg");

triangles = [];
triangles.push({
  x: 150
});
triangles.push({
  x: 50
});

var arc = d3.symbol().type(d3.symbolTriangle);

var line = svg.selectAll('path')
  .data(triangles)
  .enter()
  .append('path')
  .attr('d', arc)
  .attr('fill', 'red')
  .attr('stroke', '#000')
  .attr('stroke-width', 1)
  .attr('transform', function(d) {
    return "translate(" + d.x + ",30) rotate(180)";
  });

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>


问:
Rename a Project in Visual Studio 2017
I have a Solution in Visual Studio 2017 and one of the Projects is an ASP.NET Web Forms application.
How can I rename the Project?
I changed the name in the .sln file but within the IDE it is still showing the old name. The folder name matches the required name.</p>

答:
Thanks for the response.
I had already tried editing the .sln file but it made no difference.
I finally found the problem was in the applicationhost.config file. Once I edited that the new name appeared.</p>

Title: Rename a Project in Visual Studio 2017


问:
Validate embedded document in mongodb
I'd like to validate my documents in MongoDB. As described here, the validator query can be specified during the createCollection command.

My application is a simple todo list, so the collection list has many documents like this:

```<code>{
   "name": "the list name",
   "color: "red",
   "items": [
     {
       "title": "item1",
       "isDone": false,
       "text": "the item description"
     }
   ]
}
</code>```

How can I sure that all documents has this shape?

EDIT: I'm using MongoDB 3.4

答:
You can't.

There's no way to avoid new property. If this needed is required, you should consider to migrate a SQL solution.

Otherwise, your document will contain at least those members and those members will be validated.

I assume that all fields are mandatory, so no list can be added neither without a color nor having an item without a title.

I assume that color is an enum also.

```<code>{
  validator: {
    name: { $type: 'string', $exists: true },
    color: { $in: ['red', 'green', 'blue'], $exists: true },
    items: { $exists: true },
    $or: [
      { items: { $size: 0 } },
      {
        $and: [
          { 'items.0': { $exists: true } },
          {
            items: {
              $not: {
                $elemMatch: {
                  $not: { $type: 'object' }
                }
              }
            }
          },
          {
            items: {
              $not: {
                $elemMatch: {
                  $or: [
                    { title: { $not: { $type: 'string' } } },
                    { title: { $not: { $exists: true } } },
                    { isDone: { $not: { $type: 'bool' } } },
                    { isDone: { $not: { $exists: true } } },
                    { text: { $not: { $type: 'string' } } },
                    { text: { $not: { $exists: true } } }
                  ]
                }
              }
            }
          }
        ]
      }
    ]
  }
}
</code>```

Explanation

The solution is based on the second-order logic.
Indeed, the assertion "all elements have to match A" is equal to "no element should match !A" or, if you have many queries, "all element have to match A and B" becomes "no element should match !A or !B", where ! means the negation of the following predicate.

Long explanation

The first two query items assert that all documents have name and color, the third one the items property always exists.
NB: in the third query property, there's not the $type check because mongodb treats the array type in a odd way.

The $or operation below is needed because the item property can be empty or filled with some data.

First clause of $or checks if the array is empty.
If the array is not empty, three checks should be done:

the array contains at least one element

the array has to contain only object

all object has a specified shape.

So the first $and operator element checks that at least one element is present. The second one checks that all array elements are objects. The third one asserts that all objects have a specified shape.

In mongodb, there's an operator for checking if all array elements match a query. So, using the second order logic, the check should be turned over.

In fact, the last two clauses of $and check that no elements match none of the described query. Each sub query is the negate of a wanted query.

Example

fails

```<code>{ name: 'foo' }
{ color: 'red' }
{ color: 'unknown color' }
{ name: 'foo', color: 'red' }
{ name: 'foo', color: 'red', item: 3 }
{ name: 'foo', color: 'red', item: [ 3 ] }
{ name: 'foo', color: 'red', item: [ { } ] }
{ name: 'foo', color: 'red', item: [ { title: 'ww' } ] }
{ name: 'foo', color: 'red', item: [ { title: 'ww', isDone: false } ] }
{ name: 'foo', color: 'red', item: [ { title: 44, isDone: false, text: 'the text' } ] }
</code>```

pass

```<code>    { name: 'foo', color: 'red', items: [ ] },
    { name: 'foo', color: 'red', items: [ ] },
    { name: 'foo', color: 'red', items: [ { title: 'the title', isDone: false, text: 'the text' }, { title: 'the title1', isDone: true, text: 'the text' } ] }
</code>```

This solution is still valid using MongoDB 3.2

Title: Validate embedded document in mongodb

Body:
I'd like to validate my documents in MongoDB. As described here, the validator query can be specified during the createCollection command.

My application is a simple todo list, so the collection list has many documents like this:

{
   "name": "the list name",
   "color: "red",
   "items": [
     {
       "title": "item1",
       "isDone": false,
       "text": "the item description"
     }
   ]
}

How can I sure that all documents has this shape?

EDIT: I'm using MongoDB 3.4

Body:
You can't.

There's no way to avoid new property. If this needed is required, you should consider to migrate a SQL solution.

Otherwise, your document will contain at least those members and those members will be validated.

I assume that all fields are mandatory, so no list can be added neither without a color nor having an item without a title.

I assume that color is an enum also.

{
  validator: {
    name: { $type: 'string', $exists: true },
    color: { $in: ['red', 'green', 'blue'], $exists: true },
    items: { $exists: true },
    $or: [
      { items: { $size: 0 } },
      {
        $and: [
          { 'items.0': { $exists: true } },
          {
            items: {
              $not: {
                $elemMatch: {
                  $not: { $type: 'object' }
                }
              }
            }
          },
          {
            items: {
              $not: {
                $elemMatch: {
                  $or: [
                    { title: { $not: { $type: 'string' } } },
                    { title: { $not: { $exists: true } } },
                    { isDone: { $not: { $type: 'bool' } } },
                    { isDone: { $not: { $exists: true } } },
                    { text: { $not: { $type: 'string' } } },
                    { text: { $not: { $exists: true } } }
                  ]
                }
              }
            }
          }
        ]
      }
    ]
  }
}

Explanation

The solution is based on the second-order logic.
Indeed, the assertion "all elements have to match A" is equal to "no element should match !A" or, if you have many queries, "all element have to match A and B" becomes "no element should match !A or !B", where ! means the negation of the following predicate.

Long explanation

The first two query items assert that all documents have name and color, the third one the items property always exists.
NB: in the third query property, there's not the $type check because mongodb treats the array type in a odd way.

The $or operation below is needed because the item property can be empty or filled with some data.

First clause of $or checks if the array is empty.
If the array is not empty, three checks should be done:

the array contains at least one element

the array has to contain only object

all object has a specified shape.

So the first $and operator element checks that at least one element is present. The second one checks that all array elements are objects. The third one asserts that all objects have a specified shape.

In mongodb, there's an operator for checking if all array elements match a query. So, using the second order logic, the check should be turned over.

In fact, the last two clauses of $and check that no elements match none of the described query. Each sub query is the negate of a wanted query.

Example

fails

{ name: 'foo' }
{ color: 'red' }
{ color: 'unknown color' }
{ name: 'foo', color: 'red' }
{ name: 'foo', color: 'red', item: 3 }
{ name: 'foo', color: 'red', item: [ 3 ] }
{ name: 'foo', color: 'red', item: [ { } ] }
{ name: 'foo', color: 'red', item: [ { title: 'ww' } ] }
{ name: 'foo', color: 'red', item: [ { title: 'ww', isDone: false } ] }
{ name: 'foo', color: 'red', item: [ { title: 44, isDone: false, text: 'the text' } ] }

pass

    { name: 'foo', color: 'red', items: [ ] },
    { name: 'foo', color: 'red', items: [ ] },
    { name: 'foo', color: 'red', items: [ { title: 'the title', isDone: false, text: 'the text' }, { title: 'the title1', isDone: true, text: 'the text' } ] }

This solution is still valid using MongoDB 3.2


问:
Get index of element iterating thgrough multiple choices field django for in loop
I have MultipleChoiceFieldfield

```<code>OPTIONS = (
        ("AUT", "Austria"),
        ("DEU", "Germany"),
        ("NLD", "Neitherlands"),
    )

    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}),
                                          choices=OPTIONS)
</code>```

I build my own html structure for this field and this is simplified code:

```<code>{% for value, text in simple_search_form.countries.field.choices %}
   {{value}}
   {{text}}
 {% endfor %}
</code>```

How do I get and index of each element here?
I need to have

```<code> {{value}}
 {text}}
 {{index}}
</code>```

答:
If it's in a for loop, you can use</p>

```<code>{{ forloop.counter0 }}
</code>```

Body:
I have MultipleChoiceFieldfield

OPTIONS = (
        ("AUT", "Austria"),
        ("DEU", "Germany"),
        ("NLD", "Neitherlands"),
    )

    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={"name": "select_0","class": "fff"}),
                                          choices=OPTIONS)

I build my own html structure for this field and this is simplified code:

{% for value, text in simple_search_form.countries.field.choices %}
   {{value}}
   {{text}}
 {% endfor %}

How do I get and index of each element here?
I need to have

 {{value}}
 {text}}
 {{index}}

Body:
If it's in a for loop, you can use

{{ forloop.counter0 }}


问:
Visual Studio 2015 Community: ISLE ("Setup and Deployment" Doesn't Appear)
I am using the Visual Studio 2015 Community Edition.

I am following the tutorial here.

Although, I am stuck on step 2 of To install the ISLE setup and deployment project template, where it says:

and then select Setup and Deployment.

This option doesn't even appear for me. The only option available under "Other project types" is "Visual Studio Solutions". I have searched the web for a direct download instead of this, yet I found nothing.

答: Go and Download This Package From Here.</p>

Body: Go and Download This Package From Here.


问:
Outputting XML Information using PHP and AJAX based on Select Option
I am attempting to pull data from XML using PHP and AJAX based on the option selected from a Select box.

I do not get any output on selection change.

HTML

```<code><?php
    session_start();

    // Change the connection info in this file
    require 'dbInfo.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Member Page</title>
    <script type="text/javascript">
        // AJAX to show info for the selected City
        function ShowCityInfo(citySelection)
        {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    document.getElementById('cityInfo').innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "getCityData.php?city=" + citySelection, true);
            xmlhttp.send();
        }

        // AJAX to show info for the selected Rider
        function ShowRiderInfo(rider)
        {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    document.getElementById('riderInfo').innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "getRiderInfo.php?rider=" + rider, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <h1>Welcome User!</h1>
    <?php
        // If there is not a valid user logged in, kick back to login page
        if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
            header("Location:login.php");
            exit();
        }
        else { // Welcome the valid user
            echo "<h1>" . $_SESSION['user'] . "'s Member Page </h1>";
        }

        // Clear the session if the user is logged out based on query string
        if (isset($_GET['loggedOut'])) {
            session_unset();
            session_destroy();

            // Redirect to login and exit the script execution
            header("Location:login.php");
            exit();
        }

    ?><br/>

    <!-- On submission use query string to set that the user is logged out.
         Would be reverted by isset above on reload -->
    <form action="member.php?loggedOut=true" method="POST">
        <input type="submit" name="logOut" value="Log Out"><br/>
    </form>

    <?php
        $conn = new mysqli($host, $username, $password, $db);

        // Check for connection error
        if ($conn->connect_error) {
            die("Connection error: " . $conn->connect_error);
        }
    ?>

    <br/><br/>

    <strong>Select a City for more Information</strong> <br/>
    <!-- Populate selection from DB -->
    <select name="cities" onchange="ShowCityInfo(this.value)">
        <option>Select a City</option>
        <?php
            $sql = "SELECT * FROM webData.nwoCity";

            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    // Populate the select options from DB city names and set value to the ID
                    echo '<option value=" '. $row["cityID"] . '">'. $row["name"] . '</option>';
                }
            }

            $conn->close();
        ?>
    </select>

    <!-- Will be populated by AJAX -->
    <div id="cityInfo"></div>

    <h2>Artistic Freedom</h2>
    <p>This populates from XML using AJAX</p>

    <select name="riders" onchange="ShowRiderInfo(this.value)">
        <option><strong>Select a Rider:</strong></option>
        <option value="Ryan Dungey">Ryan Dungey</option>
        <option value="Ken Roczen">Ken Roczen</option>
        <option value="Eli Tomac">Eli Tomac</option>
        <option value="Dean Wilson">Dean Wilson</option>
    </select>

    <br/><br/>
    <div id="riderInfo"></div>

</body>
</html>
</code>```

PHP

```<code><?php
    $riderSelection = $_GET["rider"];

    // Create a DOM Document and load the XML file
    $xmlDoc = new DOMDocument();
    $xmlDoc->load("riderLineup.xml");

    // Get the rider elements
    $x = $xmlDoc->getElementsByTagName('RIDER');

    // Find all the rider elements that match the name
    for ($i = 0; $i < $x->length ; $i++)
    {
        // Only process the nodes in each element
        if ($x->item($i)->nodeType == 1)
        {
            if ($x->item($i)->childNodes->item(0)->nodeValue == $riderSelection)
            {
                $y = ($x->item($i)->parentNode);
            }
        }
    }

    $rider = ($y->childNodes);

    // Output the rider information to be used by AJAX as a response
    for ($i = 0; $i < $rider->length; $i++)
    {
        // Only process nodes in elements
        if ($rider->item($i)->nodeType == 1)
        {
            // Element node name in bold
            echo "<strong>" . $rider->item($i)->nodeName . "</strong>";

            // Element node's value
            echo $rider->item($i)->childNodes->item(0)->nodeValue;

            echo "<br/>";
        }
    }

?>
</code>```

XML

```<code><LINEUP>
    <RIDER>
        <NAME>Ryan Dungey</NAME>
        <AGE>27</AGE>
        <NICKNAME>The Diesel</NICKNAME>
        <NUMBER>1</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>7</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Ken Roczen</NAME>
        <AGE>22</AGE>
        <NICKNAME>Kenny</NICKNAME>
        <NUMBER>94</NUMBER>
        <BRAND>Honda</BRAND>
        <CHAMPIONSHIPS>3</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Eli Tomac</NAME>
        <AGE>25</AGE>
        <NICKNAME>ET3</NICKNAME>
        <NUMBER>3</NUMBER>
        <BRAND>Kawasaki</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Dean Wilson</NAME>
        <AGE>26</AGE>
        <NICKNAME>Deano</NICKNAME>
        <NUMBER>15</NUMBER>
        <BRAND>Husqvarna</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Benny Bloss</NAME>
        <AGE>20</AGE>
        <NICKNAME>The Baby Giraffe</NICKNAME>
        <NUMBER>34</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>0</CHAMPIONSHIPS>
    </RIDER>
</LINEUP>
</code>```

When I run the main page I see the Rider selection box but changing the selection does not result in any output.

Yes this code did start as code for an assignment for a College course. However, this assignment has already been submitted to the professor for marking and I am just trying to go back and understand the concepts better. This code regarding getting the info from XML was not a component of the assigned work.

答:
In the PHP file where I had coded:

```<code> $x = $xmlDoc->getElementsByTagName('RIDER');
</code>```

Should have read:

```<code>$x = $xmlDoc->getElementsByTagName('NAME');
</code>```

I was grabbing the <RIDER> elements instead of all the <NAME> nodes of the <RIDER> elements. Changing said line fixed the issue.

Body:
I am attempting to pull data from XML using PHP and AJAX based on the option selected from a Select box.

I do not get any output on selection change.

HTML

<?php
    session_start();

    // Change the connection info in this file
    require 'dbInfo.php';
?>
<!DOCTYPE html>

    <title>Member Page</title>

Welcome User!

    <?php
        // If there is not a valid user logged in, kick back to login page
        if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
            header("Location:login.php");
            exit();
        }
        else { // Welcome the valid user
            echo "
" . $_SESSION['user'] . "'s Member Page
";
        }

        // Clear the session if the user is logged out based on query string
        if (isset($_GET['loggedOut'])) {
            session_unset();
            session_destroy();

            // Redirect to login and exit the script execution
            header("Location:login.php");
            exit();
        }

    ?>

    <form action="member.php?loggedOut=true" method="POST">
        <input type="submit" name="logOut" value="Log Out">

    </form>

    <?php
        $conn = new mysqli($host, $username, $password, $db);

        // Check for connection error
        if ($conn->connect_error) {
            die("Connection error: " . $conn->connect_error);
        }
    ?>

    Select a City for more Information

    <select name="cities" onchange="ShowCityInfo(this.value)">
        <option>Select a City</option>
        <?php
            $sql = "SELECT * FROM webData.nwoCity";

            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    // Populate the select options from DB city names and set value to the ID
                    echo '<option value=" '. $row["cityID"] . '">'. $row["name"] . '</option>';
                }
            }

            $conn->close();
        ?>
    </select>

Artistic Freedom

This populates from XML using AJAX

    <select name="riders" onchange="ShowRiderInfo(this.value)">
        <option>Select a Rider:</option>
        <option value="Ryan Dungey">Ryan Dungey</option>
        <option value="Ken Roczen">Ken Roczen</option>
        <option value="Eli Tomac">Eli Tomac</option>
        <option value="Dean Wilson">Dean Wilson</option>
    </select>

PHP

<?php
    $riderSelection = $_GET["rider"];

    // Create a DOM Document and load the XML file
    $xmlDoc = new DOMDocument();
    $xmlDoc->load("riderLineup.xml");

    // Get the rider elements
    $x = $xmlDoc->getElementsByTagName('RIDER');

    // Find all the rider elements that match the name
    for ($i = 0; $i < $x->length ; $i++)
    {
        // Only process the nodes in each element
        if ($x->item($i)->nodeType == 1)
        {
            if ($x->item($i)->childNodes->item(0)->nodeValue == $riderSelection)
            {
                $y = ($x->item($i)->parentNode);
            }
        }
    }

    $rider = ($y->childNodes);

    // Output the rider information to be used by AJAX as a response
    for ($i = 0; $i < $rider->length; $i++)
    {
        // Only process nodes in elements
        if ($rider->item($i)->nodeType == 1)
        {
            // Element node name in bold
            echo "" . $rider->item($i)->nodeName . "";

            // Element node's value
            echo $rider->item($i)->childNodes->item(0)->nodeValue;

            echo "
";
        }
    }

?>

XML

<LINEUP>
    <RIDER>
        <NAME>Ryan Dungey</NAME>
        <AGE>27</AGE>
        <NICKNAME>The Diesel</NICKNAME>
        <NUMBER>1</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>7</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Ken Roczen</NAME>
        <AGE>22</AGE>
        <NICKNAME>Kenny</NICKNAME>
        <NUMBER>94</NUMBER>
        <BRAND>Honda</BRAND>
        <CHAMPIONSHIPS>3</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Eli Tomac</NAME>
        <AGE>25</AGE>
        <NICKNAME>ET3</NICKNAME>
        <NUMBER>3</NUMBER>
        <BRAND>Kawasaki</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Dean Wilson</NAME>
        <AGE>26</AGE>
        <NICKNAME>Deano</NICKNAME>
        <NUMBER>15</NUMBER>
        <BRAND>Husqvarna</BRAND>
        <CHAMPIONSHIPS>1</CHAMPIONSHIPS>
    </RIDER>
    <RIDER>
        <NAME>Benny Bloss</NAME>
        <AGE>20</AGE>
        <NICKNAME>The Baby Giraffe</NICKNAME>
        <NUMBER>34</NUMBER>
        <BRAND>KTM</BRAND>
        <CHAMPIONSHIPS>0</CHAMPIONSHIPS>
    </RIDER>
</LINEUP>

When I run the main page I see the Rider selection box but changing the selection does not result in any output.

Yes this code did start as code for an assignment for a College course. However, this assignment has already been submitted to the professor for marking and I am just trying to go back and understand the concepts better. This code regarding getting the info from XML was not a component of the assigned work.

Body:
In the PHP file where I had coded:

 $x = $xmlDoc->getElementsByTagName('RIDER');

Should have read:

$x = $xmlDoc->getElementsByTagName('NAME');

I was grabbing the <RIDER> elements instead of all the <NAME> nodes of the <RIDER> elements. Changing said line fixed the issue.


问:
Using two database reference in Cloud Functions for Firebase
I am creating 2 projects:

1: For Managers. Where all data are manipulated by managers. These are contents, pictures etc.

2: For users. Where all information are indexed for users to search contents easily. User information are stored such as names etc.

I want to configure the first project's cloud functions to index the information managed and store it to the second project.

Is this possible? Or should I just put them all in one project. I want to scale them individually in the long run. Thanks for any help.

答: Firebase rules can be used to easily limit visibility and/or modifiability by user or class/group of user so that's not a good reason to use two firebases. You can create an app that hits two firebases but you will be pretty far outside the normal usage. That means you will run into issues that few people have had to solve so you will not have much experience to draw upon. Unless you have a good reason that you can validate with experts I would recommend avoiding it. Start with the assumption one firebase is the correct design and only got to two if the requirements make it essential for some quality required.</p>


问:
Python: How to resolve URLs containing '..'
I need to uniquely identify and store some URLs. The problem is that sometimes they come containing ".." like http://somedomain.com/foo/bar/../../some/url which basically is http://somedomain.com/some/url if I'm not wrong.

Is there a Python function or a tricky way to resolve this URLs ?

答:
There’s a simple solution using urllib.parse.urljoin:

```<code>>>> from urllib.parse import urljoin
>>> urljoin('http://www.example.com/foo/bar/../../baz/bux/', '.')
'http://www.example.com/baz/bux/'
</code>```

However, if there is no trailing slash (the last component is a file, not a directory), the last component will be removed.

This fix uses the urlparse function to extract the path, then use (the posixpath version of) os.path to normalize the components. Compensate for a mysterious issue with trailing slashes, then join the URL back together. The following is doctestable:

```<code>from urllib.parse import urlparse
import posixpath

def resolve_components(url):
    """
    >>> resolve_components('http://www.example.com/foo/bar/../../baz/bux/')
    'http://www.example.com/baz/bux/'
    >>> resolve_components('http://www.example.com/some/path/../file.ext')
    'http://www.example.com/some/file.ext'
    """
    parsed = urlparse(url)
    new_path = posixpath.normpath(parsed.path)
    if parsed.path.endswith('/'):
        # Compensate for issue1707768
        new_path += '/'
    cleaned = parsed._replace(path=new_path)
    return cleaned.geturl()
</code>```

Body:
There’s a simple solution using urllib.parse.urljoin:

>>> from urllib.parse import urljoin
>>> urljoin('http://www.example.com/foo/bar/../../baz/bux/', '.')
'http://www.example.com/baz/bux/'

However, if there is no trailing slash (the last component is a file, not a directory), the last component will be removed.

This fix uses the urlparse function to extract the path, then use (the posixpath version of) os.path to normalize the components. Compensate for a mysterious issue with trailing slashes, then join the URL back together. The following is doctestable:

from urllib.parse import urlparse
import posixpath

def resolve_components(url):
    """
    >>> resolve_components('http://www.example.com/foo/bar/../../baz/bux/')
    'http://www.example.com/baz/bux/'
    >>> resolve_components('http://www.example.com/some/path/../file.ext')
    'http://www.example.com/some/file.ext'
    """
    parsed = urlparse(url)
    new_path = posixpath.normpath(parsed.path)
    if parsed.path.endswith('/'):
        # Compensate for issue1707768
        new_path += '/'
    cleaned = parsed._replace(path=new_path)
    return cleaned.geturl()


问:
pandas rolling max min mean
being new to pandas I am lost in the zillions of smooth random data generation examples.

What I have been trying to achieve is to create graphs using bokeh with rolling time window. I want x-axis to be (resampled or whatever) timestamp and 3 lines displaying max, min and mean values for let's say rolling 15 second time window for the duration field.

The joy stops before starting... I have tried to apply quite many examples without making progress or learning much.

The code below

```<code>d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], \
format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)

print (d2.head())
print (d2.rolling("15s", min_periods=1).mean().head())
print (d2.rolling("15s", min_periods=1).std().head())
print (d2.rolling("15s", min_periods=1).min().head())
print (d2.rolling("15s", min_periods=1).max().head())
</code>```

produces an exception:

ValueError: window must be an integer

If I could get the rolling stuff work, I'd probably could manage the bokeh side.

Any pointers supporting to make this happen are highly appreciated!

I have this data in csv:

```
ts_send,endpoint,duration,
2017-01-19 09:03:28.600,/api/sig,1.0
2017-01-19 09:03:29.760,/api/sig,0.5
2017-01-19 09:04:51.210,/api/sig,0.508
2017-01-19 09:04:52.410,/api/sig,0.574
2017-01-19 09:09:32.854,/api/sig,1.0
2017-01-19 09:09:36.776,/api/sig,0.637
2017-01-19 09:14:14.207,/api/sig,0.672
2017-01-19 09:14:16.906,/api/sig,0.533
2017-01-19 11:49:34.939,/api/sig,1.0
2017-01-19 11:49:38.709,/api/sig,0.529
2017-01-19 12:19:01.668,/api/sig,1.0
2017-01-19 12:19:05.559,/api/item,0.169
2017-01-19 12:19:05.559,/api/item,0.102
2017-01-19 12:19:05.559,/api/item,0.44
2017-01-19 12:19:05.585,/api/item,0.173
2017-01-19 12:19:06.633,/api/sig,0.564
2017-01-19 12:27:05.712,/api/sig,0.574
2017-01-19 12:27:08.370,/api/sig,0.497
2017-01-19 12:27:43.319,/api/sig,0.561
2017-01-19 12:27:45.873,/api/sig,0.508
2017-01-19 12:46:15.454,/api/sig,1.0
2017-01-19 12:46:20.409,/api/item,0.173
2017-01-19 12:46:20.427,/api/item,0.163
2017-01-19 12:46:20.457,/api/item,0.169
2017-01-19 12:46:20.474,/api/item,0.162
2017-01-19 12:46:20.618,/api/item,0.209
2017-01-19 12:46:20.642,/api/item,0.172
2017-01-19 12:46:20.695,/api/item,0.26
2017-01-19 12:46:20.698,/api/item,0.193
2017-01-19 12:46:20.788,/api/item,0.193
2017-01-19 12:46:20.822,/api/item,0.232
2017-01-19 12:46:20.873,/api/item,0.164
2017-01-19 12:46:20.875,/api/item,0.142
2017-01-19 12:46:20.905,/api/item,0.356
2017-01-19 12:46:20.998,/api/item,0.199
```

The timestamp ts_send is millisecond precission. There are times when no events are recorded and there are times when there multiple events on a single millisecond.

答:
Thanks to kind members Boud and Goyo I was able to move forward. </p>

<p>The code produces what I needed: </p>

```<code>d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)
d2.index = pd.DatetimeIndex(d2.ts_send, inplace=True)
d3 = d2.sort_index()
d3.drop(d3.columns[0],axis=1,inplace=True)

print (d3.index.is_monotonic_increasing)
print (d3.head())

print (d3.rolling("5s", min_periods=1).mean())
print (d3.rolling("5s", min_periods=1).std())
print (d3.rolling("5s", min_periods=1).min())
print (d3.rolling("5s", min_periods=1).max())
</code>```

Title: pandas rolling max min mean

Body:
being new to pandas I am lost in the zillions of smooth random data generation examples.

What I have been trying to achieve is to create graphs using bokeh with rolling time window. I want x-axis to be (resampled or whatever) timestamp and 3 lines displaying max, min and mean values for let's say rolling 15 second time window for the duration field.

The joy stops before starting... I have tried to apply quite many examples without making progress or learning much.

The code below

d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], \
format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)

print (d2.head())
print (d2.rolling("15s", min_periods=1).mean().head())
print (d2.rolling("15s", min_periods=1).std().head())
print (d2.rolling("15s", min_periods=1).min().head())
print (d2.rolling("15s", min_periods=1).max().head())

produces an exception:

ValueError: window must be an integer

If I could get the rolling stuff work, I'd probably could manage the bokeh side.

Any pointers supporting to make this happen are highly appreciated!

I have this data in csv:

ts_send,endpoint,duration,
2017-01-19 09:03:28.600,/api/sig,1.0
2017-01-19 09:03:29.760,/api/sig,0.5
2017-01-19 09:04:51.210,/api/sig,0.508
2017-01-19 09:04:52.410,/api/sig,0.574
2017-01-19 09:09:32.854,/api/sig,1.0
2017-01-19 09:09:36.776,/api/sig,0.637
2017-01-19 09:14:14.207,/api/sig,0.672
2017-01-19 09:14:16.906,/api/sig,0.533
2017-01-19 11:49:34.939,/api/sig,1.0
2017-01-19 11:49:38.709,/api/sig,0.529
2017-01-19 12:19:01.668,/api/sig,1.0
2017-01-19 12:19:05.559,/api/item,0.169
2017-01-19 12:19:05.559,/api/item,0.102
2017-01-19 12:19:05.559,/api/item,0.44
2017-01-19 12:19:05.585,/api/item,0.173
2017-01-19 12:19:06.633,/api/sig,0.564
2017-01-19 12:27:05.712,/api/sig,0.574
2017-01-19 12:27:08.370,/api/sig,0.497
2017-01-19 12:27:43.319,/api/sig,0.561
2017-01-19 12:27:45.873,/api/sig,0.508
2017-01-19 12:46:15.454,/api/sig,1.0
2017-01-19 12:46:20.409,/api/item,0.173
2017-01-19 12:46:20.427,/api/item,0.163
2017-01-19 12:46:20.457,/api/item,0.169
2017-01-19 12:46:20.474,/api/item,0.162
2017-01-19 12:46:20.618,/api/item,0.209
2017-01-19 12:46:20.642,/api/item,0.172
2017-01-19 12:46:20.695,/api/item,0.26
2017-01-19 12:46:20.698,/api/item,0.193
2017-01-19 12:46:20.788,/api/item,0.193
2017-01-19 12:46:20.822,/api/item,0.232
2017-01-19 12:46:20.873,/api/item,0.164
2017-01-19 12:46:20.875,/api/item,0.142
2017-01-19 12:46:20.905,/api/item,0.356
2017-01-19 12:46:20.998,/api/item,0.199

The timestamp ts_send is millisecond precission. There are times when no events are recorded and there are times when there multiple events on a single millisecond.

Body:
Thanks to kind members Boud and Goyo I was able to move forward.

The code produces what I needed:

d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)
d2.index = pd.DatetimeIndex(d2.ts_send, inplace=True)
d3 = d2.sort_index()
d3.drop(d3.columns[0],axis=1,inplace=True)

print (d3.index.is_monotonic_increasing)
print (d3.head())

print (d3.rolling("5s", min_periods=1).mean())
print (d3.rolling("5s", min_periods=1).std())
print (d3.rolling("5s", min_periods=1).min())
print (d3.rolling("5s", min_periods=1).max())


问:
Symfony form returns only token field
I'm trying to create, render, submit and validate form without entity class.

To do that, I've created FormType class using FormBuilderInterface. But when i'm trying to render form in twig template, I always get only form with token input, but no other fields.

My code is below:

Type definition:

```<code><?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;

class VendorLeadType extends AbstractType{

    /**
     * @param FormBilderInterface $builder
     * @param array $options
     */
    public function buidForm(FormBuilderInterface $builder, array $options){

        $builder
            ->add('email', EmailType::class, [
                'constraints' => [
                    new Email(),
                    new Length(['max'=>'100'])
                ]
            ])
            ->add('name', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                    new Length(['max'=>'100'])
                ]
            ])
            ->add('phone', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                    new Length(['max'=>'100'])
                ]
            ])
        ;
    }

}
</code>```

Controller:

```<code><?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Form\VendorLeadType;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $form = $this->createForm(VendorLeadType::class);
        return $this->render('index.html.twig', [
            'form' => $form->createView()
        ]);
    }

}
</code>```

Twig template

```<code>{% extends 'base.html.twig' %}

{% block body %}
{{ form(form) }}
{% endblock %}
</code>```

Output html

```<code><form name="vendor_lead" method="post">
    <div id="vendor_lead">
        <input type="hidden" id="vendor_lead__token" name="vendor_lead[_token]" value="...">
    </div>
</form>
</code>```

Any idea what i'm doing wrong?

答:
First, you have a typo in your VendorLeadType script. You need to fix the spelling of `public function buildForm'.

To get the form variables to come to your controller, you'll need to tell symfony to not expect any form variables to map to an entity by adding 'mapped' => false, to your parameters:

```<code>    $builder
        ->add('email', EmailType::class, [
            'mapped' => false,
            'constraints' => [
                new Email(),
                new Length(['max'=>'100'])
            ]
        ])
        ->add('name', TextType::class, [
            'mapped' => false,
            'constraints' => [
                new NotBlank(),
                new Length(['max'=>'100'])
            ]
        ])
        ->add('phone', TextType::class, [
            'mapped' => false,
            'constraints' => [
                new NotBlank(),
                new Length(['max'=>'100'])
            ]
        ])
    ;
</code>```

Title: Symfony form returns only token field

Body:
I'm trying to create, render, submit and validate form without entity class.

To do that, I've created FormType class using FormBuilderInterface. But when i'm trying to render form in twig template, I always get only form with token input, but no other fields.

My code is below:

Type definition:

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;

class VendorLeadType extends AbstractType{

    /**
     * @param FormBilderInterface $builder
     * @param array $options
     */
    public function buidForm(FormBuilderInterface $builder, array $options){

        $builder
            ->add('email', EmailType::class, [
                'constraints' => [
                    new Email(),
                    new Length(['max'=>'100'])
                ]
            ])
            ->add('name', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                    new Length(['max'=>'100'])
                ]
            ])
            ->add('phone', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                    new Length(['max'=>'100'])
                ]
            ])
        ;
    }

}

Controller:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Form\VendorLeadType;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $form = $this->createForm(VendorLeadType::class);
        return $this->render('index.html.twig', [
            'form' => $form->createView()
        ]);
    }

}

Twig template

{% extends 'base.html.twig' %}

{% block body %}
{{ form(form) }}
{% endblock %}

Output html

<form name="vendor_lead" method="post">

        <input type="hidden" id="vendor_lead__token" name="vendor_lead[_token]" value="...">

</form>

Any idea what i'm doing wrong?

Body:
First, you have a typo in your VendorLeadType script. You need to fix the spelling of `public function buildForm'.

To get the form variables to come to your controller, you'll need to tell symfony to not expect any form variables to map to an entity by adding 'mapped' => false, to your parameters:

    $builder
        ->add('email', EmailType::class, [
            'mapped' => false,
            'constraints' => [
                new Email(),
                new Length(['max'=>'100'])
            ]
        ])
        ->add('name', TextType::class, [
            'mapped' => false,
            'constraints' => [
                new NotBlank(),
                new Length(['max'=>'100'])
            ]
        ])
        ->add('phone', TextType::class, [
            'mapped' => false,
            'constraints' => [
                new NotBlank(),
                new Length(['max'=>'100'])
            ]
        ])
    ;


问:
Convert to Swift 3
How do you convert this to Swift 3? I tried but I keep getting errors for animation .fromValue and animation.toValue (it's only those 2 lines i need)</p>

```<code>extension UIView {

    func shake() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true

        // This line produces error
        animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 10, self.center.y))
        // And this line produces error
        animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 10, self.center.y))

        self.layer.addAnimation(animation, forKey: "position")
    }
}
</code>```

答:
Wow. It took some time to let the compiler not complain, but here's your first line, correctly done:

```<code>animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y))
</code>```

I'm saying "wow" because compared to your Swift 2 line:

```<code>animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 10, self.center.y))
</code>```

You are basically stuck between two things between Swift 2 and Swift 3:

CGPointMake is now simply CGPoint. This is very minor, and I'd think you'd have found it.

NSValue uses the Swift 3 syntax of cgPoint, but then *defining the point means using CGPoint.

This builds. But only after a few tries, and letting Xcode complain. I'm amazed that the upgrade to current syntax didn't catch this - but maybe because there were two issues to upgrade.

You can use it for your second build error. If that's all that's wrong - syntax - then I believe you are good to go.

Title: Convert to Swift 3

Body:
How do you convert this to Swift 3? I tried but I keep getting errors for animation .fromValue and animation.toValue (it's only those 2 lines i need)

extension UIView {

    func shake() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true

        // This line produces error
        animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 10, self.center.y))
        // And this line produces error
        animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 10, self.center.y))

        self.layer.addAnimation(animation, forKey: "position")
    }
}

Body:
Wow. It took some time to let the compiler not complain, but here's your first line, correctly done:

animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y))

I'm saying "wow" because compared to your Swift 2 line:

animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 10, self.center.y))

You are basically stuck between two things between Swift 2 and Swift 3:

CGPointMake is now simply CGPoint. This is very minor, and I'd think you'd have found it.

NSValue uses the Swift 3 syntax of cgPoint, but then *defining the point means using CGPoint.

This builds. But only after a few tries, and letting Xcode complain. I'm amazed that the upgrade to current syntax didn't catch this - but maybe because there were two issues to upgrade.

You can use it for your second build error. If that's all that's wrong - syntax - then I believe you are good to go.


问:
ER diagram, is this allowed?
I have to create an ER diagram based on a relational schema.

There is a table of players, and a table of zones. A player can 'live' in many zones, and each zone is owned by one or more players.

I've come up with this simple ER diagram but I'm not sure having relationships going each way is allowed?

Cheers

答: Since there's a many-to-many relationship between [Players] and [Zones] you have to add a junction table (called for ex. [PlayersZones]). The notation itself is correct (Chen notation), though I prefer the Crow's Foot Notation.</p>

Title: ER diagram, is this allowed?


问:
puma gem - Failed to build gem native extension
I was getting the following error while installing puma gem</p>

```
    $ gem install puma
    Fetching: puma-2.11.2.gem (100%)
    Building native extensions.  This could take a while...
    ERROR:  Error installing puma:
    ERROR: Failed to build gem native extension.

    ruby extconf.rb
    checking for BIO_read() in -lcrypto... no
    checking for BIO_read() in -llibeay32... no
    *** extconf.rb failed ***
```

答:
I'm on OS X 10.12.4 and the comment @mahi added worked for me:</p>

```<code>gem install puma -v '3.6.0' -- --with-opt-dir=/usr/local/opt/openssl
</code>```

Body:
I was getting the following error while installing puma gem

    $ gem install puma
    Fetching: puma-2.11.2.gem (100%)
    Building native extensions.  This could take a while...
    ERROR:  Error installing puma:
    ERROR: Failed to build gem native extension.

    ruby extconf.rb
    checking for BIO_read() in -lcrypto... no
    checking for BIO_read() in -llibeay32... no
    *** extconf.rb failed ***

Body:
I'm on OS X 10.12.4 and the comment @mahi added worked for me:

gem install puma -v '3.6.0' -- --with-opt-dir=/usr/local/opt/openssl


问:
React Native OneSignal IOS alert issue
I'm using onesignal-react-native for my react native app. However, I have an issue with alert on ios app. I don't know how to turn the alert off so that it doesn't show up when the users in app. How can I turn it off ?</p>

答:
For anyone looking into this in the future you will need to add this to your AppDelegate.m

```<code>self.oneSignal = [[RCTOneSignal alloc] initWithLaunchOptions:launchOptions
                                                     appId:@"app-id"
                                                  settings:@{kOSSettingsKeyInFocusDisplayOption : @(OSNotificationDisplayTypeNotification),kOSSettingsKeyAutoPrompt : @YES}];
</code>```

For android just add

```<code>OneSignal.inFocusDisplaying(0);
</code>```

Hope it helps.

Title: React Native OneSignal IOS alert issue

Body:
For anyone looking into this in the future you will need to add this to your AppDelegate.m

self.oneSignal = [[RCTOneSignal alloc] initWithLaunchOptions:launchOptions
                                                     appId:@"app-id"
                                                  settings:@{kOSSettingsKeyInFocusDisplayOption : @(OSNotificationDisplayTypeNotification),kOSSettingsKeyAutoPrompt : @YES}];

For android just add

OneSignal.inFocusDisplaying(0);

Hope it helps.


问:
Footer content not showing in mobile view
still very new to this so apologies in advance.

In my footer, the desktop view works fine. As does the landscape mobile view. Heres how it looks on  those two views

Landscape views

But in mobile portrait, the social media icons are missing, where have i gone wrong?

Portrait View

HTML code for my footer

```<code><footer class="nav navbar-fixed-bottom navbar-default">
                <div class="container-fluid">
                    <p>© 2017 Example Example</p>
                    <ul>
                        <li><a href=""><span class="fa fa-twitter"></span></a></li>
                        <li><a href=""><span class="fa fa-facebook"></span></a></li>
                        <li><a href=""><span class="fa fa-instagram"></span></a></li>
                        <li><a href=""><span class="fa fa-snapchat"></span></a></li>
                        <li><a href=""><span class="fa fa-youtube"></span></a></li>
                    </ul>
                </div>
            </footer>
</code>```

CSS for footer styling

```<code>footer {
    background-color: #000000;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
}

footer p {
    float: left;
    text-align: center;
    margin-top: 15px;
}

footer ul {
    list-style: none;
    display: flex;
    flex: 1;
    flex-direction: row;
    float: right;
    font-size:35px;
    margin-top: 2px;
}

.fa-twitter {
    margin-right:10px;
    color: #fff;
}

.fa-twitter:hover{
    color: #00aced;
}

.fa-facebook {
    margin-right:10px;
    color: #fff;
}

.fa-facebook:hover{
    color: #3b5998;
}

.fa-instagram {
    margin-right:10px;
    color: #fff;
}

.fa-instagram:hover{

    background-image: linear-gradient(45deg, #fccc63, #fbad50, #e95950, #cd486b, #8a3ab9, #4c68d7);
    color: transparent;
    background-clip: text;
    -webkit-background-clip: text;
}

.fa-snapchat {
    margin-right:10px;
    color: #fff;
}

.fa-snapchat:hover{
    color: #fffc00;
}

.fa-youtube {
    margin-right:5px;
    color: #fff;
}

.fa-youtube:hover{
    color: #cb2027;
}
</code>```

Any help would be appreciated!

答:
You might want to try putting body tags around everything like

        <!DOCTYPE html>

          <title></title>

        .
        .
        .

        .
        .
        .

        ```

This might help.

Another method you might want to look at is using flexbox for you unordered list
as described here: [1]: Flexbox with Unordered list
Charles

Body:
still very new to this so apologies in advance.

In my footer, the desktop view works fine. As does the landscape mobile view. Heres how it looks on  those two views

Landscape views

But in mobile portrait, the social media icons are missing, where have i gone wrong?

Portrait View

HTML code for my footer

© 2017 Example Example

CSS for footer styling

footer {
    background-color: #000000;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
}

footer p {
    float: left;
    text-align: center;
    margin-top: 15px;
}

footer ul {
    list-style: none;
    display: flex;
    flex: 1;
    flex-direction: row;
    float: right;
    font-size:35px;
    margin-top: 2px;
}

.fa-twitter {
    margin-right:10px;
    color: #fff;
}

.fa-twitter:hover{
    color: #00aced;
}

.fa-facebook {
    margin-right:10px;
    color: #fff;
}

.fa-facebook:hover{
    color: #3b5998;
}

.fa-instagram {
    margin-right:10px;
    color: #fff;
}

.fa-instagram:hover{

    background-image: linear-gradient(45deg, #fccc63, #fbad50, #e95950, #cd486b, #8a3ab9, #4c68d7);
    color: transparent;
    background-clip: text;
    -webkit-background-clip: text;
}

.fa-snapchat {
    margin-right:10px;
    color: #fff;
}

.fa-snapchat:hover{
    color: #fffc00;
}

.fa-youtube {
    margin-right:5px;
    color: #fff;
}

.fa-youtube:hover{
    color: #cb2027;
}

Any help would be appreciated!

Body:
You might want to try putting body tags around everything like

        <!DOCTYPE html>
        <html lang="en">
        <head>
          <title></title>
        </head>
        <body class="works_on_smartphone">
        .
        .
        .
        <footer>
        .
        .
        .
        </footer>
        </body>
        </html>

This might help.

Another method you might want to look at is using flexbox for you unordered list
as described here: [1]: Flexbox with Unordered list
Charles


问:
Expression Must have a Class type (operator)
I have an operator which receives the address of an unmodifiable character string. I'm trying to compare the size of the received address to the Items sku. If they are the same I return true, if not false. I'm getting an error on c.size() that says the expression must have a class type and I'm not sure why

```<code>char Item::operator==(const char* c)
{
    if (this->get_sku.size() == c.size()) //Error
    {
       return true;
    }
    else
    {
       return false;
    }
}
</code>```

//getter function

```<code>char Item::get_sku() const
{
    return *m_sku;
}
</code>```

答:
I'm not sure what you are trying to achieve.  But since get_sku returns a single char it makes not an awful lot of sense to query its length or compare it to a char* in any way.  The following compiles but I'm not sure what your exact problem is.

```<code>class Item
{
public:
  bool operator==(char c) const;
  char get_sku() const;
private:
  char * m_sku;
};

bool Item::operator==(char c) const
{
  return this->get_sku() == c;
}

char Item::get_sku() const
{
  return *m_sku;
}
</code>```

Body:
I have an operator which receives the address of an unmodifiable character string. I'm trying to compare the size of the received address to the Items sku. If they are the same I return true, if not false. I'm getting an error on c.size() that says the expression must have a class type and I'm not sure why

char Item::operator==(const char* c)
{
    if (this->get_sku.size() == c.size()) //Error
    {
       return true;
    }
    else
    {
       return false;
    }
}

//getter function

char Item::get_sku() const
{
    return *m_sku;
}

Body:
I'm not sure what you are trying to achieve.  But since get_sku returns a single char it makes not an awful lot of sense to query its length or compare it to a char* in any way.  The following compiles but I'm not sure what your exact problem is.

class Item
{
public:
  bool operator==(char c) const;
  char get_sku() const;
private:
  char * m_sku;
};

bool Item::operator==(char c) const
{
  return this->get_sku() == c;
}

char Item::get_sku() const
{
  return *m_sku;
}


问:
Error in printing AST ANTLR C# grammar: The command ""C:\Program Files\Java\jre6\bin\java" …" exited with code 3
I added output=AST; to the grammar options at the top of cs.g to print out the tree.

```<code>options
{language = 'CSharp2';
output=AST;
}
</code>```

When I build up the project after the change I got this message:

The command ""C:\Program Files\Java\jre6\bin\java" -cp "C:\Program Files\Java\jre6\lib\antlr-3.3.jar" org.antlr.Tool -message-format vs2005 cs.g  -make  -Xconversiontimeout 2500 -Xmultithreaded" exited with code 3. C:\Users\AMD\Desktop\Complier\antlrcsharp100620\UnitTest\UnitTest.csproj 68 24 UnitTest

Am I missing something here?

答:
You need to modify the following lines in UnitTest.csproj:

```<code><JavaDir>C:\Program Files\Java\jre6\bin\java</JavaDir>
<JarDir>C:\Program Files\Java\jre6\lib</JarDir>
</code>```

to

```<code><JavaDir>path to java.exe</JavaDir>
<JarDir>C:\users\amd\desktop\compiler\antlrcsharp100620\browse\browse\Antlr.Runtime\CSharp2</JarDir>
</code>```

The JavaDir path needs point to the location of "java.exe".  Mine was "C:\Program Files (x86)\Java\jre6\bin\"

The JarDir needs to have the path to the "antlr-3.3.jar" file.  I set the path from your error message above.

Body:
I added output=AST; to the grammar options at the top of cs.g to print out the tree.

options
{language = 'CSharp2';
output=AST;
}

When I build up the project after the change I got this message:

The command ""C:\Program Files\Java\jre6\bin\java" -cp "C:\Program Files\Java\jre6\lib\antlr-3.3.jar" org.antlr.Tool -message-format vs2005 cs.g  -make  -Xconversiontimeout 2500 -Xmultithreaded" exited with code 3. C:\Users\AMD\Desktop\Complier\antlrcsharp100620\UnitTest\UnitTest.csproj 68 24 UnitTest

Am I missing something here?

Body:
You need to modify the following lines in UnitTest.csproj:

<JavaDir>C:\Program Files\Java\jre6\bin\java</JavaDir>
<JarDir>C:\Program Files\Java\jre6\lib</JarDir>

to

<JavaDir>path to java.exe</JavaDir>
<JarDir>C:\users\amd\desktop\compiler\antlrcsharp100620\browse\browse\Antlr.Runtime\CSharp2</JarDir>

The JavaDir path needs point to the location of "java.exe".  Mine was "C:\Program Files (x86)\Java\jre6\bin\"

The JarDir needs to have the path to the "antlr-3.3.jar" file.  I set the path from your error message above.


问:
Apigility GET collection returns only 10 results when content negotiation is set to JSON
This issue is bugging me for some time now. To test it I just installed a fresh Apigility, set the db (PDO:mysql) and added a DB-Connected service. In the table I have 40+ records. When I make a GET collection request  the response looks OK (with the default HAL content negotiation). Then I change the content negotiation to JSON. Now when I make a GET collection request my response contains only 10 elements.

So my question is: where do I set/change this limit?

答:
This is not an ideal fix, because it requires you to go into the source code rather than using the page size given in the UI.

The collection class that is auto generated for you by the DB-Connected style derives off of Zend/Paginator/Paginator.  This class defines the $defaultItemCountPerPage static protected member which is defaulted to 10.  That's why you're only getting 10 results.  If you open up the auto-generated collection class for your entity and add: protected static $defaultItemCountPerPage = 100; in the otherwise empty class, you will see that you now get up to 100 results in the response.  You can look at other Paginator class variables and methods that you could replace in your derived class to get your desired behavior.

This is not an ideal solution.  I'd prefer that the generated code automatically used the same configed page size that the HalJson strategy uses.  Maybe I'll contribute a PR to change that.  Or, maybe I'll just use the HalJson approach.  It does seem like the better way to go.  You should have some limit to how much data you load in from the DB at a time to not have an overly long running query or an overly large collection of data coming back you have to deal with.  And, whatever limit you set, what do you do when you hit that limit?  With the simple Json method, you can't ever get "page 2" of data.  So, if you are going to work with some sizeable amount of data, it might be better to use HalJson on and then have some logic on the client side to grab pages of data at a time as needed.  The returned JSON structure is a little more complicated, but not terribly so.

I'm probably in the same spot you are -- I'm trying to do a simple little api to play with while keeping everything simple and so I didn't want the client to have to deal with the other stuff in HalJson, but probably better to deal with that complexity and have a smooth way to page through data if you're going to use this with some real set of data.  At least, that's the pep talk I'm giving myself right now. :-)


问:
Strange Output while combining files
For the output, I want a list with each index containing a number and a letter combined from two different files such as B2. Instead, when I run my program I get output listing each files values on a different line. One of the input files is a simple list of numbers and the other is a list of letters. Based on my code, I am hoping to get some help. Thanks in advance!</p>

```<code>def combine():
    mylist = []
    galaxy = open("galaxies.rtf","r")
    print("Reading from galaxies.txt...")
    for line in galaxy:
        gline = galaxy.read()
    cycle = open("cycles.rtf","r")
    print("Reading from cycle.txt...")
    for line in cycle:
        cline = cycle.read()
    print("Combining values...")
    string = gline + cline
    mylist.append(string)
    galaxy.close()
    cycle.close()
    return mylist
combine()

# the main function calls combine() to read the data from files
# then displays a formatted table with the combined values
def main():
#Print a header at start of main() function
    print("Report of BOOYA Radio Galaxy Observations\n")
 # Call the combine() function, returned list saved as radioData
    radioData = combine()
# Loop through the radioData list printing 5 columns of values
    for j in range(0,len(radioData),5):
        for k in range(0,5):
            print(radioData[j+k],end="\t")
        print()
main()
</code>```

答:
You have several problems. For instance, this

```<code>for line in galaxy:
    gline = galaxy.read()
</code>```

reads one line from galaxy and puts it in line, then reads the rest of the file to its end and puts it in gline. On the second round, the file has no more content so the for exits.

You can do the work a different ways. Files iterate lines including the \n. zip takes multiple iterators and combines them into tuples. You can use that to iterate the lines from both files, strip the line endings and add them together.

```<code>>>> with open('galaxies.rtf') as f1, open('cycles.rtf') as f2:
...     mylist = list((l1.strip() + l2.strip() for l1, l2 in zip(f1, f2)))
...
>>> mylist
['A1', 'B2', 'C3', 'D4', 'E5', 'F6']
</code>```

This may still be a problem because rtf aren't simple text files.

Title: Strange Output while combining files

Body:
For the output, I want a list with each index containing a number and a letter combined from two different files such as B2. Instead, when I run my program I get output listing each files values on a different line. One of the input files is a simple list of numbers and the other is a list of letters. Based on my code, I am hoping to get some help. Thanks in advance!

def combine():
    mylist = []
    galaxy = open("galaxies.rtf","r")
    print("Reading from galaxies.txt...")
    for line in galaxy:
        gline = galaxy.read()
    cycle = open("cycles.rtf","r")
    print("Reading from cycle.txt...")
    for line in cycle:
        cline = cycle.read()
    print("Combining values...")
    string = gline + cline
    mylist.append(string)
    galaxy.close()
    cycle.close()
    return mylist
combine()

# the main function calls combine() to read the data from files
# then displays a formatted table with the combined values
def main():
#Print a header at start of main() function
    print("Report of BOOYA Radio Galaxy Observations\n")
 # Call the combine() function, returned list saved as radioData
    radioData = combine()
# Loop through the radioData list printing 5 columns of values
    for j in range(0,len(radioData),5):
        for k in range(0,5):
            print(radioData[j+k],end="\t")
        print()
main()

Body:
You have several problems. For instance, this

for line in galaxy:
    gline = galaxy.read()

reads one line from galaxy and puts it in line, then reads the rest of the file to its end and puts it in gline. On the second round, the file has no more content so the for exits.

You can do the work a different ways. Files iterate lines including the \n. zip takes multiple iterators and combines them into tuples. You can use that to iterate the lines from both files, strip the line endings and add them together.

>>> with open('galaxies.rtf') as f1, open('cycles.rtf') as f2:
...     mylist = list((l1.strip() + l2.strip() for l1, l2 in zip(f1, f2)))
...
>>> mylist
['A1', 'B2', 'C3', 'D4', 'E5', 'F6']

This may still be a problem because rtf aren't simple text files.


问:
Order of serialized fields using JSON.NET
Is there a way to specify the order of fields in a serialized JSON object using JSON.NET?

It would be sufficient to specify that a single field always appear first.

答:
As Charlie noted, you can somewhat control the ordering of the JSON properties by ordering the properties in the class itself. Unfortunately, this approach doesn't work for properties inherited from a base class. The base class properties will be ordered as they are laid out in code, but will appear before the base class properties.

And for anyone wondering why you might want to alphabetize JSON properties, it's a whole lot easier to work with raw JSON files, particularly for classes with lots of properties, if they are ordered.


问:
bash vs csh vs others - which is better for application maintenance?

Possible Duplicate:

  What Linux shell should I use?

I am starting to get proficient in a Linux environment and i'm trying to pick a weapon of choice in terms of command shell scripting (as i'm still a big n00b at this) that will help me (and others) manage, test and administer a set of server side applications running on a *NIX environment.

My question is: What is(are) the preferred command shell(s)  out there when the following criteria are considered:

How easy is it to learn/understand for a junior dev who has never had an exposure to shell scripting?

Is there a big pool of developers out there that know this shell script?

Is it safe and easy to use - will script errors be silent or give intelligent error output, will it let the uninitiated shoot them selves in the foot?

How portable is it? - Can i expect the same script to run in OpenSolaris as well as Redhat, FreeBSD? (granted command syntax and options for specific OS will change accordingly)

How standard is it? Is it expected to be included on most distro's of *NIX or does it have to be installed additionally?

I understand that there are camps out there who hold strong feelings for/against specific command shells, i am just looking for an informed opinion.

答: csh is almost always wrong.</p>

Body: csh is almost always wrong.


问:
PHP throwing "Use of Undefined Constant" Despite Quotes in String
I have a PHP file wherein I'm trying to set a cookie; here is the code:

```<code><?php
ini_set('display_errors', 1);
error_reporting(~0);
$coname = ‘logged’;
$coval = ‘false’;
setcookie($coname,$coval);
?>
</code>```

Logged is the name of the cookie, false is the value. Right off the bat it's throwing:

Notice: Use of undefined constant ‘logged’ - assumed '‘logged’' in (path) on line 4

  Notice: Use of undefined constant ‘false’ - assumed '‘false’' in (path) on line 5

It appears to be reading these strings as constants, then. Every resource I can find recommends solving this by enclosing the string in quotes, which I've tried with both single and double quotes to no avail. If anyone knows why the error persists, it would be a huge help. Thanks!

答:
You're using back- and forward-ticks instead of single quotation marks, so PHP is trying to interpret ‘logged’ and ‘false’ as constants, which aren't defined.

Try this instead:

```<code><?php
ini_set('display_errors', 1);
error_reporting(~0);
$coname = 'logged';
$coval = 'false';
setcookie($coname,$coval);
?>
</code>```

Body:
I have a PHP file wherein I'm trying to set a cookie; here is the code:

<?php
ini_set('display_errors', 1);
error_reporting(~0);
$coname = ‘logged’;
$coval = ‘false’;
setcookie($coname,$coval);
?>

Logged is the name of the cookie, false is the value. Right off the bat it's throwing:

Notice: Use of undefined constant ‘logged’ - assumed '‘logged’' in (path) on line 4

  Notice: Use of undefined constant ‘false’ - assumed '‘false’' in (path) on line 5

It appears to be reading these strings as constants, then. Every resource I can find recommends solving this by enclosing the string in quotes, which I've tried with both single and double quotes to no avail. If anyone knows why the error persists, it would be a huge help. Thanks!

Body:
You're using back- and forward-ticks instead of single quotation marks, so PHP is trying to interpret ‘logged’ and ‘false’ as constants, which aren't defined.

Try this instead:

<?php
ini_set('display_errors', 1);
error_reporting(~0);
$coname = 'logged';
$coval = 'false';
setcookie($coname,$coval);
?>