问:
Problems accessing Connect function value in another Component in a React-Redux App
I've set up Redux in my React app, however I don't get any data passed when I use this.props to access the data in another component in a separate file. My action is being executed and it passes the data I want.
This is my actions.js:

```<code>export const ADD_CART = 'ADD_CART';

export function addCart(item){
    return {
        type: ADD_CART,
        payload: item
    }
};
</code>```

My reducer.js is:

```<code>import {ADD_CART} from './actions';

export default Reducer;

function Reducer(state, action){
    switch(action.type){
        case ADD_CART:
            return {
                ...state,
                cart: action.payload
            }
    };
}
</code>```

My action creator contains cart, which is what I want to pass to the component:

```<code>...
class WebShop extends Component {
    ...

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

   ...

    render() {
        return (
            ..
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
   return {
      cartItem: state.reducer,
   }
}

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);
</code>```

When I try to access cart in another file and component like so:

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

export default class Cart extends Component {
    render() {
        console.log(this.props.cart);
        return(
            <div className= "Webcart" id="Webcart"></div>
        );
    }
}
</code>```

This is my store.js:

```<code>import { createStore, applyMiddleware } from 'redux';
import  reducer  from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';

var initialState = {
  cart:"medium",
  data: [],
  url: "/api/comments",
  pollInterval: 2000
}

const store = createStore(
  reducer,
  applyMiddleware(
    createLogger(),
    thunkMiddleware
  )
);
export default store;
</code>```

My Provider is in my app.js file:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';

import App from 'views/App';
import Home from 'views/Home';
import About from 'views/About';
import Cart from 'views/webcart';

console.log(store);
ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Home } />
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('app') // eslint-disable-line
);
</code>```

After updating my code to use mapStateToProps now I get the error Uncaught TypeError: Cannot read property 'Reducer' of undefined. Why I'm I getting this if Reducer should be accessed by the API?

答:
So I saw your pastebin and your comments and I feel like you are so close especially with @Faaiz answer (so read this answer in line with @Faaiz's store, initialState and reducer response). So lets roll it back:

Say you have two components (WebShop and Cart); and you want to share a global state (cart) with these components. Either of these ways works:

Nested Components of a "Connected Component" - say <Cart /> is a child of <WebShop /> which is connected (via redux connect with mapStateToProps etc.) to the global state. Then within WebShop, you could do something like:

```<code>import { addCart } from './actions';
import { connect } from 'react-redux';
// other imports
class WebShop extends Component {
  ...//
  handleClick() {
    const cart = {price:0,item:"userselection",size:this.state.value};
    this.props.onCartAdd(cart);
  }
  render() {
    return (
      ...//
      <Cart cart={this.props.cart} />
    )
  }
}
// for completeness I brought the mapStateToProps
function mapStateToProps(state) {
  return { cart: state.cart };
}

const mapDispatchToProps = (dispatch) => {
  return {
    onCartAdd: (item) => {
      dispatch(addCart(item));
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(WebShop);
</code>```

and in your cart.js file, you could do:

```<code>    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }
</code>```

Two separately "Connected Component"s - which means connect both components (via redux connect with mapStateToProps etc.) to the global state. So both your cart and webshop will be similar in this respect like so:

```<code>class WebShop extends Component {
  ...//
  render() {
    console.log("cart", this.props.cart)
    return (
      ...// Other stuffs
    )
  }
}
// for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
function mapStateToProps(state) {
  return { cart: state.cart };
}
export default connect(mapStateToProps, mapDispatchToProps)(WebShop);
</code>```

and cart.js file would look like so:

```<code>    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }
    // for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
    function mapStateToProps(state) {
      return { cart: state.cart };
    }
    export default connect(mapStateToProps, mapDispatchToProps)(Cart);
</code>```

NOTE
I would rather set up your addCart action to be addItemToCart and your global state cart will now be an array of items. Your reducer.js would look similar to:

```<code>const initialState = {
  cart: [],
  data: [],
  url: "/api/comments",
  pollInterval: 2000
};

function Reducer(state = initialState, action){
  switch(action.type){
    case ADD_CART:
      return {
          ...state,
          cart: state.cart.push(action.payload)
      };
    default:
      return state;
  };
}
</code>```

and your handleClick() would look like

```<code>handleClick() {
  const item = {price:0,item:"userselection",size:this.state.value};
  this.props.onCartAdd(item);
}
</code>```

But feel free to go with your use case, my opinion may be totally off.

Hope it helps.

Body:
I've set up Redux in my React app, however I don't get any data passed when I use this.props to access the data in another component in a separate file. My action is being executed and it passes the data I want.
This is my actions.js:

export const ADD_CART = 'ADD_CART';

export function addCart(item){
    return {
        type: ADD_CART,
        payload: item
    }
};

My reducer.js is:

import {ADD_CART} from './actions';

export default Reducer;

function Reducer(state, action){
    switch(action.type){
        case ADD_CART:
            return {
                ...state,
                cart: action.payload
            }
    };
}

My action creator contains cart, which is what I want to pass to the component:

...
class WebShop extends Component {
    ...

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

   ...

    render() {
        return (
            ..
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
   return {
      cartItem: state.reducer,
   }
}

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);

When I try to access cart in another file and component like so:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default class Cart extends Component {
    render() {
        console.log(this.props.cart);
        return(

        );
    }
}

This is my store.js:

import { createStore, applyMiddleware } from 'redux';
import  reducer  from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';

var initialState = {
  cart:"medium",
  data: [],
  url: "/api/comments",
  pollInterval: 2000
}

const store = createStore(
  reducer,
  applyMiddleware(
    createLogger(),
    thunkMiddleware
  )
);
export default store;

My Provider is in my app.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';

import App from 'views/App';
import Home from 'views/Home';
import About from 'views/About';
import Cart from 'views/webcart';

console.log(store);
ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Home } />
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('app') // eslint-disable-line
);

After updating my code to use mapStateToProps now I get the error Uncaught TypeError: Cannot read property 'Reducer' of undefined. Why I'm I getting this if Reducer should be accessed by the API?

