qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
109,677 | On a site that I operate I use several layers of protection for our subscription content. Among the other protections, each content item is placed into a folder with a randomly generated 19-character name. That name can include numbers, lowercase letters, and uppercase letters.
While it will not really lower the benefit provided by this layer of protection for a second file to end up in a folder, I am curious about the chances of that happening. That leads me to two related questions:
1. Assuming that we have 2500 files/folders, what is the chance that the next folder we generate will be a repeat?
2. How many folders must exist for the chance of repetition to rise above 1%? | 2012/02/15 | [
"https://math.stackexchange.com/questions/109677",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/25055/"
] | Let's say you generate $K$-character folder names from an alphabet consisting of $A$ different symbols, and you currently have $N$ *distinctly named* folders.
The chance of a particular folder name being generated is $1 / A^K$. The chance that your next folder name matches one that already exists therefore $N/A^K$.
For this to be above a particular value $p$, you need $N > pA^K$.
For you, you have $K=19$, $A=62$ and $N=2500$, so the chance of a repeat is $2500/62^{19}$, whcih is around 1 part in $5\times 10^{30}$, i.e. vanishingly small.
For there to be a greater than 1% chance of a collision, you need $N > 0.01 \times 62^{19} = 10^{32}$ folders.
Note that since each folder name takes up around 20 bytes (19 characters plus a null character), you would need in excess of $10^{24}$ GB of disk space just to store the names of this many folders, never mind their contents. | There are a total of $62^{19} \approx 1.136 \times 10^{34}$ possible 19-character case-sensitive alphanumeric strings.
1. Thus, assuming you have 2500 distinct folders already, the chance of the next folder generated being a repeat is $\frac{2500}{1.136 \times 10^{34}} \approx 2.200 \times 10^{-31} $.
2. (a) If you are asking what the probability of *any* two folder names colliding, then
this is a classic [birthday problem](http://en.wikipedia.org/wiki/Birthday_problem). The probability that given $n$ folders, there is at least one repeat, is given by $$ p(n) = 1 - \frac{n! \cdot {62^{19} \choose n}}{62^{19n}} ,$$
but this is expensive to compute, so we approximate by $$ p(n) \approx 1 - e^{-n(n-1)/(2 \times 62^{19})}.$$
Solving for $p(n)=0.01$ gives $n \approx 1.5 \times 10^{16}$ folders required.
(b) If, on the other hand, you are asking how many folders are needed for the probability of the *next* folder colliding to be at least 0.01, then Chris Taylor's answer covers that superbly. |
29,820,214 | I need to test a JavaScript project. There are described several modules but when I try to load them something goes wrong.
```
define([
'core/BaseModel'
],
function (BaseModel) {
var MessageModel = BaseModel.extend({
defaults: {
messageType: "Advertisment",
receiver: "me",
title: "Title",
heading_1: "Heading1",
heading_2: "Heading2"
},
url: function () {
var base = this.apipath + '/companies/';
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
}
});
return MessageModel;
});
```
To load the module I do this:
```
var message;
beforeAll(function(done){
require(['../../../public/js/app/models/Message'], function(Message){
message = Message;
done();
});
});
```
Now message is not undefined but when I test if message.defaults or message.url is defined this fails. what is wrong there? | 2015/04/23 | [
"https://Stackoverflow.com/questions/29820214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2818992/"
] | Given that ***../../../public/js/app/models/Message*** corresponds to the `MessageModel`, what you want to do is:
`var Message = require('../../../public/js/app/models/Message');`
and to create a new instance: `var m = new Message();`
Hope this helps. | I found a solution that works for this exact example. Instead of
```
message = Message;
```
I write
```
message = new Message();
```
But I do exactly the same with a different module and it only gives a timeout error and keeps undefined:
```
var router;
beforeAll(function(done){
require(['../../../public/js/app/routers/DesktopRouter'], function(Router){
router = new Router();
done();
});
});
```
Its definition is:
```
define(["jquery", "underscore", "backbone", "core/BaseRouter", "models/Session", "i18n!locales",
"views/NavbarView",
"views/LoginView",
'views/SidebarView',
'views/FooterView',
'views/VehicleSidebarView',
"views/DashboardView",
"views/CompaniesView",
"views/WorkshopsView",
"views/VehiclesView",
"views/UsersView",
"views/AddVehicleView",
"views/VehicleTripsView",
"views/VehicleDataView",
"views/VehicleServiceView",
"views/VehicleErrorsView",
"views/MessageInboxView",
"views/AddUserView",
"views/EditUserView",
"views/EditProfileView",
"views/AppDownloadView",
"views/BlockBrowserView"
],
function($, _, Backbone, BaseRouter, Session, i18n,
NavbarView,
LoginView,
SideBarView,
FooterView,
VehicleSidebarView,
DashboardView,
CompaniesView,
WorkshopsView,
VehiclesView,
UsersView,
AddVehicleView,
VehicleTripsView,
VehicleDataView,
VehicleServiceView,
VehicleErrorsView,
MessageInboxView,
AddUserView,
EditUserView,
EditProfileView,
AppDownloadView,
BlockBrowserView
) {
var DesktopRouter = BaseRouter.extend({
initialize: function () {
.....
``` |
381,611 | Multiple questions on meta indicate, that code-only answers, if they are self-explanatory and, what's more important, correct, do not fall into *low quality*: [1](https://meta.stackoverflow.com/questions/303772/failed-audit-when-commenting-on-code-only-answer), [2](https://meta.stackoverflow.com/a/258676/7606764).
Meanwhile I failed the audit when I accepted a code-only answer:
[](https://i.stack.imgur.com/5mIm3.png)
What is wrong with that?
Edit: I think this question is more specific, than duplicate candidate as it limits itself to code-only answers. | 2019/03/21 | [
"https://meta.stackoverflow.com/questions/381611",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/7606764/"
] | >
> *"if they are self-explanatory"*.
>
>
>
That answer is not self-explanatory.
It's a code dump where the OP has to figure out what changed, and more importantly: *why*. It doesn't explain why the changes make the code work.
Answers like that *are* of low quality. Maybe not enough to flag or delete them, but they definitely don't look "Ok". (I usually downvote cases like that)
When in doubt, `Skip` the review. | The failure here seems to be due to two misconceptions:
1. That your only options on the first post queue are, No action
needed, Edit, Flag and Skip.
In actuality, there are several other options including upvote, downvote, and commenting. These options are conspicuously present in this queue as opposed to others like triage.
2. That the first post queue is just for checking for correctness, like triage or low quality queue.
Like Servy pointed out in the comments, action is expected as part of this queue even if the answer is not bad enough to flag. The bar is higher than triage. The whole point of it is to help others improve the quality of their posts.
In summary, I think the correct actions would have been:
* Edit: If you know about the technology, you could edit the answer yourself to provide context.
* Comment: If you don't know about the technology, you can comment and ask OP to provide context
* Downvote: You can downvote if you're inclined.
* Skip: You can skip if you're not inclined, or not sure. |
52,305,729 | I'm new to React JS and am trying to implement something similar to the Angular sample application.
I have a table of customers and want to seen the selected customer at the bottom of the table.
I tried the following with react-router-dom:
```
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
```
The line in App.js that adds the Route (Route path={`/customer/:id`} component={Customer}) is causing the error. If I remove that line I can see the table of customers but as soon as I add this line, then I get that error message.
Did I miss something on how this router works?
Thank you.
**UPDATE**
Event changing App.js to this very simple version causes the error
```
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
```
The full error message is:
**Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.** | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583658/"
] | I feel the issue is with back ticks in path. Can you try with this
```
render() {
return (
<React.Fragment>
<Customers />
<Route path='/customer/:id' component={Customer} />
</React.Fragment>
);
}
```
OR
```
render() {
return (
<React.Fragment>
<Customers />
<Route path={'/customer/:id'} component={Customer} />
</React.Fragment>
);
}
``` | Looks like you have a syntax error in the `Customer` component's `render()` method which will be causing issue when you attempt to use/render this.
Try the following fix:
```
export default class Customer extends Component {
render() {
return (<p> Customer</p>); // <-- remove the whitespace in
// closing tag </p> like so
};
}
``` |
52,305,729 | I'm new to React JS and am trying to implement something similar to the Angular sample application.
I have a table of customers and want to seen the selected customer at the bottom of the table.
I tried the following with react-router-dom:
```
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
```
The line in App.js that adds the Route (Route path={`/customer/:id`} component={Customer}) is causing the error. If I remove that line I can see the table of customers but as soon as I add this line, then I get that error message.
Did I miss something on how this router works?
Thank you.
**UPDATE**
Event changing App.js to this very simple version causes the error
```
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
```
The full error message is:
**Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.** | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583658/"
] | change this:
```
import {Route} from "react-router-dom/Route";
```
to this:
```
import Route from "react-router-dom/Route";
```
Route is a default export when you access it directly: `"react-router-dom/Route"`
You can use named exports when you import `Route` from base package
```
import {Route} from "react-router-dom";
```
But don't mix the two. | I feel the issue is with back ticks in path. Can you try with this
```
render() {
return (
<React.Fragment>
<Customers />
<Route path='/customer/:id' component={Customer} />
</React.Fragment>
);
}
```
OR
```
render() {
return (
<React.Fragment>
<Customers />
<Route path={'/customer/:id'} component={Customer} />
</React.Fragment>
);
}
``` |
52,305,729 | I'm new to React JS and am trying to implement something similar to the Angular sample application.
I have a table of customers and want to seen the selected customer at the bottom of the table.
I tried the following with react-router-dom:
```
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
```
The line in App.js that adds the Route (Route path={`/customer/:id`} component={Customer}) is causing the error. If I remove that line I can see the table of customers but as soon as I add this line, then I get that error message.
Did I miss something on how this router works?
Thank you.
**UPDATE**
Event changing App.js to this very simple version causes the error
```
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
```
The full error message is:
**Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.** | 2018/09/13 | [
"https://Stackoverflow.com/questions/52305729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583658/"
] | change this:
```
import {Route} from "react-router-dom/Route";
```
to this:
```
import Route from "react-router-dom/Route";
```
Route is a default export when you access it directly: `"react-router-dom/Route"`
You can use named exports when you import `Route` from base package
```
import {Route} from "react-router-dom";
```
But don't mix the two. | Looks like you have a syntax error in the `Customer` component's `render()` method which will be causing issue when you attempt to use/render this.
Try the following fix:
```
export default class Customer extends Component {
render() {
return (<p> Customer</p>); // <-- remove the whitespace in
// closing tag </p> like so
};
}
``` |
16,269,897 | For the last month, we've had a bot scraping our site regularly, leading to a bunch of `ArgumentError: invalid %-encoding` errors because the URLs are malformed. I've looked at a bunch of issues in rack [here](https://github.com/rack/rack/issues/337) and [here](https://github.com/rack/rack/issues/225) and rails [here](https://github.com/rails/rails/issues/2622), and looked at [this SO thread](https://stackoverflow.com/questions/15769681/rails-rack-argumenterror-invalid-encoding-for-post-data) but there doesn't seem to be a definitive solution. Is there a correct solution for GET errors? Do I have to monkeypatch rack?
edit: And here's a backtrace:
```
/usr/local/lib/ruby/1.9.1/uri/common.rb:898:in `decode_www_form_component'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:41:in `unescape'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `block (2 levels) in parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `map'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `block in parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:93:in `each'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:93:in `parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/request.rb:332:in `parse_query'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/request.rb:269:in `parse_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/request.rb:186:in `GET'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/request.rb:225:in `GET'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/parameters.rb:10:in `parameters'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/filter_parameters.rb:33:in `filtered_parameters'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/instrumentation.rb:21:in `process_action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/abstract_controller/base.rb:121:in `process'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/abstract_controller/rendering.rb:45:in `process'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal.rb:203:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal.rb:246:in `block in action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:73:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:36:in `call'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:68:in `block in call'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:56:in `each'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:56:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:601:in `call'
[GEM_ROOT]/gems/omniauth-1.1.1/lib/omniauth/strategy.rb:177:in `call!'
[GEM_ROOT]/gems/omniauth-1.1.1/lib/omniauth/strategy.rb:157:in `call'
[GEM_ROOT]/gems/sass-3.2.7/lib/sass/plugin/rack.rb:54:in `call'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:35:in `block in call'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:34:in `catch'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:34:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/etag.rb:23:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/conditionalget.rb:25:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/head.rb:14:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/params_parser.rb:21:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/flash.rb:242:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:210:in `context'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:205:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/cookies.rb:341:in `call'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/query_cache.rb:64:in `call'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:405:in `_run__497203393471184793__call__4495106819278994598__callbacks'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:405:in `__run_callback'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:81:in `run_callbacks'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:32:in `call_app'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:16:in `block in call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/tagged_logging.rb:22:in `tagged'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:16:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/request_id.rb:22:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/lock.rb:15:in `call'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in `forward'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:143:in `pass'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:172:in `rescue in lookup'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:168:in `lookup'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:66:in `call!'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/engine.rb:479:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/application.rb:223:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/railtie/configurable.rb:30:in `method_missing'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/request_handler.rb:96:in `process_request'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_request_handler.rb:516:in `accept_and_process_next_request'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_request_handler.rb:274:in `main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:206:in `start_request_handler'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:171:in `block in handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/utils.rb:479:in `safe_fork'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:166:in `handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:180:in `start'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:129:in `start'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:253:in `block (2 levels) in spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:246:in `block in spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:82:in `block in synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/helper-scripts/passenger-spawn-server:99:in `<main>'
``` | 2013/04/29 | [
"https://Stackoverflow.com/questions/16269897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703019/"
] | Java is case-sensitive. The `static` keyword must be lowercase. Your code does not have `static` in all-lowercase; therefore, the compiler interprets `Static` as a return type, interprets the actual return type as the name, and then chokes on the actual name.
To fix this, simply change `Static` to `static` everywhere. | In the function declaration, use 'static' instead of 'Static' |
80,990 | There doesn't seem to be a weight limit on [teleport](https://www.dndbeyond.com/spells/teleport) anymore but, for the purposes of looting a dungeon, what is an object?
I can see how you can fill a chest and then teleport the chest and its contents. It is container and so all its contents are also teleported.
How about a 10' long table stacked with gear? Is the table also a container in the same way or would teleporting a table not teleport the tablecloth? | 2016/05/31 | [
"https://rpg.stackexchange.com/questions/80990",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/26539/"
] | ### By RAW, an object is a single designated thing that isn't alive. In my opinion RAI extends to obvious containers.
The teleport spell states (emphasis mine):
>
> This spell instantly transports you and up to eight willing creatures of your choice that you can see within range, or a single object that you can see within range, to a destination you select. If you target **an object**, it must be able to fit entirely inside a 10-foot cube, and it can’t be held or carried by an unwilling creature.
>
>
>
This wording indicates it only applies to a single object since it does not say all objects. It also makes no exceptions for containers and their contents.
For example, if you could transport anything in a container all you would have to do is build a makeshift 10 X 10 X 10 wooden cage and call it a large box. Then you could teleport 1000 cubic feet of whatever you want because you targeted the container.
Personally, I would allow transporting obvious containers like chests, bags of holding, boxes, jars, etc because that seems in keeping with the intent of the game mechanics. It also avoids the unnecessary confusion and ceaseless arguing over just how many separate objects make up a single carriage.
I would say that common sense needs to prevail. If the contents of a table would fit in a standard chest, there's no real reason to prevent players from designating the table or shelf as a container for the purpose of transport. Especially if you're willing to let them just throw it in a Santa Claus bag and transport that anyways.
Now, if the players were trying to be deliberately game breaking with it, you can always have fun. Let's say they stack the treasure eight feet tall on a small bench and transport it. When they arrive, the mound of treasures topples, and riches are scattered everywhere. Small street urchins, poor folk, homeless beggars and Paul's girlfriend are all seen sprinting in to scoop up as much as possible. The player's are able to recover X % of the treasure before the rest disappears, and the guards come by and fine/imprison them for starting a riot.
That's just my opinion though. I don't mind people bending the rules a bit to do some ridiculous stuff, but I bend back a bit to show them I'll be just as ridiculous in response. | Make the table into a shipping container -- problem solved
----------------------------------------------------------
### Preface
The rules don't specify where the line is between "an object" and "not an object." Frankly, that's a good thing. This alleged imprecision gives both the DM and players room to work, to be creative, or to be imaginative. (Or, to not worry about it if that level of granularity / simulation / pedantry isn't where the players at the table gets their fun)
### To solve your specific problem (a table loaded with loot)
>
> How about a 10' long table stacked with gear? *Is the table also a container* in the same way or would teleporting a table not teleport the tablecloth?
>
>
>
From the spell description: (SRD, p. 183)
>
> This spell instantly transports ... a single object that you can see within range, to a destination you select. If you target an object, it must be able to fit entirely inside a 10-foot cube, and it can’t be held or carried by an unwilling creature.
>
>
>
1. Turn the table upside down, pile the stuff on the bottom of the
table. The legs define the four corners of a container.
2. Cover the pile of stuff/loot with the table cloth (and if needed, capes/blankets, etc).
3. Using the 50' of rope that one of your party carries, and adding a shield
on each long side of the table to stiffen and give shape to this
pile, strap it all down. As necessary, use ten-foot poles1 to support the top of the two long sides further. Viola! You have one object: an improvised shipping container.
4. Teleport it to your selected destination (to save on postage2).
### A weight limit (if you want one)
The weight limit can be estimated in a variety of ways. The rules give room to work, and ***D&D 5e is "rulings over rules"*** in intent.
>
> This spell instantly transports you and up to eight willing creatures of your choice that you can see within range
>
>
>
### Conservative estimate:
Whatever you and eight people like you weigh and can carry, based on the 15 x STR carrying capacity. (SRD pp. 79-80. Same as Basic Rules).
>
> Lifting and Carrying
>
> Your Strength score determines the amount of weight you can bear. The following terms define what you can lift or carry. Carrying Capacity. Your carrying capacity is your Strength score multiplied by 15. This is the weight (in pounds) that you can carry, which is high enough that most characters don’t usually have to worry about it.
>
> Push, Drag, or Lift.
>
> You can push, drag, or lift a weight in pounds up to twice your carrying capacity (or 30 times your Strength score). While pushing or dragging weight in excess of your carrying capacity, your speed drops to 5 feet.
>
>
>
While the limit would vary depending on each creature's STR score, you can use an average for your ruling. If you use 11 STR as average, then 165 x 9 for 9 human sized creatures. Add the weight of 9 human sized creatures themselves. For ease of calculation we'll say each weighs 165 pounds (*sans* gear).
165 x 18 = 2970 pounds or just under a ton and a half.
Substitute in different values for average load on a creature and average weight, and you'll get a different max weight, but that's your ballpark figure *if you want to define a weight limit*. Since movement isn't an issue here, using the 30 x STR (encumbered) would make some sense, so the above would be 165 x 27 for 4455 pounds: about two and a quarter tons.
### Liberal estimate that pushes RAW a bit
Whatever you and eight creatures that you can fit within a 10' radius circle weigh and can carry, per above. (8 horses? 8 oxen?) The limit there is how big a creature you think you can pack into that area, what it's STR score is, and thus what it can carry. Play around with creatures until you get a number you like.
---
1 Iconic dungeoneering gear. What do you mean you didn't bring a ten-foot pole? You're playing D&D, right?
2 Side effect: FedEx and UPS share prices on the Waterdeep Stock Exchange drop a bit in response to your brilliant problem solving. Agents form *Aurora's Whole Realms Catalog* contact you about trade rights infringement, through their solicitors. |
80,990 | There doesn't seem to be a weight limit on [teleport](https://www.dndbeyond.com/spells/teleport) anymore but, for the purposes of looting a dungeon, what is an object?
I can see how you can fill a chest and then teleport the chest and its contents. It is container and so all its contents are also teleported.
How about a 10' long table stacked with gear? Is the table also a container in the same way or would teleporting a table not teleport the tablecloth? | 2016/05/31 | [
"https://rpg.stackexchange.com/questions/80990",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/26539/"
] | ### By RAW, an object is a single designated thing that isn't alive. In my opinion RAI extends to obvious containers.
The teleport spell states (emphasis mine):
>
> This spell instantly transports you and up to eight willing creatures of your choice that you can see within range, or a single object that you can see within range, to a destination you select. If you target **an object**, it must be able to fit entirely inside a 10-foot cube, and it can’t be held or carried by an unwilling creature.
>
>
>
This wording indicates it only applies to a single object since it does not say all objects. It also makes no exceptions for containers and their contents.
For example, if you could transport anything in a container all you would have to do is build a makeshift 10 X 10 X 10 wooden cage and call it a large box. Then you could teleport 1000 cubic feet of whatever you want because you targeted the container.
Personally, I would allow transporting obvious containers like chests, bags of holding, boxes, jars, etc because that seems in keeping with the intent of the game mechanics. It also avoids the unnecessary confusion and ceaseless arguing over just how many separate objects make up a single carriage.
I would say that common sense needs to prevail. If the contents of a table would fit in a standard chest, there's no real reason to prevent players from designating the table or shelf as a container for the purpose of transport. Especially if you're willing to let them just throw it in a Santa Claus bag and transport that anyways.
Now, if the players were trying to be deliberately game breaking with it, you can always have fun. Let's say they stack the treasure eight feet tall on a small bench and transport it. When they arrive, the mound of treasures topples, and riches are scattered everywhere. Small street urchins, poor folk, homeless beggars and Paul's girlfriend are all seen sprinting in to scoop up as much as possible. The player's are able to recover X % of the treasure before the rest disappears, and the guards come by and fine/imprison them for starting a riot.
That's just my opinion though. I don't mind people bending the rules a bit to do some ridiculous stuff, but I bend back a bit to show them I'll be just as ridiculous in response. | Everything that is not separable is part of the object
------------------------------------------------------
You can teleport any single object that fits into a 10-foot cube and is not held or carried, there is no weight limit. So what is an object? The [definition of object](https://rpg.stackexchange.com/questions/95532/what-is-considered-an-object) (DMG, p. 246) is:
>
> For the purpose of these rules, an object is a discrete, inanimate item like a window, door, sword, book, table, chair, or stone, not a building or a vehicle that is composed of many other objects.
>
>
>
What you consider part of an object is not more explictly defined, and it will be up to the DM to adjudicate, but the examples in the DMG provide support that loose parts that cannot be easily separated from the object are part of the object.
First, the part about not being composed only applies to large objects, such as a ship or house, that you would want to divide into components for purposes of attacking and damaging. This is therefore not a hinderance for having small, composed objects.
Second, example objects listed in a table on p. 247 DMG about object sizes include a *lock* and, explicitly, a *chest*. That means, these must be *bona fide* objects, and attributes they have cannot be attributes that exclude something from being an object.
**Both of these items have, moving, separate components**. The lock will include tumblers and other, internal moving parts of the locking mechanism. The chest will have a lid with hinges, handles, and may even have it's own lock in turn. All these are lose, in a similar way coins in a locked chest or tied up sack are loose: they can move, and there can be air, oil or other substances in between them and other parts of the object. In all these examples, the components however are interlocking and not easily separated from the main bulk of the object. This gives us a baseline for judging what should be transported.
#### Table
It seems pretty clear that a table with stuff lying on it is not an integral thing in the same way, and only the table would be teleported. All the other items are loose and unconnected to it. If you however fastened all the items to the table with 50 feet of rope wrapped around (or built a parcel as suggested in Korvin's excellent answer), it would qualify as a single object.
#### Chest
A chest by itself is clearly an object, it is even in the given examples. The items within a locked chest can not be separated from the chest and would count as part of the object. However, if you hacked the chest open, or unlocked and opened it, then they could easily fall out, and would not be part of it any more nor be teleported along with it.
One side consequence is that if you target a locked chest with [disintegrate](https://www.dndbeyond.com/spells/disintegrate), all the (non-magical) items in the chest would likewise disintegrate. This has the added benefit that *disintegrate* cannot be used as a pseudo-masterkey for potentially trapped treasure chests. Unless you prefer your treasure in the form of a pile of grey dust. |
80,990 | There doesn't seem to be a weight limit on [teleport](https://www.dndbeyond.com/spells/teleport) anymore but, for the purposes of looting a dungeon, what is an object?
I can see how you can fill a chest and then teleport the chest and its contents. It is container and so all its contents are also teleported.
How about a 10' long table stacked with gear? Is the table also a container in the same way or would teleporting a table not teleport the tablecloth? | 2016/05/31 | [
"https://rpg.stackexchange.com/questions/80990",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/26539/"
] | Make the table into a shipping container -- problem solved
----------------------------------------------------------
### Preface
The rules don't specify where the line is between "an object" and "not an object." Frankly, that's a good thing. This alleged imprecision gives both the DM and players room to work, to be creative, or to be imaginative. (Or, to not worry about it if that level of granularity / simulation / pedantry isn't where the players at the table gets their fun)
### To solve your specific problem (a table loaded with loot)
>
> How about a 10' long table stacked with gear? *Is the table also a container* in the same way or would teleporting a table not teleport the tablecloth?
>
>
>
From the spell description: (SRD, p. 183)
>
> This spell instantly transports ... a single object that you can see within range, to a destination you select. If you target an object, it must be able to fit entirely inside a 10-foot cube, and it can’t be held or carried by an unwilling creature.
>
>
>
1. Turn the table upside down, pile the stuff on the bottom of the
table. The legs define the four corners of a container.
2. Cover the pile of stuff/loot with the table cloth (and if needed, capes/blankets, etc).
3. Using the 50' of rope that one of your party carries, and adding a shield
on each long side of the table to stiffen and give shape to this
pile, strap it all down. As necessary, use ten-foot poles1 to support the top of the two long sides further. Viola! You have one object: an improvised shipping container.
4. Teleport it to your selected destination (to save on postage2).
### A weight limit (if you want one)
The weight limit can be estimated in a variety of ways. The rules give room to work, and ***D&D 5e is "rulings over rules"*** in intent.
>
> This spell instantly transports you and up to eight willing creatures of your choice that you can see within range
>
>
>
### Conservative estimate:
Whatever you and eight people like you weigh and can carry, based on the 15 x STR carrying capacity. (SRD pp. 79-80. Same as Basic Rules).
>
> Lifting and Carrying
>
> Your Strength score determines the amount of weight you can bear. The following terms define what you can lift or carry. Carrying Capacity. Your carrying capacity is your Strength score multiplied by 15. This is the weight (in pounds) that you can carry, which is high enough that most characters don’t usually have to worry about it.
>
> Push, Drag, or Lift.
>
> You can push, drag, or lift a weight in pounds up to twice your carrying capacity (or 30 times your Strength score). While pushing or dragging weight in excess of your carrying capacity, your speed drops to 5 feet.
>
>
>
While the limit would vary depending on each creature's STR score, you can use an average for your ruling. If you use 11 STR as average, then 165 x 9 for 9 human sized creatures. Add the weight of 9 human sized creatures themselves. For ease of calculation we'll say each weighs 165 pounds (*sans* gear).
165 x 18 = 2970 pounds or just under a ton and a half.
Substitute in different values for average load on a creature and average weight, and you'll get a different max weight, but that's your ballpark figure *if you want to define a weight limit*. Since movement isn't an issue here, using the 30 x STR (encumbered) would make some sense, so the above would be 165 x 27 for 4455 pounds: about two and a quarter tons.
### Liberal estimate that pushes RAW a bit
Whatever you and eight creatures that you can fit within a 10' radius circle weigh and can carry, per above. (8 horses? 8 oxen?) The limit there is how big a creature you think you can pack into that area, what it's STR score is, and thus what it can carry. Play around with creatures until you get a number you like.
---
1 Iconic dungeoneering gear. What do you mean you didn't bring a ten-foot pole? You're playing D&D, right?
2 Side effect: FedEx and UPS share prices on the Waterdeep Stock Exchange drop a bit in response to your brilliant problem solving. Agents form *Aurora's Whole Realms Catalog* contact you about trade rights infringement, through their solicitors. | Everything that is not separable is part of the object
------------------------------------------------------
You can teleport any single object that fits into a 10-foot cube and is not held or carried, there is no weight limit. So what is an object? The [definition of object](https://rpg.stackexchange.com/questions/95532/what-is-considered-an-object) (DMG, p. 246) is:
>
> For the purpose of these rules, an object is a discrete, inanimate item like a window, door, sword, book, table, chair, or stone, not a building or a vehicle that is composed of many other objects.
>
>
>
What you consider part of an object is not more explictly defined, and it will be up to the DM to adjudicate, but the examples in the DMG provide support that loose parts that cannot be easily separated from the object are part of the object.
First, the part about not being composed only applies to large objects, such as a ship or house, that you would want to divide into components for purposes of attacking and damaging. This is therefore not a hinderance for having small, composed objects.
Second, example objects listed in a table on p. 247 DMG about object sizes include a *lock* and, explicitly, a *chest*. That means, these must be *bona fide* objects, and attributes they have cannot be attributes that exclude something from being an object.
**Both of these items have, moving, separate components**. The lock will include tumblers and other, internal moving parts of the locking mechanism. The chest will have a lid with hinges, handles, and may even have it's own lock in turn. All these are lose, in a similar way coins in a locked chest or tied up sack are loose: they can move, and there can be air, oil or other substances in between them and other parts of the object. In all these examples, the components however are interlocking and not easily separated from the main bulk of the object. This gives us a baseline for judging what should be transported.
#### Table
It seems pretty clear that a table with stuff lying on it is not an integral thing in the same way, and only the table would be teleported. All the other items are loose and unconnected to it. If you however fastened all the items to the table with 50 feet of rope wrapped around (or built a parcel as suggested in Korvin's excellent answer), it would qualify as a single object.
#### Chest
A chest by itself is clearly an object, it is even in the given examples. The items within a locked chest can not be separated from the chest and would count as part of the object. However, if you hacked the chest open, or unlocked and opened it, then they could easily fall out, and would not be part of it any more nor be teleported along with it.
One side consequence is that if you target a locked chest with [disintegrate](https://www.dndbeyond.com/spells/disintegrate), all the (non-magical) items in the chest would likewise disintegrate. This has the added benefit that *disintegrate* cannot be used as a pseudo-masterkey for potentially trapped treasure chests. Unless you prefer your treasure in the form of a pile of grey dust. |
36,015,250 | I have many to many relation between `users` and `projects` through `user_project`. I know I could simply add `has_many :projects` in User Serializer (and vice versa in project serializer) to nest projects inside users.
But I also have a few additional fields in `user_projects` table (eg. start and end dates for user's participation in a corresponding project) and I have no idea what is the correct way to include them in the returned json. Should I create a special serializer for projects that are returned inside user with `start_date` included as a project's attribute or there's another way to do that? | 2016/03/15 | [
"https://Stackoverflow.com/questions/36015250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5679283/"
] | The best way to do this would be to establish a `'has-many-through'` (HMT) relationship between the `user` and `project` models and create a serializer for relationship's model.
```
class UserProjectSerializer < ActiveModel::Serializer
...
end
```
This will then be used in the `UserSerializer` via:
```
has_many :users_projects
```
The reason is that the relationship between the models contains additional data.
To implement the HMT, you'll need to create the `user_projects` model and define the HMT relationship in the related models:
**users\_project.rb**
```
class UserProjects < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
```
**user.rb**
```
class User < ActiveRecord::Base
has_many: users_projects
has_many: projects, through: :user_projects
end
```
**project.rb**
```
class Project < ActiveRecord::Base
has_many: users_projects
has_many: users, through: :user_projects
end
``` | I have had a similar problem before and I made use of [rabl](https://github.com/nesquena/rabl). There is a good tutorial on [railscasts](http://railscasts.com/episodes/322-rabl) to help you get started. |
48,481,492 | I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] | let's compare your problem with function statements and lambdas (because they play the same role here), consider this function `f` :
```
def f ():
return 1
```
the above snippet of code is not an expression at all, it is a python statement that creates a function named `f` returning `1` upon calling it.
let's now do the same thing, but in a different way :
```
f = lambda : 1
```
the above snippet of code is a python expression (an assignment) that assigns the symbol `f` to the lambda expression (which is our function) `lambda : 1`. if we didn't do the assignment, the lambda expression would be lost, it is the same as writing `>>> 1` in the python REPL and then trying after that to reference it. | From [documentation](https://docs.python.org/2/library/functions.html#type)
>
> class **type**(name, bases, dict)
>
>
> With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the **name** attribute; the bases tuple itemizes the base classes and becomes the **bases** attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the **dict** attribute. For example, the following two statements create identical type objects:
>
>
>
```
class X(object):
a = 1
X = type('X', (object,), dict(a=1))
```
So yes, I think you have the right idea. `type()` does create a class but a dynamic form. |
48,481,492 | I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] | let's compare your problem with function statements and lambdas (because they play the same role here), consider this function `f` :
```
def f ():
return 1
```
the above snippet of code is not an expression at all, it is a python statement that creates a function named `f` returning `1` upon calling it.
let's now do the same thing, but in a different way :
```
f = lambda : 1
```
the above snippet of code is a python expression (an assignment) that assigns the symbol `f` to the lambda expression (which is our function) `lambda : 1`. if we didn't do the assignment, the lambda expression would be lost, it is the same as writing `>>> 1` in the python REPL and then trying after that to reference it. | Using `type` with 3 argument is analogous to using the `lambda` to create a function. Without assignment the evaluated expression is garbage collected.
However, just you can still create an instance of the class, just like you can immediately call a lambda function.
```
>>> lambda x: True
<function <lambda> at 0x0000022FF95AB598>
>>> type('Test', (), {'x': True})
<class '__main__.Test'>
```
You can also create an instance of the class, just like you can immediately call a function
```
>>> t = type('Test', (), {'x': True})()
>>> t.x
True
>>> type('Test2', (), {'y': 123})().y
123
>>> (lambda x: True)(1000) # any input returns True
True
``` |
48,481,492 | I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] | let's compare your problem with function statements and lambdas (because they play the same role here), consider this function `f` :
```
def f ():
return 1
```
the above snippet of code is not an expression at all, it is a python statement that creates a function named `f` returning `1` upon calling it.
let's now do the same thing, but in a different way :
```
f = lambda : 1
```
the above snippet of code is a python expression (an assignment) that assigns the symbol `f` to the lambda expression (which is our function) `lambda : 1`. if we didn't do the assignment, the lambda expression would be lost, it is the same as writing `>>> 1` in the python REPL and then trying after that to reference it. | I think you're making this too complicated. If you don't assign a value / object to a symbol, it is always "lost". Doesn't matter if the value / object is a class or something else. Example:
```
x = 2 + 2
```
That assigns the value `4` to the symbol `x`. Compare to:
```
2 + 2
```
The operation is carried out but the result `4` isn't assigned to a symbol.
Exact situation you have with classes. |
48,481,492 | I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] | Using `type` with 3 argument is analogous to using the `lambda` to create a function. Without assignment the evaluated expression is garbage collected.
However, just you can still create an instance of the class, just like you can immediately call a lambda function.
```
>>> lambda x: True
<function <lambda> at 0x0000022FF95AB598>
>>> type('Test', (), {'x': True})
<class '__main__.Test'>
```
You can also create an instance of the class, just like you can immediately call a function
```
>>> t = type('Test', (), {'x': True})()
>>> t.x
True
>>> type('Test2', (), {'y': 123})().y
123
>>> (lambda x: True)(1000) # any input returns True
True
``` | From [documentation](https://docs.python.org/2/library/functions.html#type)
>
> class **type**(name, bases, dict)
>
>
> With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the **name** attribute; the bases tuple itemizes the base classes and becomes the **bases** attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the **dict** attribute. For example, the following two statements create identical type objects:
>
>
>
```
class X(object):
a = 1
X = type('X', (object,), dict(a=1))
```
So yes, I think you have the right idea. `type()` does create a class but a dynamic form. |
48,481,492 | I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] | Using `type` with 3 argument is analogous to using the `lambda` to create a function. Without assignment the evaluated expression is garbage collected.
However, just you can still create an instance of the class, just like you can immediately call a lambda function.
```
>>> lambda x: True
<function <lambda> at 0x0000022FF95AB598>
>>> type('Test', (), {'x': True})
<class '__main__.Test'>
```
You can also create an instance of the class, just like you can immediately call a function
```
>>> t = type('Test', (), {'x': True})()
>>> t.x
True
>>> type('Test2', (), {'y': 123})().y
123
>>> (lambda x: True)(1000) # any input returns True
True
``` | I think you're making this too complicated. If you don't assign a value / object to a symbol, it is always "lost". Doesn't matter if the value / object is a class or something else. Example:
```
x = 2 + 2
```
That assigns the value `4` to the symbol `x`. Compare to:
```
2 + 2
```
The operation is carried out but the result `4` isn't assigned to a symbol.
Exact situation you have with classes. |
48,204 | My website is in PHP, running on Apache.
One of my users is on a WAN with 2 IPs and his connection gets routed to our server by any one of them.
PHP seems to log out the user out, if it detects change in IP.
It is an open source app and I think some common popular file must have been used.
Any way to prevent it? | 2009/07/30 | [
"https://serverfault.com/questions/48204",
"https://serverfault.com",
"https://serverfault.com/users/15055/"
] | I don't think apache has anything to do with that. The problem is most likely in php session although I don't think php checks the client ip by default. Are you sure there's nothing in your code checking the ip for a session? | I think it would be in PHP, not Apache. You might want to look see if the REMOTE\_ADDR is being used with $\_SERVER in generating the sessions. See [this PHP reference](http://us3.php.net/manual/en/reserved.variables.server.php), and [here is a whole thread](http://www.daniweb.com/forums/thread49898.html#) on the topic.
You might have better luck on stackoverflow. |
48,204 | My website is in PHP, running on Apache.
One of my users is on a WAN with 2 IPs and his connection gets routed to our server by any one of them.
PHP seems to log out the user out, if it detects change in IP.
It is an open source app and I think some common popular file must have been used.
Any way to prevent it? | 2009/07/30 | [
"https://serverfault.com/questions/48204",
"https://serverfault.com",
"https://serverfault.com/users/15055/"
] | I don't think apache has anything to do with that. The problem is most likely in php session although I don't think php checks the client ip by default. Are you sure there's nothing in your code checking the ip for a session? | This is not PHP, or Apache -- it is a security 'option' of whatever FOSS package you are using. PHP sessions have no inherent security.
If *Joe* with IP 192.168.0.1 logs into your site, he might get a session token of **ABC123**. If *Jane* then goes to her workstation, manually creates the cookie that contains the session ID **ABC123** and then goes to <http://yoursite>, she will appear as if she is *Joe* to your system. This is critically important when users are using a proxy (users from the UAE for example are routed out via a series of 3 regional routers) that can change -- AOL is another example.
There should be a configuration option to turn this security feature off. |
30,401,920 | I am trying to copy files, folders, sub folders, zip files etc from a given location to another location. I used the code below.
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyDirectoryExample
{
public static void main(String[] args)
{
File srcFolder = new File("C:\\Users\\Yohan\\Documents");
File destFolder = new File("D:\\Test");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
```
Now, I used the above code to take a copy of "My Documents". But unfortunatly, it ended up with `NullPointerException` after running for a while.
The reason for the error is it tried to take a copy of "My Music" folder, which is not even inside of the "My Documents" folder. I tested this code in 2 different machines running windows 7, got the same error in both.
A windows specific solution is fine for me, as I am targeting windows machines at the moment. What have I done wrong?
The error I am getting is below
```
Directory copied from C:\Users\Yohan\Documents\My Music to D:\Test\My Music
Exception in thread "main" java.lang.NullPointerException
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:51)
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:56)
at CopyDirectoryExample.main(CopyDirectoryExample.java:25)
``` | 2015/05/22 | [
"https://Stackoverflow.com/questions/30401920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] | The reason this isn't working is because "My Music", "My Pictures" (or Images) and other directories are just symbolic links. See this post on how to detect symbolic links: [Java 1.6 - determine symbolic links](https://stackoverflow.com/questions/813710/java-1-6-determine-symbolic-links) | You are not handling the empty directories -- try making the following change,
It will work after making the below change.
```
//list all the directory contents
String files[] = src.list();
if (files!=null && files.length>0) {
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}
``` |
30,401,920 | I am trying to copy files, folders, sub folders, zip files etc from a given location to another location. I used the code below.
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyDirectoryExample
{
public static void main(String[] args)
{
File srcFolder = new File("C:\\Users\\Yohan\\Documents");
File destFolder = new File("D:\\Test");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
```
Now, I used the above code to take a copy of "My Documents". But unfortunatly, it ended up with `NullPointerException` after running for a while.
The reason for the error is it tried to take a copy of "My Music" folder, which is not even inside of the "My Documents" folder. I tested this code in 2 different machines running windows 7, got the same error in both.
A windows specific solution is fine for me, as I am targeting windows machines at the moment. What have I done wrong?
The error I am getting is below
```
Directory copied from C:\Users\Yohan\Documents\My Music to D:\Test\My Music
Exception in thread "main" java.lang.NullPointerException
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:51)
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:56)
at CopyDirectoryExample.main(CopyDirectoryExample.java:25)
``` | 2015/05/22 | [
"https://Stackoverflow.com/questions/30401920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] | Unfortunately, these folders (Images, Music, Videos) are NOT considered symbolic links in Java. Using Java 8,
```
Files.isSymbolicLink(srcFile.toPath())
```
While return false, and `Files.readSymbolicLink(srcFile.toPath())` will fail with an Access Denied Exception.
So you can't process them automatically. Fix your code so that you handle properly the case where `srcFile.isDirectory()` returns true, but `srcFile.listFiles()` return null.
On my Windows 8 machine, three folders were in that case. I'm on a French machine, so I got a "Ma Musique" folder that gave null for `listFiles`. However,
```
new File("C:\\Users\\<user>\\Music").listFiles()
```
Does NOT return null. So I'm afraid you'll have to hardcode special code for the three folders (Music, Videos, Images) if you want to copy the data too. | You are not handling the empty directories -- try making the following change,
It will work after making the below change.
```
//list all the directory contents
String files[] = src.list();
if (files!=null && files.length>0) {
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}
``` |
36,093,126 | The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
``` | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] | `argv` variable contains command line arguments. In your code you expected 4 arguments, but got only 1 (first argument always script name). You could configure arguments in `pycharm`. Go to `Run` -> `Edit Configurations`. Then create a new python configuration. And there you could specify `Script parameters` field. Or you could run your script from command line as mentioned by dnit13. | Run it from the shell like this:
```
python script.py arg1 arg2 arg3
``` |
36,093,126 | The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
``` | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] | Run it from the shell like this:
```
python script.py arg1 arg2 arg3
``` | You could run it like this: python script.py first, second, third |
36,093,126 | The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
``` | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] | Run it from the shell like this:
```
python script.py arg1 arg2 arg3
``` | I think you are running the following command:
```
python script.py
```
You are writing a program which is aksing for 4 inputs and you are giving onle one. That's why you are receiving an error. You can use the below command:
```
python script.py Hello How Are
``` |
36,093,126 | The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
``` | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] | `argv` variable contains command line arguments. In your code you expected 4 arguments, but got only 1 (first argument always script name). You could configure arguments in `pycharm`. Go to `Run` -> `Edit Configurations`. Then create a new python configuration. And there you could specify `Script parameters` field. Or you could run your script from command line as mentioned by dnit13. | You could run it like this: python script.py first, second, third |
36,093,126 | The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
``` | 2016/03/18 | [
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] | `argv` variable contains command line arguments. In your code you expected 4 arguments, but got only 1 (first argument always script name). You could configure arguments in `pycharm`. Go to `Run` -> `Edit Configurations`. Then create a new python configuration. And there you could specify `Script parameters` field. Or you could run your script from command line as mentioned by dnit13. | I think you are running the following command:
```
python script.py
```
You are writing a program which is aksing for 4 inputs and you are giving onle one. That's why you are receiving an error. You can use the below command:
```
python script.py Hello How Are
``` |
17,322,583 | I'm trying to to install my rails app on a second computer. But when I run `bundle install` I get an error with the json gem:
```
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.0), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.0'` succeeds before bundling.
```
The computer runs Mac OS X 10.8.4 with Xcode 4.6.3 and the latest command line tools.
I installed the latest ruby using rvm:
```
$ rvm -v
rvm 1.21.2 (stable) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.4.0]
$ gem -v
2.0.3
```
When I try to install the json gem using `gem install json` I get almost the same error:
```
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
```
Trying to install using `sudo` does not change anything.
I uninstalled and reinstalled homebrew, rvm, ruby & the command line tools but nothing helps.
**Update**
Contentent of `/Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out`:
```
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
```
GCC Version:
```
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
```
**Update 2**
I did a fresh install of OS X, Xcode, Command Line Tools, Homebrew, rvm and Ruby. Ruby is now patch level 247 and the damn problem is still there. What a waste of time... If it is important: rvm installed json 1.7.7 together with ruby
**Update 3**
Seems that my machine fails on all native extensions. `gem install bcrypt-ruby` gives the same error message. | 2013/06/26 | [
"https://Stackoverflow.com/questions/17322583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183192/"
] | The problem was that my home folder is on a separate volume which contained a space in its name. Because of the space the second part of the name was interpreted as an option. The volumes name was something like `My Data` and thus I got the message`invalid option -D`.
I just renamed this volume and now everything installs fine. | This seems to still be a bug...
<https://github.com/flori/json/issues/163>
Only caused with bundle.
Can you try the gem install json?
It might solve the problem after. |
17,322,583 | I'm trying to to install my rails app on a second computer. But when I run `bundle install` I get an error with the json gem:
```
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.0), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.0'` succeeds before bundling.
```
The computer runs Mac OS X 10.8.4 with Xcode 4.6.3 and the latest command line tools.
I installed the latest ruby using rvm:
```
$ rvm -v
rvm 1.21.2 (stable) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.4.0]
$ gem -v
2.0.3
```
When I try to install the json gem using `gem install json` I get almost the same error:
```
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
```
Trying to install using `sudo` does not change anything.
I uninstalled and reinstalled homebrew, rvm, ruby & the command line tools but nothing helps.
**Update**
Contentent of `/Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out`:
```
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
```
GCC Version:
```
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
```
**Update 2**
I did a fresh install of OS X, Xcode, Command Line Tools, Homebrew, rvm and Ruby. Ruby is now patch level 247 and the damn problem is still there. What a waste of time... If it is important: rvm installed json 1.7.7 together with ruby
**Update 3**
Seems that my machine fails on all native extensions. `gem install bcrypt-ruby` gives the same error message. | 2013/06/26 | [
"https://Stackoverflow.com/questions/17322583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183192/"
] | This seemed to happen with Json versions 1.8.0 and 1.8.1 (Ruby 2.2.3) ... I was able to upgrade to 1.8.2 and 1.8.3 with no problems ... specifying those versions
```
gem 'json', '~> 1.8.2'
```
in my bundle got me around the problem. | This seems to still be a bug...
<https://github.com/flori/json/issues/163>
Only caused with bundle.
Can you try the gem install json?
It might solve the problem after. |
17,322,583 | I'm trying to to install my rails app on a second computer. But when I run `bundle install` I get an error with the json gem:
```
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.0), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.0'` succeeds before bundling.
```
The computer runs Mac OS X 10.8.4 with Xcode 4.6.3 and the latest command line tools.
I installed the latest ruby using rvm:
```
$ rvm -v
rvm 1.21.2 (stable) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.4.0]
$ gem -v
2.0.3
```
When I try to install the json gem using `gem install json` I get almost the same error:
```
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
```
Trying to install using `sudo` does not change anything.
I uninstalled and reinstalled homebrew, rvm, ruby & the command line tools but nothing helps.
**Update**
Contentent of `/Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out`:
```
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
```
GCC Version:
```
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
```
**Update 2**
I did a fresh install of OS X, Xcode, Command Line Tools, Homebrew, rvm and Ruby. Ruby is now patch level 247 and the damn problem is still there. What a waste of time... If it is important: rvm installed json 1.7.7 together with ruby
**Update 3**
Seems that my machine fails on all native extensions. `gem install bcrypt-ruby` gives the same error message. | 2013/06/26 | [
"https://Stackoverflow.com/questions/17322583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183192/"
] | The problem was that my home folder is on a separate volume which contained a space in its name. Because of the space the second part of the name was interpreted as an option. The volumes name was something like `My Data` and thus I got the message`invalid option -D`.
I just renamed this volume and now everything installs fine. | This seemed to happen with Json versions 1.8.0 and 1.8.1 (Ruby 2.2.3) ... I was able to upgrade to 1.8.2 and 1.8.3 with no problems ... specifying those versions
```
gem 'json', '~> 1.8.2'
```
in my bundle got me around the problem. |
94,644 | Excluding vocabulary items which are entirely new or have fallen into disuse, what are some ways in which Japanese syntax itself has changed between the 1950s and today?
(I would also like to exclude phenomena such as the semi-productivity of terms like ググる, since I'd argue these are new vocabulary and not fully productive ways of deriving new words.) | 2022/05/23 | [
"https://japanese.stackexchange.com/questions/94644",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/816/"
] | [言文一致](https://en.wikipedia.org/wiki/Genbun_itchi) and the shift to modern kana orthography (1946) happened shortly before this period, and they were undoubtedly much more fundamental than anything that happened after 1950. But I'll focus on the change of modern 口語 here. The list is far from complete; I just wrote down things that came to mind.
* Decline of ましょう as a way to express future inference.
>
> 明日は雨が降りましょう。
>
>
>
This was common in weather forecast until the 1970's, but we never hear this today. See: <https://ameblo.jp/heppokomental/entry-12527905042.html>
* Decline of some "heavy" keigo patterns (でございます, でありました, くださいませ, ...)
* Continued decline of ぬ as a negation marker (ありませぬ, 分からぬ, ...)
* Decline of many gender-specific sentence endings (かしら, だわ, ...), although many remain in fictional works as part of お嬢様言葉
* Decline of most iteration marks (ゝ, [〱](https://japanese.stackexchange.com/q/40805/5010), ...) except 々. (If I understand correctly, these symbols have never been officially standardized nor banned by the government.)
* Increased acceptance of ら抜き of ichidan potential forms (食べれる, 見れる, ...)
* Increased acceptance of `i-adjective + です` (嬉しいです, よかったです, ...) and the decline of ~うございます. See: [Conjugating present and past negative i-adjectives](https://japanese.stackexchange.com/q/68964/5010) | If you mean by "syntax" basic structures of the language and fundamental rules of how you construct a sentence (like the subject-object-verb order), I'd say nothing has changed. Most languages don't change at the fundamental level in 70 years, or in the lifetime of a person.
That said, which grammatical words and constructions are preferred have changed in some cases, especially in spoken Japanese. Off the top of my head, in negation constructions, ないです is a much more acceptable alternative to ありません than it was, and -ぬ (as in 足らぬ) became less preferred over -ない (as in 足りない). You hear less いかに and いかなる for "how" and "what", more どう/どのように and どんな. I'm sure there are many more examples like these. The old words like these can still be spoken, and maybe part of set phrases in some cases, but they generally add an old-fashioned tone to how you speak. (Not too unlike how "thou" and "thee" may sound in English, I think.)
There is a famous song starting with 兎追いしかの山. This would be 兎を追ったあの山 ("the mountain where I chased after rabbits") in today's Japanese. Children learn this song in school and may misunderstand 追いし as 美味し(い), because the 追いし form of the verb 追う is simply not used any more. |
30,208,595 | I am building a form where I need to programmatically set bindings and the dataset (as it is variable and different documents can be loaded in to it). I've managed to get the form to load any information in to a `DataGridView` and also load that information from the `DataGridView` in to some TextBoxes for structured editing:

However I am struggling to get the edited information to save back to the database. It won't even update the `DataGridView` with anything. Here's the code I'm currently using:
```
Imports System.Data.SqlClient
Imports System.Data.OleDb
Module DataGridView_Setup
Public Sub Set_Datasource(mode As Integer)
Dim connString As String = My.Settings.Database_String
Dim myConnection As OleDbConnection = New OleDbConnection
myConnection.ConnectionString = connString
' create a data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT ID, [Name Of Person], [SAP Job Number], [Site Name], [Asset Description], [Spares Supplier], [Supplier Contact Name], [Supplier Contact Phone Number], [Supplier Contact Email], [Spares Description], [Part Number], [Quantity To Order], Cost, [Request Date], [Date Ordered], [Ordered By], [Invoice Received], [Invoice Paid], [Method Of Payment], [Date Item Received], [Additional Comments], [Quote Attatchment] FROM Spares", myConnection)
' create a new dataset
Dim ds As DataSet = New DataSet
' fill dataset
da.Fill(ds, "Spares")
Main.DataGridView1.DataSource = ds.Tables(0)
Main.DataGridView1.AllowUserToAddRows = False
'Set Site Listbox
Dim SiteString = My.Settings.SETTINGS_SiteNames
Dim SiteBox = Main.VIEW_Site.Items
SiteBox.Clear()
Do Until SiteString = ""
Dim ActiveSiteName = Left(SiteString, InStr(SiteString, "¦"))
ActiveSiteName = ActiveSiteName.Remove(ActiveSiteName.Length - 1)
With SiteBox
.Add(ActiveSiteName)
End With
SiteString = Replace(SiteString, ActiveSiteName + "¦", "")
Loop
'Set DataBindings
Main.VIEW_Ref.DataBindings.Clear()
Main.VIEW_Ref.DataBindings.Add(New Binding("Text", ds, "Spares.ID", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_NameOfPerson.DataBindings.Clear()
Main.VIEW_NameOfPerson.DataBindings.Add(New Binding("Text", ds, "Spares.Name Of Person", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SAPJobNo.DataBindings.Clear()
Main.VIEW_SAPJobNo.DataBindings.Add(New Binding("Text", ds, "Spares.SAP Job Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_Site.DataBindings.Clear()
Main.VIEW_Site.DataBindings.Add(New Binding("Text", ds, "Spares.Site Name", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_AssetDesc.DataBindings.Clear()
Main.VIEW_AssetDesc.DataBindings.Add(New Binding("Text", ds, "Spares.Asset Description", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SparesSupplier.DataBindings.Clear()
Main.VIEW_SparesSupplier.DataBindings.Add(New Binding("Text", ds, "Spares.Spares Supplier", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactName.DataBindings.Clear()
Main.VIEW_SupplierContactName.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Name", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactNumber.DataBindings.Clear()
Main.VIEW_SupplierContactNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Phone Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactNumber.DataBindings.Clear()
Main.VIEW_SupplierContactNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Phone Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactEmail.DataBindings.Clear()
Main.VIEW_SupplierContactEmail.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Email", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SparesDesc.DataBindings.Clear()
Main.VIEW_SparesDesc.DataBindings.Add(New Binding("Text", ds, "Spares.Spares Description", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_PartNumber.DataBindings.Clear()
Main.VIEW_PartNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Part Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_QuantityToOrder.DataBindings.Clear()
Main.VIEW_QuantityToOrder.DataBindings.Add(New Binding("Text", ds, "Spares.Quantity To Order", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_CostEach.DataBindings.Clear()
Main.VIEW_CostEach.DataBindings.Add(New Binding("Text", ds, "Spares.Cost", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_DateRequested.DataBindings.Clear()
Main.VIEW_DateRequested.DataBindings.Add(New Binding("Text", ds, "Spares.Request Date", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_DateOrdered.DataBindings.Clear()
Main.VIEW_DateOrdered.DataBindings.Add(New Binding("Text", ds, "Spares.Date Ordered", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_OrderedBy.DataBindings.Clear()
Main.VIEW_OrderedBy.DataBindings.Add(New Binding("Text", ds, "Spares.Ordered By", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_InvoiceReceivedDate.DataBindings.Clear()
Main.VIEW_InvoiceReceivedDate.DataBindings.Add(New Binding("Text", ds, "Spares.Invoice Received", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_InvoicePaidDate.DataBindings.Clear()
Main.VIEW_InvoicePaidDate.DataBindings.Add(New Binding("Text", ds, "Spares.Invoice Paid", False, DataSourceUpdateMode.OnPropertyChanged))
DataGridView_Setup.BindingUpdates()
End Sub
Public Sub BindingUpdates()
Dim curr As DataGridViewRow = Main.DataGridView1.CurrentRow
Main.VIEW_Ref.Text = curr.Cells("ID").Value
Main.VIEW_NameOfPerson.Text = curr.Cells("Name Of Person").Value
Main.VIEW_SAPJobNo.Text = curr.Cells("SAP Job Number").Value
Main.VIEW_Site.Text = curr.Cells("Site Name").Value
Main.VIEW_AssetDesc.Text = curr.Cells("Asset Description").Value
Main.VIEW_SparesSupplier.Text = curr.Cells("Spares Supplier").Value
Main.VIEW_SupplierContactName.Text = curr.Cells("Supplier Contact Name").Value
Main.VIEW_SupplierContactNumber.Text = curr.Cells("Supplier Contact Phone Number").Value
Main.VIEW_SupplierContactEmail.Text = curr.Cells("Supplier Contact Email").Value
Main.VIEW_SparesDesc.Text = curr.Cells("Spares Description").Value
Main.VIEW_PartNumber.Text = curr.Cells("Part Number").Value
Main.VIEW_QuantityToOrder.Text = curr.Cells("Quantity To Order").Value
Main.VIEW_CostEach.Text = "£" + CStr(curr.Cells("Cost").Value)
Main.VIEW_DateRequested.Text = curr.Cells("Request Date").Value
'Handle DBNULL From now on
If IsDBNull(curr.Cells("Date Ordered").Value) = True Then
With Main.VIEW_DateOrdered
.Text = "Not Ordered Yet"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_DateOrdered
.Text = curr.Cells("Date Ordered").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Ordered By").Value) = True Then
With Main.VIEW_OrderedBy
.Text = "Not Ordered Yet"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_OrderedBy
.Text = curr.Cells("Ordered By").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Invoice Received").Value) = True Then
With Main.VIEW_InvoiceReceivedDate
.Text = "No Invoice"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_InvoiceReceivedDate
.Text = curr.Cells("Invoice Received").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Invoice Paid").Value) = True Then
With Main.VIEW_InvoicePaidDate
.Text = "Not Paid"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_InvoicePaidDate
.Text = curr.Cells("Invoice Paid").Value
.BackColor = Color.White
End With
End If
End Sub
End Module
```
I have set `DataSourceUpdateMode.OnPropertyChanged` and assumed that this means when the textbox's are changed, it will update the datasource (being the database). I'm guessing this isn't the case as it doesn't work.
What I'd really like is to be able to edit multiple fields on one data row (via the textboxes) and then click the "Save Changes" button to update the Database.
Thanks
**UPDATE 1**
I've done a bit more research following some comments and answers and have written this code in to my `Save` button:
```
Public Sub Save()
Dim myCon = New OleDbConnection(My.Settings.Database_String)
myCon.Open()
Dim sqr = "UPDATE [Spares] SET [Name Of Person] = '" & Main.VIEW_NameOfPerson.Text & "', [SAP Job Number] = '" & CInt(Main.VIEW_SAPJobNo.Text) & "', " & _
"[Site Name] = '" & Main.VIEW_Site.Text & "', [Asset Description] = '" & Main.VIEW_AssetDesc.Text & "', " & _
"[Spares Supplier] = '" & Main.VIEW_SparesSupplier.Text & "', [Supplier Contact Name] = '" & Main.VIEW_SupplierContactName.Text & "', " & _
"[Supplier Contact Phone Number] = '" & Main.VIEW_SupplierContactNumber.Text & "', " & _
"[Supplier Contact Email] = '" & Main.VIEW_SupplierContactEmail.Text & "', [Spares Description] = '" & Main.VIEW_SparesDesc.Text & "', " & _
"[Part Number] = '" & Main.VIEW_PartNumber.Text & "', [Quantity To Order] = '" & CInt(Main.VIEW_QuantityToOrder.Text) & "', " & _
"[Cost] = '" & CDbl(Main.VIEW_CostEach.Text) & "', [Request Date] = '" & CDate(Main.VIEW_DateRequested.Text) & "' WHERE [ID] = '" & CInt(Main.VIEW_Ref.Text) & "'"
Dim Command = New OleDbCommand(sqr, myCon)
Command.ExecuteNonQuery()
myCon.Close()
End Sub
```
When the `Command.ExecuteNonQuery` line attempts to execute I get an error that states the following:
>
> An unhandled exception of type 'System.Data.OleDb.OleDbException'
> occurred in System.Data.dll
>
>
> Additional information: Data type mismatch
> in criteria expression.
>
>
>
**NB:** The string that is produced in `sqr` is:
```
UPDATE [Spares] SET [Name Of Person] = 'Name', [SAP Job Number] = '2', [Site Name] = 'Site', [Asset Description] = 'Asset', [Spares Supplier] = 'Spares Supplier', [Supplier Contact Name] = 'Contact Name', [Supplier Contact Phone Number] = 'Contact Email', [Supplier Contact Email] = 'Contact Number', [Spares Description] = 'Spare Desc', [Part Number] = 'Part Number', [Quantity To Order] = '1', [Cost] = '1', [Request Date] = '12/02/02' WHERE [ID] = '5'"
```
I am obviously using dummy information
I can't be too far away now surely! | 2015/05/13 | [
"https://Stackoverflow.com/questions/30208595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925536/"
] | `svcState` should be provider rather than service. Because service/factory won't be accessible inside config phase. You need to change the implementation of `svcState` to provider so that it will be available in config block of angular.
After provider implementation you could inject that provider using `svcStateProvider` in config block.
```
.config(function($routeProvider, svcStateProvider, cApp){
$routeProvider
.when('/home', {
templateUrl: "partials/home"
})
.when('/info', {
templateUrl: "partials/info"
})
.otherwise({
redirectTo: svcStateProvider.getState() //<--change herer
})
})
```
Look at [**this answer**](https://stackoverflow.com/a/28262966/2435473) to know more about provider | Here is what I changed:
```
angular
.module('main', [
'ngRoute'
])
.provider('appState', function(){
var appState;
this.setState = function(newState) {
appState = newState;
};
this.getState = function() {
return appState;
};
this.$get = function() {
return appState;
};
function init() {appState='/home';}
init();
})
.config(function($routeProvider, appStateProvider){
$routeProvider
.when('/home', {
templateUrl: "partials/home"
})
.when('/info', {
templateUrl: "partials/info"
})
.otherwise({
redirectTo: appStateProvider.getState()
})
})
;
``` |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | It's always about the brand.
============================
What does the brand stand for in it's audience's mind? Is it offensive, irreverent, tasteless? Then you have to live up to that. Anything less wouldn't be true to their intended message. If you aren't comfortable with that type of material, you shouldn't be working with a brand that stands for it in the first place.
Another commenter mentioned McDonald's "healthy" messaging. It's a lie, but so is everything else about McD's. Their audience doesn't care that their products are only vaguely related to food. They like the taste of additives and being told that it's good for them. Their audience is notoriously disinterested in genuineness.
Brands are people too. Sorta.
=============================
Every brand should be first understood as a character, a personality, something an audience can personify in their minds. Once you have an accurate persona of the brand in your mind, then you'll know where to go with just about any message.
The tricky part is when a brand wants to transform it's persona. Then things get very murky and you'll be leaning on either a lot of market research or (in the most stressful circumstances) intuition. It's awefully fun, though :) |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | Purely from a graphic designer's POV, it's a decision that each designer has to make on their own based on the particulars of the given situation.
In general, being offensive isn't a typical marketing strategy, though it does get used. You as a designer have to decide if you want to work on projects that are purposefully attempting to be offensive. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | This is really Your Mileage May Vary, or in this case Your Audience's Mileage May Vary.
What one audience thinks is tasteless is another audience's boring. The multi-racial family in the Cheerios ad, for example: in some corners of the U.S. it's shocking to the point of boycotting the cereal, in some areas the reaction is "Finally!", in some it's "huh? there's an issue?" and in still others viewers say "Wait, is the problem that the dad undermined the mom by telling the daughter she could have a dog without clearing it with the mom first?"
If you're worried about future employment, then you have to calculate your entire career trajectory every time you take on a client. Or you have to decide if you have enough projects at Offense Level 4 that you can afford to remove the one at Offense Level 7 from your portfolio.
There are very few DEFCON 1 projects which nearly everyone will find offensive. X-rated ads are probably up there. Tobacco in the U.S. is high on the list but not necessarily a career killer. Below that, well, know your audience. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | Great answers here, I just wanted to mention something that hasn't been raised yet (except in the question), and it's the matter of **dignity**.
Humor, even if slightly offensive for a group or the other, is one thing. I love humor. Playing on people's weaknesses for the sake of profit is entirely different. I don't mind the 'colorful' Benetton ads, but I do not feel comfortable for example with the [Bosnian soldier ad](http://top10bay.com/wp-content/uploads/2011/12/bosnian-soldier1-300x198.jpg). We need to talk about war, yes. We need to talk about war so we can sell t-shirts, well, don't count me in. Now if it's UNICEF using pictures of poor little children to cause a reaction that's a different story. Is it ethical? Maybe they could find an alternative way of promoting what they do and get donations. But is the goal ethical? Yes, it is.
Witty marketing ideas (products can in fact provoke feelings) is different from ruthless manipulation of emotions.
But I guess for me it comes down to what are you trying to sell. I would never work for Monsanto, and I would never think of one of their ads as art, no matter how genius it is. I can't divorce what a company does/sells from the company itself. McDonalds stating their food is *healthy* is plain harmful. Can you oversee the sexist and borderline racist stereotyping of Axe's campaign [Make love not war](https://www.google.co.nz/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCwQtwIwAA&url=http://www.youtube.com/watch?v=63b4O_2HCYM&ei=ycg5U5vtOc7ukgXuyIDoAg&usg=AFQjCNGPN6OPQexNxwbDUb-mKt48h9LRvA&sig2=UaqCaZOYLcdUMI4RNUAudA)? No matter how nicely filmed it is, or how well executed the idea was, I can't. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | I second Emilie in saying that everything will offend someone somewhere. Personally, I am pretty sick of people finding offence left right and centre. Some people are *looking for* things that will get their knickers in a twist, and as Alan so elegantly points out: pleasing everyone ends up in the bland, the invisible and - *at best* - mediocre work. And therefore not efficient communication or marketing.
Cultural preferences imposed from other countries and other cultures ideas of PC is incredibly annoying. *That* is offensive. I will not have USA, Italy, Uganda or Fiji telling me how *not* to make ads for Scandinavia.
You could say that this is really about a *communication language,* and do not forget that some level of offence can be very effective marketing. You can annoy some people, stereotype them; and this will strengthen the brand among those who sees themselves the opposite. You can be upset, offended or intrigued by the series of [**United Colors of Benetton,**](http://top10buzz.com/top-ten-controversial-united-colors-of-benetton-ads/) they will rarely leave you indifferent. Funnily enough, regarding United Colors, their clothes are pretty non-descript (though colourful), but the ads often makes people go rabid. I think you can annoy people and still sell them things: if you first annoy them, and then make them think.
I once saw an ad, with four gray, grave, boring, suited, miserable guys with the caption "the most colourful thing (accountants) Johnson, Hansen, Jensen and Nielsen did last year, was to switch to eco-friendly printing paper". I think accountants might find it funny too
Good ads makes you see things a little differently, they surprise you a little: enough to have your attention for a little bit. You cannot do this by pleasing everyone. Sometimes you have to be bold, be brave, and just go for it. Political correctness is too often stupid. | Great answers here, I just wanted to mention something that hasn't been raised yet (except in the question), and it's the matter of **dignity**.
Humor, even if slightly offensive for a group or the other, is one thing. I love humor. Playing on people's weaknesses for the sake of profit is entirely different. I don't mind the 'colorful' Benetton ads, but I do not feel comfortable for example with the [Bosnian soldier ad](http://top10bay.com/wp-content/uploads/2011/12/bosnian-soldier1-300x198.jpg). We need to talk about war, yes. We need to talk about war so we can sell t-shirts, well, don't count me in. Now if it's UNICEF using pictures of poor little children to cause a reaction that's a different story. Is it ethical? Maybe they could find an alternative way of promoting what they do and get donations. But is the goal ethical? Yes, it is.
Witty marketing ideas (products can in fact provoke feelings) is different from ruthless manipulation of emotions.
But I guess for me it comes down to what are you trying to sell. I would never work for Monsanto, and I would never think of one of their ads as art, no matter how genius it is. I can't divorce what a company does/sells from the company itself. McDonalds stating their food is *healthy* is plain harmful. Can you oversee the sexist and borderline racist stereotyping of Axe's campaign [Make love not war](https://www.google.co.nz/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCwQtwIwAA&url=http://www.youtube.com/watch?v=63b4O_2HCYM&ei=ycg5U5vtOc7ukgXuyIDoAg&usg=AFQjCNGPN6OPQexNxwbDUb-mKt48h9LRvA&sig2=UaqCaZOYLcdUMI4RNUAudA)? No matter how nicely filmed it is, or how well executed the idea was, I can't. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | I second Emilie in saying that everything will offend someone somewhere. Personally, I am pretty sick of people finding offence left right and centre. Some people are *looking for* things that will get their knickers in a twist, and as Alan so elegantly points out: pleasing everyone ends up in the bland, the invisible and - *at best* - mediocre work. And therefore not efficient communication or marketing.
Cultural preferences imposed from other countries and other cultures ideas of PC is incredibly annoying. *That* is offensive. I will not have USA, Italy, Uganda or Fiji telling me how *not* to make ads for Scandinavia.
You could say that this is really about a *communication language,* and do not forget that some level of offence can be very effective marketing. You can annoy some people, stereotype them; and this will strengthen the brand among those who sees themselves the opposite. You can be upset, offended or intrigued by the series of [**United Colors of Benetton,**](http://top10buzz.com/top-ten-controversial-united-colors-of-benetton-ads/) they will rarely leave you indifferent. Funnily enough, regarding United Colors, their clothes are pretty non-descript (though colourful), but the ads often makes people go rabid. I think you can annoy people and still sell them things: if you first annoy them, and then make them think.
I once saw an ad, with four gray, grave, boring, suited, miserable guys with the caption "the most colourful thing (accountants) Johnson, Hansen, Jensen and Nielsen did last year, was to switch to eco-friendly printing paper". I think accountants might find it funny too
Good ads makes you see things a little differently, they surprise you a little: enough to have your attention for a little bit. You cannot do this by pleasing everyone. Sometimes you have to be bold, be brave, and just go for it. Political correctness is too often stupid. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | I second Emilie in saying that everything will offend someone somewhere. Personally, I am pretty sick of people finding offence left right and centre. Some people are *looking for* things that will get their knickers in a twist, and as Alan so elegantly points out: pleasing everyone ends up in the bland, the invisible and - *at best* - mediocre work. And therefore not efficient communication or marketing.
Cultural preferences imposed from other countries and other cultures ideas of PC is incredibly annoying. *That* is offensive. I will not have USA, Italy, Uganda or Fiji telling me how *not* to make ads for Scandinavia.
You could say that this is really about a *communication language,* and do not forget that some level of offence can be very effective marketing. You can annoy some people, stereotype them; and this will strengthen the brand among those who sees themselves the opposite. You can be upset, offended or intrigued by the series of [**United Colors of Benetton,**](http://top10buzz.com/top-ten-controversial-united-colors-of-benetton-ads/) they will rarely leave you indifferent. Funnily enough, regarding United Colors, their clothes are pretty non-descript (though colourful), but the ads often makes people go rabid. I think you can annoy people and still sell them things: if you first annoy them, and then make them think.
I once saw an ad, with four gray, grave, boring, suited, miserable guys with the caption "the most colourful thing (accountants) Johnson, Hansen, Jensen and Nielsen did last year, was to switch to eco-friendly printing paper". I think accountants might find it funny too
Good ads makes you see things a little differently, they surprise you a little: enough to have your attention for a little bit. You cannot do this by pleasing everyone. Sometimes you have to be bold, be brave, and just go for it. Political correctness is too often stupid. | I don't think it is marketing genius as you could get as much visibility with a great ad that is not tasteless.
As for the calculation, I don't think there is a way to do the calculation by yourself, especially if you're not the target audience. Different target audience have different flexibility for humor, you likely won't have the same tolerance for certain things if you're a geek vs. if you are investing in a diamonds or something. That's where I would push for a focus group. If you're designing for that kind of client, you should have the budget to hold one anyways.
Everyone gets offended by everything these days. If your target audience thinks you ad is good, I would tend to say you're on the right track.
As for future employers, it depends on the fit. Some look for that kind of "in your face" portfolio and others are more conservative. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | *De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try. | I don't think it is marketing genius as you could get as much visibility with a great ad that is not tasteless.
As for the calculation, I don't think there is a way to do the calculation by yourself, especially if you're not the target audience. Different target audience have different flexibility for humor, you likely won't have the same tolerance for certain things if you're a geek vs. if you are investing in a diamonds or something. That's where I would push for a focus group. If you're designing for that kind of client, you should have the budget to hold one anyways.
Everyone gets offended by everything these days. If your target audience thinks you ad is good, I would tend to say you're on the right track.
As for future employers, it depends on the fit. Some look for that kind of "in your face" portfolio and others are more conservative. |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | I second Emilie in saying that everything will offend someone somewhere. Personally, I am pretty sick of people finding offence left right and centre. Some people are *looking for* things that will get their knickers in a twist, and as Alan so elegantly points out: pleasing everyone ends up in the bland, the invisible and - *at best* - mediocre work. And therefore not efficient communication or marketing.
Cultural preferences imposed from other countries and other cultures ideas of PC is incredibly annoying. *That* is offensive. I will not have USA, Italy, Uganda or Fiji telling me how *not* to make ads for Scandinavia.
You could say that this is really about a *communication language,* and do not forget that some level of offence can be very effective marketing. You can annoy some people, stereotype them; and this will strengthen the brand among those who sees themselves the opposite. You can be upset, offended or intrigued by the series of [**United Colors of Benetton,**](http://top10buzz.com/top-ten-controversial-united-colors-of-benetton-ads/) they will rarely leave you indifferent. Funnily enough, regarding United Colors, their clothes are pretty non-descript (though colourful), but the ads often makes people go rabid. I think you can annoy people and still sell them things: if you first annoy them, and then make them think.
I once saw an ad, with four gray, grave, boring, suited, miserable guys with the caption "the most colourful thing (accountants) Johnson, Hansen, Jensen and Nielsen did last year, was to switch to eco-friendly printing paper". I think accountants might find it funny too
Good ads makes you see things a little differently, they surprise you a little: enough to have your attention for a little bit. You cannot do this by pleasing everyone. Sometimes you have to be bold, be brave, and just go for it. Political correctness is too often stupid. | It's always about the brand.
============================
What does the brand stand for in it's audience's mind? Is it offensive, irreverent, tasteless? Then you have to live up to that. Anything less wouldn't be true to their intended message. If you aren't comfortable with that type of material, you shouldn't be working with a brand that stands for it in the first place.
Another commenter mentioned McDonald's "healthy" messaging. It's a lie, but so is everything else about McD's. Their audience doesn't care that their products are only vaguely related to food. They like the taste of additives and being told that it's good for them. Their audience is notoriously disinterested in genuineness.
Brands are people too. Sorta.
=============================
Every brand should be first understood as a character, a personality, something an audience can personify in their minds. Once you have an accurate persona of the brand in your mind, then you'll know where to go with just about any message.
The tricky part is when a brand wants to transform it's persona. Then things get very murky and you'll be leaning on either a lot of market research or (in the most stressful circumstances) intuition. It's awefully fun, though :) |
28,859 | When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*. | 2014/03/31 | [
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] | I second Emilie in saying that everything will offend someone somewhere. Personally, I am pretty sick of people finding offence left right and centre. Some people are *looking for* things that will get their knickers in a twist, and as Alan so elegantly points out: pleasing everyone ends up in the bland, the invisible and - *at best* - mediocre work. And therefore not efficient communication or marketing.
Cultural preferences imposed from other countries and other cultures ideas of PC is incredibly annoying. *That* is offensive. I will not have USA, Italy, Uganda or Fiji telling me how *not* to make ads for Scandinavia.
You could say that this is really about a *communication language,* and do not forget that some level of offence can be very effective marketing. You can annoy some people, stereotype them; and this will strengthen the brand among those who sees themselves the opposite. You can be upset, offended or intrigued by the series of [**United Colors of Benetton,**](http://top10buzz.com/top-ten-controversial-united-colors-of-benetton-ads/) they will rarely leave you indifferent. Funnily enough, regarding United Colors, their clothes are pretty non-descript (though colourful), but the ads often makes people go rabid. I think you can annoy people and still sell them things: if you first annoy them, and then make them think.
I once saw an ad, with four gray, grave, boring, suited, miserable guys with the caption "the most colourful thing (accountants) Johnson, Hansen, Jensen and Nielsen did last year, was to switch to eco-friendly printing paper". I think accountants might find it funny too
Good ads makes you see things a little differently, they surprise you a little: enough to have your attention for a little bit. You cannot do this by pleasing everyone. Sometimes you have to be bold, be brave, and just go for it. Political correctness is too often stupid. | Purely from a graphic designer's POV, it's a decision that each designer has to make on their own based on the particulars of the given situation.
In general, being offensive isn't a typical marketing strategy, though it does get used. You as a designer have to decide if you want to work on projects that are purposefully attempting to be offensive. |
56,071,682 | I have two DF's, DF A and DF B. Both have identical schema.
DF A's column C have a different value and DF B's column C have a different value, other data is exactly same. Now, If I want to combine both tables DF C, how to do it in spark? I tried to do join operation, but it is creating duplicate columns.
For example:
DF A:
`+---+----+
| k| v|
+---+----+
| 1| |
| 2|bar1|
+---+----+`
DF B:
`+---+----+
| k| v|
+---+----+
| 1|foo1|
| 2| |
+---+----+`
Expected result:
`+---+----+
| k| v|
+---+----+
| 1|foo1|
| 2|bar1|
+---+----+` | 2019/05/10 | [
"https://Stackoverflow.com/questions/56071682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176086/"
] | The system is looking for a main class `restaurantclient.RestaurantClient`, so a class `RestaurantClient` in package `restaurantClient`, but your class `RestaurantClient` seems to be in the default package. | try this if you are not getting any compilation issues.
You can :
1. RightClick on project node and go to Set configuration.
2. Select the main class for your application.
3. Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
Fore more details
Follow the stackOverflow question
[Netbeans - Error: Could not find or load main class](https://stackoverflow.com/questions/20034377/netbeans-error-could-not-find-or-load-main-class) |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | The premise of the question that:
```
s1 + s2 + s3 + s4 + s5 + ... + sn
```
will require n allocations is incorrect.
Instead it will require O(Log(n)) allocations. The first `s1 + s1` will generate a temporary. Subsequently a temporary (rvalue) will be the left argument to all subsequent `+` operations. The standard specifies that when the lhs of a `string +` is an rvalue, that the implementation simply append to that temporary and move it out:
```
operator+(basic_string<charT,traits,Allocator>&& lhs,
const basic_string<charT,traits,Allocator>& rhs);
Returns: std::move(lhs.append(rhs))
```
The standard also specifies that the capacity of the string will grow geometrically (a factor between 1.5 and 2 is common). So on every allocation, capacity will grow geometrically, and that capacity is propagated down the chain of `+` operations. More specifically, the original code:
```
s = s1 + s2 + s3 + s4 + s5 + ... + sn;
```
is *actually* equivalent to:
```
s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;
```
When geometric capacity growth is combined with the short string optimization, the value of "pre-reserving" the correct capacity is limited. I would only bother doing that if such code actually shows up as a hot spot in your performance testing. | How about this:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
std::string ret;
ret.reserve(s1.length() + s2.length() + s3.length() + s4.length() + s5.length());
ret.append(s1.c_str());
ret.append(s2.c_str());
ret.append(s3.c_str());
ret.append(s4.c_str());
ret.append(s5.c_str());
return ret;
}
```
There are two allocations, one really small to construct `std::string` another reserves memory for data. |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | There is no engineering like over engineering.
In this case, I create a type `string_builder::op<?>` that reasonably efficiently collects a pile of strings to concatenate, and when cast into a `std::string` proceeds to do so.
It stores copies of any temporary `std::string`s provided, and references to longer-lived ones, as a bit of paranoia.
It ends up reducing to:
```
std::string retval;
retval.reserve(the right amount);
retval+=perfect forwarded first string
...
retval+=perfect forwarded last string
return retval;
```
but it wraps it all in lots of syntaxtic sugar.
```
namespace string_builder {
template<class String, class=std::enable_if_t< std::is_same< String, std::string >::value >>
std::size_t get_size( String const& s ) { return s.size(); }
template<std::size_t N>
constexpr std::size_t get_size( const char(&)[N] ) { return N; }
template<std::size_t N>
constexpr std::size_t get_size( char(&)[N] ) { return N; }
std::size_t get_size( const char* s ) { return std::strlen(s); }
template<class Indexes, class...Ss>
struct op;
struct tuple_tag {};
template<size_t... Is, class... Ss>
struct op<std::integer_sequence<size_t, Is...>, Ss...> {
op() = default;
op(op const&) = delete;
op(op&&) = default;
std::tuple<Ss...> data;
template<class... Tuples>
op( tuple_tag, Tuples&&... ts ): data( std::tuple_cat( std::forward<Tuples>(ts)... ) ) {}
std::size_t size() const {
std::size_t retval = 0;
int unused[] = {((retval+=get_size(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
operator std::string() && {
std::string retval;
retval.reserve( size()+1 );
int unused[] = {((retval+=std::forward<Ss>(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
template<class S0>
op<std::integer_sequence<size_t, Is..., sizeof...(Is)>, Ss..., S0>
operator+(S0&&s0)&& {
return { tuple_tag{}, std::move(data), std::forward_as_tuple( std::forward<S0>(s0) ) };
}
auto operator()()&& {return std::move(*this);}
template<class T0, class...Ts>
auto operator()(T0&&t0, Ts&&... ts)&&{
return (std::move(*this)+std::forward<T0>(t0))(std::forward<Ts>(ts)...);
}
};
}
string_builder::op< std::integer_sequence<std::size_t> >
string_build() { return {}; }
template<class... Strings>
auto
string_build(Strings&&...strings) {
return string_build()(std::forward<Strings>(strings)...);
}
```
and now we get:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return string_build() + s1 + s2 + s3 + s4 + s5;
}
```
or more generically and efficiently:
```
template<class... Strings>
std::string Concatenate(Strings&&...strings)
{
return string_build(std::forward<Strings>(strings)...);
}
```
there are extraneous moves, but no extraneous allocations. And it works with raw `"strings"` with no extra allocations.
[live example](http://coliru.stacked-crooked.com/a/f197aad63e486cce) | You can use code like:
```
std::string(s1) + s2 + s3 + s4 + s5 + s6 + ....
```
This will allocates a single unnamed temporary (copy of the first string), and then append each of the other strings to it. A smart optimizer could optimize this into the same code as the reserve+append code others have posted, as all these functions are generally inlineable.
This works by using the move-enhanced version of operator+, which is defined as (roughly)
```
std::string operator+(std::string &&lhs, const std::string &rhs) {
return std::move(lhs.append(rhs));
}
```
combined with RVO, it means that no additional `string` objects need to be created or destroyed. |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | You can use code like:
```
std::string(s1) + s2 + s3 + s4 + s5 + s6 + ....
```
This will allocates a single unnamed temporary (copy of the first string), and then append each of the other strings to it. A smart optimizer could optimize this into the same code as the reserve+append code others have posted, as all these functions are generally inlineable.
This works by using the move-enhanced version of operator+, which is defined as (roughly)
```
std::string operator+(std::string &&lhs, const std::string &rhs) {
return std::move(lhs.append(rhs));
}
```
combined with RVO, it means that no additional `string` objects need to be created or destroyed. | How about this:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
std::string ret;
ret.reserve(s1.length() + s2.length() + s3.length() + s4.length() + s5.length());
ret.append(s1.c_str());
ret.append(s2.c_str());
ret.append(s3.c_str());
ret.append(s4.c_str());
ret.append(s5.c_str());
return ret;
}
```
There are two allocations, one really small to construct `std::string` another reserves memory for data. |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | There is no engineering like over engineering.
In this case, I create a type `string_builder::op<?>` that reasonably efficiently collects a pile of strings to concatenate, and when cast into a `std::string` proceeds to do so.
It stores copies of any temporary `std::string`s provided, and references to longer-lived ones, as a bit of paranoia.
It ends up reducing to:
```
std::string retval;
retval.reserve(the right amount);
retval+=perfect forwarded first string
...
retval+=perfect forwarded last string
return retval;
```
but it wraps it all in lots of syntaxtic sugar.
```
namespace string_builder {
template<class String, class=std::enable_if_t< std::is_same< String, std::string >::value >>
std::size_t get_size( String const& s ) { return s.size(); }
template<std::size_t N>
constexpr std::size_t get_size( const char(&)[N] ) { return N; }
template<std::size_t N>
constexpr std::size_t get_size( char(&)[N] ) { return N; }
std::size_t get_size( const char* s ) { return std::strlen(s); }
template<class Indexes, class...Ss>
struct op;
struct tuple_tag {};
template<size_t... Is, class... Ss>
struct op<std::integer_sequence<size_t, Is...>, Ss...> {
op() = default;
op(op const&) = delete;
op(op&&) = default;
std::tuple<Ss...> data;
template<class... Tuples>
op( tuple_tag, Tuples&&... ts ): data( std::tuple_cat( std::forward<Tuples>(ts)... ) ) {}
std::size_t size() const {
std::size_t retval = 0;
int unused[] = {((retval+=get_size(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
operator std::string() && {
std::string retval;
retval.reserve( size()+1 );
int unused[] = {((retval+=std::forward<Ss>(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
template<class S0>
op<std::integer_sequence<size_t, Is..., sizeof...(Is)>, Ss..., S0>
operator+(S0&&s0)&& {
return { tuple_tag{}, std::move(data), std::forward_as_tuple( std::forward<S0>(s0) ) };
}
auto operator()()&& {return std::move(*this);}
template<class T0, class...Ts>
auto operator()(T0&&t0, Ts&&... ts)&&{
return (std::move(*this)+std::forward<T0>(t0))(std::forward<Ts>(ts)...);
}
};
}
string_builder::op< std::integer_sequence<std::size_t> >
string_build() { return {}; }
template<class... Strings>
auto
string_build(Strings&&...strings) {
return string_build()(std::forward<Strings>(strings)...);
}
```
and now we get:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return string_build() + s1 + s2 + s3 + s4 + s5;
}
```
or more generically and efficiently:
```
template<class... Strings>
std::string Concatenate(Strings&&...strings)
{
return string_build(std::forward<Strings>(strings)...);
}
```
there are extraneous moves, but no extraneous allocations. And it works with raw `"strings"` with no extra allocations.
[live example](http://coliru.stacked-crooked.com/a/f197aad63e486cce) | How about this:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
std::string ret;
ret.reserve(s1.length() + s2.length() + s3.length() + s4.length() + s5.length());
ret.append(s1.c_str());
ret.append(s2.c_str());
ret.append(s3.c_str());
ret.append(s4.c_str());
ret.append(s5.c_str());
return ret;
}
```
There are two allocations, one really small to construct `std::string` another reserves memory for data. |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | The premise of the question that:
```
s1 + s2 + s3 + s4 + s5 + ... + sn
```
will require n allocations is incorrect.
Instead it will require O(Log(n)) allocations. The first `s1 + s1` will generate a temporary. Subsequently a temporary (rvalue) will be the left argument to all subsequent `+` operations. The standard specifies that when the lhs of a `string +` is an rvalue, that the implementation simply append to that temporary and move it out:
```
operator+(basic_string<charT,traits,Allocator>&& lhs,
const basic_string<charT,traits,Allocator>& rhs);
Returns: std::move(lhs.append(rhs))
```
The standard also specifies that the capacity of the string will grow geometrically (a factor between 1.5 and 2 is common). So on every allocation, capacity will grow geometrically, and that capacity is propagated down the chain of `+` operations. More specifically, the original code:
```
s = s1 + s2 + s3 + s4 + s5 + ... + sn;
```
is *actually* equivalent to:
```
s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;
```
When geometric capacity growth is combined with the short string optimization, the value of "pre-reserving" the correct capacity is limited. I would only bother doing that if such code actually shows up as a hot spot in your performance testing. | After some thought, I think it might be worth at least considering a slightly different approach.
```
std::stringstream s;
s << s1 << s2 << s3 << s4 << s5;
return s.str();
```
Although it doesn't guarantee only a single allocation, we can expect a `stringstream` to be optimized for accumulating relatively large amounts of data, so chances are pretty good that (unless the input strings are huge) it will keep the number of allocations quite minimal.
At the same time, especially if the individual strings are reasonably small, it certainly avoids the situation we expect with something like `a + b + c + d` where (at least in C++03) we *expect* to see a number of temporary objects created and destroyed in the process of evaluating the expression. In fact, we can typically expect this to get pretty much the same kind of result we'd expect from something like expression templates, but with a lot less complexity.
There is something of a downside though: iostreams (in general) have enough baggage such a associated locales that especially if the strings are small, there could be more overhead in creating the stream than we save in individual allocations.
With a current compiler/library, I'd expect the overhead of creating a stream to make this slower. With an older implementation, I'd have to test to have any certainty at all (and I don't have an old enough compiler handy to do so). |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | There is no engineering like over engineering.
In this case, I create a type `string_builder::op<?>` that reasonably efficiently collects a pile of strings to concatenate, and when cast into a `std::string` proceeds to do so.
It stores copies of any temporary `std::string`s provided, and references to longer-lived ones, as a bit of paranoia.
It ends up reducing to:
```
std::string retval;
retval.reserve(the right amount);
retval+=perfect forwarded first string
...
retval+=perfect forwarded last string
return retval;
```
but it wraps it all in lots of syntaxtic sugar.
```
namespace string_builder {
template<class String, class=std::enable_if_t< std::is_same< String, std::string >::value >>
std::size_t get_size( String const& s ) { return s.size(); }
template<std::size_t N>
constexpr std::size_t get_size( const char(&)[N] ) { return N; }
template<std::size_t N>
constexpr std::size_t get_size( char(&)[N] ) { return N; }
std::size_t get_size( const char* s ) { return std::strlen(s); }
template<class Indexes, class...Ss>
struct op;
struct tuple_tag {};
template<size_t... Is, class... Ss>
struct op<std::integer_sequence<size_t, Is...>, Ss...> {
op() = default;
op(op const&) = delete;
op(op&&) = default;
std::tuple<Ss...> data;
template<class... Tuples>
op( tuple_tag, Tuples&&... ts ): data( std::tuple_cat( std::forward<Tuples>(ts)... ) ) {}
std::size_t size() const {
std::size_t retval = 0;
int unused[] = {((retval+=get_size(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
operator std::string() && {
std::string retval;
retval.reserve( size()+1 );
int unused[] = {((retval+=std::forward<Ss>(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
template<class S0>
op<std::integer_sequence<size_t, Is..., sizeof...(Is)>, Ss..., S0>
operator+(S0&&s0)&& {
return { tuple_tag{}, std::move(data), std::forward_as_tuple( std::forward<S0>(s0) ) };
}
auto operator()()&& {return std::move(*this);}
template<class T0, class...Ts>
auto operator()(T0&&t0, Ts&&... ts)&&{
return (std::move(*this)+std::forward<T0>(t0))(std::forward<Ts>(ts)...);
}
};
}
string_builder::op< std::integer_sequence<std::size_t> >
string_build() { return {}; }
template<class... Strings>
auto
string_build(Strings&&...strings) {
return string_build()(std::forward<Strings>(strings)...);
}
```
and now we get:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return string_build() + s1 + s2 + s3 + s4 + s5;
}
```
or more generically and efficiently:
```
template<class... Strings>
std::string Concatenate(Strings&&...strings)
{
return string_build(std::forward<Strings>(strings)...);
}
```
there are extraneous moves, but no extraneous allocations. And it works with raw `"strings"` with no extra allocations.
[live example](http://coliru.stacked-crooked.com/a/f197aad63e486cce) | After some thought, I think it might be worth at least considering a slightly different approach.
```
std::stringstream s;
s << s1 << s2 << s3 << s4 << s5;
return s.str();
```
Although it doesn't guarantee only a single allocation, we can expect a `stringstream` to be optimized for accumulating relatively large amounts of data, so chances are pretty good that (unless the input strings are huge) it will keep the number of allocations quite minimal.
At the same time, especially if the individual strings are reasonably small, it certainly avoids the situation we expect with something like `a + b + c + d` where (at least in C++03) we *expect* to see a number of temporary objects created and destroyed in the process of evaluating the expression. In fact, we can typically expect this to get pretty much the same kind of result we'd expect from something like expression templates, but with a lot less complexity.
There is something of a downside though: iostreams (in general) have enough baggage such a associated locales that especially if the strings are small, there could be more overhead in creating the stream than we save in individual allocations.
With a current compiler/library, I'd expect the overhead of creating a stream to make this slower. With an older implementation, I'd have to test to have any certainty at all (and I don't have an old enough compiler handy to do so). |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | The premise of the question that:
```
s1 + s2 + s3 + s4 + s5 + ... + sn
```
will require n allocations is incorrect.
Instead it will require O(Log(n)) allocations. The first `s1 + s1` will generate a temporary. Subsequently a temporary (rvalue) will be the left argument to all subsequent `+` operations. The standard specifies that when the lhs of a `string +` is an rvalue, that the implementation simply append to that temporary and move it out:
```
operator+(basic_string<charT,traits,Allocator>&& lhs,
const basic_string<charT,traits,Allocator>& rhs);
Returns: std::move(lhs.append(rhs))
```
The standard also specifies that the capacity of the string will grow geometrically (a factor between 1.5 and 2 is common). So on every allocation, capacity will grow geometrically, and that capacity is propagated down the chain of `+` operations. More specifically, the original code:
```
s = s1 + s2 + s3 + s4 + s5 + ... + sn;
```
is *actually* equivalent to:
```
s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;
```
When geometric capacity growth is combined with the short string optimization, the value of "pre-reserving" the correct capacity is limited. I would only bother doing that if such code actually shows up as a hot spot in your performance testing. | ```
std::string combined;
combined.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size());
combined += s1;
combined += s2;
combined += s3;
combined += s4;
combined += s5;
return combined;
``` |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | ```
std::string combined;
combined.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size());
combined += s1;
combined += s2;
combined += s3;
combined += s4;
combined += s5;
return combined;
``` | How about this:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
std::string ret;
ret.reserve(s1.length() + s2.length() + s3.length() + s4.length() + s5.length());
ret.append(s1.c_str());
ret.append(s2.c_str());
ret.append(s3.c_str());
ret.append(s4.c_str());
ret.append(s5.c_str());
return ret;
}
```
There are two allocations, one really small to construct `std::string` another reserves memory for data. |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | ```
std::string combined;
combined.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size());
combined += s1;
combined += s2;
combined += s3;
combined += s4;
combined += s5;
return combined;
``` | There is no engineering like over engineering.
In this case, I create a type `string_builder::op<?>` that reasonably efficiently collects a pile of strings to concatenate, and when cast into a `std::string` proceeds to do so.
It stores copies of any temporary `std::string`s provided, and references to longer-lived ones, as a bit of paranoia.
It ends up reducing to:
```
std::string retval;
retval.reserve(the right amount);
retval+=perfect forwarded first string
...
retval+=perfect forwarded last string
return retval;
```
but it wraps it all in lots of syntaxtic sugar.
```
namespace string_builder {
template<class String, class=std::enable_if_t< std::is_same< String, std::string >::value >>
std::size_t get_size( String const& s ) { return s.size(); }
template<std::size_t N>
constexpr std::size_t get_size( const char(&)[N] ) { return N; }
template<std::size_t N>
constexpr std::size_t get_size( char(&)[N] ) { return N; }
std::size_t get_size( const char* s ) { return std::strlen(s); }
template<class Indexes, class...Ss>
struct op;
struct tuple_tag {};
template<size_t... Is, class... Ss>
struct op<std::integer_sequence<size_t, Is...>, Ss...> {
op() = default;
op(op const&) = delete;
op(op&&) = default;
std::tuple<Ss...> data;
template<class... Tuples>
op( tuple_tag, Tuples&&... ts ): data( std::tuple_cat( std::forward<Tuples>(ts)... ) ) {}
std::size_t size() const {
std::size_t retval = 0;
int unused[] = {((retval+=get_size(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
operator std::string() && {
std::string retval;
retval.reserve( size()+1 );
int unused[] = {((retval+=std::forward<Ss>(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
template<class S0>
op<std::integer_sequence<size_t, Is..., sizeof...(Is)>, Ss..., S0>
operator+(S0&&s0)&& {
return { tuple_tag{}, std::move(data), std::forward_as_tuple( std::forward<S0>(s0) ) };
}
auto operator()()&& {return std::move(*this);}
template<class T0, class...Ts>
auto operator()(T0&&t0, Ts&&... ts)&&{
return (std::move(*this)+std::forward<T0>(t0))(std::forward<Ts>(ts)...);
}
};
}
string_builder::op< std::integer_sequence<std::size_t> >
string_build() { return {}; }
template<class... Strings>
auto
string_build(Strings&&...strings) {
return string_build()(std::forward<Strings>(strings)...);
}
```
and now we get:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return string_build() + s1 + s2 + s3 + s4 + s5;
}
```
or more generically and efficiently:
```
template<class... Strings>
std::string Concatenate(Strings&&...strings)
{
return string_build(std::forward<Strings>(strings)...);
}
```
there are extraneous moves, but no extraneous allocations. And it works with raw `"strings"` with no extra allocations.
[live example](http://coliru.stacked-crooked.com/a/f197aad63e486cce) |
25,755,297 | ```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] | The premise of the question that:
```
s1 + s2 + s3 + s4 + s5 + ... + sn
```
will require n allocations is incorrect.
Instead it will require O(Log(n)) allocations. The first `s1 + s1` will generate a temporary. Subsequently a temporary (rvalue) will be the left argument to all subsequent `+` operations. The standard specifies that when the lhs of a `string +` is an rvalue, that the implementation simply append to that temporary and move it out:
```
operator+(basic_string<charT,traits,Allocator>&& lhs,
const basic_string<charT,traits,Allocator>& rhs);
Returns: std::move(lhs.append(rhs))
```
The standard also specifies that the capacity of the string will grow geometrically (a factor between 1.5 and 2 is common). So on every allocation, capacity will grow geometrically, and that capacity is propagated down the chain of `+` operations. More specifically, the original code:
```
s = s1 + s2 + s3 + s4 + s5 + ... + sn;
```
is *actually* equivalent to:
```
s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;
```
When geometric capacity growth is combined with the short string optimization, the value of "pre-reserving" the correct capacity is limited. I would only bother doing that if such code actually shows up as a hot spot in your performance testing. | There is no engineering like over engineering.
In this case, I create a type `string_builder::op<?>` that reasonably efficiently collects a pile of strings to concatenate, and when cast into a `std::string` proceeds to do so.
It stores copies of any temporary `std::string`s provided, and references to longer-lived ones, as a bit of paranoia.
It ends up reducing to:
```
std::string retval;
retval.reserve(the right amount);
retval+=perfect forwarded first string
...
retval+=perfect forwarded last string
return retval;
```
but it wraps it all in lots of syntaxtic sugar.
```
namespace string_builder {
template<class String, class=std::enable_if_t< std::is_same< String, std::string >::value >>
std::size_t get_size( String const& s ) { return s.size(); }
template<std::size_t N>
constexpr std::size_t get_size( const char(&)[N] ) { return N; }
template<std::size_t N>
constexpr std::size_t get_size( char(&)[N] ) { return N; }
std::size_t get_size( const char* s ) { return std::strlen(s); }
template<class Indexes, class...Ss>
struct op;
struct tuple_tag {};
template<size_t... Is, class... Ss>
struct op<std::integer_sequence<size_t, Is...>, Ss...> {
op() = default;
op(op const&) = delete;
op(op&&) = default;
std::tuple<Ss...> data;
template<class... Tuples>
op( tuple_tag, Tuples&&... ts ): data( std::tuple_cat( std::forward<Tuples>(ts)... ) ) {}
std::size_t size() const {
std::size_t retval = 0;
int unused[] = {((retval+=get_size(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
operator std::string() && {
std::string retval;
retval.reserve( size()+1 );
int unused[] = {((retval+=std::forward<Ss>(std::get<Is>(data))), 0)..., 0};
(void)unused;
return retval;
}
template<class S0>
op<std::integer_sequence<size_t, Is..., sizeof...(Is)>, Ss..., S0>
operator+(S0&&s0)&& {
return { tuple_tag{}, std::move(data), std::forward_as_tuple( std::forward<S0>(s0) ) };
}
auto operator()()&& {return std::move(*this);}
template<class T0, class...Ts>
auto operator()(T0&&t0, Ts&&... ts)&&{
return (std::move(*this)+std::forward<T0>(t0))(std::forward<Ts>(ts)...);
}
};
}
string_builder::op< std::integer_sequence<std::size_t> >
string_build() { return {}; }
template<class... Strings>
auto
string_build(Strings&&...strings) {
return string_build()(std::forward<Strings>(strings)...);
}
```
and now we get:
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return string_build() + s1 + s2 + s3 + s4 + s5;
}
```
or more generically and efficiently:
```
template<class... Strings>
std::string Concatenate(Strings&&...strings)
{
return string_build(std::forward<Strings>(strings)...);
}
```
there are extraneous moves, but no extraneous allocations. And it works with raw `"strings"` with no extra allocations.
[live example](http://coliru.stacked-crooked.com/a/f197aad63e486cce) |
42,295,298 | My application calls some functions which are placed in an external static library. I link the external static library to my application and everything works (in this case I'm using GCC).
Nevertheless, the locations (addresses) of text, .data and .bss sections of the library are chosen by the linker. I can choose/change their locations by modifying the linker script, but it's tedious as I have to specify all the functions, variables, etc. of the library. What I mean it's something like:
```
. = 0x1000; /* new location */
KEEP(*(.text.library_function1));
KEEP(*(.text.library_function2));
[...]
```
An alternative solution is to build the external library by placing a *section attribute* for each function/variable, and then modifying the linker by re-locating the whole section. Something like:
```
/* C source file */
unsigned char __attribute__((section (".myLibrarySection"))) variable1[10];
unsigned char __attribute__((section (".myLibrarySection"))) variable2[10];
/* Linker script */
. = 0x1000;
KEEP(*(.myLibrarySection))
```
However, I'd like to be able to relocate entire .text, .data and .bss segments of an external static library without the need of using these tricks.
I'd like something like this (in linker script):
```
. = 0x1000;
KEEP(*(.text.library_file_name))
```
Is it possible using GCC toolchain?
Is it possible using other toolchains (IAR, Keil, etc.)? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42295298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447290/"
] | You can use the [`archive:filename`](https://sourceware.org/binutils/docs/ld/Input-Section-Basics.html) syntax in ld.
First place all the `.o` files from your external library into a static library `.a` file, if they aren't already. That is the normal way static library binaries are distributed.
Then in the linker script, specify:
```
.text.special : {
. = 0x1000;
*libspecial.a:*(.text .text.*)
}
.text {
*(.text .text.*)
}
```
The wildcard will pick all the files coming from `libspecial.a` and place them in the first section. The later wildcard will then pick anything left over. If there is a need to place the `.text.special` section after the normal section, you can use `EXCLUDE_FILE` directive in a similar way. | Can you just postprocess your lib to rename sections?
```
# Untested!
TMP=`mktemp -d`
trap "rm -rf $TMP" EXIT
cd $TMP
ar x path/to/your/lib.a
for o in *.o; do
for s in text data bss; do
objcopy --rename-section .$s=.mynew$s $o
done
done
ar rcs path/to/your/lib.a *.o
``` |
73,863,765 | I am a beginner in Unity and I am currently making a simple game. I have a problem where the button should reappear on the object I am getting contact with. It only shows on the first object that I put the script on.
What I wanted to do is to have a recyclable button that will appear whenever I have contact with objects like the "view" button in most of the games. What keeps happening in my project is that the collision is triggered but the position of the object is in the first object where I put the script to set it active and set the position. I put it in another object because I want the button to show in that object but it keeps appearing in the first object.
This is the script I used:
```
using UnityEngine;
using UnityEngine.UI;
public class InteractNPC : MonoBehaviour
{
//public Button UI;
[SerializeField] GameObject uiUse, nameBtn, dialogBox;
[SerializeField] TextAsset characterData;
// [SerializeField] UnityEngine.UI.Text dialogMessage;
private Transform head;
private Vector3 offset = new Vector3(0, 1.0f, 0);
// Start is called before the first frame update
void Start()
{
//uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
uiUse.gameObject.SetActive(true);
head = this.transform.GetChild(0);
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.GetComponent<Button>().onClick.AddListener(onNameClick);
}
// Update is called once per frame
void Update()
{
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
//Character characterJson = JsonUtility.FromJson<Character>(characterData.text);
nameBtn.gameObject.SetActive(true);
// Text lbl = nameBtn.gameObject.GetComponentInChildren(typeof(Text), true) as Text;
// lbl.text = "BOBO";
// nameBtn.GetComponent<Button>().GetComponentInChildren<Text>().text = characterJson.name;
}
}
private void OnTriggerExit(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.gameObject.SetActive(false);
}
}
// DIALOGUE SYSTEM
public void onNameClick()
{
Text dialogMessage, dialogName;
if (dialogBox.gameObject.activeInHierarchy)
{
dialogName = GameObject.Find("Canvas/DialogBox/DialogueName").GetComponent<Text>();
dialogMessage = GameObject.Find("Canvas/DialogBox/Dialogue").GetComponent<Text>();
if (dialogMessage != null && dialogName != null)
{
loadCharacterData(dialogMessage, dialogName);
Debug.Log("not null dialog message");
}
else
{
Debug.Log("null dialog message");
}
}
}
public void loadCharacterData(Text dialogMessage, Text dialogName)
{
Character characterJson = JsonUtility.FromJson<Character>(characterData.text);
dialogName.text = characterJson.name;
dialogMessage.text = characterJson.dialogs[0].choices[1];
}
}
``` | 2022/09/27 | [
"https://Stackoverflow.com/questions/73863765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11050464/"
] | Well your issue is that each and every instnce of your scrip will all the time overwrite
```
void Update()
{
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
}
```
**every frame**.
What you want is set it only **once** in
```
[SerializeField] private Button nameBtn;
pivate Character character;
private void Start()
{
...
// do this only once!
character = JsonUtility.FromJson<Character>(characterData.text);
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.gameObject.SetActive(true);
var lbl = nameBtn.gameObject.GetComponentInChildren<Text>(true);
lbl.text = characterJson.name;
var position = Camera.main.WorldToScreenPoint(head.position + offset);
uiUse.transform.position = position;
nameBtn.transform.position = position;
}
}
```
---
Further you will have another issue: Each and every instance of your script attaches a callback
```
nameBtn.GetComponent<Button>().onClick.AddListener(onNameClick);
```
that is not good! Now whenever you click the button once, the allback is fired for each and every instance of your script.
You would rather do this only if the click was actually invoked for the current object.
For this you could attach the listener only add-hoc when needed like e.g.
```
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
...
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.onClick.AddListener(onNameClick);
}
}
private void OnTriggerExit(Collider other)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.gameObject.SetActive(false);
}
}
```
---
ok we didn't know before your objects move
so well you will need to go back to what you had before and update the position continuously, **BUT** only while you are the current active object so e.g.
```
private static InteractNPC buttonOwner;
private Camera mainCamera;
void Update()
{
if(buttonOwner != this) return;
if(!mainCamera) mainCamera = Camera.main;
var position = mainCamera.WorldToScreenPoint(head.position + offset);
uiUse.transform.position = position;
nameBtn.transform.position = position;
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player") && !buttonOwner)
{
...
buttonOwner = this;
}
}
private void OnTriggerExit(Collider other)
{
if (collisionInfo.CompareTag("Player") && buttonOwner == this)
{
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.gameObject.SetActive(false);
buttonOwner = null;
}
}
``` | As far as I see you never create a new Button, I guess that Unity may think, you want the same Button on all NPCs.
Maybe try to call the constructor for a new Button in the Start Method and see if it then generates a new Button per NPC. |
56,134,100 | I'm new to f# and want to use it to alter the format of a propositional logic formula string:
I want to replace "aX" by the string "next(a)", with 'a' being an element of [a..z] and 'X' being the capital X' character.
All sources i found, e.g. <https://www.dotnetperls.com/replace-fs> either replace a string by another string,
```
let s = "a & b & c & aX & !bX"
let sReplaced = s.Replace("X", "next()") // val it : string = "a & b & c & anext() & !bnext()"
```
in which case you can not put the original character in between or if they work characterwise, as eg.
```
let sArray = s.ToCharArray()
for c in 0 .. sArray.Length - 1 do
if sArray.[c] = 'X' then
sArray.[c-2] <- '('
sArray.[c] <- ')'
let sArrayResult = new string(sArray) // val sArrayResult : string = "a & b & c &(a) & (b)"
```
only allow the same length for the output string.
"a & b & c & aX & !bX"
should be replaced with
"a & b & c & next(a) & !next(b)"
Is there some convinient way to handle this problem? Thanks in advance. | 2019/05/14 | [
"https://Stackoverflow.com/questions/56134100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499357/"
] | You could use a [`MatchEvaluator`](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.matchevaluator?view=netframework-4.8):
```
open System.Text.RegularExpressions
let s = "a & b & c & aX & !bX"
Regex.Replace(s, "([a-z]X)", fun m -> "next(" + m.Value.TrimEnd('X') + ")")
- ;;
val it : string = "a & b & c & next(a) & !next(b)"
``` | [Regex.Replace](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=netframework-4.5.2#System_Text_RegularExpressions_Regex_Replace_System_String_System_String_System_Text_RegularExpressions_MatchEvaluator_) is your friend:
```
open System.Text.RegularExpressions
let myReplace s =
Regex.Replace (s, ".X", fun mat -> sprintf "next(%c)" <| mat.ToString().[0])
```
You can change the `.` to `[a-z]` or whatever pattern that matches what you call *a arbitrary character*. |
56,134,100 | I'm new to f# and want to use it to alter the format of a propositional logic formula string:
I want to replace "aX" by the string "next(a)", with 'a' being an element of [a..z] and 'X' being the capital X' character.
All sources i found, e.g. <https://www.dotnetperls.com/replace-fs> either replace a string by another string,
```
let s = "a & b & c & aX & !bX"
let sReplaced = s.Replace("X", "next()") // val it : string = "a & b & c & anext() & !bnext()"
```
in which case you can not put the original character in between or if they work characterwise, as eg.
```
let sArray = s.ToCharArray()
for c in 0 .. sArray.Length - 1 do
if sArray.[c] = 'X' then
sArray.[c-2] <- '('
sArray.[c] <- ')'
let sArrayResult = new string(sArray) // val sArrayResult : string = "a & b & c &(a) & (b)"
```
only allow the same length for the output string.
"a & b & c & aX & !bX"
should be replaced with
"a & b & c & next(a) & !next(b)"
Is there some convinient way to handle this problem? Thanks in advance. | 2019/05/14 | [
"https://Stackoverflow.com/questions/56134100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499357/"
] | You could use a [`MatchEvaluator`](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.matchevaluator?view=netframework-4.8):
```
open System.Text.RegularExpressions
let s = "a & b & c & aX & !bX"
Regex.Replace(s, "([a-z]X)", fun m -> "next(" + m.Value.TrimEnd('X') + ")")
- ;;
val it : string = "a & b & c & next(a) & !next(b)"
``` | Apologies for necro-posting on an old thread with an accepted answer but using regex has a certain overhead, and a naïve iterative solution using lists might compare favourably in terms of performance:
```
let strXToNext (s : string) =
let next c a =
')' :: c :: '(' :: 't' :: 'x' :: 'e' :: 'n' :: a
let rec replX a = function
| [] -> List.rev a
| c :: 'X' :: cs when c >= 'a' && c <= 'z' ->
replX (next c a) cs
| c :: cs -> replX (c :: a) cs
s |> List.ofSeq
|> replX []
|> List.toArray
|> fun a -> Core.string a
``` |
56,134,100 | I'm new to f# and want to use it to alter the format of a propositional logic formula string:
I want to replace "aX" by the string "next(a)", with 'a' being an element of [a..z] and 'X' being the capital X' character.
All sources i found, e.g. <https://www.dotnetperls.com/replace-fs> either replace a string by another string,
```
let s = "a & b & c & aX & !bX"
let sReplaced = s.Replace("X", "next()") // val it : string = "a & b & c & anext() & !bnext()"
```
in which case you can not put the original character in between or if they work characterwise, as eg.
```
let sArray = s.ToCharArray()
for c in 0 .. sArray.Length - 1 do
if sArray.[c] = 'X' then
sArray.[c-2] <- '('
sArray.[c] <- ')'
let sArrayResult = new string(sArray) // val sArrayResult : string = "a & b & c &(a) & (b)"
```
only allow the same length for the output string.
"a & b & c & aX & !bX"
should be replaced with
"a & b & c & next(a) & !next(b)"
Is there some convinient way to handle this problem? Thanks in advance. | 2019/05/14 | [
"https://Stackoverflow.com/questions/56134100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499357/"
] | Apologies for necro-posting on an old thread with an accepted answer but using regex has a certain overhead, and a naïve iterative solution using lists might compare favourably in terms of performance:
```
let strXToNext (s : string) =
let next c a =
')' :: c :: '(' :: 't' :: 'x' :: 'e' :: 'n' :: a
let rec replX a = function
| [] -> List.rev a
| c :: 'X' :: cs when c >= 'a' && c <= 'z' ->
replX (next c a) cs
| c :: cs -> replX (c :: a) cs
s |> List.ofSeq
|> replX []
|> List.toArray
|> fun a -> Core.string a
``` | [Regex.Replace](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=netframework-4.5.2#System_Text_RegularExpressions_Regex_Replace_System_String_System_String_System_Text_RegularExpressions_MatchEvaluator_) is your friend:
```
open System.Text.RegularExpressions
let myReplace s =
Regex.Replace (s, ".X", fun mat -> sprintf "next(%c)" <| mat.ToString().[0])
```
You can change the `.` to `[a-z]` or whatever pattern that matches what you call *a arbitrary character*. |
54,221,366 | I'm trying to test off route detection in mapbox navigation and it is not working. I've traced through and the OffRouteDetector.isUserOffRouteWith *is* getting called, but the status.getRouteState() is only ever returning "INITIALIZED" (which is not the expected RouteState.OFFROUTE)
I suspect there's an edge case I'm hitting as I'm using a trip with a start and end that are very far away from my current location. As such, it never "gets going". However, this *is* a valid scenario in my application (it involves stored routes that are immutable due to public safety concerns).
I've made an issue (that was closed) on github, but for background, it is [here](https://github.com/mapbox/mapbox-navigation-android/issues/1680)
EDIT:
Here is some code to get closer to what I'm trying to do. This is from the onCreate of the MainActivity of a default android studio project:
```
String jsonRoute = "{\"routes\":[{\"legs\":[{\"steps\":[{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[0,90],\"location\":[-71.45082724993496,43.070903929852619],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[27,90],\"location\":[-71.444301000091471,43.023085298378462],\"in\":0}],\"driving_side\":\"right\",\"weight\":7560.0,\"geometry\":\"mbxcqArekhgCoG{B}HmGuHaLaGiT{@mPHs[bJggEUqYiA_KgCcJyKyVyGgJ\",\"maneuver\":{\"bearing_after\":90,\"type\":\"depart\",\"modifier\":\"\",\"bearing_before\":0,\"location\":[-71.45082724993496,43.070903929852619],\"instruction\":\"Travel on NO NAME\"},\"duration\":0.0,\"distance\":547.06000000000006,\"name\":\"NO NAME\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":547.06000000000006,\"announcement\":\"Travel on NO NAME, then Turn right onto US-3 [NH-28], [HOOKSETT RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Travel on NO NAME, then Turn right onto US-3 [NH-28], [HOOKSETT RD]</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Turn right onto US-3 [NH-28], [HOOKSETT RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Turn right onto US-3 [NH-28], [HOOKSETT RD]</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":547.06000000000006,\"primary\":{\"text\":\"US-3 / NH-28 / HOOKSETT RD\",\"type\":\"turn\",\"modifier\":\"right\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"US-3\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"NH-28\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"HOOKSETT RD\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[27,90],\"location\":[-71.444301000091471,43.023085298378462],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[197,211],\"location\":[-71.444535949177578,43.0230007289918],\"in\":0}],\"driving_side\":\"right\",\"weight\":6677.0,\"geometry\":\"}yycqAzk_hgCpLqOrNaNhTqMlfAsm@|\\\\eSb`@{ZvoBinBrKkJ~t@cg@r\\\\wQvrHimDv}Asz@xz@gd@n\\\\}PrpAil@prCmvAhgBa_A|m@qZvPcJlx@{]l_@iN~GuC~VgFpO}@bGEd[zBvo@jJ|cAeHvoCsWn]eJzuAkf@p`@aQ|sBypAzSkKrMsExPmDlUgAzNx@~OrC|NjFvaBp|@h]dMtmAbZb`Bv`@h\\\\fOxpCvtB|SjSrKxNjO`\\\\~FtNzKp_@xI|NrI`JvlHdmG\",\"maneuver\":{\"bearing_after\":90,\"type\":\"turn\",\"modifier\":\"right\",\"bearing_before\":27,\"location\":[-71.444301000091471,43.023085298378462],\"instruction\":\"Turn right onto US-3 [NH-28], [HOOKSETT RD]\"},\"duration\":186.0,\"distance\":5921.12,\"name\":\"US-3\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":5792.4000000000005,\"announcement\":\"In 3.6miles, I-93 SB ON RAMP\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 3.6miles, I-93 SB ON RAMP</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"I-93 SB ON RAMP\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">I-93 SB ON RAMP</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":5921.12,\"primary\":{\"text\":\"I-93 NB EXIT 9 OFF RAMP\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"I-93 NB EXIT 9 OFF RAMP\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[197,211],\"location\":[-71.444535949177578,43.0230007289918],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[126,135],\"location\":[-71.2864750743811,42.81703500887609],\"in\":0}],\"driving_side\":\"right\",\"weight\":838.0,\"geometry\":\"im|`qA~srggCfe@`l@lGlLtDpZ]~LoDpReEfJoHbIw`Ajt@mPlEiIQyNcGuFkG_HmUq@}QV{EfB_MfAqDpIaOxtAetA\",\"maneuver\":{\"bearing_after\":211,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":197,\"location\":[-71.444535949177578,43.0230007289918],\"instruction\":\"I-93 SB ON RAMP\"},\"duration\":23.0,\"distance\":788.41,\"name\":\"I-93 NB EXIT 9 OFF RAMP\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":643.6,\"announcement\":\"In 0.4miles, Continue straight on I-93 SOUTH\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 0.4miles, Continue straight on I-93 SOUTH</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Continue straight on I-93 SOUTH\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Continue straight on I-93 SOUTH</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":788.41,\"primary\":{\"text\":\"I-93 SOUTH\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"I-93 SOUTH\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[126,135],\"location\":[-71.2864750743811,42.81703500887609],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[136,140],\"location\":[-71.275545391600389,42.809408142172572],\"in\":0}],\"driving_side\":\"right\",\"weight\":27322.0,\"geometry\":\"_h|`qAtbsggCbE}C~FgGbxK_zIloDguC|i@w`@j\\\\mSn\\\\}Pf]aOf`AmYx`@aIjdGmz@nrCqb@rb@}Irs@uSzo@s^x]{ZvZ}_@hO}TzV}f@lMy\\\\tJsZfu@auCxdA}gE`W_z@b_@}zApO_h@pHsRnIoQ`JiQbJ{NpXq]`[sXn\\\\cT`_@eO|c@mMxp@kN|]gIpiAyVho@oLjcBeR`wBmIb{DiQpq@cFl~BuZvmDcf@|a@eF|u@sGdQk@xPgAvc@w@|uDaHz}CsIv{@}Gvr@kR`k@sWvpB{eAjfAij@`o@cZf}@}XvkB{_@ft@_Qtp@qYbXoRzZiZbXm^x`Ak{A`^mk@na@_k@|m@k~@zDsEvF}HzYm[~KqLlLsKrPoLlzAajAx]yZz\\\\c_@xN}Q~MyS~s@{hAzd@ov@hrKetP~n@caA`NyS|J_M|\\\\gb@l\\\\{\\\\n^k[z_@gYfr@ua@bo@sWr_@_Od|Aif@lrAoc@~cCsw@blA}`@riBql@tk@}T`_A_e@pyDgaCvpUauNhlAyp@b}B{fAv`@}TlwH}zCzjK}dEphAki@dj@{[viAuu@l}@ut@xgAifAfpIg~JjcFwbGhSgTh_@s\\\\r]yVfb@wVld@yRxWsJlM{D`tW}kHhvBwo@nl@qXnr@cc@|pAqhAto@g{@tj@k_AlWyi@lUeh@~^sgAr\\\\usAl`@abC~]qxBvU_wAvYoyAnJqb@fT}v@j]ghAd]q{@xSqe@ls@{tAlWoc@dTy[hv@qeAd]o`@nm@{l@r}UouSt}@u{@~z@w_AdcDkfEtmBkfCvZy_@p^sa@l^u]d_@y[haAup@vp@q\\\\|cAgf@|wA_n@xi@w\\\\xm@sYtlHcgDdnAek@nvAko@v~@ic@lx@of@\",\"maneuver\":{\"bearing_after\":135,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":126,\"location\":[-71.2864750743811,42.81703500887609],\"instruction\":\"Continue straight on I-93 SOUTH\"},\"duration\":803.0,\"distance\":27320.82,\"name\":\"I-93 SOUTH\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":25744.0,\"announcement\":\"In 16miles, I-93 SB EXIT 3 OFF RAMP TO NH-111\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 16miles, I-93 SB EXIT 3 OFF RAMP TO NH-111</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"I-93 SB EXIT 3 OFF RAMP TO NH-111\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">I-93 SB EXIT 3 OFF RAMP TO NH-111</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[136,140],\"location\":[-71.275545391600389,42.809408142172572],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[90,0],\"location\":[-71.408027396106363,42.771592398141067],\"in\":0}],\"driving_side\":\"right\",\"weight\":1481.0,\"geometry\":\"c_jtpAzk~}fC`o@c]br@}o@~f@eo@n\\\\uh@`e@{_AdZyw@dW_}@lnAcnEz^yrAnBaHhM_\\\\lJgPfKmN|O{KbIgCzQ_D`FpAxC|CjBjKpCn`@\",\"maneuver\":{\"bearing_after\":140,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":136,\"location\":[-71.275545391600389,42.809408142172572],\"instruction\":\"I-93 SB EXIT 3 OFF RAMP TO NH-111\"},\"duration\":41.0,\"distance\":1383.74,\"name\":\"I-93 I93 S OFF RAMP\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":1287.2,\"announcement\":\"In 0.8miles, Merge onto NH-111 [INDIAN ROCK RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 0.8miles, Merge onto NH-111 [INDIAN ROCK RD]</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Merge onto NH-111 [INDIAN ROCK RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Merge onto NH-111 [INDIAN ROCK RD]</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":1383.74,\"primary\":{\"text\":\"NH-111 / INDIAN ROCK RD\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"NH-111\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"INDIAN ROCK RD\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[90,0],\"location\":[-71.408027396106363,42.771592398141067],\"in\":0}],\"driving_side\":\"right\",\"weight\":20698.0,\"geometry\":\"mb{spAx`i}fCLhi@~CvvAzj@laHlN|u@dyAnwFpIh\\\\tLvo@jM`gAjJ~|Afb@`gHhDfn@rDz`@rH`g@zObt@~Vns@~`@pu@lv@pdAxbBjuBxUj^vIfUtOhc@zSzw@vC`SnIt}@v@lfAuBbj@gDb`@urAlhNcWtlB}dA`rGiuBjjM_UxxA_OtcBuCfl@iB|bACxu@pCdpAl_AfnMzNjoBzIxu@hJfm@`UncApT~p@dc@fbAph@n{@ds@nfAhuBphDhtAnuBthC`eEr{AnnCfkAvwBdwBvvDz[bf@pqA~bBdwB|rCpe@~o@vg@py@f_@zx@h~G~vPhTti@ba@xoAvMnj@ppAbgG~\\\\p|At]zxAt]`pA`f@n}Ap\\\\p`ArdBduEro@|dB`cChrG\",\"maneuver\":{\"bearing_after\":0,\"type\":\"arrive\",\"modifier\":\"\",\"bearing_before\":90,\"location\":[-71.408027396106363,42.771592398141067],\"instruction\":\"Merge onto NH-111 [INDIAN ROCK RD]\"},\"duration\":503.0,\"distance\":12421.48,\"name\":\"NH-111\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":12389.300000000001,\"announcement\":\"In 7.7miles, Arrive at destination.\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 7.7miles, Arrive at destination.</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Arrive at destination.\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Arrive at destination.</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":12421.48,\"primary\":{\"text\":\"NH-111 / CENTRAL ST\",\"type\":\"arrive\",\"modifier\":\"\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"NH-111\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"CENTRAL ST\",\"delimiter\":false}]},\"secondary\":null}]}],\"summary\":\"NO NAME, 1.4mi S of Hooksett - NH-111, 3.1mi NE of Nashua\",\"duration\":1556.0,\"distance\":48366.5390625,\"weight\":66578.0}],\"geometry\":\"mbxcqArekhgCoG{BcOoNyEyKwDgTQif@bJggEUqYiA_KcI{UwNiVdUkX~EgEv{Ae|@`w@yh@`aAu~@tt@{t@rKkJ~t@cg@vr@m^b|BceAze@uTzV{KlhDydB|`Aei@nVyLnuAyp@huHowDhWcN~VqLzt@mZxZeKdP}CtWcAd[zBta@lHvU|@~kEy`@ni@mO|bBin@vPaJ|_Awl@tQcL`WwOzSkKrMsExPmDbPw@hDOzNx@rWjFj_@dQlq@v_@bh@vVb{Ax_@b`Bv`@h\\\\fOzaCbhBr[rXzRdVpIjPxRnh@zElQlOvUxgH`iG|HjGhk@xs@rC`KlBdTkAlT}EfQ{FtIueA|x@mPlEcToCuKqK{EiNwBuRXgLfB_MtDmJfKoNjyAiwAjn@wh@j|JyaIf`DmhC|i@w`@j\\\\mSn\\\\}Pf]aOd_@yLhOyEvOyDx`@aIr\\\\wErlKq|AzdAiYzo@s^x]{ZhLaNvf@it@nV_k@tXs|@zsA}kF~]i{A`W_z@vWofAnNmh@lG_SpHsRnIoQ`JiQdWs_@nKyL`[sXfMwIfNkIbOoG|NuF|c@mMzx@_Q`iA_Wp}@sQnlBoTlZe@nxHk_@ffAiK~hAuPvmDcf@zs@eI~c@sD~b@sBvrHqMtXeCzhBsJvr@kRlcG}{CxO_Hr^_Mr]}Jt_@kIbpBoa@~^_Ln_@mQtK}Gth@_f@|o@_`A`hAgfBrvAorBhn@mq@lLsKt|@_q@jn@qe@hv@ct@~J}LrnHgiLvuE}kH`~@}uAzh@gp@l\\\\{\\\\n^k[z_@gYfr@ua@bo@sWr_@_OroDyjAv{HcgCtk@}T`_A_e@|hOcjJl_D{nBd_CswA~a@oXlWwNhe@mZtn@e^flAsm@vb@mSnkAkl@dhMccFh`HyqCxz@cd@zdAcq@`uAifAv}Ae~AthOirQhi@al@h_@s\\\\r]yVfb@wVld@yRxWsJriRskFx_AaWtdDu~@thAe^nl@qX`i@g\\\\|a@yZlw@ss@vWe\\\\zr@}eAd_@ws@pl@exAfj@cpBd[uiBl[qqBx`@caCnH}`@rTaeAxTa}@rY{`Ap\\\\g~@zUkj@lPg]zj@mfAlWoc@fl@s{@`m@qv@z|@q}@feP_oNluA_nA|`BovAt}@u{@~z@w_Axc@{j@j~BozCd}A}rBnOmRtE{Frs@qz@ln@uk@dOyMhaAup@tuBycA|wA_n@xi@w\\\\xmBg|@~dNcqGrWoO|MgJ`o@c]br@}o@zu@ecAn^}o@db@c`AlZ}~@jxAoiFjb@{{AdCsHbIkRrDgG`QmWhKyHvRmHzL{A`FpAxC|CjBjKpCn`@Lhi@~CvvA`b@foFxGdq@lN|u@lv@`xCrZjjAtPjp@nE`VjPpfApNdwBfb@`gH|IbpA~CzWlMdo@`FbSzM`a@bHlQpSna@~]dj@nhAtxAd_AbjAxUj^lDvI~Txn@zSzw@`H|f@xFfbAPx_@cChx@kTjbCqbAdfKqg@zoDyV`|Aab@tgCox@p`Fsp@xzDyZ|pBeGnl@oKlcBuBzyAhAbpA`F~eAzz@dgLzNjoBzIxu@hJfm@`UncApT~p@dc@fbAjsG|eKhlCdgEp[xj@~iCjyEziCxsEz[bf@||@~iAjeDhlEfTpZn_@rn@f_@zx@jmH`uQlM|\\\\|Xn~@zW~iAj`@`lBjXppA|z@bzDbk@jvBhs@v{B|tBnxFzmA~eDbOr`@ds@djBlPvb@fz@~~Bgi@e|A\",\"duration\":1556.0,\"distance\":48366.54,\"weight\":66578.0,\"weight_name\":\"routability\",\"voiceLocale\":\"en-US\"}],\"waypoints\":[{\"name\":\"NO NAME, 1.4mi S of Hooksett\",\"location\":[-71.45688,43.07003]},{\"name\":\"NH-111, 3.1mi NE of Nashua\",\"location\":[-71.40803,42.77159]}],\"code\":\"Ok\",\"uuid\":\"cjqsavmw70crz3po391gqh3mp\"}";
DirectionsResponse directions = DirectionsResponse.fromJson(jsonRoute);
DirectionsRoute route = directions.routes().get(0);
ArrayList<Point> wpPoints = new ArrayList<Point>();
for(DirectionsWaypoint w : directions.waypoints())
wpPoints.add((w.location()));
RouteOptions newRO = RouteOptions.builder()
.profile(DirectionsCriteria.PROFILE_DRIVING)
.coordinates(wpPoints)
.user("mapbox")
.geometries(DirectionsCriteria.GEOMETRY_POLYLINE6)
.accessToken(accessToken)
.requestUuid(directions.uuid())
.baseUrl("https://api.mapbox.com")
.waypointNames("")
.continueStraight(true)
.annotations("distance")
.approaches("")
.bearings(";")
.alternatives(false)
.language("en")
.radiuses("")
.voiceInstructions(true)
.bannerInstructions(true)
.roundaboutExits(true)
.overview("full")
.steps(true)
.voiceUnits("imperial")
.exclude("")
.waypointTargets("")
.build();
route = route.toBuilder().routeOptions(newRO).build();
boolean simulateRoute = false;
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(this, options);
``` | 2019/01/16 | [
"https://Stackoverflow.com/questions/54221366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6542610/"
] | @Troy Berg Let me take a quick second to explain how the route following code works internally when a fresh route is loaded.
Upon loading a new route, if the route json is valid, the `MapboxNavigator` will start in the `INITIALIZED` state. From there it will attempt to gain confidence that the GPS locations being passed in are actually the location where the user is. To establish this trust it needs to receive at least a few location updates and those must be consequtively coherent in both time and space. While it's in the process of establishing this trust it will report the `INITIALIZED` state.
Once trust of the users current stream of location updates has been established, the `MapboxNavigator` will attempt to measure the user's progress along the currently loaded route. If the user's location is found to be unreasonably far from the route itself, the state is flipped to the `OFFROUTE` state.
If the user's current location is within a reasonable distance from the currently loaded route but not close enough to be considered on-route (`TRACKING`) we will continue to return the `INITIALIZED` state and wait for the user to make their way to the route. We call this corraling. Corraling allows a user, in his/her driveway or a store's parking lot for example, to load up a route and not immediately get marked as `OFFROUTE`. While corraling, if the user continually makes progress away from the route they will eventually be marked `OFFROUTE`. | I went ahead and just set my own offRouteEngine. I kept the original, though, and reference that in mine. The code is:
```
MapboxNavigation mbn = navigationView.retrieveMapboxNavigation();
orEngine = (OffRouteDetector)mbn.getOffRouteEngine();
mbn.setOffRouteEngine(new OffRouteDetector() {
@Override
public boolean isUserOffRoute(Location location, RouteProgress routeProgress, MapboxNavigationOptions options) {
Boolean isOffRoute = orEngine.isUserOffRoute(location, routeProgress, options);
// User will never be off-route
return isOffRoute;
}
public boolean isUserOffRouteWith(NavigationStatus status) {
return orEngine.isUserOffRouteWith(status) || status.getRouteState() == RouteState.INITIALIZED;
}
});
```
In that code, I'm counting the "INITIALIZED" state as off route. As I do not reroute but, instead, show a message, I think this should work out ok.
Please let me know if you see any issues with this method and thanks for your help! |
63,142,638 | I m using GooglePlacesAutocomplete where while typing getting the list of places but some places text containing more than that,so I wanted to wrap the text there.
```
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
styles={ styles }>
</GooglePlacesAutocomplete>
```
and my styles for that is as follows
```
const styles = StyleSheet.create({
textInputContainer:{
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth:0,
zIndex:999,
width:'90%',
},
textInput: {
marginLeft: 0,
marginRight: 0,
height: 45,
color: '#5d5d5d',
fontSize: 16,
borderWidth:1,
zIndex:999,
},
predefinedPlacesDescription: {
color: '#1faadb'
},
listView:{
top:45.5,
zIndex:10,
position: 'absolute',
color: 'black',
backgroundColor:"white",
width:'89%',
},
separator:{
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: 'blue',
},
description:{
flexDirection:"row",
flexWrap:"wrap",
fontSize:14,
maxWidth:'89%',
},
```
});
refer this link <https://reactnativeexample.com/customizable-google-places-autocomplete-component-for-ios-and-android-react-native-apps/>
but not able to find the solution.help would be appreciated | 2020/07/28 | [
"https://Stackoverflow.com/questions/63142638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714229/"
] | The width of the ListView showing the results has its width hardcoded to window.with. That is why you wrapping the text isn't working.
There is a potential workaround, and that would be to split the description into multiple lines. You can do this with the [`renderRow`](https://github.com/FaridSafi/react-native-google-places-autocomplete#props) prop. Styling would need to be adjusted for your specific use case.
```
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
renderRow={(rowData) => {
const title = rowData.structured_formatting.main_text;
const address = rowData.structured_formatting.secondary_text;
return (
<View>
<Text style={{ fontSize: 14 }}>{title}</Text>
<Text style={{ fontSize: 14 }}>{address}</Text>
</View>
);
}}
styles={ styles }>
</GooglePlacesAutocomplete>
```
You would need to add `row` to your styles and you can `description` from styles, because it is being overwritten by `renderRow`
```
row: {
height: "100%",
},
```
Disclosure: I am the maintainer of this package. | You can even style the field too.
Follow official doc-
```
<GooglePlacesAutocomplete
placeholder='Enter Location'
minLength={2}
autoFocus={false}
returnKeyType={'default'}
fetchDetails={true}
styles={{
textInputContainer: {
backgroundColor: 'grey',
},
textInput: {
height: 38,
color: '#5d5d5d',
fontSize: 16,
},
predefinedPlacesDescription: {
color: '#1faadb',
},
}}
/>
``` |
56,710,146 | I have some issues to convert jQuery code to JavaScript code.
For example, I have this piece of code :
```
$(document).ready(function() {
doing some stuff
});
```
I tried to code like this :
```
document.getElementById("canvas").onload = function () {
doing some stuff
};
```
but it's not working.
Here is bigger code I'm trying to convert :
```
$(document).ready(function() {
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = $("#canvas");
var cursorX, cursorY;
var context = canvas[0].getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
$(this).mousedown(function(e) {
sign = true;
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
});
$(this).mouseup(function() {
sign = false;
begin_sign = false;
});
```
For information, I want to get this result, in JavaScript:
<http://p4547.phpnet.org/bikes/canvas.html> | 2019/06/21 | [
"https://Stackoverflow.com/questions/56710146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11624270/"
] | Continuing on from the partial solution you provided, since you changing from jQuery element to a DOM node, you have to access a few properties differently as outlined below.
```
document.addEventListener("DOMContentLoaded", function(event) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d'); // <--- remove [0] index
canvas.addEventListener('mousemove', function(e) { ... ))
function clear_canvas() {
// offsetWidth and offsetHeight instead of Height() and Width()
context.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
}
});
``` | Use `addEventListener` instead of `onload` as then you can have multiple 'listeners'. Also, I don't think that canvas elements have the 'load' event, so use the document instead. Same with `document.offsetX` and `document.body.offsetX`.
Your first example would be:
```
document.addEventListener('load', function() {
// doing some stuff
});
```
And your second one:
```
document.addEventListener('load', function() {
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = document.getElementById('canvas');
var cursorX, cursorY;
var context = canvas.getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
document.addEventListener('mousedown', function(e) {
sign = true;
cursorX = (e.pageX - document.body.offsetLeft);
cursorY = (e.pageY - document.body.offsetTop);
});
document.addEventListener('mouseup', function(e) {
sign = false;
begin_sign = false;
});
});
``` |
56,710,146 | I have some issues to convert jQuery code to JavaScript code.
For example, I have this piece of code :
```
$(document).ready(function() {
doing some stuff
});
```
I tried to code like this :
```
document.getElementById("canvas").onload = function () {
doing some stuff
};
```
but it's not working.
Here is bigger code I'm trying to convert :
```
$(document).ready(function() {
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = $("#canvas");
var cursorX, cursorY;
var context = canvas[0].getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
$(this).mousedown(function(e) {
sign = true;
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
});
$(this).mouseup(function() {
sign = false;
begin_sign = false;
});
```
For information, I want to get this result, in JavaScript:
<http://p4547.phpnet.org/bikes/canvas.html> | 2019/06/21 | [
"https://Stackoverflow.com/questions/56710146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11624270/"
] | Continuing on from the partial solution you provided, since you changing from jQuery element to a DOM node, you have to access a few properties differently as outlined below.
```
document.addEventListener("DOMContentLoaded", function(event) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d'); // <--- remove [0] index
canvas.addEventListener('mousemove', function(e) { ... ))
function clear_canvas() {
// offsetWidth and offsetHeight instead of Height() and Width()
context.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
}
});
``` | This will work try
```
$(document).ready(function() {
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = $("#canvas");
var cursorX, cursorY;
var context = canvas[0].getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
});
$(document).mousedown(function(e) {
sign = true;
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
});
$(document).mouseup(function() {
sign = false;
begin_sign = false;
});
``` |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | You can indeed join two separate nodes from unrelated vector lines.
Do this by :
1. Select both lines using the Move Tool.
2. Using the Node Tool select both end nodes you want to join (hold down Shift to select them both).
3. Choose 'Join Curves' from the Action section of the Node context toolbar. | With the node tool (hit A) shift-select both curves you want to join together. Then, in the context toolbar at the top there are a bunch of buttons labelled "Action" - they look like this:

the fourth button along from the left is "Join Curves" (you'll see that when you hover over it) and clicking on that will join the two separate lines together. Hope that's what you're after... |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | With the node tool (hit A) shift-select both curves you want to join together. Then, in the context toolbar at the top there are a bunch of buttons labelled "Action" - they look like this:

the fourth button along from the left is "Join Curves" (you'll see that when you hover over it) and clicking on that will join the two separate lines together. Hope that's what you're after... | Just to clarify a bit, I think you mean this: Say you had a line with 3 nodes, a,b, and c, with a and c being the endpoint of the nodes. You wish to attach another another line with two nodes d and e. You wish to connect the nodes b and e.
As of right now, I can't seem to find functionality of the program where it attaches two unrelated lines that AREN'T endpoints of each line.
I think the Pen module Affinity designed assumes you are always wanting to produce an endpoint to endpoint shape. But unfortunately, when creating lambda shapes, asterisks, x's, f's, $'s, etc. you're going to run into some issues. I would love to see the ability of the pen to create complex shapes that are much less dependent on endpoint snapping. |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | With the node tool (hit A) shift-select both curves you want to join together. Then, in the context toolbar at the top there are a bunch of buttons labelled "Action" - they look like this:

the fourth button along from the left is "Join Curves" (you'll see that when you hover over it) and clicking on that will join the two separate lines together. Hope that's what you're after... | I think what you are looking for is the compound. E.g. I was trying to create an object out of 2 shapes where the inner shape forms a hole. So I used the complement compound (The square with the circle and the intersection is missing).
For other stuff you might need the other operations for forming compounds. |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | You can indeed join two separate nodes from unrelated vector lines.
Do this by :
1. Select both lines using the Move Tool.
2. Using the Node Tool select both end nodes you want to join (hold down Shift to select them both).
3. Choose 'Join Curves' from the Action section of the Node context toolbar. | Just to clarify a bit, I think you mean this: Say you had a line with 3 nodes, a,b, and c, with a and c being the endpoint of the nodes. You wish to attach another another line with two nodes d and e. You wish to connect the nodes b and e.
As of right now, I can't seem to find functionality of the program where it attaches two unrelated lines that AREN'T endpoints of each line.
I think the Pen module Affinity designed assumes you are always wanting to produce an endpoint to endpoint shape. But unfortunately, when creating lambda shapes, asterisks, x's, f's, $'s, etc. you're going to run into some issues. I would love to see the ability of the pen to create complex shapes that are much less dependent on endpoint snapping. |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | You can indeed join two separate nodes from unrelated vector lines.
Do this by :
1. Select both lines using the Move Tool.
2. Using the Node Tool select both end nodes you want to join (hold down Shift to select them both).
3. Choose 'Join Curves' from the Action section of the Node context toolbar. | I think what you are looking for is the compound. E.g. I was trying to create an object out of 2 shapes where the inner shape forms a hole. So I used the complement compound (The square with the circle and the intersection is missing).
For other stuff you might need the other operations for forming compounds. |
42,146 | I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help. | 2014/11/13 | [
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] | I think what you are looking for is the compound. E.g. I was trying to create an object out of 2 shapes where the inner shape forms a hole. So I used the complement compound (The square with the circle and the intersection is missing).
For other stuff you might need the other operations for forming compounds. | Just to clarify a bit, I think you mean this: Say you had a line with 3 nodes, a,b, and c, with a and c being the endpoint of the nodes. You wish to attach another another line with two nodes d and e. You wish to connect the nodes b and e.
As of right now, I can't seem to find functionality of the program where it attaches two unrelated lines that AREN'T endpoints of each line.
I think the Pen module Affinity designed assumes you are always wanting to produce an endpoint to endpoint shape. But unfortunately, when creating lambda shapes, asterisks, x's, f's, $'s, etc. you're going to run into some issues. I would love to see the ability of the pen to create complex shapes that are much less dependent on endpoint snapping. |
22,950,053 | ```
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
event.setName(parser.getValue(e, NODE_NAME));
event.setDate(parser.getValue(e, NODE_DATE));
event.setLocation(parser.getValue(e, NODE_LOC));
Log.d("Thisworks!:", event.getName());
eventsList.addLast(event);
}
for (Event curevent : eventsList) {
Log.d("ThisDoesnt!?:", curevent.getName());
}
```
Output should be:
```
name1
name1
name1
name2
name2
name3
name3
```
Thisworks! outputs different values every time, as expected.
But when i loop through the list and output, it only outputs:
```
name3
name3
name3
name3
name3
name3
name3
```
Am i missing something completely obvious here? | 2014/04/08 | [
"https://Stackoverflow.com/questions/22950053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2859891/"
] | You should be adding a new `Event` to the `eventsList` each time through the loop, not setting the values of the same `event`.
`eventsList.addLast(event)` does *not* make a copy, it just adds a reference to `event` to the list. So there is only ever one `event` object, which you keep overwriting. | You're forgetting to create a new Event object in your loop. What's happening is that the **same** Event object keeps getting updated. Try this:
```
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
Event event = new Event(); // You're missing this.
event.setName(parser.getValue(e, NODE_NAME));
event.setDate(parser.getValue(e, NODE_DATE));
event.setLocation(parser.getValue(e, NODE_LOC));
Log.d("Thisworks!:", event.getName());
eventsList.addLast(event);
}
``` |
46,573,113 | [Image of Description](https://i.stack.imgur.com/Kc9Ke.png)
The aim is to have the user select a shape (Square, Triangle or Circle) and then enter a boundary length. Once this information has been input I can then calculate the perimeter and area of their choice.
The problem is I don't want to create new variables for the length and area in each class if I don't have to and would rather have the variables declared and then passed into the classes if I can.
Basically I don't want to do it like this,
```
class square {
double bLength;
double area;
}
class triangle {
double bLength;
double area;
}
class circle {
double bLength;
double area;
}
```
Can I declare them outside of the classes and then have the classes use/inherit them or anything?
I must apologise for such a basic question, I am quite new to Java and I can't really think around this one. | 2017/10/04 | [
"https://Stackoverflow.com/questions/46573113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7921329/"
] | The classic solution is to use inheritance:
```
class Shape {
double bLength;
double area;
Shape(double bLength, double area) {
this.bLength = bLength;
this.area = area;
}
}
class Square extends Shape {
Square(double bLength, double area) {
super(bLength, area);
}
// additional field, methods...
}
// same for the other shapes
``` | You can use inheritance for this problem in following way :
Declare a class called Shape from which all other classes would inherit
```
public class Shape {
public double length = 0;
public abstract double GetPerimeter();
public abstract double GetArea();
public Shape(double length) {
this.length = length;
}
}
```
Then have your specialized classes. E.g. :
```
public class Circle extends Shape {
public Circle(double length) {
super(length);
}
public double GetPerimeter() {
// Implement the perimeter logic here
}
public double GetArea() {
// Implement the area logic here
}
}
```
Do this for all classes. This way you have the variable in only one class, and all others inherit from it.
**EDIT**
If you want even further optimization (for instance, you don't want function call overhead), something like perhaps
```
public class Shape {
public double length = 0;
public double perimeter= 0;
public double area= 0;
public Shape(double length, double perimeter, double area) {
this.length = length;
this.perimeter= perimeter;
this.area = area;
}
}
public class Circle extends Shape {
public Circle(double length) {
super(length, 2 * Math.PI * length, Math.PI * length * length);
}
}
``` |
16,001,999 | I have a couple media queries in my stylesheet, each modifying some styles, but not others. I'm using the `max-width` query:
```
@media screen and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
@media screen and (max-width: 768px) {
#header .span6 { width: 80%; margin-left: 75px; }
#error .span6 { width: 80; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 75px; }
.control { width: 300px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 800px) {
#header .span6 { width: 80%; margin-left: 75px; }
h1 { font-size: 3.5em; margin-bottom: 0px;}
#error .span6 { width: 80%; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px; }
#timer { font-size: 5em; }
.little { font-size: 0.5em; }
#start-pause { margin-left: 75px; }
.control { width: 312px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 600px) {
#header .span6 { width: 90%; margin-left: 25px; }
#error .span6 { width: 90%; margin-left: 30px; }
#timer-block { width: 90%; margin-left: 30px;}
#start-pause { margin-left: 30px; }
.control { width: 264px; margin-top: -5px; }
#footer { width: 90%; margin-left: 25px; }
}
@media screen and (max-width: 480px) {
#header { margin-top: -10px; }
#header .span6 { width: 90%; margin-left: 25px; }
h1 { font-size: 3em; margin-left: -15px; padding-left: 10px; }
#interval { width: 150px; height: 40px; font-size: 2em; margin-bottom: 20px; width: 150px; }
#error .span6 { width: 90%; margin-left: 25px; }
#timer-block { width: 90%; margin-left: 24px; height: 100px; padding: 10px; }
#start-pause { margin-left: 25px; }
.control { margin-top: -5px; width: 210px; }
#footer { width: 100%; margin-top: -20px; margin-left: 0; }
}
@media screen and (max-width: 320px) {
#timer-block { width: 90%; margin-left: 15px; padding: 10px; font-size: 0.8em; }
#header { margin-top: 0px; }
#header .span6 { margin-left: 37px; }
#interval { margin-top: -45px; margin-left: 20px; }
#error .span6 { width: 90%; margin-left: 15px; }
.control { width: 141px; margin-top: -10px; }
#start-pause { margin-left: 15px; }
#footer { width: 95%; margin-left: 10px; }
}
```
Is there a way I can change what I'm doing to make there be no collisions? This is the first time I use media queries so I may be missing something entirely. | 2013/04/14 | [
"https://Stackoverflow.com/questions/16001999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Set a min width 1 pixel higher than the max width of the next query
Example
```
@media screen and (min-width: 769px) and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
``` | I think you need to use `min-width` in this case to prevent collision, for example:
```
@media only screen and (min-width : 321px) and (max-width : 480px) {
/* Styles */
}
``` |
16,001,999 | I have a couple media queries in my stylesheet, each modifying some styles, but not others. I'm using the `max-width` query:
```
@media screen and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
@media screen and (max-width: 768px) {
#header .span6 { width: 80%; margin-left: 75px; }
#error .span6 { width: 80; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 75px; }
.control { width: 300px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 800px) {
#header .span6 { width: 80%; margin-left: 75px; }
h1 { font-size: 3.5em; margin-bottom: 0px;}
#error .span6 { width: 80%; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px; }
#timer { font-size: 5em; }
.little { font-size: 0.5em; }
#start-pause { margin-left: 75px; }
.control { width: 312px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 600px) {
#header .span6 { width: 90%; margin-left: 25px; }
#error .span6 { width: 90%; margin-left: 30px; }
#timer-block { width: 90%; margin-left: 30px;}
#start-pause { margin-left: 30px; }
.control { width: 264px; margin-top: -5px; }
#footer { width: 90%; margin-left: 25px; }
}
@media screen and (max-width: 480px) {
#header { margin-top: -10px; }
#header .span6 { width: 90%; margin-left: 25px; }
h1 { font-size: 3em; margin-left: -15px; padding-left: 10px; }
#interval { width: 150px; height: 40px; font-size: 2em; margin-bottom: 20px; width: 150px; }
#error .span6 { width: 90%; margin-left: 25px; }
#timer-block { width: 90%; margin-left: 24px; height: 100px; padding: 10px; }
#start-pause { margin-left: 25px; }
.control { margin-top: -5px; width: 210px; }
#footer { width: 100%; margin-top: -20px; margin-left: 0; }
}
@media screen and (max-width: 320px) {
#timer-block { width: 90%; margin-left: 15px; padding: 10px; font-size: 0.8em; }
#header { margin-top: 0px; }
#header .span6 { margin-left: 37px; }
#interval { margin-top: -45px; margin-left: 20px; }
#error .span6 { width: 90%; margin-left: 15px; }
.control { width: 141px; margin-top: -10px; }
#start-pause { margin-left: 15px; }
#footer { width: 95%; margin-left: 10px; }
}
```
Is there a way I can change what I'm doing to make there be no collisions? This is the first time I use media queries so I may be missing something entirely. | 2013/04/14 | [
"https://Stackoverflow.com/questions/16001999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of
```
@media screen and (max-width: 480px)
```
You can use
```
@media screen and (max-width: 480px) and (min-width: 321px)
```
This way it will look only at screen sizes between 320 and 481;
instead of 0 and 481 | Set a min width 1 pixel higher than the max width of the next query
Example
```
@media screen and (min-width: 769px) and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
``` |
16,001,999 | I have a couple media queries in my stylesheet, each modifying some styles, but not others. I'm using the `max-width` query:
```
@media screen and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
@media screen and (max-width: 768px) {
#header .span6 { width: 80%; margin-left: 75px; }
#error .span6 { width: 80; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 75px; }
.control { width: 300px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 800px) {
#header .span6 { width: 80%; margin-left: 75px; }
h1 { font-size: 3.5em; margin-bottom: 0px;}
#error .span6 { width: 80%; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px; }
#timer { font-size: 5em; }
.little { font-size: 0.5em; }
#start-pause { margin-left: 75px; }
.control { width: 312px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 600px) {
#header .span6 { width: 90%; margin-left: 25px; }
#error .span6 { width: 90%; margin-left: 30px; }
#timer-block { width: 90%; margin-left: 30px;}
#start-pause { margin-left: 30px; }
.control { width: 264px; margin-top: -5px; }
#footer { width: 90%; margin-left: 25px; }
}
@media screen and (max-width: 480px) {
#header { margin-top: -10px; }
#header .span6 { width: 90%; margin-left: 25px; }
h1 { font-size: 3em; margin-left: -15px; padding-left: 10px; }
#interval { width: 150px; height: 40px; font-size: 2em; margin-bottom: 20px; width: 150px; }
#error .span6 { width: 90%; margin-left: 25px; }
#timer-block { width: 90%; margin-left: 24px; height: 100px; padding: 10px; }
#start-pause { margin-left: 25px; }
.control { margin-top: -5px; width: 210px; }
#footer { width: 100%; margin-top: -20px; margin-left: 0; }
}
@media screen and (max-width: 320px) {
#timer-block { width: 90%; margin-left: 15px; padding: 10px; font-size: 0.8em; }
#header { margin-top: 0px; }
#header .span6 { margin-left: 37px; }
#interval { margin-top: -45px; margin-left: 20px; }
#error .span6 { width: 90%; margin-left: 15px; }
.control { width: 141px; margin-top: -10px; }
#start-pause { margin-left: 15px; }
#footer { width: 95%; margin-left: 10px; }
}
```
Is there a way I can change what I'm doing to make there be no collisions? This is the first time I use media queries so I may be missing something entirely. | 2013/04/14 | [
"https://Stackoverflow.com/questions/16001999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of
```
@media screen and (max-width: 480px)
```
You can use
```
@media screen and (max-width: 480px) and (min-width: 321px)
```
This way it will look only at screen sizes between 320 and 481;
instead of 0 and 481 | I think you need to use `min-width` in this case to prevent collision, for example:
```
@media only screen and (min-width : 321px) and (max-width : 480px) {
/* Styles */
}
``` |
56,011,201 | What i'm trying to do is to create a dropdown with all my "Stations" from database and when choosing one to zoom on it on map.
I have just created a controller called AdminMapController with this code:
```
public class AdminMapController : Controller
{
private readonly ApplicationDbContext _context;
public AdminMapController(ApplicationDbContext context)
{
_context = context;
}
public ActionResult GetListOfStations()
{
ViewBag.ListOfDropdown = _context.Stations.ToList();
return View("~/Areas/Identity/Pages/Account/AdminMap.cshtml");
}
public JsonResult GetAllLocation()
{
var data = _context.Stations.ToList();
return Json(data);
}
```
and the View ( only the drop down test ):
```
</style>
<br/><br/>
<div>
<select class="form-control">
<option>--Select--</option>
@foreach (var item in ViewBag.ListOfDropdown)
{
<option value ="@item.Id">@item.Name</option>
}
</select>
</div>
<br/>
```
Funny thing that `GetAllLocation` method works properly, but `GetListOfStations` throws me the error `NullReferenceException: Object reference not set to an instance of an object.` with these being the "problems": `@foreach (var item in ViewBag.ListOfDropdown)` and `ViewData["Title"] = "Admin Map";`
Any idea how can i fix this? | 2019/05/06 | [
"https://Stackoverflow.com/questions/56011201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I think you should use this one in return Action:
```
var model = _context.Stations.ToList();
return View("~/Areas/Identity/Pages/Account/AdminMap.cshtml", model);
```
View:
```
@model List<Stations>
<div>
<select class="form-control">
<option>--Select--</option>
@foreach (var item in Model)
{
<option value ="@item.Id">@item.Name</option>
}
</select>
</div>
``` | Another way if you want to keep no using a model in this case would be to use "ViewData" instead:
```
ViewData["Stations"] = _context.Stations.ToList();
```
And in the view something like this:
```
@foreach (var item in ViewData["Stations"] as IList<Stations>)
```
But I still think a model is more uselful in your case.
Use the ViewData for extra information that wouldn't be part of the model. |
19,005,570 | We recently developed a website that essentially has 2 modes, mobile and a tablet + desktop one. The css file is laid out with mobile rules first, then there is a breakpoint for any sizes above 640px, so we could show the desktop version to the 7" tablets when on landspace.
However, although it is working great for all iphones, my galaxy s4, even the windows phone and of course for the ipad and desktop, some mobile phones pick up the desktop styles, essentially showing the desktop version, namely the galaxy s2 and the galaxy s3 among others.
As i said, my css code is built mobile first, so all mobiles with a width of less than 640px (pretty much all) should not pick up the desktop styles, the media query is as follows:
```
@media all and (min-width: 641px) { .... }
```
So i do not really understand why.. any ideas?
edit: I forgot to add we have added a conditional that will check whether the size of the device is larger than 640, in which case it sets the viewport size to the full width of the website so it scales down on tablets, or else it just sets it to device-width.
```
<meta id="testViewport" name="viewport" content="width=device-width, maximum-scale=1">
<script>
if (screen.width > 640) {
var mvp = document.getElementById('testViewport');
mvp.setAttribute('content','width=1000');
}
</script>
``` | 2013/09/25 | [
"https://Stackoverflow.com/questions/19005570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171878/"
] | You can use `.trigger` and target your buttons ID:
```
$("#idOfButton").trigger("click");
```
Or the shorthand, just call a `click()` on your target
```
$("#idOfButton").click();
``` | Try [trigger()](http://api.jquery.com/trigger)
```
$("#button").on('click',function(){
$('#fileUpload').trigger("click");
});
``` |
711,425 | I'm very new to Ubuntu 14.04 and want to install and run Teamviewer on my PC.
I have to maintain someone else's PC in another country who has Ubuntu installed.
I've installed it from the "Files and Folders" but can't find the application saved anywhere.
I've followed the instructions give by others to install and it seemed to work.
Where do I look for the teamviewer application and how to I run it?
Thank you | 2015/12/20 | [
"https://askubuntu.com/questions/711425",
"https://askubuntu.com",
"https://askubuntu.com/users/484270/"
] | run:
```
sudo teamviewer --daemon enable
```
and then open teamviewer from the GUI | If you have installed TeamViewer, by downloading the `'*.deb'` file from their website, then it should be installed in the `/opt` folder as default. Now, to launch the application, open up terminal and type:
```
/opt/teamviewer/tv_bin/script/teamviewer
```
Also, if you are unable to find the application in the `/opt` directory, then type this command to find the file:
```
sudo find / -type f -iname teamviewer
```
`sudo` to be sure that it searches all directories.
The above command will give you the location of the teamviewer file. After you get the location, type:
```
/new/path/to/teamviewer/tv_bin/script/teamviewer
``` |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Your first problem is that you cannot use name based virtual hosts in Apache without having a hostname in DNS or local /etc/hosts which resolves to the IP of the server Apache is running on.
The second problem is because EvalException cannot be used in a multi process server configuration. Read:
<http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Browser_Based_Debugger>
Either disable EvalException or configure mod\_wsgi such that you are using daemon mode with 'default' of a single process (don't use processes=1).
For background on various process/thread configurations possible for Apache/mod\_wsgi read:
<http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading>
You want to use one whereby 'wsgi.multiprocess' is False. | Not an expert on the ''paste'' environment, but shouldn't be:
```
from paste.deploy.loadwsgi import loadapp
``` |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this:
```
[app:main]
set debug = false
``` | Not an expert on the ''paste'' environment, but shouldn't be:
```
from paste.deploy.loadwsgi import loadapp
``` |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Not an expert on the ''paste'' environment, but shouldn't be:
```
from paste.deploy.loadwsgi import loadapp
``` | I agree that in production debug should be disabled, but I would really like to see stacktraces of exceptions.
Right now if I get 500 Server error inside CKAN (nice CKAN page with error info is shown) in logs I can find only error description with no stacktrace:
`[Thu Feb 12 17:04:55.037785 2015] [:error] [pid 15293:tid 139979468994304] [remote 89.71.231.138:5513] Error - <type 'exceptions.TypeError'>: 'NoneType' object is not iterable`
Is there a way to enable full stacktrace with debug = false. |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this:
```
[app:main]
set debug = false
``` | Your first problem is that you cannot use name based virtual hosts in Apache without having a hostname in DNS or local /etc/hosts which resolves to the IP of the server Apache is running on.
The second problem is because EvalException cannot be used in a multi process server configuration. Read:
<http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Browser_Based_Debugger>
Either disable EvalException or configure mod\_wsgi such that you are using daemon mode with 'default' of a single process (don't use processes=1).
For background on various process/thread configurations possible for Apache/mod\_wsgi read:
<http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading>
You want to use one whereby 'wsgi.multiprocess' is False. |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Your first problem is that you cannot use name based virtual hosts in Apache without having a hostname in DNS or local /etc/hosts which resolves to the IP of the server Apache is running on.
The second problem is because EvalException cannot be used in a multi process server configuration. Read:
<http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Browser_Based_Debugger>
Either disable EvalException or configure mod\_wsgi such that you are using daemon mode with 'default' of a single process (don't use processes=1).
For background on various process/thread configurations possible for Apache/mod\_wsgi read:
<http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading>
You want to use one whereby 'wsgi.multiprocess' is False. | I agree that in production debug should be disabled, but I would really like to see stacktraces of exceptions.
Right now if I get 500 Server error inside CKAN (nice CKAN page with error info is shown) in logs I can find only error description with no stacktrace:
`[Thu Feb 12 17:04:55.037785 2015] [:error] [pid 15293:tid 139979468994304] [remote 89.71.231.138:5513] Error - <type 'exceptions.TypeError'>: 'NoneType' object is not iterable`
Is there a way to enable full stacktrace with debug = false. |
5,485,790 | I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing? | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] | Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this:
```
[app:main]
set debug = false
``` | I agree that in production debug should be disabled, but I would really like to see stacktraces of exceptions.
Right now if I get 500 Server error inside CKAN (nice CKAN page with error info is shown) in logs I can find only error description with no stacktrace:
`[Thu Feb 12 17:04:55.037785 2015] [:error] [pid 15293:tid 139979468994304] [remote 89.71.231.138:5513] Error - <type 'exceptions.TypeError'>: 'NoneType' object is not iterable`
Is there a way to enable full stacktrace with debug = false. |
34,879,281 | Lets say I have two lists of colors and I need to compare them. I have a function of comparing colors but I'm a little bit confused of types which function gets. How to cast them?
```
public bool AreColorsSimilar(Color c1, Color c2, int tolerance)
{
return Math.Abs(c1.R - c2.R) < tolerance &&
Math.Abs(c1.G - c2.G) < tolerance &&
Math.Abs(c1.B - c2.B) < tolerance;
}
```
Here is my first list:
```
public static List<Color> PaletteOfSeasons()
{
List<Color> springColors = new List<Color>();
springColors.Add(ColorTranslator.FromHtml("#80a44c"));
springColors.Add(ColorTranslator.FromHtml("#b4cc3a"));
return springColors;
}
```
And in another list I'm pulling pixels from image:
```
public static IEnumerable<Color> GetPixels(Bitmap bitmap)
{
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Color pixel = bitmap.GetPixel(x, y);
yield return pixel;
}
}
}
```
And question is, how can I compare this colors ? | 2016/01/19 | [
"https://Stackoverflow.com/questions/34879281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5787061/"
] | If I understand you right:
```
var springColors = null;
springColors = PaletteOfSeasons(springColors);
var similarColors = GetPixels(bitmap).Intersect(springColors, new ColorComparer(tolerance));
```
And you need this class:
```
public class ColorComparer : IEqualityComparer<Color>
{
private _tolerance;
public ColorComparer(int tolerance)
{
_tolerance = tolerance;
}
public bool Equals(Color x, Color y)
{
return AreColorsSimilar(x, y, _tolerance);
}
public int GetHashCode(Foo x)
{
return 0;
}
private bool AreColorsSimilar(Color c1, Color c2, int tolerance)
{
return Math.Abs(c1.R - c2.R) < tolerance &&
Math.Abs(c1.G - c2.G) < tolerance &&
Math.Abs(c1.B - c2.B) < tolerance;
}
}
```
P.S. Your method PaletteOfSeasons is a little confusing. Passing list to method foolishly.
P.P.S. Use Bitmap.LockBits() to increase code performance.
P.P.P.S. Such implementation of GetHashCode isn't good. But in our situation it is OK. | Simply compare all pixels of the bitmap with all the colors in the palettes:
```
foreach(var pixel in GetPixels(myBitmap))
{
foreach(var candidate in paletteOfSeasons)
{
if(AreColorsSimilar(pixel, candidate, 42)
{
// Hooray, found some similar colors.
}
}
}
``` |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here's an example that works with the Windows API:
```
#include <windows.h>
#include <iostream>
DWORD WINAPI threadProc()
{
for (int i = 0; ; ++i)
{
std::cout << i << '\n';
Sleep (1000);
}
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int iCmdShow)
{
CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)threadProc, NULL, 0, NULL);
int i;
std::cin >> i;
return ERROR_SUCCESS;
}
```
Basically the main function creates a thread that executes using the procedure `threadProc`. You can think of `threadProc` as the thread. Once it ends, the thread ends.
`threadProc` just outputs a running count every second or so, while the main function waits for a blocking input. Once an input is given, the whole thing ends.
Also be aware that `CreateThread` was used with minimal arguments. It returns a handle to the thread that you can use in functions like `WaitForSingleObject`, and the last argument can receive the thread id. | You can use a [Waitable Timer Objects](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687012%28v=vs.85%29.aspx) either in or outside a thread. To use such kind of object just use `SetWaitableTimer` function. The function definition according to MSDN:
>
> Activates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.
>
>
> |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here's an example that works with the Windows API:
```
#include <windows.h>
#include <iostream>
DWORD WINAPI threadProc()
{
for (int i = 0; ; ++i)
{
std::cout << i << '\n';
Sleep (1000);
}
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int iCmdShow)
{
CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)threadProc, NULL, 0, NULL);
int i;
std::cin >> i;
return ERROR_SUCCESS;
}
```
Basically the main function creates a thread that executes using the procedure `threadProc`. You can think of `threadProc` as the thread. Once it ends, the thread ends.
`threadProc` just outputs a running count every second or so, while the main function waits for a blocking input. Once an input is given, the whole thing ends.
Also be aware that `CreateThread` was used with minimal arguments. It returns a handle to the thread that you can use in functions like `WaitForSingleObject`, and the last argument can receive the thread id. | Here is another solution which will work cross-platform if you implement the kbhit() function for them:
```
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#if defined(WIN32)
#include <conio.h>
#else
// kbhit() implementation for other platforms
#endif
boost::mutex mutex_;
bool timeExpired_ = false;
void threadFunc()
{
while(1) {
{
boost::mutex::scoped_lock lock(mutex_);
if (timeExpired_)
break;
#if defined(WIN32)
kbhit();
#endif
}
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
int main(int argc, char *argv[])
{
boost::thread worker(threadFunc);
worker.timed_join(boost::posix_time::milliseconds(5000));
{
boost::mutex::scoped_lock lock(mutex_);
timeExpired_ = true;
}
worker.join();
return 0;
}
```
This approach uses boost::thread and after creating the thread waits for 5 seconds to set the expiration flag and then waits for the thread again until it is done with its functionality. |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here's an example that works with the Windows API:
```
#include <windows.h>
#include <iostream>
DWORD WINAPI threadProc()
{
for (int i = 0; ; ++i)
{
std::cout << i << '\n';
Sleep (1000);
}
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int iCmdShow)
{
CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)threadProc, NULL, 0, NULL);
int i;
std::cin >> i;
return ERROR_SUCCESS;
}
```
Basically the main function creates a thread that executes using the procedure `threadProc`. You can think of `threadProc` as the thread. Once it ends, the thread ends.
`threadProc` just outputs a running count every second or so, while the main function waits for a blocking input. Once an input is given, the whole thing ends.
Also be aware that `CreateThread` was used with minimal arguments. It returns a handle to the thread that you can use in functions like `WaitForSingleObject`, and the last argument can receive the thread id. | Looking for a solution to the same problem, I found this article very helpful:
<http://www.codeproject.com/Articles/1236/Timers-Tutorial>
As you seem to have figured out, the best answer (in the post-Windows 2000 world) seems to be Queue Timers, à la [CreateTimerQueueTimer](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682485%28v=vs.85%29.aspx). |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here's an example that works with the Windows API:
```
#include <windows.h>
#include <iostream>
DWORD WINAPI threadProc()
{
for (int i = 0; ; ++i)
{
std::cout << i << '\n';
Sleep (1000);
}
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int iCmdShow)
{
CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)threadProc, NULL, 0, NULL);
int i;
std::cin >> i;
return ERROR_SUCCESS;
}
```
Basically the main function creates a thread that executes using the procedure `threadProc`. You can think of `threadProc` as the thread. Once it ends, the thread ends.
`threadProc` just outputs a running count every second or so, while the main function waits for a blocking input. Once an input is given, the whole thing ends.
Also be aware that `CreateThread` was used with minimal arguments. It returns a handle to the thread that you can use in functions like `WaitForSingleObject`, and the last argument can receive the thread id. | try this one:
```
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
``` |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | You can use a [Waitable Timer Objects](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687012%28v=vs.85%29.aspx) either in or outside a thread. To use such kind of object just use `SetWaitableTimer` function. The function definition according to MSDN:
>
> Activates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.
>
>
> | Here is another solution which will work cross-platform if you implement the kbhit() function for them:
```
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#if defined(WIN32)
#include <conio.h>
#else
// kbhit() implementation for other platforms
#endif
boost::mutex mutex_;
bool timeExpired_ = false;
void threadFunc()
{
while(1) {
{
boost::mutex::scoped_lock lock(mutex_);
if (timeExpired_)
break;
#if defined(WIN32)
kbhit();
#endif
}
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
int main(int argc, char *argv[])
{
boost::thread worker(threadFunc);
worker.timed_join(boost::posix_time::milliseconds(5000));
{
boost::mutex::scoped_lock lock(mutex_);
timeExpired_ = true;
}
worker.join();
return 0;
}
```
This approach uses boost::thread and after creating the thread waits for 5 seconds to set the expiration flag and then waits for the thread again until it is done with its functionality. |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | You can use a [Waitable Timer Objects](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687012%28v=vs.85%29.aspx) either in or outside a thread. To use such kind of object just use `SetWaitableTimer` function. The function definition according to MSDN:
>
> Activates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.
>
>
> | Looking for a solution to the same problem, I found this article very helpful:
<http://www.codeproject.com/Articles/1236/Timers-Tutorial>
As you seem to have figured out, the best answer (in the post-Windows 2000 world) seems to be Queue Timers, à la [CreateTimerQueueTimer](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682485%28v=vs.85%29.aspx). |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | You can use a [Waitable Timer Objects](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687012%28v=vs.85%29.aspx) either in or outside a thread. To use such kind of object just use `SetWaitableTimer` function. The function definition according to MSDN:
>
> Activates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.
>
>
> | try this one:
```
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
``` |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here is another solution which will work cross-platform if you implement the kbhit() function for them:
```
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#if defined(WIN32)
#include <conio.h>
#else
// kbhit() implementation for other platforms
#endif
boost::mutex mutex_;
bool timeExpired_ = false;
void threadFunc()
{
while(1) {
{
boost::mutex::scoped_lock lock(mutex_);
if (timeExpired_)
break;
#if defined(WIN32)
kbhit();
#endif
}
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
int main(int argc, char *argv[])
{
boost::thread worker(threadFunc);
worker.timed_join(boost::posix_time::milliseconds(5000));
{
boost::mutex::scoped_lock lock(mutex_);
timeExpired_ = true;
}
worker.join();
return 0;
}
```
This approach uses boost::thread and after creating the thread waits for 5 seconds to set the expiration flag and then waits for the thread again until it is done with its functionality. | Looking for a solution to the same problem, I found this article very helpful:
<http://www.codeproject.com/Articles/1236/Timers-Tutorial>
As you seem to have figured out, the best answer (in the post-Windows 2000 world) seems to be Queue Timers, à la [CreateTimerQueueTimer](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682485%28v=vs.85%29.aspx). |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Here is another solution which will work cross-platform if you implement the kbhit() function for them:
```
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#if defined(WIN32)
#include <conio.h>
#else
// kbhit() implementation for other platforms
#endif
boost::mutex mutex_;
bool timeExpired_ = false;
void threadFunc()
{
while(1) {
{
boost::mutex::scoped_lock lock(mutex_);
if (timeExpired_)
break;
#if defined(WIN32)
kbhit();
#endif
}
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
int main(int argc, char *argv[])
{
boost::thread worker(threadFunc);
worker.timed_join(boost::posix_time::milliseconds(5000));
{
boost::mutex::scoped_lock lock(mutex_);
timeExpired_ = true;
}
worker.join();
return 0;
}
```
This approach uses boost::thread and after creating the thread waits for 5 seconds to set the expiration flag and then waits for the thread again until it is done with its functionality. | try this one:
```
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
``` |
10,777,714 | On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] | Looking for a solution to the same problem, I found this article very helpful:
<http://www.codeproject.com/Articles/1236/Timers-Tutorial>
As you seem to have figured out, the best answer (in the post-Windows 2000 world) seems to be Queue Timers, à la [CreateTimerQueueTimer](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682485%28v=vs.85%29.aspx). | try this one:
```
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
``` |
27,633,093 | I am able to successfully run the WordCount example using DataflowPipelineRunner with the maven exec:java command shown in the docs.
However, when I attempt to run it in my own 1.8 VM, it doesn't work. I am using these args (on Windows):
```
--project=highfive-metrics-service \
--stagingLocation=gs://highfive-dataflow-test/staging \
--runner=BlockingDataflowPipelineRunner \
--gCloudPath=C:/Progra~1/Google/CloudS~1/google-cloud-sdk/bin/gcloud.cmd
```
I get the following error:
```
2014-12-24T04:53:34.849Z: (5eada047929dcead): Workflow failed. Causes: (5eada047929dce2e): There was a problem creating the GCE VMs or starting Dataflow on the VMs so no data was processed. Possible causes:
1. A failure in user code on in the worker.
2. A failure in the Dataflow code.
Next Steps:
1. Check the GCE serial console for possible errors in the logs.
2. Look for similar issues on http://stackoverflow.com/questions/tagged/google-cloud-dataflow.
```
Prior to the subsequent cleanup, I observed three harness instances on GCE as expected. Looking at the serial console for the first one, wordcount-jroy-1224043800-12232038-8cfa-harness-0, I see "normal" (comparing to what I see when running with Maven) looking output that ends with:
```
Dec 24 04:38:45 [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.438005] IPv6: ADDRCONF(NETDEV_CHANGE): veth30b3796: link becomes ready
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.439395] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.440262] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 12898 100 12898 0 0 2009k 0 --:--:-- --:--:-- --:--:-- 3148k
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: {"attributes":{"config":"{\"alsologtostderr\":true,\"base_task_dir\":\"/tmp/tasks/\",\"commandlines_file_name\":\"commandlines.txt\",\"continue_on_exception\":true,\"dataflow_api_endpoint\":\"https://www.googleapis.com/\",\"dataflow_api_version\":\"v1beta1\",\"log_dir\":\"/dataflow/logs/taskrunner/harness\",\"log_to_gcs\":true,\"log_to_serialconsole\":true,\"parallel_worker_flags\":{\"job_id\":\"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588\",\"project_id\":\"highfive-metrics-service\",\"reporting_enabled\":true,\"root_url\":\"https://www.googleapis.com/\",\"service_path\":\"dataflow/v1b3/projects/\",\"temp_gcs_directory\":\"gs://highfive-dataflow-test/staging\",\"worker_id\":\"wordcount-jroy-1224043800-12232038-8cfa-harness-0\"},\"project_id\":\"highfive-metrics-service\",\"python_harness_cmd\":\"python_harness_main\",\"scopes\":[\"https://www.googleapis.com/auth/devstorage.full_control\",\"https://www.googleapis.com/auth/cloud-platform\"],\"task_group\":\"nogroup\",\"task_user\":\"nobody\",\"temp_g
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 goo[ 16.494163] device veth29b6136 entered promiscuous mode
gle: cs_directory\":\"gs://highfive-dataflow-test/staging\",\"vm_id\":\"wordcoun[ 16.505311] IPv6: ADDRCONF(NETDEV_UP): veth29b6136: link is not ready
[ 16.507623] docker0: port 2(veth29b6136) entered forwarding state
t-jroy-122404380[ 16.507633] docker0: port 2(veth29b6136) entered forwarding state
0-12232038-8cfa-harness-0\"}","google-container-manifest":"\ncontainers:\n-\n env:\n -\n name: GCS_BUCKET\n value: dataflow-docker-images\n image: google/docker-registry\n imagePullPolicy: PullNever\n name: repository\n ports:\n -\n containerPort: 5000\n hostPort: 5000\n name: registry\n-\n image: localhost:5000/dataflow/taskrunner:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: taskrunner\n volumeMounts:\n -\n mountPath: /dataflow/logs/taskrunner/harness\n name: dataflowlogs-harness\n-\n env:\n -\n name: LOG_DIR\n value: /dataflow/logs\n image: localhost:5000/dataflow/shuffle:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: shuffle\n ports:\n -\n containerPort: 12345\n hostPort: 12345\n name: shuffle1\n -\n containerPort: 22349\n hostPort: 22349\n name: shuffle2\n volumeMounts:\n -\n mountPath: /var/shuffle\n name: dataflow-shuffle\n -\n mountPath: /dataflow/logs\n name: dataflow-logs\nversion: v1
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: beta2\nvolumes:\n-\n name: dataflowlogs-harness\n source:\n hostDir:\n path: /var/log/dataflow/taskrunner/harness\n-\n name: dataflow-shuffle\n source:\n hostDir:\n path: /dataflow/shuffle\n-\n name: dataflow-logs\n source:\n hostDir:\n path: /var/log/dataflow/shuffle\n","job_id":"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588","packages":"gs://dataflow-releases-prod/worker_packages/NOTICES.shuffle|NOTICES.shuffler|gs://highfive-dataflow-test/staging/access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|gs://highfive-dataflow-test/staging/avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|gs://highfive-dataflow-test/staging/charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|gs://highfive-dataflow-test/staging/cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|gs://highfive-dataflow-test/staging/commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|gs://highfive-dataflow-test/staging/commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|gs://highfive-dataflow-test/staging/dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|gs://highfive-dataflow-test/staging/deploy-eLnif2izXW_mrleXudK0Eg.jar|deploy-eLnif2izXW_mrleXudK0Eg.jar|gs://highfive-dataflow-test/staging/dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|gs://highfive-dataflow-test/staging/google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|gs://highfive-dataflow-test/staging/google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|gs://highfive-dataflow-test/staging/google-api-services-compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|google-api-services
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|gs://highfive-dataflow-test/staging/google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|gs://highfive-dataflow-test/staging/google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|gs://highfive-dataflow-test/staging/google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|gs://highfive-dataflow-test/staging/google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|gs://highfive-dataflow-test/staging/google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|gs://highfive-dataflow-test/staging/google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|gs://highfive-dataflow-test/st
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: aging/google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|gs://highfive-dataflow-test/staging/google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|gs://highfive-dataflow-test/staging/guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|gs://highfive-dataflow-test/staging/hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|gs://highfive-dataflow-test/staging/hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|gs://highfive-dataflow-test/staging/httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|gs://highfive-dataflow-test/staging/httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|gs://highfive-dataflow-test/staging/idea_rt-6II88e1BKUeCOQqcrZht-w.jar|idea_rt-6II88e1BKUeCOQqcrZht-w.jar|gs://highfive-dataflow-test/staging/jacce
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: ss-laKenN34W6jKKivkBUzVcA.jar|jaccess-laKenN34W6jKKivkBUzVcA.jar|gs://highfive-dataflow-test/staging/jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|gs://highfive-dataflow-test/staging/jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|gs://highfive-dataflow-test/staging/jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|gs://highfive-dataflow-test/staging/jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|gs://highfive-dataflow-test/staging/jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|gs://highfive-dataflow-test/staging/javaws-O8JqID6BpsXsCSRRkhii3w.jar|javaws-O8JqID6BpsXsCSRRkhii3w.jar|gs://highfive-dataflow-test/staging/jce-eMjjWzdqQh30yNZ9HMuXMA.jar|jce-eMjjWzdqQh30yNZ9HMuXMA.jar|gs://highfive-dataflow-test/staging/jfr-xDzacRGMQeIR4SdPe69o1A.jar|jfr
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -xDzacRGMQeIR4SdPe69o1A.jar|gs://highfive-dataflow-test/staging/jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|gs://highfive-dataflow-test/staging/jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|gs://highfive-dataflow-test/staging/joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|gs://highfive-dataflow-test/staging/jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|gs://highfive-dataflow-test/staging/jsse-HOItnWzBlT4hG5HPmlF56w.jar|jsse-HOItnWzBlT4hG5HPmlF56w.jar|gs://highfive-dataflow-test/staging/junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|gs://highfive-dataflow-test/staging/localedata-R9ei3T8qar8cibFNN0X7Qg.jar|localedata-R9ei3T8qar8cibFNN0X7Qg.jar|gs://highfive-dataflow-test/staging/management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|gs://highfive-dataflow-test/staging/mockito-all-1.9.5-_T4jPTp05rc7PhcOO34Saw.jar|mockito-all-1.9.5-_T4jPTp0
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: 5rc7PhcOO34Saw.jar|gs://highfive-dataflow-test/staging/nashorn-x8si6abt-U04QaVUHvl_bg.jar|nashorn-x8si6abt-U04QaVUHvl_bg.jar|gs://highfive-dataflow-test/staging/paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|gs://highfive-dataflow-test/staging/plugin-TG6U30mOzKi8yMGKYd7ong.jar|plugin-TG6U30mOzKi8yMGKYd7ong.jar|gs://highfive-dataflow-test/staging/protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|gs://highfive-dataflow-test/staging/resources-RavNZwakZf55HEtrC9KyCw.jar|resources-RavNZwakZf55HEtrC9KyCw.jar|gs://highfive-dataflow-test/staging/rt-Z2kDZdIt-eG8CCtFIinW1g.jar|rt-Z2kDZdIt-eG8CCtFIinW1g.jar|gs://highfive-dataflow-test/staging/slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|gs://highfive-dataflow-test/staging/slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|gs://highfive-dataflow-test/staging/snappy-java-1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|snappy-java
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|gs://highfive-dataflow-test/staging/sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|gs://highfive-dataflow-test/staging/sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|gs://highfive-dataflow-test/staging/sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|gs://highfive-dataflow-test/staging/sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|gs://highfive-dataflow-test/staging/xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|gs://highfive-dataflow-test/staging/zipfs-SIKQJJIhpGOgSa4tT6nStA.jar|zipfs-SIKQJJIhpGOgSa4tT6nStA.jar"},"description":"GCE Instance created for Dataflow","disks":[{"deviceName":"persistent-disk-0","index":0,"mode":"READ_WRITE","type":"PERSISTENT"}],"hostname":"wordcount-jroy-1224043800-12232038-8cfa-harness-0.c.highfive-metrics-service.internal","id":8960015560553137779,"image":"","machineType":"projects/537312487774/machineTypes/n1-stan
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: dard-4","maintenanceEvent":"NONE","networkInterfaces":[{"accessConfigs":[{"externalIp":"130.211.184.44","type":"ONE_TO_ONE_NAT"}],"forwardedIps":[],"ip":"10.240.173.213","network":"projects/537312487774/networks/default"}],"scheduling":{"automaticRestart":"TRUE","onHostMaintenance":"MIGRATE"},"serviceAccounts":{"[email protected]":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.googleapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]},"default":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.goog
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: leapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]}},"tags":["dataflow"],"zone":"projects/537312487774/zones/us-central1-a"}
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: No startup script found in metadata.
```
Not sure what I should be looking for, but this seems to reliably fail for me in this manner. I see the same problem when I try to run a custom pipeline of my own (i.e. not WordCount), and also when I run the WordCount example on Linux.
I saved off a file where I recorded:
* The complete output from the WordCount main class
* The metadata field values set on the GCE instance
* The complete serial console output
It is available [here](https://docs.google.com/uc?id=0B5K6jhTgGQohVTZhSUFYdFRZMTA&export=download).
Things I've tried so far, without success:
* Forcing the language level of the compiled classes to 1.7 (am using 1.8 JRE)
* Modifying DataflowPipelineRunner::detectClassPathResourcesToStage to not emit JRE jar files (this is a difference I noticed in the log compared to Maven; when running under Maven the JRE jars are not staged).
* EDIT: Attempting to set the classpath to EXACTLY the same as what Maven ends up using (removing all of our projects' dependencies). This seemed to change the behavior a bit and I got to a `java.lang.ClassNotFoundException: com.google.cloud.dataflow.examples.WordCount$ExtractWordsFn` in the worker output.
Strongly suspicious that the problem lies with the staged classpath, but without more specific error messages, I'm shooting in the dark. Would appreciate ideas of where to look next or other things to try. | 2014/12/24 | [
"https://Stackoverflow.com/questions/27633093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390587/"
] | There's a very high likelihood that this is an issue with staging dependencies.
There's a high probability if you create a bundled jar it will just work. You can create a bundled jar by running the command
```
mvn bundle:bundle
```
This will create a single jar that should pull in all dependencies transitively. You then just need to add that jar to your class path and Dataflow should automatically stage it; Thereby ensuring your code as well as any dependencies are available on the worker.
Most likely the job worked with mvn exec, because maven automatically generates a class path with all dependencies from the POM. When running manually, that doesn't happen. i.e if you invoke java directly e.g.
```
java -cp <JAR FILES> your.main.class --project=<YOUR PROJECT> ....
```
then you must add all dependencies to the class path so that they get staged. Creating a bundled jar as suggested above is usually the easiest way to do that. | My suggestion would be to look at the worker logs to see if we can find additional information about what's going on in the workers.
There are three ways to get this information. The first is via the Dataflow UI. Go to the Google Cloud Console and then select the Dataflow option in the left hand frame. You should see a list of your jobs. You can click on the job in question. This should show you a graph of your job. On the right side you should see a button "view logs". Please click that. You should then see a UI for navigating the logs and you can look for errors.
The second option is to look for the logs on GCS. The location to look for is:
```
gs://PATH TO YOUR STAGING DIRECTORY/logs/JOB-ID/VM-ID/LOG-FILE
```
You might see multiple log files. The one we are most interested in is the one that starts with "start\_java\_worker". If that log file doesn't exist then the worker didn't make enough progress to actually upload the file; or else there might have been a permission problem uploading the log file.
In that case the best thing to do is to try to ssh into one of the VMs before it gets torn down. You should have about 15 minutes before the job fails and the VMs are deleted.
Once you login to the VM you can find all the logs in
```
/var/log/dataflow/...
```
The log we care most about at this point is:
```
/var/log/dataflow/taskrunner/harness/start_java_worker-SOME ID.log
```
If there is a problem starting the code that runs on the VM that log should tell us. That log and the other logs should also tell us if there is a permission problem that prevents the code running on the worker from being able to access Dataflow.
Please take a look and let us know if you find anything. |
27,633,093 | I am able to successfully run the WordCount example using DataflowPipelineRunner with the maven exec:java command shown in the docs.
However, when I attempt to run it in my own 1.8 VM, it doesn't work. I am using these args (on Windows):
```
--project=highfive-metrics-service \
--stagingLocation=gs://highfive-dataflow-test/staging \
--runner=BlockingDataflowPipelineRunner \
--gCloudPath=C:/Progra~1/Google/CloudS~1/google-cloud-sdk/bin/gcloud.cmd
```
I get the following error:
```
2014-12-24T04:53:34.849Z: (5eada047929dcead): Workflow failed. Causes: (5eada047929dce2e): There was a problem creating the GCE VMs or starting Dataflow on the VMs so no data was processed. Possible causes:
1. A failure in user code on in the worker.
2. A failure in the Dataflow code.
Next Steps:
1. Check the GCE serial console for possible errors in the logs.
2. Look for similar issues on http://stackoverflow.com/questions/tagged/google-cloud-dataflow.
```
Prior to the subsequent cleanup, I observed three harness instances on GCE as expected. Looking at the serial console for the first one, wordcount-jroy-1224043800-12232038-8cfa-harness-0, I see "normal" (comparing to what I see when running with Maven) looking output that ends with:
```
Dec 24 04:38:45 [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.438005] IPv6: ADDRCONF(NETDEV_CHANGE): veth30b3796: link becomes ready
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.439395] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.440262] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 12898 100 12898 0 0 2009k 0 --:--:-- --:--:-- --:--:-- 3148k
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: {"attributes":{"config":"{\"alsologtostderr\":true,\"base_task_dir\":\"/tmp/tasks/\",\"commandlines_file_name\":\"commandlines.txt\",\"continue_on_exception\":true,\"dataflow_api_endpoint\":\"https://www.googleapis.com/\",\"dataflow_api_version\":\"v1beta1\",\"log_dir\":\"/dataflow/logs/taskrunner/harness\",\"log_to_gcs\":true,\"log_to_serialconsole\":true,\"parallel_worker_flags\":{\"job_id\":\"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588\",\"project_id\":\"highfive-metrics-service\",\"reporting_enabled\":true,\"root_url\":\"https://www.googleapis.com/\",\"service_path\":\"dataflow/v1b3/projects/\",\"temp_gcs_directory\":\"gs://highfive-dataflow-test/staging\",\"worker_id\":\"wordcount-jroy-1224043800-12232038-8cfa-harness-0\"},\"project_id\":\"highfive-metrics-service\",\"python_harness_cmd\":\"python_harness_main\",\"scopes\":[\"https://www.googleapis.com/auth/devstorage.full_control\",\"https://www.googleapis.com/auth/cloud-platform\"],\"task_group\":\"nogroup\",\"task_user\":\"nobody\",\"temp_g
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 goo[ 16.494163] device veth29b6136 entered promiscuous mode
gle: cs_directory\":\"gs://highfive-dataflow-test/staging\",\"vm_id\":\"wordcoun[ 16.505311] IPv6: ADDRCONF(NETDEV_UP): veth29b6136: link is not ready
[ 16.507623] docker0: port 2(veth29b6136) entered forwarding state
t-jroy-122404380[ 16.507633] docker0: port 2(veth29b6136) entered forwarding state
0-12232038-8cfa-harness-0\"}","google-container-manifest":"\ncontainers:\n-\n env:\n -\n name: GCS_BUCKET\n value: dataflow-docker-images\n image: google/docker-registry\n imagePullPolicy: PullNever\n name: repository\n ports:\n -\n containerPort: 5000\n hostPort: 5000\n name: registry\n-\n image: localhost:5000/dataflow/taskrunner:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: taskrunner\n volumeMounts:\n -\n mountPath: /dataflow/logs/taskrunner/harness\n name: dataflowlogs-harness\n-\n env:\n -\n name: LOG_DIR\n value: /dataflow/logs\n image: localhost:5000/dataflow/shuffle:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: shuffle\n ports:\n -\n containerPort: 12345\n hostPort: 12345\n name: shuffle1\n -\n containerPort: 22349\n hostPort: 22349\n name: shuffle2\n volumeMounts:\n -\n mountPath: /var/shuffle\n name: dataflow-shuffle\n -\n mountPath: /dataflow/logs\n name: dataflow-logs\nversion: v1
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: beta2\nvolumes:\n-\n name: dataflowlogs-harness\n source:\n hostDir:\n path: /var/log/dataflow/taskrunner/harness\n-\n name: dataflow-shuffle\n source:\n hostDir:\n path: /dataflow/shuffle\n-\n name: dataflow-logs\n source:\n hostDir:\n path: /var/log/dataflow/shuffle\n","job_id":"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588","packages":"gs://dataflow-releases-prod/worker_packages/NOTICES.shuffle|NOTICES.shuffler|gs://highfive-dataflow-test/staging/access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|gs://highfive-dataflow-test/staging/avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|gs://highfive-dataflow-test/staging/charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|gs://highfive-dataflow-test/staging/cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|gs://highfive-dataflow-test/staging/commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|gs://highfive-dataflow-test/staging/commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|gs://highfive-dataflow-test/staging/dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|gs://highfive-dataflow-test/staging/deploy-eLnif2izXW_mrleXudK0Eg.jar|deploy-eLnif2izXW_mrleXudK0Eg.jar|gs://highfive-dataflow-test/staging/dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|gs://highfive-dataflow-test/staging/google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|gs://highfive-dataflow-test/staging/google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|gs://highfive-dataflow-test/staging/google-api-services-compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|google-api-services
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|gs://highfive-dataflow-test/staging/google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|gs://highfive-dataflow-test/staging/google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|gs://highfive-dataflow-test/staging/google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|gs://highfive-dataflow-test/staging/google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|gs://highfive-dataflow-test/staging/google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|gs://highfive-dataflow-test/staging/google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|gs://highfive-dataflow-test/st
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: aging/google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|gs://highfive-dataflow-test/staging/google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|gs://highfive-dataflow-test/staging/guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|gs://highfive-dataflow-test/staging/hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|gs://highfive-dataflow-test/staging/hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|gs://highfive-dataflow-test/staging/httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|gs://highfive-dataflow-test/staging/httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|gs://highfive-dataflow-test/staging/idea_rt-6II88e1BKUeCOQqcrZht-w.jar|idea_rt-6II88e1BKUeCOQqcrZht-w.jar|gs://highfive-dataflow-test/staging/jacce
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: ss-laKenN34W6jKKivkBUzVcA.jar|jaccess-laKenN34W6jKKivkBUzVcA.jar|gs://highfive-dataflow-test/staging/jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|gs://highfive-dataflow-test/staging/jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|gs://highfive-dataflow-test/staging/jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|gs://highfive-dataflow-test/staging/jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|gs://highfive-dataflow-test/staging/jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|gs://highfive-dataflow-test/staging/javaws-O8JqID6BpsXsCSRRkhii3w.jar|javaws-O8JqID6BpsXsCSRRkhii3w.jar|gs://highfive-dataflow-test/staging/jce-eMjjWzdqQh30yNZ9HMuXMA.jar|jce-eMjjWzdqQh30yNZ9HMuXMA.jar|gs://highfive-dataflow-test/staging/jfr-xDzacRGMQeIR4SdPe69o1A.jar|jfr
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -xDzacRGMQeIR4SdPe69o1A.jar|gs://highfive-dataflow-test/staging/jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|gs://highfive-dataflow-test/staging/jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|gs://highfive-dataflow-test/staging/joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|gs://highfive-dataflow-test/staging/jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|gs://highfive-dataflow-test/staging/jsse-HOItnWzBlT4hG5HPmlF56w.jar|jsse-HOItnWzBlT4hG5HPmlF56w.jar|gs://highfive-dataflow-test/staging/junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|gs://highfive-dataflow-test/staging/localedata-R9ei3T8qar8cibFNN0X7Qg.jar|localedata-R9ei3T8qar8cibFNN0X7Qg.jar|gs://highfive-dataflow-test/staging/management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|gs://highfive-dataflow-test/staging/mockito-all-1.9.5-_T4jPTp05rc7PhcOO34Saw.jar|mockito-all-1.9.5-_T4jPTp0
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: 5rc7PhcOO34Saw.jar|gs://highfive-dataflow-test/staging/nashorn-x8si6abt-U04QaVUHvl_bg.jar|nashorn-x8si6abt-U04QaVUHvl_bg.jar|gs://highfive-dataflow-test/staging/paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|gs://highfive-dataflow-test/staging/plugin-TG6U30mOzKi8yMGKYd7ong.jar|plugin-TG6U30mOzKi8yMGKYd7ong.jar|gs://highfive-dataflow-test/staging/protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|gs://highfive-dataflow-test/staging/resources-RavNZwakZf55HEtrC9KyCw.jar|resources-RavNZwakZf55HEtrC9KyCw.jar|gs://highfive-dataflow-test/staging/rt-Z2kDZdIt-eG8CCtFIinW1g.jar|rt-Z2kDZdIt-eG8CCtFIinW1g.jar|gs://highfive-dataflow-test/staging/slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|gs://highfive-dataflow-test/staging/slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|gs://highfive-dataflow-test/staging/snappy-java-1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|snappy-java
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|gs://highfive-dataflow-test/staging/sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|gs://highfive-dataflow-test/staging/sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|gs://highfive-dataflow-test/staging/sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|gs://highfive-dataflow-test/staging/sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|gs://highfive-dataflow-test/staging/xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|gs://highfive-dataflow-test/staging/zipfs-SIKQJJIhpGOgSa4tT6nStA.jar|zipfs-SIKQJJIhpGOgSa4tT6nStA.jar"},"description":"GCE Instance created for Dataflow","disks":[{"deviceName":"persistent-disk-0","index":0,"mode":"READ_WRITE","type":"PERSISTENT"}],"hostname":"wordcount-jroy-1224043800-12232038-8cfa-harness-0.c.highfive-metrics-service.internal","id":8960015560553137779,"image":"","machineType":"projects/537312487774/machineTypes/n1-stan
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: dard-4","maintenanceEvent":"NONE","networkInterfaces":[{"accessConfigs":[{"externalIp":"130.211.184.44","type":"ONE_TO_ONE_NAT"}],"forwardedIps":[],"ip":"10.240.173.213","network":"projects/537312487774/networks/default"}],"scheduling":{"automaticRestart":"TRUE","onHostMaintenance":"MIGRATE"},"serviceAccounts":{"[email protected]":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.googleapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]},"default":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.goog
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: leapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]}},"tags":["dataflow"],"zone":"projects/537312487774/zones/us-central1-a"}
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: No startup script found in metadata.
```
Not sure what I should be looking for, but this seems to reliably fail for me in this manner. I see the same problem when I try to run a custom pipeline of my own (i.e. not WordCount), and also when I run the WordCount example on Linux.
I saved off a file where I recorded:
* The complete output from the WordCount main class
* The metadata field values set on the GCE instance
* The complete serial console output
It is available [here](https://docs.google.com/uc?id=0B5K6jhTgGQohVTZhSUFYdFRZMTA&export=download).
Things I've tried so far, without success:
* Forcing the language level of the compiled classes to 1.7 (am using 1.8 JRE)
* Modifying DataflowPipelineRunner::detectClassPathResourcesToStage to not emit JRE jar files (this is a difference I noticed in the log compared to Maven; when running under Maven the JRE jars are not staged).
* EDIT: Attempting to set the classpath to EXACTLY the same as what Maven ends up using (removing all of our projects' dependencies). This seemed to change the behavior a bit and I got to a `java.lang.ClassNotFoundException: com.google.cloud.dataflow.examples.WordCount$ExtractWordsFn` in the worker output.
Strongly suspicious that the problem lies with the staged classpath, but without more specific error messages, I'm shooting in the dark. Would appreciate ideas of where to look next or other things to try. | 2014/12/24 | [
"https://Stackoverflow.com/questions/27633093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390587/"
] | When running pipelines using `[Blocking]DataflowPipelineRunner` from the Cloud Dataflow Java SDK, the runner automatically copies everything from your local Java class path to a staging location in Google Cloud Storage, which is being accessed by workers on-demand.
`ClassNotFoundException` in the Cloud Dataflow worker environment is an indication that required dependencies for your pipeline are not properly staged in a Google Cloud Storage bucket. This likely root cause can be confirmed by looking at the contents of your staging bucket in Google Developers Console and the console output of `BlockingDataflowPipelineRunner`.
Now, the problem can be fixed by bundling all dependencies into a single, monolithic jar. In Maven, the following command can be used to create such a jar as long as the bundle plugin is properly configured to embed all transitive dependencies:
```
mvn bundle:bundle
```
Then, the bundled jar can be executed normally, such as:
```
java -cp <bundled jar> <main class> --project=<project> ...
```
Alternatively, the problem can be fixed by manually adding dependencies to your local class path. For example, the following command may be helpful when running an unbundled jar:
```
java -cp <unbundled jar>:<dep1>:<dep2>:...:<depN> <main class> --project=<project> ...
```
where `dep1` to `depN` are all the dependencies needed for execution of the program. This is clearly error prone, and we don't endorse it. Our documentation recommends using `mvn exec:java` because that sets the execution class path automatically from the dependencies listed in the POM file. Specifically, to run WordCount example, use:
```
mvn exec:java -pl examples \
-Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \
-Dexec.args="--project=<YOUR GCP PROJECT NAME> --stagingLocation=<YOUR GCS LOCATION> --runner=BlockingDataflowPipelineRunner"
```
The main difference between bundled and unbundled version is in the upload activity before pipeline submission. Unbundled version has an advantage that it can automatically use unchanged dependencies that may have been uploaded in previous submissions.
To summarize, use `mvn exec:java` when running an unbundled jar, or bundle the dependencies into a monolithic jar. We'll try to clarify this in the documentation. | My suggestion would be to look at the worker logs to see if we can find additional information about what's going on in the workers.
There are three ways to get this information. The first is via the Dataflow UI. Go to the Google Cloud Console and then select the Dataflow option in the left hand frame. You should see a list of your jobs. You can click on the job in question. This should show you a graph of your job. On the right side you should see a button "view logs". Please click that. You should then see a UI for navigating the logs and you can look for errors.
The second option is to look for the logs on GCS. The location to look for is:
```
gs://PATH TO YOUR STAGING DIRECTORY/logs/JOB-ID/VM-ID/LOG-FILE
```
You might see multiple log files. The one we are most interested in is the one that starts with "start\_java\_worker". If that log file doesn't exist then the worker didn't make enough progress to actually upload the file; or else there might have been a permission problem uploading the log file.
In that case the best thing to do is to try to ssh into one of the VMs before it gets torn down. You should have about 15 minutes before the job fails and the VMs are deleted.
Once you login to the VM you can find all the logs in
```
/var/log/dataflow/...
```
The log we care most about at this point is:
```
/var/log/dataflow/taskrunner/harness/start_java_worker-SOME ID.log
```
If there is a problem starting the code that runs on the VM that log should tell us. That log and the other logs should also tell us if there is a permission problem that prevents the code running on the worker from being able to access Dataflow.
Please take a look and let us know if you find anything. |
27,633,093 | I am able to successfully run the WordCount example using DataflowPipelineRunner with the maven exec:java command shown in the docs.
However, when I attempt to run it in my own 1.8 VM, it doesn't work. I am using these args (on Windows):
```
--project=highfive-metrics-service \
--stagingLocation=gs://highfive-dataflow-test/staging \
--runner=BlockingDataflowPipelineRunner \
--gCloudPath=C:/Progra~1/Google/CloudS~1/google-cloud-sdk/bin/gcloud.cmd
```
I get the following error:
```
2014-12-24T04:53:34.849Z: (5eada047929dcead): Workflow failed. Causes: (5eada047929dce2e): There was a problem creating the GCE VMs or starting Dataflow on the VMs so no data was processed. Possible causes:
1. A failure in user code on in the worker.
2. A failure in the Dataflow code.
Next Steps:
1. Check the GCE serial console for possible errors in the logs.
2. Look for similar issues on http://stackoverflow.com/questions/tagged/google-cloud-dataflow.
```
Prior to the subsequent cleanup, I observed three harness instances on GCE as expected. Looking at the serial console for the first one, wordcount-jroy-1224043800-12232038-8cfa-harness-0, I see "normal" (comparing to what I see when running with Maven) looking output that ends with:
```
Dec 24 04:38:45 [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.438005] IPv6: ADDRCONF(NETDEV_CHANGE): veth30b3796: link becomes ready
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.439395] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.440262] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 12898 100 12898 0 0 2009k 0 --:--:-- --:--:-- --:--:-- 3148k
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: {"attributes":{"config":"{\"alsologtostderr\":true,\"base_task_dir\":\"/tmp/tasks/\",\"commandlines_file_name\":\"commandlines.txt\",\"continue_on_exception\":true,\"dataflow_api_endpoint\":\"https://www.googleapis.com/\",\"dataflow_api_version\":\"v1beta1\",\"log_dir\":\"/dataflow/logs/taskrunner/harness\",\"log_to_gcs\":true,\"log_to_serialconsole\":true,\"parallel_worker_flags\":{\"job_id\":\"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588\",\"project_id\":\"highfive-metrics-service\",\"reporting_enabled\":true,\"root_url\":\"https://www.googleapis.com/\",\"service_path\":\"dataflow/v1b3/projects/\",\"temp_gcs_directory\":\"gs://highfive-dataflow-test/staging\",\"worker_id\":\"wordcount-jroy-1224043800-12232038-8cfa-harness-0\"},\"project_id\":\"highfive-metrics-service\",\"python_harness_cmd\":\"python_harness_main\",\"scopes\":[\"https://www.googleapis.com/auth/devstorage.full_control\",\"https://www.googleapis.com/auth/cloud-platform\"],\"task_group\":\"nogroup\",\"task_user\":\"nobody\",\"temp_g
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 goo[ 16.494163] device veth29b6136 entered promiscuous mode
gle: cs_directory\":\"gs://highfive-dataflow-test/staging\",\"vm_id\":\"wordcoun[ 16.505311] IPv6: ADDRCONF(NETDEV_UP): veth29b6136: link is not ready
[ 16.507623] docker0: port 2(veth29b6136) entered forwarding state
t-jroy-122404380[ 16.507633] docker0: port 2(veth29b6136) entered forwarding state
0-12232038-8cfa-harness-0\"}","google-container-manifest":"\ncontainers:\n-\n env:\n -\n name: GCS_BUCKET\n value: dataflow-docker-images\n image: google/docker-registry\n imagePullPolicy: PullNever\n name: repository\n ports:\n -\n containerPort: 5000\n hostPort: 5000\n name: registry\n-\n image: localhost:5000/dataflow/taskrunner:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: taskrunner\n volumeMounts:\n -\n mountPath: /dataflow/logs/taskrunner/harness\n name: dataflowlogs-harness\n-\n env:\n -\n name: LOG_DIR\n value: /dataflow/logs\n image: localhost:5000/dataflow/shuffle:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: shuffle\n ports:\n -\n containerPort: 12345\n hostPort: 12345\n name: shuffle1\n -\n containerPort: 22349\n hostPort: 22349\n name: shuffle2\n volumeMounts:\n -\n mountPath: /var/shuffle\n name: dataflow-shuffle\n -\n mountPath: /dataflow/logs\n name: dataflow-logs\nversion: v1
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: beta2\nvolumes:\n-\n name: dataflowlogs-harness\n source:\n hostDir:\n path: /var/log/dataflow/taskrunner/harness\n-\n name: dataflow-shuffle\n source:\n hostDir:\n path: /dataflow/shuffle\n-\n name: dataflow-logs\n source:\n hostDir:\n path: /var/log/dataflow/shuffle\n","job_id":"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588","packages":"gs://dataflow-releases-prod/worker_packages/NOTICES.shuffle|NOTICES.shuffler|gs://highfive-dataflow-test/staging/access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|gs://highfive-dataflow-test/staging/avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|gs://highfive-dataflow-test/staging/charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|gs://highfive-dataflow-test/staging/cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|gs://highfive-dataflow-test/staging/commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|gs://highfive-dataflow-test/staging/commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|gs://highfive-dataflow-test/staging/dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|gs://highfive-dataflow-test/staging/deploy-eLnif2izXW_mrleXudK0Eg.jar|deploy-eLnif2izXW_mrleXudK0Eg.jar|gs://highfive-dataflow-test/staging/dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|gs://highfive-dataflow-test/staging/google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|gs://highfive-dataflow-test/staging/google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|gs://highfive-dataflow-test/staging/google-api-services-compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|google-api-services
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|gs://highfive-dataflow-test/staging/google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|gs://highfive-dataflow-test/staging/google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|gs://highfive-dataflow-test/staging/google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|gs://highfive-dataflow-test/staging/google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|gs://highfive-dataflow-test/staging/google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|gs://highfive-dataflow-test/staging/google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|gs://highfive-dataflow-test/st
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: aging/google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|gs://highfive-dataflow-test/staging/google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|gs://highfive-dataflow-test/staging/guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|gs://highfive-dataflow-test/staging/hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|gs://highfive-dataflow-test/staging/hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|gs://highfive-dataflow-test/staging/httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|gs://highfive-dataflow-test/staging/httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|gs://highfive-dataflow-test/staging/idea_rt-6II88e1BKUeCOQqcrZht-w.jar|idea_rt-6II88e1BKUeCOQqcrZht-w.jar|gs://highfive-dataflow-test/staging/jacce
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: ss-laKenN34W6jKKivkBUzVcA.jar|jaccess-laKenN34W6jKKivkBUzVcA.jar|gs://highfive-dataflow-test/staging/jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|gs://highfive-dataflow-test/staging/jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|gs://highfive-dataflow-test/staging/jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|gs://highfive-dataflow-test/staging/jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|gs://highfive-dataflow-test/staging/jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|gs://highfive-dataflow-test/staging/javaws-O8JqID6BpsXsCSRRkhii3w.jar|javaws-O8JqID6BpsXsCSRRkhii3w.jar|gs://highfive-dataflow-test/staging/jce-eMjjWzdqQh30yNZ9HMuXMA.jar|jce-eMjjWzdqQh30yNZ9HMuXMA.jar|gs://highfive-dataflow-test/staging/jfr-xDzacRGMQeIR4SdPe69o1A.jar|jfr
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -xDzacRGMQeIR4SdPe69o1A.jar|gs://highfive-dataflow-test/staging/jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|gs://highfive-dataflow-test/staging/jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|gs://highfive-dataflow-test/staging/joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|gs://highfive-dataflow-test/staging/jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|gs://highfive-dataflow-test/staging/jsse-HOItnWzBlT4hG5HPmlF56w.jar|jsse-HOItnWzBlT4hG5HPmlF56w.jar|gs://highfive-dataflow-test/staging/junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|gs://highfive-dataflow-test/staging/localedata-R9ei3T8qar8cibFNN0X7Qg.jar|localedata-R9ei3T8qar8cibFNN0X7Qg.jar|gs://highfive-dataflow-test/staging/management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|gs://highfive-dataflow-test/staging/mockito-all-1.9.5-_T4jPTp05rc7PhcOO34Saw.jar|mockito-all-1.9.5-_T4jPTp0
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: 5rc7PhcOO34Saw.jar|gs://highfive-dataflow-test/staging/nashorn-x8si6abt-U04QaVUHvl_bg.jar|nashorn-x8si6abt-U04QaVUHvl_bg.jar|gs://highfive-dataflow-test/staging/paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|gs://highfive-dataflow-test/staging/plugin-TG6U30mOzKi8yMGKYd7ong.jar|plugin-TG6U30mOzKi8yMGKYd7ong.jar|gs://highfive-dataflow-test/staging/protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|gs://highfive-dataflow-test/staging/resources-RavNZwakZf55HEtrC9KyCw.jar|resources-RavNZwakZf55HEtrC9KyCw.jar|gs://highfive-dataflow-test/staging/rt-Z2kDZdIt-eG8CCtFIinW1g.jar|rt-Z2kDZdIt-eG8CCtFIinW1g.jar|gs://highfive-dataflow-test/staging/slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|gs://highfive-dataflow-test/staging/slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|gs://highfive-dataflow-test/staging/snappy-java-1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|snappy-java
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|gs://highfive-dataflow-test/staging/sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|gs://highfive-dataflow-test/staging/sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|gs://highfive-dataflow-test/staging/sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|gs://highfive-dataflow-test/staging/sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|gs://highfive-dataflow-test/staging/xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|gs://highfive-dataflow-test/staging/zipfs-SIKQJJIhpGOgSa4tT6nStA.jar|zipfs-SIKQJJIhpGOgSa4tT6nStA.jar"},"description":"GCE Instance created for Dataflow","disks":[{"deviceName":"persistent-disk-0","index":0,"mode":"READ_WRITE","type":"PERSISTENT"}],"hostname":"wordcount-jroy-1224043800-12232038-8cfa-harness-0.c.highfive-metrics-service.internal","id":8960015560553137779,"image":"","machineType":"projects/537312487774/machineTypes/n1-stan
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: dard-4","maintenanceEvent":"NONE","networkInterfaces":[{"accessConfigs":[{"externalIp":"130.211.184.44","type":"ONE_TO_ONE_NAT"}],"forwardedIps":[],"ip":"10.240.173.213","network":"projects/537312487774/networks/default"}],"scheduling":{"automaticRestart":"TRUE","onHostMaintenance":"MIGRATE"},"serviceAccounts":{"[email protected]":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.googleapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]},"default":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.goog
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: leapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]}},"tags":["dataflow"],"zone":"projects/537312487774/zones/us-central1-a"}
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: No startup script found in metadata.
```
Not sure what I should be looking for, but this seems to reliably fail for me in this manner. I see the same problem when I try to run a custom pipeline of my own (i.e. not WordCount), and also when I run the WordCount example on Linux.
I saved off a file where I recorded:
* The complete output from the WordCount main class
* The metadata field values set on the GCE instance
* The complete serial console output
It is available [here](https://docs.google.com/uc?id=0B5K6jhTgGQohVTZhSUFYdFRZMTA&export=download).
Things I've tried so far, without success:
* Forcing the language level of the compiled classes to 1.7 (am using 1.8 JRE)
* Modifying DataflowPipelineRunner::detectClassPathResourcesToStage to not emit JRE jar files (this is a difference I noticed in the log compared to Maven; when running under Maven the JRE jars are not staged).
* EDIT: Attempting to set the classpath to EXACTLY the same as what Maven ends up using (removing all of our projects' dependencies). This seemed to change the behavior a bit and I got to a `java.lang.ClassNotFoundException: com.google.cloud.dataflow.examples.WordCount$ExtractWordsFn` in the worker output.
Strongly suspicious that the problem lies with the staged classpath, but without more specific error messages, I'm shooting in the dark. Would appreciate ideas of where to look next or other things to try. | 2014/12/24 | [
"https://Stackoverflow.com/questions/27633093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390587/"
] | When running pipelines using `[Blocking]DataflowPipelineRunner` from the Cloud Dataflow Java SDK, the runner automatically copies everything from your local Java class path to a staging location in Google Cloud Storage, which is being accessed by workers on-demand.
`ClassNotFoundException` in the Cloud Dataflow worker environment is an indication that required dependencies for your pipeline are not properly staged in a Google Cloud Storage bucket. This likely root cause can be confirmed by looking at the contents of your staging bucket in Google Developers Console and the console output of `BlockingDataflowPipelineRunner`.
Now, the problem can be fixed by bundling all dependencies into a single, monolithic jar. In Maven, the following command can be used to create such a jar as long as the bundle plugin is properly configured to embed all transitive dependencies:
```
mvn bundle:bundle
```
Then, the bundled jar can be executed normally, such as:
```
java -cp <bundled jar> <main class> --project=<project> ...
```
Alternatively, the problem can be fixed by manually adding dependencies to your local class path. For example, the following command may be helpful when running an unbundled jar:
```
java -cp <unbundled jar>:<dep1>:<dep2>:...:<depN> <main class> --project=<project> ...
```
where `dep1` to `depN` are all the dependencies needed for execution of the program. This is clearly error prone, and we don't endorse it. Our documentation recommends using `mvn exec:java` because that sets the execution class path automatically from the dependencies listed in the POM file. Specifically, to run WordCount example, use:
```
mvn exec:java -pl examples \
-Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \
-Dexec.args="--project=<YOUR GCP PROJECT NAME> --stagingLocation=<YOUR GCS LOCATION> --runner=BlockingDataflowPipelineRunner"
```
The main difference between bundled and unbundled version is in the upload activity before pipeline submission. Unbundled version has an advantage that it can automatically use unchanged dependencies that may have been uploaded in previous submissions.
To summarize, use `mvn exec:java` when running an unbundled jar, or bundle the dependencies into a monolithic jar. We'll try to clarify this in the documentation. | There's a very high likelihood that this is an issue with staging dependencies.
There's a high probability if you create a bundled jar it will just work. You can create a bundled jar by running the command
```
mvn bundle:bundle
```
This will create a single jar that should pull in all dependencies transitively. You then just need to add that jar to your class path and Dataflow should automatically stage it; Thereby ensuring your code as well as any dependencies are available on the worker.
Most likely the job worked with mvn exec, because maven automatically generates a class path with all dependencies from the POM. When running manually, that doesn't happen. i.e if you invoke java directly e.g.
```
java -cp <JAR FILES> your.main.class --project=<YOUR PROJECT> ....
```
then you must add all dependencies to the class path so that they get staged. Creating a bundled jar as suggested above is usually the easiest way to do that. |
2,228,430 | I know that this code works on another site I've got but it's not playing ball today.
I get three warnings:
>
> Warning: mysqli\_stmt\_bind\_param() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 33
>
>
> Warning: mysqli\_execute() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 34
>
>
> Warning: mysqli\_stmt\_affected\_rows() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 35
>
>
>
Can someone help me figure this out?
I am having to use htaccess to upgrade to PHP5 if this helps.
```
$connection = mysqli_connect($hostname, $username, $password, $dbname);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
$query = "INSERT INTO entries (name, dob, school, postcode, date) VALUES (?,?,?,?,?)";
$stmt1 = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt1, 'sssss',$name,$dob,$school,$postcode,$date);
mysqli_execute($stmt1);
if(mysqli_stmt_affected_rows($stmt1) != 1)
die("issues");
mysqli_stmt_close($stmt1);
return "new";
```
EDIT
After some investigation it transpires that the prepare statement doesn't play ball with mysql4. I have created a new mysql5 database but I now get this error when I try to connect:
>
> Warning: mysqli\_connect() [function.mysqli-connect]: (HY000/2005): Unknown MySQL server host 'localhost:/tmp/mysql5.sock' (1)
>
>
>
Does anyone have any idea as to why this is happening? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2228430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] | Add more error handling.
When the connection fails, [mysqli\_connect\_error()](http://docs.php.net/mysqli_connect_error) can tell you more details.
When preparing the statement fails [mysqli\_error()](http://docs.php.net/mysqli_error) has more infos about the error.
When executing the statement fails, ask [mysqli\_stmt\_error()](http://docs.php.net/mysqli-stmt.error). And so on and on...
Any time a function/method of the mysqli module returns false to indicate an error, a) handle that error and b) decide whether it makes sense or not to continue. E.g. it doesn't make sense to continue with database operations when the connection failed. But it may make sense to continue inserting data when just one insertion failed (may make sense, may not).
For testing you can use something like this:
```
$connection = mysqli_connect(...);
if ( !$connection ) {
die( 'connect error: '.mysqli_connect_error() );
}
$query = "INSERT INTO entries (name, dob, school, postcode, date) VALUES (?,?,?,?,?)";
$stmt1 = mysqli_prepare($connection, $query);
if ( !$stmt1 ) {
die('mysqli error: '.mysqli_error($connection);
}
mysqli_stmt_bind_param($stmt1, 'sssss',$name,$dob,$school,$postcode,$date);
if ( !mysqli_execute($stmt1) ) {
die( 'stmt error: '.mysqli_stmt_error($stmt1) );
}
...
```
For a real production environment this approach is to talkative and dies to easily ;-) | The problem comes from `mysqli_prepare()`, which in your case returns `false`, hence the 'boolean given' error. As your query seems ok, the error must be in `$connection`. Are you sure that the connection works and is defined?
The connection should be defined as something like this:
```
$connection = mysqli_connect("localhost", "my_user", "my_password", "world");
```
If the connection is properly defined, you can use `echo mysqli_connect_error()` to see if something went wrong. You said that the code works on another site, so perhaps you forgot to change the credentials or host? |
17,744 | For a 3D scanning project I need to capture a video/snapshots of an object and a projector image that is projected on the object. The projector works (only) with a framerate of 60Hz, the camera supports rates in {3.75,7.5,15,30,60} Hz. I have to work in Matlab, and since it's an IEEE 1394 camera, I can only use the [CMU 1394 Camera driver](http://www.cs.cmu.edu/~iwan/1394/) since other drivers are not supported by matlab.
Now, my problem is, that the framerates of the camera (driver) seem to have a tiny non-zero phase-offset that adds up over time such that the captured image gets darker and darker until it reaches some minimum and becomes brighter and brighter again and so on. This is annoying. There are sample applications for 3D scanners that are able to work with different drivers. There, the problem does not exist, so I am pretty sure that it's the driver's fault.
Fortunately, the driver is open source, so putting a little offset somewhere in it and trying to solve the problem by trying out different times, could work. There is, however, one additional idea I had: The camera supports triggering. Is there any way that I can trigger it using the output of the projector? If that would work, that would be much easier and more elegant than fiddling around with that driver. The projector uses VGA. Do you know of any possibility to capture the signal and use it as a trigger? If possible without lot's of additional hardware. | 2011/08/03 | [
"https://electronics.stackexchange.com/questions/17744",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/5235/"
] | (1) You mention 60 Hz for both **frame and capture rates** so the following should not be an issue, and it's obvious enough, but I mention it "just in case" as such things can trip you up.
I'd have expected that if your frame capture lasted exactly "one frame" that brightness variation would not be a major issue. If capture time is less than frame time then location of your capture window affects result. If capture time is > frame time you get a whole image and then part of another. Both arrangements can (will) affect image quality.
(2) **Frame sync signal:**
Camera synchronisation to the VGA signal **should** be easy.
The VGA signal set includes a Vsync (Vertical Synchronisation) signal that allows the start of the frame to be detected.
This is on pin 14 on a PC (DB15) video connector and on pin 12 on a Macintosh video connector.

The above diagram is from [Javier Valcarce's Personal Website - VGA Video Signal Format and Timing](http://www.javiervalcarce.eu/wiki/VGA_Video_Signal_Format_and_Timing_Specifications)
To add to the fun the polarity of the sync signal varies with resolution,but that's liable to not worry you once you work out which of he two possibilities applies in your case.
Assuming that you can synchronise the camera triggering to this signal (**seems** likely to be simple enough). Worst case you may have to add a fixed delay to move the picture phase into the correct location for you operation.
---
**VGA timing:**

Polarity is inverted for some resolutions.
From [VGA video signal generation](http://www.scribd.com/doc/4559939/VGA-Video-Signal-Generation) | If you want to try triggering off it VGA has its horizontal sync on pin 13, formally referenced to the sync ground on pin 10. (As Russel points out in comments, VSYNC on 14 is what should be used)
There's a slight chance you might find you need some means to provide a phase delay to trigger the camera at the right relative time, though you might be able to do something by adjusting the width of the sync pulse to an extreme in video low level settings depending on what the monitor(projector) can tolerate. A simple outboard circuit (a 555 and pot?) would be crude but likely workable.
If a pure software solution is workable that could seem cleaner, but I don't know if that is supported. 60Hz is easily within the realm of software control - jitter is always a concern in non-hard-realtime setups, especially with packetized IO buses - but it might stay within your tolerance. This would require that there be a software triggering mechanism in the driver that you can exploit.
Finally I wouldn't necessarily say that matlab restricts you to using a particular camera driver and thus assortment of cameras, because matlab seems to have a workable interface to user libraries written in other languages like C, and from there it should be possible to obtain data from just about anything you can find documentation for how to talk to either directly or via an existing OS driver interface not supported by matlab. |
15,823,756 | I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.
Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.
The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.
jQuery Code:
```
$(document).ready(function(){
$('.form_error').hide();
$('a.launch-1').click(function() {
var launcher = $(this).attr('id'),
launcher = launcher.split('_');
launcher, launcher[1], $('td .'+launcher[1]);
$('.'+launcher[1]).each(function(){
var field = $(this).attr('data-name'),
fieldValue = $(this).html();
if(field === 'InvoiceID'){
$("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
$("#previouspaymentsloader").hide();
});
} else if(field === 'InvoiceNumber'){
$("#addinvoicenum").html(fieldValue);
}
$('#'+field).val(fieldValue);
});
});
$("#addpayment_submit").click(function(event) {
$('.form_error').hide();
var amount = $("input#amount").val();
if (amount == "") {
$("#amount_error").show();
$("input#amount").focus();
return false;
}
date = $("input#date").val();
if (date == "") {
$("#date_error").show();
$("input#date").focus();
return false;
}
credit = $("input#credit").val();
invoiceID = $("input#InvoiceID").val();
by = $("input#by").val();
dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
$.ajax({
type: "POST",
url: "functions/invoicing_payments_make.php",
data: dataString,
success: function(result) {
if(result == 1){
$('#payment_window_message_success').fadeIn(300);
$('#payment_window_message_success').delay(5000).fadeOut(700);
return false;
} else {
$('#payment_window_message_error_mes').html(result);
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
return false;
}
},
error: function() {
$('#payment_window_message_error_mes').html("An error occured, form was not submitted");
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
}
});
return false;
});
});
```
Here is the html form:
```
<div id="makepayment_form">
<form name="payment" id="payment" class="halfboxform">
<input type="hidden" name="InvoiceID" id="InvoiceID" />
<input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
<fieldset>
<label for="amount" class="label">Amount:</label>
<input type="text" id="amount" name="amount" value="0.00" />
<p class="form_error clearb red input" id="amount_error">This field is required.</p>
<label for="credit" class="label">Credit:</label>
<input type="text" id="credit" name="credit" />
<label for="amount" class="label">Date:</label>
<input type="text" id="date" name="date" />
<p class="form_error clearb red input" id="date_error">This field is required.</p>
</fieldset>
<input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
</form>
</div>
```
Hope someone can help as its driving me crazy. Thanks. | 2013/04/04 | [
"https://Stackoverflow.com/questions/15823756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513473/"
] | Some times you have to not only prevent the default behauviour for handling the event, but also to prevent executing any downstream chain of event handlers.
This can be done by calling [`event.stopImmediatePropagation()`](https://api.jquery.com/event.stopimmediatepropagation/) in addition to [`event.preventDefault()`](https://api.jquery.com/event.preventDefault/).
Example code:
```
$("#addpayment_submit").on('submit', function(event) {
event.preventDefault();
event.stopImmediatePropagation();
});
``` | while all the listed solutions are valid, in my case, what what causing my multiple form submission was the e i was passing to the function called on submit.
i had
```
$('form').bind('submit', function(e){
e.preventDefault()
return false
})
```
but i changed it to
```
$('form').bind('submit', function(){
event.preventDefault()
return false;
})
```
and this worked for me. not including the return false should still not stop the code from working though |
15,823,756 | I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.
Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.
The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.
jQuery Code:
```
$(document).ready(function(){
$('.form_error').hide();
$('a.launch-1').click(function() {
var launcher = $(this).attr('id'),
launcher = launcher.split('_');
launcher, launcher[1], $('td .'+launcher[1]);
$('.'+launcher[1]).each(function(){
var field = $(this).attr('data-name'),
fieldValue = $(this).html();
if(field === 'InvoiceID'){
$("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
$("#previouspaymentsloader").hide();
});
} else if(field === 'InvoiceNumber'){
$("#addinvoicenum").html(fieldValue);
}
$('#'+field).val(fieldValue);
});
});
$("#addpayment_submit").click(function(event) {
$('.form_error').hide();
var amount = $("input#amount").val();
if (amount == "") {
$("#amount_error").show();
$("input#amount").focus();
return false;
}
date = $("input#date").val();
if (date == "") {
$("#date_error").show();
$("input#date").focus();
return false;
}
credit = $("input#credit").val();
invoiceID = $("input#InvoiceID").val();
by = $("input#by").val();
dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
$.ajax({
type: "POST",
url: "functions/invoicing_payments_make.php",
data: dataString,
success: function(result) {
if(result == 1){
$('#payment_window_message_success').fadeIn(300);
$('#payment_window_message_success').delay(5000).fadeOut(700);
return false;
} else {
$('#payment_window_message_error_mes').html(result);
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
return false;
}
},
error: function() {
$('#payment_window_message_error_mes').html("An error occured, form was not submitted");
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
}
});
return false;
});
});
```
Here is the html form:
```
<div id="makepayment_form">
<form name="payment" id="payment" class="halfboxform">
<input type="hidden" name="InvoiceID" id="InvoiceID" />
<input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
<fieldset>
<label for="amount" class="label">Amount:</label>
<input type="text" id="amount" name="amount" value="0.00" />
<p class="form_error clearb red input" id="amount_error">This field is required.</p>
<label for="credit" class="label">Credit:</label>
<input type="text" id="credit" name="credit" />
<label for="amount" class="label">Date:</label>
<input type="text" id="date" name="date" />
<p class="form_error clearb red input" id="date_error">This field is required.</p>
</fieldset>
<input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
</form>
</div>
```
Hope someone can help as its driving me crazy. Thanks. | 2013/04/04 | [
"https://Stackoverflow.com/questions/15823756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513473/"
] | Also, you're binding the action to the submit button 'click'. But, what if the user presses 'enter' while typing in a text field and triggers the default form action? Your function won't run.
I would change this:
```
$("#addpayment_submit").click(function(event) {
event.preventDefault();
//code
}
```
to this:
```
$("#payment").bind('submit', function(event) {
event.preventDefault();
//code
}
```
Now it doesn't matter **how** the user submits the form, because you're going to capture it no matter what. | Try adding the following lines.
```
event.preventDefault();
event.stopImmediatePropagation();
```
This worked for me. |
15,823,756 | I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.
Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.
The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.
jQuery Code:
```
$(document).ready(function(){
$('.form_error').hide();
$('a.launch-1').click(function() {
var launcher = $(this).attr('id'),
launcher = launcher.split('_');
launcher, launcher[1], $('td .'+launcher[1]);
$('.'+launcher[1]).each(function(){
var field = $(this).attr('data-name'),
fieldValue = $(this).html();
if(field === 'InvoiceID'){
$("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
$("#previouspaymentsloader").hide();
});
} else if(field === 'InvoiceNumber'){
$("#addinvoicenum").html(fieldValue);
}
$('#'+field).val(fieldValue);
});
});
$("#addpayment_submit").click(function(event) {
$('.form_error').hide();
var amount = $("input#amount").val();
if (amount == "") {
$("#amount_error").show();
$("input#amount").focus();
return false;
}
date = $("input#date").val();
if (date == "") {
$("#date_error").show();
$("input#date").focus();
return false;
}
credit = $("input#credit").val();
invoiceID = $("input#InvoiceID").val();
by = $("input#by").val();
dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
$.ajax({
type: "POST",
url: "functions/invoicing_payments_make.php",
data: dataString,
success: function(result) {
if(result == 1){
$('#payment_window_message_success').fadeIn(300);
$('#payment_window_message_success').delay(5000).fadeOut(700);
return false;
} else {
$('#payment_window_message_error_mes').html(result);
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
return false;
}
},
error: function() {
$('#payment_window_message_error_mes').html("An error occured, form was not submitted");
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
}
});
return false;
});
});
```
Here is the html form:
```
<div id="makepayment_form">
<form name="payment" id="payment" class="halfboxform">
<input type="hidden" name="InvoiceID" id="InvoiceID" />
<input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
<fieldset>
<label for="amount" class="label">Amount:</label>
<input type="text" id="amount" name="amount" value="0.00" />
<p class="form_error clearb red input" id="amount_error">This field is required.</p>
<label for="credit" class="label">Credit:</label>
<input type="text" id="credit" name="credit" />
<label for="amount" class="label">Date:</label>
<input type="text" id="date" name="date" />
<p class="form_error clearb red input" id="date_error">This field is required.</p>
</fieldset>
<input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
</form>
</div>
```
Hope someone can help as its driving me crazy. Thanks. | 2013/04/04 | [
"https://Stackoverflow.com/questions/15823756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513473/"
] | Try adding the following lines.
```
event.preventDefault();
event.stopImmediatePropagation();
```
This worked for me. | As you are using AJAX request to send data to the server there's no reason even to use `form` tag and `<input type="submit" .../>` (you can use simple button instead). Also I think Cumbo's answer should work. If it doesn't you can also try `event.stopPropagation()`. |
15,823,756 | I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.
Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.
The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.
jQuery Code:
```
$(document).ready(function(){
$('.form_error').hide();
$('a.launch-1').click(function() {
var launcher = $(this).attr('id'),
launcher = launcher.split('_');
launcher, launcher[1], $('td .'+launcher[1]);
$('.'+launcher[1]).each(function(){
var field = $(this).attr('data-name'),
fieldValue = $(this).html();
if(field === 'InvoiceID'){
$("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
$("#previouspaymentsloader").hide();
});
} else if(field === 'InvoiceNumber'){
$("#addinvoicenum").html(fieldValue);
}
$('#'+field).val(fieldValue);
});
});
$("#addpayment_submit").click(function(event) {
$('.form_error').hide();
var amount = $("input#amount").val();
if (amount == "") {
$("#amount_error").show();
$("input#amount").focus();
return false;
}
date = $("input#date").val();
if (date == "") {
$("#date_error").show();
$("input#date").focus();
return false;
}
credit = $("input#credit").val();
invoiceID = $("input#InvoiceID").val();
by = $("input#by").val();
dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
$.ajax({
type: "POST",
url: "functions/invoicing_payments_make.php",
data: dataString,
success: function(result) {
if(result == 1){
$('#payment_window_message_success').fadeIn(300);
$('#payment_window_message_success').delay(5000).fadeOut(700);
return false;
} else {
$('#payment_window_message_error_mes').html(result);
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
return false;
}
},
error: function() {
$('#payment_window_message_error_mes').html("An error occured, form was not submitted");
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
}
});
return false;
});
});
```
Here is the html form:
```
<div id="makepayment_form">
<form name="payment" id="payment" class="halfboxform">
<input type="hidden" name="InvoiceID" id="InvoiceID" />
<input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
<fieldset>
<label for="amount" class="label">Amount:</label>
<input type="text" id="amount" name="amount" value="0.00" />
<p class="form_error clearb red input" id="amount_error">This field is required.</p>
<label for="credit" class="label">Credit:</label>
<input type="text" id="credit" name="credit" />
<label for="amount" class="label">Date:</label>
<input type="text" id="date" name="date" />
<p class="form_error clearb red input" id="date_error">This field is required.</p>
</fieldset>
<input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
</form>
</div>
```
Hope someone can help as its driving me crazy. Thanks. | 2013/04/04 | [
"https://Stackoverflow.com/questions/15823756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513473/"
] | Some times you have to not only prevent the default behauviour for handling the event, but also to prevent executing any downstream chain of event handlers.
This can be done by calling [`event.stopImmediatePropagation()`](https://api.jquery.com/event.stopimmediatepropagation/) in addition to [`event.preventDefault()`](https://api.jquery.com/event.preventDefault/).
Example code:
```
$("#addpayment_submit").on('submit', function(event) {
event.preventDefault();
event.stopImmediatePropagation();
});
``` | As you are using AJAX request to send data to the server there's no reason even to use `form` tag and `<input type="submit" .../>` (you can use simple button instead). Also I think Cumbo's answer should work. If it doesn't you can also try `event.stopPropagation()`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.