Body:
So I saw your pastebin and your comments and I feel like you are so close especially with @Faaiz answer (so read this answer in line with @Faaiz's store, initialState and reducer response). So lets roll it back:

Say you have two components (WebShop and Cart); and you want to share a global state (cart) with these components. Either of these ways works:

Nested Components of a "Connected Component" - say <Cart /> is a child of <WebShop /> which is connected (via redux connect with mapStateToProps etc.) to the global state. Then within WebShop, you could do something like:

import { addCart } from './actions';
import { connect } from 'react-redux';
// other imports
class WebShop extends Component {
  ...//
  handleClick() {
    const cart = {price:0,item:"userselection",size:this.state.value};
    this.props.onCartAdd(cart);
  }
  render() {
    return (
      ...//
      <Cart cart={this.props.cart} />
    )
  }
}
// for completeness I brought the mapStateToProps
function mapStateToProps(state) {
  return { cart: state.cart };
}

const mapDispatchToProps = (dispatch) => {
  return {
    onCartAdd: (item) => {
      dispatch(addCart(item));
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(WebShop);

and in your cart.js file, you could do:

    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }

Two separately "Connected Component"s - which means connect both components (via redux connect with mapStateToProps etc.) to the global state. So both your cart and webshop will be similar in this respect like so:

class WebShop extends Component {
  ...//
  render() {
    console.log("cart", this.props.cart)
    return (
      ...// Other stuffs
    )
  }
}
// for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
function mapStateToProps(state) {
  return { cart: state.cart };
}
export default connect(mapStateToProps, mapDispatchToProps)(WebShop);

and cart.js file would look like so:

    class Cart extends Component {
      ...//
      render() {
        console.log("cart", this.props.cart)
        return (
          ...//
        )
      }
    }
    // for completeness I brought the mapStateToProps, you should include the mapDispatchToProps
    function mapStateToProps(state) {
      return { cart: state.cart };
    }
    export default connect(mapStateToProps, mapDispatchToProps)(Cart);

NOTE
I would rather set up your addCart action to be addItemToCart and your global state cart will now be an array of items. Your reducer.js would look similar to:

const initialState = {
  cart: [],
  data: [],
  url: "/api/comments",
  pollInterval: 2000
};

function Reducer(state = initialState, action){
  switch(action.type){
    case ADD_CART:
      return {
          ...state,
          cart: state.cart.push(action.payload)
      };
    default:
      return state;
  };
}

and your handleClick() would look like

handleClick() {
  const item = {price:0,item:"userselection",size:this.state.value};
  this.props.onCartAdd(item);
}

But feel free to go with your use case, my opinion may be totally off.

Hope it helps.


来源: stackexchange

问:
Adding :default => true to boolean in existing Rails column
I've seen a few questions (namely this one) here on SO about adding a default boolean value to an existing column. So I tried the change_column suggestion but I mustn't be doing it right.

I tried:

```<code>$ change_column :profiles, :show_attribute, :boolean, :default => true
</code>```

Which returns -bash: change_column: command not found

I then ran:

```<code>$ rails g change_column :profiles, :show_attribute, :boolean, :default => true
</code>```

...and

```<code>$ rails change_column :profiles, :show_attribute, :boolean, :default => true
</code>```

Then ran rake db:migrate, but the value for :show_attribute remained nil. In the question I referenced above it says in PostgreSQL you need to update it manually. Since I'm using PostgreSQL I added the following in my create_profiles migration:

```<code>t.boolean :show_attribute, :default => true
</code>```

Can someone tell me what I'm doing wrong here?

答:
```<code>change_column :things, :price_1, :integer, default: 123, null: false
</code>```

Seems to be best way to add a default to an existing column that doesn't have null: false already.

Otherwise:

```<code>change_column :things, :price_1, :integer, default: 123
</code>```

Some research I did on this:

https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b

ContentLicense: CC BY-SA 3.0

Body:
I've seen a few questions (namely this one) here on SO about adding a default boolean value to an existing column. So I tried the change_column suggestion but I mustn't be doing it right.

I tried:

$ change_column :profiles, :show_attribute, :boolean, :default => true

Which returns -bash: change_column: command not found

I then ran:

$ rails g change_column :profiles, :show_attribute, :boolean, :default => true

...and

$ rails change_column :profiles, :show_attribute, :boolean, :default => true

Then ran rake db:migrate, but the value for :show_attribute remained nil. In the question I referenced above it says in PostgreSQL you need to update it manually. Since I'm using PostgreSQL I added the following in my create_profiles migration:

t.boolean :show_attribute, :default => true

Can someone tell me what I'm doing wrong here?

Body:
change_column :things, :price_1, :integer, default: 123, null: false

Seems to be best way to add a default to an existing column that doesn't have null: false already.

Otherwise:

change_column :things, :price_1, :integer, default: 123

Some research I did on this:

https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b


问:
Sending multiple values from servlet to jsp
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);</p>

```<code>String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);
</code>```

答:
response.sendRedirect() will clear the buffer, which apparently means any request attributes previously set will not be retained.

In your case, I believe, its better to use RequestDispatcher.forward(), after setting your desired attributes in request object.

NB:By convention you must define your variable names starting with a small letter. For example, String user;, instead of String User;. Second, the method names should not use underscores. Further, I would suggest self-explanatory names. Below is your snippet with a little renaming.

```<code>String userNamesStr =t.userNamesSpaceDelimited();
String[] userNameArr = userNamesStr.trim().split(" "); // Or userNames, but we usually follow this for List
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);

String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);

Body:
response.sendRedirect() will clear the buffer, which apparently means any request attributes previously set will not be retained.

In your case, I believe, its better to use RequestDispatcher.forward(), after setting your desired attributes in request object.

NB:By convention you must define your variable names starting with a small letter. For example, String user;, instead of String User;. Second, the method names should not use underscores. Further, I would suggest self-explanatory names. Below is your snippet with a little renaming.

String userNamesStr =t.userNamesSpaceDelimited();
String[] userNameArr = userNamesStr.trim().split(" "); // Or userNames, but we usually follow this for List


问:
How to fprintf on file with recursive
I'm a newbie with recursion.  How do I fopen and fclose a file in a recursive function?

```<code>void make(LINK lis, char *name, int flag, FILE *f)
{
    if (lis == NULL) {
        fclose(f);
    }
    else {
        if (flag == 0) {
            FILE *f = fopen(name, "w");
            flag = 1;
        }
        else {
            fprintf(f, "CODICE: %d\n", lis->d.codice);
            make(lis->next, name, 1, f);
        }
    }
}
</code>```

My goal is to recursively write "codice" --> CODE in a file.

答:
Your most immediate problem is that on the first call, you open the file and then return to the main program, without processing anything.  Opening the file should be a simple test, not an if-then-else.

```<code>void make(LINK lis, char *name, FILE *f)
{
    if (!lis) {
        fclose(f);
    }
    else {
        if (f) {
            f = fopen(name, "w");
            }
        fprintf(f, "CODICE: %d\n", lis->d.codice);
        make(lis->next, name, f);
        }
    }
}
</code>```

Title: How to fprintf on file with recursive

Body:
I'm a newbie with recursion.  How do I fopen and fclose a file in a recursive function?

void make(LINK lis, char *name, int flag, FILE *f)
{
    if (lis == NULL) {
        fclose(f);
    }
    else {
        if (flag == 0) {
            FILE *f = fopen(name, "w");
            flag = 1;
        }
        else {
            fprintf(f, "CODICE: %d\n", lis->d.codice);
            make(lis->next, name, 1, f);
        }
    }
}

My goal is to recursively write "codice" --> CODE in a file.

Body:
Your most immediate problem is that on the first call, you open the file and then return to the main program, without processing anything.  Opening the file should be a simple test, not an if-then-else.

void make(LINK lis, char *name, FILE *f)
{
    if (!lis) {
        fclose(f);
    }
    else {
        if (f) {
            f = fopen(name, "w");
            }
        fprintf(f, "CODICE: %d\n", lis->d.codice);
        make(lis->next, name, f);
        }
    }
}


问:
JUNOS PYEZ: Over write the Base config of a Device in SET command
I am writing the below code to push the base config to my device.
But it is merging the lines and not over writing.

Merging is still keeping the not required lines of Base config which is a problem to me

My config is in set command format .
Can some one help me achieve the over write option.
Can some one tell me how to convert my set formats to .xml formats so that over write function could be used.

/usr/bin/python

-- coding: utf-8 -

```<code>from jnpr.junos import Device
from jnpr.junos.utils.config import Config

dev = Device(host='host', port='22', user='maint', password='jnpr16',
         gather_facts=False)

dev.open()
cu = Config(dev)
data ="""set version 14.2R5-S1.2
set groups re0 system host-name host
set groups re0 interfaces fxp0 unit 0 family inet address 10.202.64/24
master-only
set groups CUST-NAT-POOL-TEMPLATE services nat pool <*> snmp-trap-
thresholds"""

cu.load(data)
if cu.commit_check():
cu.commit()
else:
cu.rollback()
</code>```

答: If you manually enter your set statements into the CLI's configuration mode, you can then use the "show" command to see the equivalent configuration in text format or "show | display xml" to see the equivalent configuration in XML format.</p>

Body:
I am writing the below code to push the base config to my device.
But it is merging the lines and not over writing.

Merging is still keeping the not required lines of Base config which is a problem to me

My config is in set command format .
Can some one help me achieve the over write option.
Can some one tell me how to convert my set formats to .xml formats so that over write function could be used.

/usr/bin/python

-- coding: utf-8 -

from jnpr.junos import Device
from jnpr.junos.utils.config import Config

dev = Device(host='host', port='22', user='maint', password='jnpr16',
         gather_facts=False)

dev.open()
cu = Config(dev)
data ="""set version 14.2R5-S1.2
set groups re0 system host-name host
set groups re0 interfaces fxp0 unit 0 family inet address 10.202.64/24
master-only
set groups CUST-NAT-POOL-TEMPLATE services nat pool <*> snmp-trap-
thresholds"""

cu.load(data)
if cu.commit_check():
cu.commit()
else:
cu.rollback()


问:
c++ how to initialize const elements of an array
i need a way to initialize const elements of an array for the program i am currently working on.
The problem is that i have to initialize these elements with a function, there is no way to do it like this:

```<code>const int array[255] = {1, 1278632, 188, ...};
</code>```

because its alot of data i have to generate.
What i tried is to memcpy data to the const int's but that can't work and hasn't worked.

```<code> const int array[255];

 void generateData(){
      for(int i = 0; i < 255; i++) {
          initializeSomehowTo(5, array[i]);
      }
 }
</code>```

I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it.

答:
You can create a writable array, initialize it, and, then, create a const reference to it.</p>

```<code>int arry[255];

void generateData(){
  for(int i = 0; i < 255; i++) {
      initializeSomehowTo(5, arry[i]);
  }
}

const int (&array)[255] = arry;
</code>```

Body:
i need a way to initialize const elements of an array for the program i am currently working on.
The problem is that i have to initialize these elements with a function, there is no way to do it like this:

const int array[255] = {1, 1278632, 188, ...};

because its alot of data i have to generate.
What i tried is to memcpy data to the const int's but that can't work and hasn't worked.

 const int array[255];

 void generateData(){
      for(int i = 0; i < 255; i++) {
          initializeSomehowTo(5, array[i]);
      }
 }

I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it.

Body:
You can create a writable array, initialize it, and, then, create a const reference to it.

int arry[255];

void generateData(){
  for(int i = 0; i < 255; i++) {
      initializeSomehowTo(5, arry[i]);
  }
}

const int (&array)[255] = arry;


问:
manage all Bizspark subscription
I benefited from a  Bizspark subscription I created 5 other subscriptions my question how can i manage all resources in one account

example

I want to create VM1 in account 1 and other VM2 in account 2 after that i want to manage VM1 and VM2 in one account somthing like load balancing

答:
I see two ways to do this:
1. Share Acces from account 1 for the account 2
2. Add the subscription from account 1 to the tenant to the account 2</p>

Title: manage all Bizspark subscription


问:
Phantomjs can't load iframe
I'm a newbie, recently started to use phantomjs with casperjs. I want to get info from an iframe but phantomjs fails to load it.

This is my script:

```<code>var casper = require('casper').create({
   verbose: true,
   logLevel: "debug",
   waitTimeout: 20000,
   retryTimeout: 100,
   viewportSize: {
     width: 1920,
     height: 1080
   },
   pageSettings: {
       "userAgent": 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1'
   },
   localToRemoteUrlAccessEnabled: true
});

casper.start();

casper.open('http://www.badboysbarber.ru/online');

casper.waitForSelector('.y-main-container', function() {
   this.echo("Selector appeared.");
});

casper.then(function() {
   this.capture('screen.png');
});

casper.run();
</code>```

So, phantom throws an error (although selector is defined correctly):

```<code>[error] [phantom] Wait timeout of 20000ms expired, exiting.
</code>```

Could somebody help me please? Maybe I'm doing something wrong? Thank you.

答:
An iframe loads a document inside another document. If you want to work with frames and use CasperJS to get data, you will probably need withFrame() in Casper.prototype.

The following script captures the raw HTML content of the first iframe in your main page:

```<code>var casper = require('casper').create({
  viewportSize: {
    width: 1920,
    height: 1080
  },
  pageSettings: {
    'userAgent': 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1'
  },
  localToRemoteUrlAccessEnabled: true
});

casper.start('http://www.badboysbarber.ru/online');

casper.withFrame(0, function () {
  this.echo(this.getHTML()); // HTML code of the first iframe
});

casper.run();
</code>```

Title: Phantomjs can't load iframe

Body:
I'm a newbie, recently started to use phantomjs with casperjs. I want to get info from an iframe but phantomjs fails to load it.

This is my script:

var casper = require('casper').create({
   verbose: true,
   logLevel: "debug",
   waitTimeout: 20000,
   retryTimeout: 100,
   viewportSize: {
     width: 1920,
     height: 1080
   },
   pageSettings: {
       "userAgent": 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1'
   },
   localToRemoteUrlAccessEnabled: true
});

casper.start();

casper.open('http://www.badboysbarber.ru/online');

casper.waitForSelector('.y-main-container', function() {
   this.echo("Selector appeared.");
});

casper.then(function() {
   this.capture('screen.png');
});

casper.run();

So, phantom throws an error (although selector is defined correctly):

[error] [phantom] Wait timeout of 20000ms expired, exiting.

Could somebody help me please? Maybe I'm doing something wrong? Thank you.

Body:
An iframe loads a document inside another document. If you want to work with frames and use CasperJS to get data, you will probably need withFrame() in Casper.prototype.

The following script captures the raw HTML content of the first iframe in your main page:

var casper = require('casper').create({
  viewportSize: {
    width: 1920,
    height: 1080
  },
  pageSettings: {
    'userAgent': 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1'
  },
  localToRemoteUrlAccessEnabled: true
});

casper.start('http://www.badboysbarber.ru/online');

casper.withFrame(0, function () {
  this.echo(this.getHTML()); // HTML code of the first iframe
});

casper.run();


问:
ASP.NET Agility Pack | How to parse a web page. that is taking post parameters?
I want to parse and page that takes POST parameters. like this is my scenario. i have to parse some search results. but the search parameter are sent in post body to that page.

To parse the search result i have to send parameters to that page in POST. how i can do that with agility pack ?

please help me.

答:
Yes, It is possible, you can post parameters using HTML Agility Pack. Have a look on below code.

```<code>BrowserSession b = new BrowserSession();
b.Get("http://www.skyline-eng.com/");
b.FormElements["navigationTypeID"] = rblCategory.SelectedItem.Value;
b.FormElements["navigationSeriesID"] = boxItem.Value;
HtmlDocument docSkyLine = b.Post("http://www.skyline-eng.com/");
</code>```

Here navigationTypeID and navigationSeriesID are the post parameters. Use like this and keep parsing data using the great tool HTMLAgility Pack.

Body:
Yes, It is possible, you can post parameters using HTML Agility Pack. Have a look on below code.

BrowserSession b = new BrowserSession();
b.Get("http://www.skyline-eng.com/");
b.FormElements["navigationTypeID"] = rblCategory.SelectedItem.Value;
b.FormElements["navigationSeriesID"] = boxItem.Value;
HtmlDocument docSkyLine = b.Post("http://www.skyline-eng.com/");

Here navigationTypeID and navigationSeriesID are the post parameters. Use like this and keep parsing data using the great tool HTMLAgility Pack.


问:
Mask some fields when loading hdb in kdb
If there are two instances: a1 and a2, and both connect to the same hdb. I would like a2 connect to the hdb but add some filter. For example, there is a table called elec.

I would like a2 starts with filtering some of the values. If I write codes and let a2 load it when starting, doesn't that load the information to memory? Is there any way I can load it like normal hdb when starting a2 instance?

Basically, the question is how to mask some fields in one table when loading hdb?

答:
It is possible to prevent columns from being returned by select statements be manipulating the table definition in your HDB instance. The below example has a single date paritioned table. We update the definition to a flipped dictionary with only a subset of the columns defined. This however is reversible and will not update the meta of the table in your instance which will still show all columns.</p>

```<code>q)meta trade
c   | t f a
----| -----
date| d
sym | s   p
size| j
px  | f
side| s

q)flip trade
`sym`size`px`side!`trade

q)`trade set flip `sym`size`px!`trade
q)select from trade where date=2017.05.27
date       sym  size px
------------------------------
2017.05.27 APPl 9968 92.79204
2017.05.27 APPl 9788 94.97189
2017.05.27 APPl 9660 27.62907

q)meta trade
c   | t f a
----| -----
date| d
sym | s   p
size| j
px  | f
side| s
</code>```

Body:
It is possible to prevent columns from being returned by select statements be manipulating the table definition in your HDB instance. The below example has a single date paritioned table. We update the definition to a flipped dictionary with only a subset of the columns defined. This however is reversible and will not update the meta of the table in your instance which will still show all columns.

q)meta trade
c   | t f a
----| -----
date| d
sym | s   p
size| j
px  | f
side| s

q)flip trade
`sym`size`px`side!`trade

q)`trade set flip `sym`size`px!`trade
q)select from trade where date=2017.05.27
date       sym  size px
------------------------------
2017.05.27 APPl 9968 92.79204
2017.05.27 APPl 9788 94.97189
2017.05.27 APPl 9660 27.62907

q)meta trade
c   | t f a
----| -----
date| d
sym | s   p
size| j
px  | f
side| s


问:
What free Delphi component can you recommend for reading an email and an attachment?
What free Delphi component can you recommend for reading an email and an attachment?

I mean reading an email from pop3 server.

I use Delphi 7.

Thank you.

答:
Try Synapse from Lukas Gebauer. Actually it's not a component, it's just a set of units, which you simply add to your uses list. It's simple, stable and verified by many users.
Check these links ...

Synapse - download page
Synapse - tutorials page
Synapse - POP3 simple example


问:
Can I use multiple H1 tags in bootstrap carousel
I am not able to decide how to structure my HTML document and how to place heading tags

Following is my page structure

```<code><html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <nav>
            //Logo and navigation using bootstrap code - site wide
        </nav>
    </header>
    <div>
        //bootstrap carouse
        <div>
            .....
            .....
            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">
                <div class="item active" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 1</h1>
                        <span>Brief description</span>
                    </div>
                </div>
                <div class="item" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 2</h1>
                        <span>Brief description</span>
                    </div>
                </div>
                <div class="item" style="background-image: url('assets/ssp365.jpg')">
                    <div class="carousel-caption">
                        <h1>Heading for slide 3</h1>
                        <span>Brief description</span>
                    </div>
                </div>
            </div>
            ......
            ......

            //rest of the content
        </div>
    </div>
    <footer>
        //page footer - site wide
    </footer>
</body>
</html>
</code>```

I want to know if I can use H1's the way I have used within the bootstrap carousel caption.

I always find it difficult to decide where to place H1 tag when there is a carousel used at the top of the home page and there is no real heading to describe the page. Also, normally a home page tries to cover a lot of content about the entire website so it becomes difficult to structure the page.

Please help.

答: Yes, you can use multiple H1 tags in a page or document. The purpose of an H1 is to be the main header of a part of the page that is (thematically/semantically) independent from other similar parts/sections of the page.

Body:
I am not able to decide how to structure my HTML document and how to place heading tags

Following is my page structure

    <link rel="stylesheet" href="style.css">

            //Logo and navigation using bootstrap code - site wide

        //bootstrap carouse

            .....
            .....

Heading for slide 1

                        Brief description

Heading for slide 2

                        Brief description

Heading for slide 3

                        Brief description

            ......
            ......

            //rest of the content

        //page footer - site wide

I want to know if I can use H1's the way I have used within the bootstrap carousel caption.

I always find it difficult to decide where to place H1 tag when there is a carousel used at the top of the home page and there is no real heading to describe the page. Also, normally a home page tries to cover a lot of content about the entire website so it becomes difficult to structure the page.

Please help.


问:
Improving O(n) while looping through a 2d array in C++
A goal of mine is to reduce my O(n^2) algorithms into O(n), as it's a common algorithm in my Array2D class. Array2D holds a multidimensional array of type T. A common issue I see is using doubly-nested for loops to traverse through an array, which is slow depending on the size.

As you can see, I reduced my doubly-nested for loops into a single for loop here. It's running fine when I execute it. Speed has surely improved. Is there any other way to improve the speed of this member function? I'm hoping to use this algorithm as a model for my other member functions that have similar operations on multidimensional arrays.

```<code>        /// <summary>
        /// Fills all items within the array with a value.
        /// </summary>
        /// <param name="ob">The object to insert.</param>
        void fill(const T &ob)
        {
            if (m_array == NULL)
                return;

            //for (int y = 0; y < m_height; y++)
            //{
            //  for (int x = 0; x < m_width; x++)
            //  {
            //      get(x, y) = ob;
            //  }
            //}

            int size = m_width * m_height;
            int y = 0;
            int x = 0;

            for (int i = 0; i < size; i++)
            {
                get(x, y) = ob;

                x++;

                if (x >= m_width)
                {
                    x = 0;
                    y++;
                }
            }
        }
</code>```

答:
Sometimes you can compute Big O by counting loops, but not always.

```<code>for (int m = 0; m < M; m++)
{
    for (int n = 0; n < N; n++)
    {
        doStuff();
    }
}
</code>```

Big O is a measure of "How many times is doStuff executed?" With the nested loops above it is executed MxN times.

If we flatten it to 1 dimension

```<code>for (int i = 0; i < M * N; i++)
{
    doStuff();
}
</code>```

We now have one loop that executes MxN times. One loop. No improvement.

If we unroll the loop or play games with something like Duff's device

```<code>for (int i = 0; i < M * N; i += N)
{
     doStuff(); // 0
     doStuff(); // 1
     ....
     doStuff(); // N-1
}
</code>```

We still have MxN calls to doStuff. Some days you just can't win with Big O. If you must call doStuff on every element in an array, no matter how many dimensions, you cannot reduce Big O. But if you can find a smarter algorithm that allows you to avoid calls to doStuff... That's what you are looking for.

For Big O, anyway. Sometimes you'll find stuff that has an as-bad-or-worse Big O yet it outperforms. One of the classic examples of this is std::vector vs std::list. Due to caching and prediction in a modern CPU, std::vector scores a victory that slavish obedience to Big O would miss.

Side note (Because I regularly smurf this up myself) O(n) means if you double n, you double the work. This is why O(n) is the same as O(1,000,000 n). O(n2) means if you double n you do 22 times the work. If you are ever puzzled by an algorithm, drop a counter into the operation you're concerned with and do a batch of test runs with various Ns. Then check the relationship between the counters at those Ns.

Body:
A goal of mine is to reduce my O(n^2) algorithms into O(n), as it's a common algorithm in my Array2D class. Array2D holds a multidimensional array of type T. A common issue I see is using doubly-nested for loops to traverse through an array, which is slow depending on the size.

As you can see, I reduced my doubly-nested for loops into a single for loop here. It's running fine when I execute it. Speed has surely improved. Is there any other way to improve the speed of this member function? I'm hoping to use this algorithm as a model for my other member functions that have similar operations on multidimensional arrays.

        ///
        /// Fills all items within the array with a value.
        ///
        /// <param name="ob">The object to insert.</param>
        void fill(const T &ob)
        {
            if (m_array == NULL)
                return;

            //for (int y = 0; y < m_height; y++)
            //{
            //  for (int x = 0; x < m_width; x++)
            //  {
            //      get(x, y) = ob;
            //  }
            //}

            int size = m_width * m_height;
            int y = 0;
            int x = 0;

            for (int i = 0; i < size; i++)
            {
                get(x, y) = ob;

                x++;

                if (x >= m_width)
                {
                    x = 0;
                    y++;
                }
            }
        }

Body:
Sometimes you can compute Big O by counting loops, but not always.

for (int m = 0; m < M; m++)
{
    for (int n = 0; n < N; n++)
    {
        doStuff();
    }
}

Big O is a measure of "How many times is doStuff executed?" With the nested loops above it is executed MxN times.

If we flatten it to 1 dimension

for (int i = 0; i < M * N; i++)
{
    doStuff();
}

We now have one loop that executes MxN times. One loop. No improvement.

If we unroll the loop or play games with something like Duff's device

for (int i = 0; i < M * N; i += N)
{
     doStuff(); // 0
     doStuff(); // 1
     ....
     doStuff(); // N-1
}

We still have MxN calls to doStuff. Some days you just can't win with Big O. If you must call doStuff on every element in an array, no matter how many dimensions, you cannot reduce Big O. But if you can find a smarter algorithm that allows you to avoid calls to doStuff... That's what you are looking for.

For Big O, anyway. Sometimes you'll find stuff that has an as-bad-or-worse Big O yet it outperforms. One of the classic examples of this is std::vector vs std::list. Due to caching and prediction in a modern CPU, std::vector scores a victory that slavish obedience to Big O would miss.

Side note (Because I regularly smurf this up myself) O(n) means if you double n, you double the work. This is why O(n) is the same as O(1,000,000 n). O(n2) means if you double n you do 22 times the work. If you are ever puzzled by an algorithm, drop a counter into the operation you're concerned with and do a batch of test runs with various Ns. Then check the relationship between the counters at those Ns.


问:
How to run Fabric command against specific remote host?
I'd like to run a Fabric command that would look something like this:

```<code>fab show_users:web01
</code>```

where show_users would be defined like this:

```<code>def show_users(webserver):
  if webserver == 'web01':
    DB_NAME = 'db01'
  elif webserver == 'web02':
    DB_NAME = 'db02'
  elif webserver == 'web03':
    DB_NAME = 'db03'
  else:
    print "Error: invalid webserver."

  cmd = "psql -h {0} -U <role> -d <database> -c 'SELECT id, username FROM auth_user;'".format(DB_NAME)
  run(cmd)
</code>```

When I run the command, I get this error:

```<code>No hosts found. Please specify (single) host string for connection: web01.
</code>```

If I enter 'web01', which is defined in my /etc/hosts file, the command will then work.  What is the correct way to do this?

答:
I figured it out based on this SO question:</p>

```<code># usage: fab show_users:[dev|stage|prod]
def show_users(tier):
    env.tier = tier
    if env.tier=="dev":
        env.host_string = 'web01'
        DB_HOST = 'db01'
    elif env.tier=="stage":
        env.host_string = 'web02'
        DB_HOST = 'db02'
    elif env.tier=="prod":
        env.host_string = 'web03'
        DB_HOST = 'db03'
    else:
        print "Error: Tier %s is not a valid server tier name." % (tier)
        exit(1)

    cmd = "psql -h {0} -U {1} -d {2} -c 'SELECT id, username FROM auth_user;'".format(DB_HOST, env.me, env.db)
    run(cmd)
</code>```

Body:
I'd like to run a Fabric command that would look something like this:

fab show_users:web01

where show_users would be defined like this:

def show_users(webserver):
  if webserver == 'web01':
    DB_NAME = 'db01'
  elif webserver == 'web02':
    DB_NAME = 'db02'
  elif webserver == 'web03':
    DB_NAME = 'db03'
  else:
    print "Error: invalid webserver."

  cmd = "psql -h {0} -U <role> -d <database> -c 'SELECT id, username FROM auth_user;'".format(DB_NAME)
  run(cmd)

When I run the command, I get this error:

No hosts found. Please specify (single) host string for connection: web01.

If I enter 'web01', which is defined in my /etc/hosts file, the command will then work.  What is the correct way to do this?

Body:
I figured it out based on this SO question:

# usage: fab show_users:[dev|stage|prod]
def show_users(tier):
    env.tier = tier
    if env.tier=="dev":
        env.host_string = 'web01'
        DB_HOST = 'db01'
    elif env.tier=="stage":
        env.host_string = 'web02'
        DB_HOST = 'db02'
    elif env.tier=="prod":
        env.host_string = 'web03'
        DB_HOST = 'db03'
    else:
        print "Error: Tier %s is not a valid server tier name." % (tier)
        exit(1)

    cmd = "psql -h {0} -U {1} -d {2} -c 'SELECT id, username FROM auth_user;'".format(DB_HOST, env.me, env.db)
    run(cmd)


问:
Does TensorFlow optimize to avoid unnecessary re-execution of graphs?
I understand roughly how a TensorFlow graph is evaluated when one of the Tensors it contains is evaluated: the execution of run or eval for that tensor will trigger all of the cascading computations in the graph needed compute the value of that tensor and, as a result, any tensors that "lead to it" in the graph will also have been computed, and any operations connecting them will have been run.

As a consequence, if I have a graph containing the tensor out_a the computation of which involves (perhaps among many other things) operations that use int_b which in turn (eventually) requires execution of the operation an_op which itself (eventually) uses in, executing

```<code>a, b, o = sess.run([out_a, int_b, an_op], feed_dict={in: x})
</code>```

will evaluate out_a, int_b and an_op just once: the computation of out_a and int_b both use the same execution of an_op; and the computation used to supply int_b is the same one used in computing out_a. (And if I later reference a, for example, I'm using the value of the evaluated tensor out_a, so no further execution occurs as a result.)

But what happens if I don't combine my operations in this way:

```<code>o = sess.run(an_op, feed_dict={in: x})
# ... and later yet, after I remember I need `int_b`:
b = sess.run(int_b, feed_dict={in: x})
# ... later, after I remember I need `out_a`:
a = sess.run(out_a, feed_dict={in: x})
</code>```

Is there any optimization that TensorFlow performs in this case to avoid computing an_op a second and third time, and int_b a second time, possibly triggering side effects of those computations?

答:
Is there any optimization that TensorFlow performs in this case to
  avoid computing an_op a second and third time, and int_b a second
  time, possibly triggering side effects of those computations?

No, it is up to a developer to remember what computations will need to be executed and put all of them in the list in your sess.run function (the way you described).

You can verify it by running the following code:

```<code>import tensorflow as tf
import numpy as np
from datetime import datetime

n = 3000
t = np.random.rand(n,n)
a = tf.Variable(t)
b = tf.matmul(a, a)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime

    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime

    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime
</code>```

which on my machine returns:

```<code>0:00:02.798704
0:00:02.940005
0:00:03.039798
</code>```

If the data would be cached, the second run would return in no time.

Body:
I understand roughly how a TensorFlow graph is evaluated when one of the Tensors it contains is evaluated: the execution of run or eval for that tensor will trigger all of the cascading computations in the graph needed compute the value of that tensor and, as a result, any tensors that "lead to it" in the graph will also have been computed, and any operations connecting them will have been run.

As a consequence, if I have a graph containing the tensor out_a the computation of which involves (perhaps among many other things) operations that use int_b which in turn (eventually) requires execution of the operation an_op which itself (eventually) uses in, executing

a, b, o = sess.run([out_a, int_b, an_op], feed_dict={in: x})

will evaluate out_a, int_b and an_op just once: the computation of out_a and int_b both use the same execution of an_op; and the computation used to supply int_b is the same one used in computing out_a. (And if I later reference a, for example, I'm using the value of the evaluated tensor out_a, so no further execution occurs as a result.)

But what happens if I don't combine my operations in this way:

o = sess.run(an_op, feed_dict={in: x})
# ... and later yet, after I remember I need `int_b`:
b = sess.run(int_b, feed_dict={in: x})
# ... later, after I remember I need `out_a`:
a = sess.run(out_a, feed_dict={in: x})

Is there any optimization that TensorFlow performs in this case to avoid computing an_op a second and third time, and int_b a second time, possibly triggering side effects of those computations?

Body:
Is there any optimization that TensorFlow performs in this case to
  avoid computing an_op a second and third time, and int_b a second
  time, possibly triggering side effects of those computations?

No, it is up to a developer to remember what computations will need to be executed and put all of them in the list in your sess.run function (the way you described).

You can verify it by running the following code:

import tensorflow as tf
import numpy as np
from datetime import datetime

n = 3000
t = np.random.rand(n,n)
a = tf.Variable(t)
b = tf.matmul(a, a)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime

    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime

    startTime = datetime.now()
    _ = sess.run(b)
    print datetime.now() - startTime

which on my machine returns:

0:00:02.798704
0:00:02.940005
0:00:03.039798

If the data would be cached, the second run would return in no time.


问:
Getting the required output in SQL server
I have an issue in getting the required output for below scenario.

```<code>name | provider  | visit_dt    | rd | rn
 A   | 100000    | 06/05/'17   | 1  |  1
 A   | 100001    | 06/04/'17   | 1  |  0
 A   | 100001    | 06/03/'17   | 1  |  0
 B   | 100000    | 06/05/'17   | 1  |  0
 B   | 100001    | 06/05/'17   | 1  |  1
 C   | 100000    | 06/05/'17   | 1  |  0
 C   | 100001    | 06/04/'17   | 1  |  0
 C   | 100001    | 06/03/'17   | 1  |  1
 D   | 100001    | 06/05/'17   | 1  |  0
 D   | 100001    | 06/04/'17   | 1  |  0
</code>```

There are 4 different scenarios here:

If the most recent has rd = 1 and rn = 1 then pull the most recent visit(person A)

Get the most recent visit for each person with rn = 1 (person C)

If rn = 0, then pull the most recent RD (person D)

If both the visits for a person are with different providers on the same date, then pull both the providers irrespective of rd and rn values (person B)

So the expected output should be as below.

```<code>name | provider  | visit_dt    | rd | rn
A    | 100000    | 06/05/'17   | 1  |  1
B    | 100000    | 06/05/'17   | 1  |  0
B    | 100001    | 06/05/'17   | 1  |  1
C    | 100001    | 06/03/'17   | 1  |  1
D    | 100001    | 06/05/'17   | 1  |  0
</code>```

It would be great if anyone could help me to solve this issue.

Any suggestion would be appreciable.

Thank you in advance.

答:
If this is SQL 2008+, I believe this will work (as long as visit_dt is a date datatype).

```<code>WITH cte1 AS (
  SELECT name, provider, visit_dt, rd, rn, DENSE_RANK() OVER (PARTITION BY name ORDER BY visit_dt DESC) AS thisrow
  FROM t
)
SELECT *
FROM cte1
WHERE thisrow =1
</code>```

http://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=1dc1bf626aed520d601fe68f1f11be55

Body:
I have an issue in getting the required output for below scenario.

name | provider  | visit_dt    | rd | rn
 A   | 100000    | 06/05/'17   | 1  |  1
 A   | 100001    | 06/04/'17   | 1  |  0
 A   | 100001    | 06/03/'17   | 1  |  0
 B   | 100000    | 06/05/'17   | 1  |  0
 B   | 100001    | 06/05/'17   | 1  |  1
 C   | 100000    | 06/05/'17   | 1  |  0
 C   | 100001    | 06/04/'17   | 1  |  0
 C   | 100001    | 06/03/'17   | 1  |  1
 D   | 100001    | 06/05/'17   | 1  |  0
 D   | 100001    | 06/04/'17   | 1  |  0

There are 4 different scenarios here:

If the most recent has rd = 1 and rn = 1 then pull the most recent visit(person A)

Get the most recent visit for each person with rn = 1 (person C)

If rn = 0, then pull the most recent RD (person D)

If both the visits for a person are with different providers on the same date, then pull both the providers irrespective of rd and rn values (person B)

So the expected output should be as below.

name | provider  | visit_dt    | rd | rn
A    | 100000    | 06/05/'17   | 1  |  1
B    | 100000    | 06/05/'17   | 1  |  0
B    | 100001    | 06/05/'17   | 1  |  1
C    | 100001    | 06/03/'17   | 1  |  1
D    | 100001    | 06/05/'17   | 1  |  0

It would be great if anyone could help me to solve this issue.

Any suggestion would be appreciable.

Thank you in advance.

Body:
If this is SQL 2008+, I believe this will work (as long as visit_dt is a date datatype).

WITH cte1 AS (
  SELECT name, provider, visit_dt, rd, rn, DENSE_RANK() OVER (PARTITION BY name ORDER BY visit_dt DESC) AS thisrow
  FROM t
)
SELECT *
FROM cte1
WHERE thisrow =1

http://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=1dc1bf626aed520d601fe68f1f11be55


问:
Animations when scrolled not working - JQuery
I have a website where when you scroll, it goes "smoothly" (with animate scrolltop in jquery) to another section, denying you to scroll to another site. Now, what I want to do is that when you scroll to section2, the elements appear with some animations and when you left it, it disappears, and so on...

I did this but it only works when I refresh the page and I'm already in that section. In other case, it doesn't work. I think it doesnt work because when you call the $(window).scrollTop() it returns instantly the scrollTop, but it actually should wait 750ms for the scroll animation to finish. I tried to use setTimeOut and other things but I couldn't make it run.

Here is the code:

```<code>function animacionObjetosDeSections() {
$(window).scroll(function() {
    //each height of the sections
    var altoSection2 = $('#section2').offset().top;
    var altoSection3 = $('#section3').offset().top;

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state
    if ($(window).scrollTop() == altoSection2) {
        $('.view-of-page').animate({left: '2%'},600);
        $('.page-info h2').animate({opacity: 1}, 650);
    } else {
        $('.view-of-page').animate({left: '-50%'},600);
        $('.page-info h2').animate({opacity: 0}, 650);
    }
});
</code>```

}

EDIT:

Know it works but for each scroll it recognizes like 30 scroll events and I have to wait those 30 events * 750ms to make the function work again.

CODE:

```<code>function animacionObjetosDeSections() {
$(window).scroll(function() {
    setTimeout(function() {
    //each height of the sections
    var altoSection2 = $('#section2').offset().top;
    var altoSection3 = $('#section3').offset().top;

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state
    if ($(window).scrollTop() == altoSection2) {
        alert("hola");
        $('#section2 .view-of-page').animate({left: '2%'},600);
        $('#section2 .page-info h2').animate({opacity: 1}, 650);
    } else {
        $('#section2 .view-of-page').animate({left: '-50%'},600);
        $('#section2 .page-info h2').animate({opacity: 0}, 650);
    }
        },701);
});
</code>```

}

答:
use slideup() and slidedown() functions when you reach to that section.
for example when you scroll to section2 use slidedown() function on your section div and it will appear with animation and when you leave that section make use of slideup()function and your section will disappear with animation.

Body:
I have a website where when you scroll, it goes "smoothly" (with animate scrolltop in jquery) to another section, denying you to scroll to another site. Now, what I want to do is that when you scroll to section2, the elements appear with some animations and when you left it, it disappears, and so on...

I did this but it only works when I refresh the page and I'm already in that section. In other case, it doesn't work. I think it doesnt work because when you call the $(window).scrollTop() it returns instantly the scrollTop, but it actually should wait 750ms for the scroll animation to finish. I tried to use setTimeOut and other things but I couldn't make it run.

Here is the code:

function animacionObjetosDeSections() {
$(window).scroll(function() {
    //each height of the sections
    var altoSection2 = $('#section2').offset().top;
    var altoSection3 = $('#section3').offset().top;

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state
    if ($(window).scrollTop() == altoSection2) {
        $('.view-of-page').animate({left: '2%'},600);
        $('.page-info h2').animate({opacity: 1}, 650);
    } else {
        $('.view-of-page').animate({left: '-50%'},600);
        $('.page-info h2').animate({opacity: 0}, 650);
    }
});

}

EDIT:

Know it works but for each scroll it recognizes like 30 scroll events and I have to wait those 30 events * 750ms to make the function work again.

CODE:

function animacionObjetosDeSections() {
$(window).scroll(function() {
    setTimeout(function() {
    //each height of the sections
    var altoSection2 = $('#section2').offset().top;
    var altoSection3 = $('#section3').offset().top;

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state
    if ($(window).scrollTop() == altoSection2) {
        alert("hola");
        $('#section2 .view-of-page').animate({left: '2%'},600);
        $('#section2 .page-info h2').animate({opacity: 1}, 650);
    } else {
        $('#section2 .view-of-page').animate({left: '-50%'},600);
        $('#section2 .page-info h2').animate({opacity: 0}, 650);
    }
        },701);
});

}


问:
Rect Errors on Pygame
Hi I have been creating a game where a player has to dodge oil barrels and have been working on getting rect so I can create something when the 2 sprites collide. However it seems that the collision boxes are messed up because whenever I start up the game it automatically detect a collision between the player and the barrel.

This is my code:

```<code>import pygame
import os
import time
import sys
import pyganim
import random
global rand

from threading import Thread

class UpdateThread(Thread):
    def __init__(self):
        self.stopped = False
        Thread.__init__(self)
    def run(self):
        while not self.stopped:
            self.downloadValue()
            time.sleep(2)
    def downloadValue(self):
        rand=random.randrange(1, 10)

class oil(object):
    def __init__(self):
        self.image = pygame.image.load('oil.png')
        self.image = pygame.transform.scale(self.image,(300,300))
        self.rect = self.image.get_rect()
        self.x = 1600
        self.y = 400
    def handle_keys(self):
        key = pygame.key.get_pressed()
        distance = 10
        self.x -= distance

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

    def checkCollision(self, oil, sprite):
        col = sprite.colliderect(oil)
        if col == True:
            print ("GameOver")

def blit_alpha(target, source, location, opacity):
        x = location[0]
        y = location[1]
        temp = pygame.Surface((source.get_width(), source.get_height())).convert()
        temp.blit(target, (-x, -y))
        temp.blit(source, (0, 0))
        temp.set_alpha()
        target.blit(temp, location)

class sprite(object):
    def __init__(self):

        self.image = pygame.image.load('image1.png')
        self.rect = self.image.get_rect()
        self.x = 0
        self.y = 0
    def handle_keys(self):

        key = pygame.key.get_pressed()
        distance = 10
        if key[pygame.K_DOWN]:
            self.y += distance
        if key[pygame.K_UP]:
            self.y -= distance
        if key[pygame.K_RIGHT]:
            self.x += distance
        if key[pygame.K_LEFT]:
            self.x -= distance

    def draw(self, surface):

        #surface.blit(self.image, (self.x, self.y))
        anim.blit(surface, (self.x, self.y))

anim = pyganim.PygAnimation([("image1.png", 0.5), ("image2.png", 0.5)])

pygame.init()
screen = pygame.display.set_mode((1600, 800))
oil=oil()
sprite=sprite()
clock = pygame.time.Clock()
backgroundo= pygame.image.load('background.png')
background = pygame.transform.scale(backgroundo, (1600, 800))
anim.play()

myThread = UpdateThread()
myThread.start()
oil.checkCollision(oil.rect,sprite.rect)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

    sprite.handle_keys()
    oil.handle_keys()

    screen.fill((255,255,255))
    blit_alpha(screen, background, (0, 0), 128)
    sprite.draw(screen)
    oil.draw(screen)

    pygame.display.update()

    clock.tick(30)
</code>```

Any help would be greatly appreciated.

答:
```<code>The problem is it:

    > class sprite(object):
    > > >def __init__(self):
    > > > >self.image = pygame.image.load('image1.png')
    > > > >self.rect = self.image.get_rect()
    > > > >self.x = 0
    > > > >self.y = 0

when you use "getRect()" you can't use x or y for this image, you must to use othres attrib, for example:

   > class sprite(object):
    > > >def __init__(self):
    > > > >self.image = pygame.image.load('image1.png')
    > > > >self.rect = self.image.get_rect()
    > > > >self.rect.centery = 325
    > > > >self.rect.centerx = 300
</code>```

Title: Rect Errors on Pygame

Body:
Hi I have been creating a game where a player has to dodge oil barrels and have been working on getting rect so I can create something when the 2 sprites collide. However it seems that the collision boxes are messed up because whenever I start up the game it automatically detect a collision between the player and the barrel.

This is my code:

import pygame
import os
import time
import sys
import pyganim
import random
global rand

from threading import Thread

class UpdateThread(Thread):
    def __init__(self):
        self.stopped = False
        Thread.__init__(self)
    def run(self):
        while not self.stopped:
            self.downloadValue()
            time.sleep(2)
    def downloadValue(self):
        rand=random.randrange(1, 10)

class oil(object):
    def __init__(self):
        self.image = pygame.image.load('oil.png')
        self.image = pygame.transform.scale(self.image,(300,300))
        self.rect = self.image.get_rect()
        self.x = 1600
        self.y = 400
    def handle_keys(self):
        key = pygame.key.get_pressed()
        distance = 10
        self.x -= distance

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

    def checkCollision(self, oil, sprite):
        col = sprite.colliderect(oil)
        if col == True:
            print ("GameOver")

def blit_alpha(target, source, location, opacity):
        x = location[0]
        y = location[1]
        temp = pygame.Surface((source.get_width(), source.get_height())).convert()
        temp.blit(target, (-x, -y))
        temp.blit(source, (0, 0))
        temp.set_alpha()
        target.blit(temp, location)

class sprite(object):
    def __init__(self):

        self.image = pygame.image.load('image1.png')
        self.rect = self.image.get_rect()
        self.x = 0
        self.y = 0
    def handle_keys(self):

        key = pygame.key.get_pressed()
        distance = 10
        if key[pygame.K_DOWN]:
            self.y += distance
        if key[pygame.K_UP]:
            self.y -= distance
        if key[pygame.K_RIGHT]:
            self.x += distance
        if key[pygame.K_LEFT]:
            self.x -= distance

    def draw(self, surface):

        #surface.blit(self.image, (self.x, self.y))
        anim.blit(surface, (self.x, self.y))

anim = pyganim.PygAnimation([("image1.png", 0.5), ("image2.png", 0.5)])

pygame.init()
screen = pygame.display.set_mode((1600, 800))
oil=oil()
sprite=sprite()
clock = pygame.time.Clock()
backgroundo= pygame.image.load('background.png')
background = pygame.transform.scale(backgroundo, (1600, 800))
anim.play()

myThread = UpdateThread()
myThread.start()
oil.checkCollision(oil.rect,sprite.rect)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

    sprite.handle_keys()
    oil.handle_keys()

    screen.fill((255,255,255))
    blit_alpha(screen, background, (0, 0), 128)
    sprite.draw(screen)
    oil.draw(screen)

    pygame.display.update()

    clock.tick(30)

Any help would be greatly appreciated.


问:
CasperJS running out of memory
I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow.  What am i doing wrong here?

searchPages is an array of 54 numbers corresponding to a URL value for a search page.

```<code>casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}
</code>```

And it adds about 3GB per loop.

答:
Well turns out this is a very well-known issue with PhantomJS.  3+ years as an open bug and apparently it has something to do with QT Webkit.  Nonetheless, i was able to solve it by closing each page during the loop and re-opening a new Phantom page.  It's a bit of a hacky work-around, but the memory consumption is far less.  However, after about 200 pages, it still has a pretty high memory usage (1GB+).  So, i break up my scripts into blocks of 200 and just start the next one upon completion.   Here is the finished product that completes successfully without too much memory usage.  It uses less on MacOS than Windows for some reason.</p>

```<code>casper.start(url,function(){
    this.echo('continuing captures...');
}).each(searchPages,function(casper,index){
    loadSearch(this,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate() + 1;
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    var fortnightAway = new Date(+new Date + 12096e5);
    var dateEnd = fortnightAway.getMonth() + 1 + "/" + fortnightAway.getDate() + "/" + fortnightAway.getFullYear();

    casper.page.close();
    casper.page = require('webpage').create();

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });
        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Search failed to load. Retrying");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out. Retrying");
            loadSearch(casper,index);
        },20000);
    });
}
</code>```

Title: CasperJS running out of memory

Body:
I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow.  What am i doing wrong here?

searchPages is an array of 54 numbers corresponding to a URL value for a search page.

casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}

And it adds about 3GB per loop.

Body:
Well turns out this is a very well-known issue with PhantomJS.  3+ years as an open bug and apparently it has something to do with QT Webkit.  Nonetheless, i was able to solve it by closing each page during the loop and re-opening a new Phantom page.  It's a bit of a hacky work-around, but the memory consumption is far less.  However, after about 200 pages, it still has a pretty high memory usage (1GB+).  So, i break up my scripts into blocks of 200 and just start the next one upon completion.   Here is the finished product that completes successfully without too much memory usage.  It uses less on MacOS than Windows for some reason.

casper.start(url,function(){
    this.echo('continuing captures...');
}).each(searchPages,function(casper,index){
    loadSearch(this,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate() + 1;
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    var fortnightAway = new Date(+new Date + 12096e5);
    var dateEnd = fortnightAway.getMonth() + 1 + "/" + fortnightAway.getDate() + "/" + fortnightAway.getFullYear();

    casper.page.close();
    casper.page = require('webpage').create();

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });
        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Search failed to load. Retrying");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out. Retrying");
            loadSearch(casper,index);
        },20000);
    });
}


问:
Tools, rules or processes for checking internal consistency of XML config files
I've worked on projects that have very complex XML configuration, and one problem that's faced is maintaining the internal consistency of the XML.

In this case I don't mean the strict XML schema consistency, but rather the higher level relation between the nodes used. Most problems were caused by implicit linking between information encoded in the XML, and implicit relation of that information to the codebase. Examples might be:

XML node data implicitly linked to enums in code

Business objects in the same config that are related (in that they share information that needs to be consistent) without any explicit relation between them

Code in XML to be compiled and parsed at runtime

It struck me that a) this might become a practice of increasing frequency and b) that in some cases we're implicitly creating a new coding language that's not compile-time checked -- and in fact has few checks at all until it's run.

Is anyone else out there facing similar scenarios, and are there any tools or approaches that make the problem more tractable? I'd like some general examples that are technology-agnostic -- my own specific experience has been with C# and with config for proprietary systems.

Note: although I have an answer to this below, I've no intent of taking my own as the final answer.

答: A good link on from @David Peleg's is Topologi, which offer products to check XML, including "business rules" checks.</p>


问:
ListView's refresh command not working with binded IRelayCommand
I created a form with listview and ISingleOperation fo data refresh.

Then i created command in ViewModel.

```<code> public IRelayCommand LoadInvoicesCommand
    {
        get
        {
            return GetCommand(() => Execution.ViewModelExecute(new LoadInvoicesOperation(_model), 10000));
        }
    }
</code>```

ISingleOperation works well and returns

```<code>new Result() { ResultAction = ResultType.None };
</code>```

Refresh operation is bound well

```<code>RefreshCommand="{Binding LoadInvoicesCommand}"
</code>```

But  refresh indicator "hangs" and not disapearing, what is wrong here?

答:
You need to bind a second property from the ListView named IsRefreshing to your ViewModel. This is a boolean property and is the one responsible to tell the ListView that the refreshing has started/completed.

An example of a ListView XAML

```<code><ListView
    VerticalOptions="FillAndExpand"
    IsPullToRefreshEnabled="true"
    RefreshCommand="{Binding LoadInvoicesCommand}"
    IsRefreshing="{Binding IsRefreshing, Mode=OneWay}"
    ItemsSource="{Binding YourItemSource}"
    ItemTemplate="{StaticResource ItemTemplate" />
</code>```

Your ViewModel will need a public property called IsRefreshing and you will need to set this to false when you the refresh command has completed.

Body:
I created a form with listview and ISingleOperation fo data refresh.

Then i created command in ViewModel.

 public IRelayCommand LoadInvoicesCommand
    {
        get
        {
            return GetCommand(() => Execution.ViewModelExecute(new LoadInvoicesOperation(_model), 10000));
        }
    }

ISingleOperation works well and returns

new Result() { ResultAction = ResultType.None };

Refresh operation is bound well

RefreshCommand="{Binding LoadInvoicesCommand}"

But  refresh indicator "hangs" and not disapearing, what is wrong here?

Body:
You need to bind a second property from the ListView named IsRefreshing to your ViewModel. This is a boolean property and is the one responsible to tell the ListView that the refreshing has started/completed.

An example of a ListView XAML

<ListView
    VerticalOptions="FillAndExpand"
    IsPullToRefreshEnabled="true"
    RefreshCommand="{Binding LoadInvoicesCommand}"
    IsRefreshing="{Binding IsRefreshing, Mode=OneWay}"
    ItemsSource="{Binding YourItemSource}"
    ItemTemplate="{StaticResource ItemTemplate" />

Your ViewModel will need a public property called IsRefreshing and you will need to set this to false when you the refresh command has completed.


问:
How to generate any color in PyX
Many Visualisation libraries and languages provide easy ways of generating any color. for example you could simple add a style tag with a css color code to set the color of an object in html.

Is there a similiar way to set the color of a pyx drawing to any wanted color code instead of the predefined pyx color codes?

(for example something like color.code = #1122DD instead of color.rgb.blue)

答:
Here is the way I found as the most convenient to have a simple RGB color:

pyx.color.rgb(r,g,b)

where r, g, b are numbers in the range [0, 1] and set the percentage of each base color in RGB format.

Title: How to generate any color in PyX


问:
Moment.js How to display time remaining in day (with timezone offset)
How to display time remaining until midnight, like this:
22 hours 48 minutes 12 seconds remaining

To make things a bit more difficult, this should show in the UTC+2 timezone.
Is this possible in plain javascript or easier with momentjs?
Any help appreciated!

答:
let now = moment();
let timeDiff = moment(now).utcOffset(120).endOf('day') - now;

let dur = moment.duration(timeDiff);

console.log(`${dur.hours()} hrs ${dur.minutes()} min ${dur.seconds()} sec until midnight.`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.min.js"></script></code>```

Body:
let now = moment();
let timeDiff = moment(now).utcOffset(120).endOf('day') - now;

let dur = moment.duration(timeDiff);

console.log(`${dur.hours()} hrs ${dur.minutes()} min ${dur.seconds()} sec until midnight.`);

<script src="https://momentjs.com/downloads/moment.min.js"></script>


问:
python symlink in windows 10 creators update
Since the windows 10 creator update, you can enable developer mode to circumvent administrator privileges when creating a symlink. Now, I was able to create a symlink using mklink like this:

```<code>os.system('mklink %s %s' %(dst, src))
</code>```

Hopefully it's obvious that dst is the destination symlink path, and src is the source file for the symlink.  While it seems to work ok, it doesn't error if it fails which makes it a little more difficult to ensure each symlink is successful.  I can check if the path exists after each symlink, but that's less efficient than a try/except clause.  There's also what looks like a command shell window(?) that pops up and closes quickly every time - and that's really annoying when you're symlinking a lot of files...

So, I've been trying other options I've found on stack overflow like this one: How to create symlinks in windows using Python?  Unfortunately, the CreateSymbolicLinkW command doesn't seem to work for me... I also found this: OS.symlink support in windows where it appears you need to adjust the group policy editor; however, it apparently still requires users in the administrator group to run the process as an administrator even if you explicitly set that user with symlink privileges.

With the windows 10 creator update, there's mention of a new dwflag in the CreateSymbolicLink api (SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) you can see the reference for that here: symlinks windows 10

Using the ctypes stuff is a bit over my head, so I'm wondering if anyone knows: Can I actually use that new dwflag?  How do I use it? Will it work without running the process as administrator?

I use Autodesk Maya, so I'm stuck with python 2.7 options...  I have not tried launching Maya as an administrator so I don't know if that will work, but it seems like a rather annoying hoop to jump through even if it does...  I appreciate any assistance you can give

答:
it doesn't error if it fails

os.system will return the exit status of the call. It does not raise an exception.

If you look at the docs for os.system, they recommend using the subprocess module. In fact, subprocess.check_call does what you describe (raise an exception on a non-zero exit status). Perhaps that would work better.

On the other hand, the command mklink will return a zero exit status even if the source does not exist (it will create a link to non-existent file and return 0). You might want to validate the actual link as you mentioned, depending on what errors you are trying to find.

As far as hiding the console window, see this.

Body:
Since the windows 10 creator update, you can enable developer mode to circumvent administrator privileges when creating a symlink. Now, I was able to create a symlink using mklink like this:

os.system('mklink %s %s' %(dst, src))

Hopefully it's obvious that dst is the destination symlink path, and src is the source file for the symlink.  While it seems to work ok, it doesn't error if it fails which makes it a little more difficult to ensure each symlink is successful.  I can check if the path exists after each symlink, but that's less efficient than a try/except clause.  There's also what looks like a command shell window(?) that pops up and closes quickly every time - and that's really annoying when you're symlinking a lot of files...

So, I've been trying other options I've found on stack overflow like this one: How to create symlinks in windows using Python?  Unfortunately, the CreateSymbolicLinkW command doesn't seem to work for me... I also found this: OS.symlink support in windows where it appears you need to adjust the group policy editor; however, it apparently still requires users in the administrator group to run the process as an administrator even if you explicitly set that user with symlink privileges.

With the windows 10 creator update, there's mention of a new dwflag in the CreateSymbolicLink api (SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) you can see the reference for that here: symlinks windows 10

Using the ctypes stuff is a bit over my head, so I'm wondering if anyone knows: Can I actually use that new dwflag?  How do I use it? Will it work without running the process as administrator?

I use Autodesk Maya, so I'm stuck with python 2.7 options...  I have not tried launching Maya as an administrator so I don't know if that will work, but it seems like a rather annoying hoop to jump through even if it does...  I appreciate any assistance you can give


问:
BLOB Storage - 100+ GB, MySQL, SQLite, or PostgreSQL + Python
I have an idea for a simple application which will monitor a group of folders, index any files it finds. A gui will allow me quickly tag new files and move them into a single database for storage and also provide an easy mechanism for querying the db by tag, name, file type and date. At the moment I have about 100+ GB of files on a couple removable hard drives, the database will be at least that big. If possible I would like to support full text search of the embedded binary and text documents. This will be a single user application.

Not trying to start a DB war, but what open source DB is going to work best for me? I am pretty sure SQLLite is off the table but I could be wrong.

答:
Why store the files in the database at all?  Simply store your meta-data and a filename.  If you need to copy them to a new location for some reason, just do that as a file system copy.

Once you remove the file contents then any competent database will be able to handle the meta-data for a few hundred thousand files.

OwnerDisplayName: Ethan Post

LastEditorDisplayName: Eddie

OwnerDisplayName: Rob Walker


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答: I would like to recommend XStream which simply takes your POJOs and creates XML out of them so you can store it on disk. It is very easy to use and is also open source.</p>

OwnerDisplayName: willcodejavaforfood


问:
how to open app store with in our ipad or iphone application?
Hi i want to open app store with in our application with the specific publisher search or specific application types..on clicking of button..let's say More App's...</p>

答:
You can get the appropriate URL to your app here:

http://itunes.apple.com/linkmaker

If you enter the name of your company the linkmaker will provide an "artist link" that shows all of your apps.

If you use the itms-apps:// prefix the user is sent directly to the
App Store App with the specified app showing rather than the ugly
first-Safari-then-the-App-Store-App shuffle that you get without that
UTI. A la:

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
                                            @"itms-apps://yourAppLinkHere"]];
</code>```

Body:
You can get the appropriate URL to your app here:

http://itunes.apple.com/linkmaker

If you enter the name of your company the linkmaker will provide an "artist link" that shows all of your apps.

If you use the itms-apps:// prefix the user is sent directly to the
App Store App with the specified app showing rather than the ugly
first-Safari-then-the-App-Store-App shuffle that you get without that
UTI. A la:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
                                            @"itms-apps://yourAppLinkHere"]];


问:
Add ID to each rendered element inside canvas
I need little help.

How can I add a text inside each rendered element inside canvas ?

here is a fiddle representing my idea:

 var canvas = document.getElementById("myCanvas");
   var ctx = canvas.getContext("2d");

var x_width = canvas.width;
var y_height = canvas.height;

var dx = 2;
var dy = -2;

var ballRadius = 10;

var data = [

   [1,0.506,0.648],
    [2,0.253,0.433],
    [5,0.339,0.445],
    [7,0.396,0.569],
    [8,0.271,0.583],
    [9,0.307,0.187],
    [10,0.431,0.213],
    [12,0.71,1.045],
    [13,0.2,0.259],
    [14,0.272,0.259],
    [15,0.477,0.379]

    ];

for (var i = 0; i<=data.length-1; i++) {
    var x = x_width*data[i][1];
    var y = y_height*data[i][2];
    var id = data[i][0];
    drawPlayer (id, x,y);
}

function drawPlayer(id, x, y) {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.fillText(id, 0, 0);
    ctx.closePath();
}

drawPlayer();
//setInterval(draw , 100);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myCanvas {
  border: 1px solid red;
}</code>```

<canvas id="myCanvas" width="480" height="320"></canvas>

  <button class="play">Graj</button>

```

Can I somehow add a text inside each element ? Idealy the text should be the data[i][0] number. Is it possible ? I can not wrap my head around it.

Or Should I use classic html and css to create similar effect ?

Cheers

答:
you need to set the x and y position of the text to be the same as the circle's position.
plus measuring the text in order to have it aligned nicely.

here you go:

```<code>function drawPlayer(id, x, y) {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();

  const textWidth = ctx.measureText(id);
  const textHeight = 12 * 0.5;
  ctx.font = "12px Arial"
  ctx.fillStyle = "#fff";
  ctx.fillText(id, x-textWidth.width/2, y+textHeight/2);
}
</code>```

Body:
I need little help.

How can I add a text inside each rendered element inside canvas ?

here is a fiddle representing my idea:

 var canvas = document.getElementById("myCanvas");
   var ctx = canvas.getContext("2d");

var x_width = canvas.width;
var y_height = canvas.height;

var dx = 2;
var dy = -2;

var ballRadius = 10;

var data = [

   [1,0.506,0.648],
    [2,0.253,0.433],
    [5,0.339,0.445],
    [7,0.396,0.569],
    [8,0.271,0.583],
    [9,0.307,0.187],
    [10,0.431,0.213],
    [12,0.71,1.045],
    [13,0.2,0.259],
    [14,0.272,0.259],
    [15,0.477,0.379]

    ];

for (var i = 0; i<=data.length-1; i++) {
    var x = x_width*data[i][1];
    var y = y_height*data[i][2];
    var id = data[i][0];
    drawPlayer (id, x,y);
}

function drawPlayer(id, x, y) {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.fillText(id, 0, 0);
    ctx.closePath();
}

drawPlayer();
//setInterval(draw , 100);

#myCanvas {
  border: 1px solid red;
}

<canvas id="myCanvas" width="480" height="320"></canvas>

  <button class="play">Graj</button>

Can I somehow add a text inside each element ? Idealy the text should be the data[i][0] number. Is it possible ? I can not wrap my head around it.

Or Should I use classic html and css to create similar effect ?

Cheers

Body:
you need to set the x and y position of the text to be the same as the circle's position.
plus measuring the text in order to have it aligned nicely.

here you go:

function drawPlayer(id, x, y) {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();

  const textWidth = ctx.measureText(id);
  const textHeight = 12 * 0.5;
  ctx.font = "12px Arial"
  ctx.fillStyle = "#fff";
  ctx.fillText(id, x-textWidth.width/2, y+textHeight/2);
}


问:
websocket javascript request for x-lite or Bria soft phone
I'd like create a web application which is communicating with X-lite SIP phone. I found API documentation Click here but I don't understand how should I parsed the data for request. For example GET /status "phone". I know use just simple request as GET /showHistory. Thanks for any advice.        </p>

```<code>function WebSocketTest(){
    var ws = new WebSocket("wss://cpclientapi.softphone.com:9002/counterpath/socketapi/v1");

    ws.onopen = function (event) {
        //here I dont know how to write xml request from documentation
        //for example GET /status "phone"
        ws.send('GET /showHistory');
    };
    ws.onerror = function(error){
        console.log('Error detected: ' + error);
    }
    ws.onmessage = function(messageEvent) {
        if (typeof messageEvent.data === "string"){
            console.log("received text data from the server: " + messageEvent.data);
        } else if (messageEvent.data instanceof Blob){
            console.log("Blob data received")
        }
    };
}
</code>```

答:
Try using localhost:9002</p>

```<code>function WebSocketTest(){
    var ws = new WebSocket("wss://localhost:9002/counterpath/socketapi/v1");

    ws.onopen = function (event) {
        //here I dont know how to write xml request from documentation
        //for example GET /status "phone"
        ws.send('GET /showHistory');
    };
    ws.onerror = function(error){
        console.log('Error detected: ' + error);
    }
    ws.onmessage = function(messageEvent) {
        if (typeof messageEvent.data === "string"){
            console.log("received text data from the server: " + messageEvent.data);
        } else if (messageEvent.data instanceof Blob){
            console.log("Blob data received")
        }
    };
}
</code>```

Body:
I'd like create a web application which is communicating with X-lite SIP phone. I found API documentation Click here but I don't understand how should I parsed the data for request. For example GET /status "phone". I know use just simple request as GET /showHistory. Thanks for any advice.

function WebSocketTest(){
    var ws = new WebSocket("wss://cpclientapi.softphone.com:9002/counterpath/socketapi/v1");

    ws.onopen = function (event) {
        //here I dont know how to write xml request from documentation
        //for example GET /status "phone"
        ws.send('GET /showHistory');
    };
    ws.onerror = function(error){
        console.log('Error detected: ' + error);
    }
    ws.onmessage = function(messageEvent) {
        if (typeof messageEvent.data === "string"){
            console.log("received text data from the server: " + messageEvent.data);
        } else if (messageEvent.data instanceof Blob){
            console.log("Blob data received")
        }
    };
}

Body:
Try using localhost:9002

function WebSocketTest(){
    var ws = new WebSocket("wss://localhost:9002/counterpath/socketapi/v1");

    ws.onopen = function (event) {
        //here I dont know how to write xml request from documentation
        //for example GET /status "phone"
        ws.send('GET /showHistory');
    };
    ws.onerror = function(error){
        console.log('Error detected: ' + error);
    }
    ws.onmessage = function(messageEvent) {
        if (typeof messageEvent.data === "string"){
            console.log("received text data from the server: " + messageEvent.data);
        } else if (messageEvent.data instanceof Blob){
            console.log("Blob data received")
        }
    };
}

ContentLicense: CC BY-SA 4.0