qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
510,152 | Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.
Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?
If so, what is the best way to run a "distant" script? Is it
```
. /path/to/script
```
or
```
sh /path/to/script
```
and how to use `sudo` in such cases? This, for example, doesn't work:
```
sudo . /path/to/script
``` | 2012/11/24 | [
"https://superuser.com/questions/510152",
"https://superuser.com",
"https://superuser.com/users/105968/"
] | Say you want to run `./script` and the path is `/home/test/stuff/`
But the path you're currently in is `/home/test/public_html/a/`
Then you would need to do `../../stuff/./script`
Which goes back 2 folders, then into into the folder there and run the script. | I'm not sure it works like this in linux, assuming it doesn't if no-ones suggested it. But instead of using ././ to go back directories. Can you use quotes to give it an absolute path? Maybe it doesn't give you access to the whole drive to even be able to do that actually come to think of it. |
510,152 | Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.
Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?
If so, what is the best way to run a "distant" script? Is it
```
. /path/to/script
```
or
```
sh /path/to/script
```
and how to use `sudo` in such cases? This, for example, doesn't work:
```
sudo . /path/to/script
``` | 2012/11/24 | [
"https://superuser.com/questions/510152",
"https://superuser.com",
"https://superuser.com/users/105968/"
] | I usually do like you say
```
sh /path/to/script
```
And to run it as root/superuser
```
sudo sh /path/to/script
```
Your current directory only matters if the scripts assumes you are in the same folder as it. I would assume most scripts don't do this and you are save to run it like above. | I usually keep my scripts in `/usr/local/bin` or `/usr/local/sbin/` (if the script needs root privileges) where, according to the Filesystem Hierarchy Standard (FHS), they belong.
All you have to do is to make sure these two directories are added to your `PATH`. You can do this by editing your `$HOME/.bashrc` file and adding this line:
```
export PATH=$PATH:/usr/local/sbin:/usr/local/bin
```
If you want to be able to execute a script as root via `sudo`, you have to add these directories to the variable `secure_path` in your `/etc/sudoers`.
```
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
```
Editing this file is done by running `visudo` which ensures you don't have any mistakes. |
510,152 | Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.
Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?
If so, what is the best way to run a "distant" script? Is it
```
. /path/to/script
```
or
```
sh /path/to/script
```
and how to use `sudo` in such cases? This, for example, doesn't work:
```
sudo . /path/to/script
``` | 2012/11/24 | [
"https://superuser.com/questions/510152",
"https://superuser.com",
"https://superuser.com/users/105968/"
] | sh /path/to/script will spawn a new shell and run she script independent of your current shell. The `source` (.) command will call all the commands in the script in the current shell. If the script happens to call `exit` for example, then you'll lose the current shell. Because of this it is usually safer to call scripts in a separate shell with sh or to execute them as binaries using either the full (starting with `/`) or relative path (`./`). If called as binaries, they will be executed with the specified interpreter (`#!/bin/bash`, for example).
As for knowing whether or not a script will find the files it needs, there is no good answer, other than looking at the script to see what it does. As an option, you could always go to the script's folder in a sub-process without leaving your current folder:
```
(cd /wherever/ ; sh script.sh)
``` | I usually keep my scripts in `/usr/local/bin` or `/usr/local/sbin/` (if the script needs root privileges) where, according to the Filesystem Hierarchy Standard (FHS), they belong.
All you have to do is to make sure these two directories are added to your `PATH`. You can do this by editing your `$HOME/.bashrc` file and adding this line:
```
export PATH=$PATH:/usr/local/sbin:/usr/local/bin
```
If you want to be able to execute a script as root via `sudo`, you have to add these directories to the variable `secure_path` in your `/etc/sudoers`.
```
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
```
Editing this file is done by running `visudo` which ensures you don't have any mistakes. |
510,152 | Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.
Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?
If so, what is the best way to run a "distant" script? Is it
```
. /path/to/script
```
or
```
sh /path/to/script
```
and how to use `sudo` in such cases? This, for example, doesn't work:
```
sudo . /path/to/script
``` | 2012/11/24 | [
"https://superuser.com/questions/510152",
"https://superuser.com",
"https://superuser.com/users/105968/"
] | I usually keep my scripts in `/usr/local/bin` or `/usr/local/sbin/` (if the script needs root privileges) where, according to the Filesystem Hierarchy Standard (FHS), they belong.
All you have to do is to make sure these two directories are added to your `PATH`. You can do this by editing your `$HOME/.bashrc` file and adding this line:
```
export PATH=$PATH:/usr/local/sbin:/usr/local/bin
```
If you want to be able to execute a script as root via `sudo`, you have to add these directories to the variable `secure_path` in your `/etc/sudoers`.
```
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
```
Editing this file is done by running `visudo` which ensures you don't have any mistakes. | I'm not sure it works like this in linux, assuming it doesn't if no-ones suggested it. But instead of using ././ to go back directories. Can you use quotes to give it an absolute path? Maybe it doesn't give you access to the whole drive to even be able to do that actually come to think of it. |
510,152 | Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.
Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?
If so, what is the best way to run a "distant" script? Is it
```
. /path/to/script
```
or
```
sh /path/to/script
```
and how to use `sudo` in such cases? This, for example, doesn't work:
```
sudo . /path/to/script
``` | 2012/11/24 | [
"https://superuser.com/questions/510152",
"https://superuser.com",
"https://superuser.com/users/105968/"
] | sh /path/to/script will spawn a new shell and run she script independent of your current shell. The `source` (.) command will call all the commands in the script in the current shell. If the script happens to call `exit` for example, then you'll lose the current shell. Because of this it is usually safer to call scripts in a separate shell with sh or to execute them as binaries using either the full (starting with `/`) or relative path (`./`). If called as binaries, they will be executed with the specified interpreter (`#!/bin/bash`, for example).
As for knowing whether or not a script will find the files it needs, there is no good answer, other than looking at the script to see what it does. As an option, you could always go to the script's folder in a sub-process without leaving your current folder:
```
(cd /wherever/ ; sh script.sh)
``` | I usually do like you say
```
sh /path/to/script
```
And to run it as root/superuser
```
sudo sh /path/to/script
```
Your current directory only matters if the scripts assumes you are in the same folder as it. I would assume most scripts don't do this and you are save to run it like above. |
75,214 | I copied 3.62 GB of data on to a re-writable DVD instead of erasing it. Now there is no data on the disc but it shows used space as 3.62 GB and 690 MB of free space. Now I am unable to erase my disc. What should I do to erase the disc and get the space back? | 2009/11/25 | [
"https://superuser.com/questions/75214",
"https://superuser.com",
"https://superuser.com/users/96938/"
] | You aren't supposed to format a DVD-RW. Use something like [CDBurnerXP](http://cdburnerxp.se/)'s erase function:
 | As stated elsewhere, you need to erase the DVD-RW before using it again. I have a very simple low profile program I use called Active@DVD Eraser located here:<http://www.ntfs.com/dvd_eraser.htm> |
75,214 | I copied 3.62 GB of data on to a re-writable DVD instead of erasing it. Now there is no data on the disc but it shows used space as 3.62 GB and 690 MB of free space. Now I am unable to erase my disc. What should I do to erase the disc and get the space back? | 2009/11/25 | [
"https://superuser.com/questions/75214",
"https://superuser.com",
"https://superuser.com/users/96938/"
] | Another free alternative:
[ImgBurn](http://www.imgburn.com/)
 | As stated elsewhere, you need to erase the DVD-RW before using it again. I have a very simple low profile program I use called Active@DVD Eraser located here:<http://www.ntfs.com/dvd_eraser.htm> |
75,214 | I copied 3.62 GB of data on to a re-writable DVD instead of erasing it. Now there is no data on the disc but it shows used space as 3.62 GB and 690 MB of free space. Now I am unable to erase my disc. What should I do to erase the disc and get the space back? | 2009/11/25 | [
"https://superuser.com/questions/75214",
"https://superuser.com",
"https://superuser.com/users/96938/"
] | if you don't want to install additional software, use **[InfraRecorder](http://infrarecorder.org/)** Portable.
Go to **Actions** > **Erase/Format Disc...** | As stated elsewhere, you need to erase the DVD-RW before using it again. I have a very simple low profile program I use called Active@DVD Eraser located here:<http://www.ntfs.com/dvd_eraser.htm> |
150,258 | Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense.
The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure.
Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked. | 2014/06/20 | [
"https://wordpress.stackexchange.com/questions/150258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15209/"
] | By default, no, WordPress doesn't keep track of who changes post statuses (at least that I can see).
you can hook into `transition_post_status` and log the user id.
```
add_action( 'transition_post_status', 'wwm_transition_post_status', 10, 3 );
function wwm_transition_post_status( $new_status, $old_status, $post ) {
if ( 'trash' == $new_status ) {
$uid = get_current_user_id();
//somehow or another log the $uid with the $post->ID
}
}
``` | No, natively WordPress does not log any activity. While plugins for it exist, they won't work retroactively.
However don't forget that any action taken in WordPress is technically a HTTP request, such as page load, form submit, or Ajax request.
These are often logged pretty thoroughly in web server's access log and if available it's pretty realistic to reconstruct action that happened and details like user's IP from them. |
150,258 | Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense.
The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure.
Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked. | 2014/06/20 | [
"https://wordpress.stackexchange.com/questions/150258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15209/"
] | By default, no, WordPress doesn't keep track of who changes post statuses (at least that I can see).
you can hook into `transition_post_status` and log the user id.
```
add_action( 'transition_post_status', 'wwm_transition_post_status', 10, 3 );
function wwm_transition_post_status( $new_status, $old_status, $post ) {
if ( 'trash' == $new_status ) {
$uid = get_current_user_id();
//somehow or another log the $uid with the $post->ID
}
}
``` | WP can not do it, but you can go to the server logs and find the user's IP. It may take some effort and success is not guaranteed but this is the only possible way. Will's answer will help you in future mistakes.
Finding a user based on their IP is not usually hard especially if the number of authors is limited. |
150,258 | Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense.
The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure.
Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked. | 2014/06/20 | [
"https://wordpress.stackexchange.com/questions/150258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15209/"
] | By default, no, WordPress doesn't keep track of who changes post statuses (at least that I can see).
you can hook into `transition_post_status` and log the user id.
```
add_action( 'transition_post_status', 'wwm_transition_post_status', 10, 3 );
function wwm_transition_post_status( $new_status, $old_status, $post ) {
if ( 'trash' == $new_status ) {
$uid = get_current_user_id();
//somehow or another log the $uid with the $post->ID
}
}
``` | There is a free plugin called *Stream* that will make your life much easier. Search within the WordPress plugins page. It logs all changes to posts and who is responsible for them. |
150,258 | Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense.
The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure.
Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked. | 2014/06/20 | [
"https://wordpress.stackexchange.com/questions/150258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15209/"
] | No, natively WordPress does not log any activity. While plugins for it exist, they won't work retroactively.
However don't forget that any action taken in WordPress is technically a HTTP request, such as page load, form submit, or Ajax request.
These are often logged pretty thoroughly in web server's access log and if available it's pretty realistic to reconstruct action that happened and details like user's IP from them. | There is a free plugin called *Stream* that will make your life much easier. Search within the WordPress plugins page. It logs all changes to posts and who is responsible for them. |
150,258 | Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense.
The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure.
Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked. | 2014/06/20 | [
"https://wordpress.stackexchange.com/questions/150258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15209/"
] | WP can not do it, but you can go to the server logs and find the user's IP. It may take some effort and success is not guaranteed but this is the only possible way. Will's answer will help you in future mistakes.
Finding a user based on their IP is not usually hard especially if the number of authors is limited. | There is a free plugin called *Stream* that will make your life much easier. Search within the WordPress plugins page. It logs all changes to posts and who is responsible for them. |
28,958,290 | We have recently switched over to React + Flux from Angular to build a rather complex business application.
Taking the approach of having one container component that passes all state as properties down the component tree isn't a practical way to develop the app for us as the app makes use of large page-like modals. Enough state does get passed down to the modals for them to load their data into their stores.
The problem I have is I need to get some initial state (passed down as props) into the modal component's store. In [this post](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) the good guys over at Facebook say it's ok to use props for initial state when synchronization is not the goal.
This is how I get the initial state into my store currently:
```
var ABC = React.createClass({
...
getInitialState: function() {
return ABCStore.getInitialABCState(this.props.initialA);
},
...
var ABCStore = Reflux.createStore({
...
init: function() {
_state = {
a: null,
b: 'B init',
c: 'C init'
};
},
getInitialABCState: function(initialA) {
_state.a = initialA;
return _state;
},
getABCState: function() {
return _state;
}
...
```
I am unsure what the best practice is to do this, or whether this is a Flux anti-pattern? | 2015/03/10 | [
"https://Stackoverflow.com/questions/28958290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525096/"
] | It feels wrong to me that you are using `getInitialState()` to change the state of your store. You should at least be doing that in [`componentWillMount`](http://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount).
I would trigger an action in `componentWillMount` and have the store handler update the internal state of the store (this should always be the case in flux). Then your component's change handler for the store can consume whatever data that you are currently calling your "initial state" | [`Reflux.listenTo`](https://github.com/spoike/refluxjs/#sending-initial-state-with-the-listento-function) does this when you provide a third argument and `Reflux.connect` mixin factory (that uses `Reflux.listenTo` under the hood) handles this for you automatically. Here is an example:
```
var Actions = Reflux.createActions({"doIt"});
var Store = Reflux.createStore({
listenables: [Actions],
init: function() {
this.state = "I like to";
},
onDoIt: function() {
this.state = "Do it";
this.trigger(this.state);
},
getInitialState: function() {
return this.state;
}
});
var DoItButton = React.createClass({
mixins: [Reflux.connect(Store, "label")],
onClick: function() {
Actions.doIt();
},
render: function() {
return (<div onClick={this.onClick}>{this.state.label}</div>);
}
});
``` |
28,958,290 | We have recently switched over to React + Flux from Angular to build a rather complex business application.
Taking the approach of having one container component that passes all state as properties down the component tree isn't a practical way to develop the app for us as the app makes use of large page-like modals. Enough state does get passed down to the modals for them to load their data into their stores.
The problem I have is I need to get some initial state (passed down as props) into the modal component's store. In [this post](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) the good guys over at Facebook say it's ok to use props for initial state when synchronization is not the goal.
This is how I get the initial state into my store currently:
```
var ABC = React.createClass({
...
getInitialState: function() {
return ABCStore.getInitialABCState(this.props.initialA);
},
...
var ABCStore = Reflux.createStore({
...
init: function() {
_state = {
a: null,
b: 'B init',
c: 'C init'
};
},
getInitialABCState: function(initialA) {
_state.a = initialA;
return _state;
},
getABCState: function() {
return _state;
}
...
```
I am unsure what the best practice is to do this, or whether this is a Flux anti-pattern? | 2015/03/10 | [
"https://Stackoverflow.com/questions/28958290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525096/"
] | It feels wrong to me that you are using `getInitialState()` to change the state of your store. You should at least be doing that in [`componentWillMount`](http://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount).
I would trigger an action in `componentWillMount` and have the store handler update the internal state of the store (this should always be the case in flux). Then your component's change handler for the store can consume whatever data that you are currently calling your "initial state" | Like other posters have said, the best thing to do is to trigger an action in `componentWillMount`. In ES6, this is usually done with a `constructor`.
Below is an example on how to do this with ES6:
(note that `AuthorActions.initAuthors()` is dependent on implementation, this is just an example. This could get initial state from database. Most importantly though, this action should dispatch the payload with the initial state to the dispatcher)
```
var _authors = [];
var AuthorStoreInstance;
class AuthorStore extends EventEmitter {
constructor(props) {
super(props);
}
init() {
AuthorActions.initAuthors();
this.emitChange();
}
addChangeListener(cb) {
this.on(CHANGE_EVENT, cb);
}
removeChangeListener(cb) {
this.removeListener(CHANGE_EVENT, cb);
}
emitChange() {
this.emit(CHANGE_EVENT);
}
getAllAuthors() {
return _authors;
}
addAuthor(author) {
_authors.push(author);
this.emitChange();
}
setAuthors(authors) {
_authors = authors;
}
};
AuthorStoreInstance = new AuthorStore();
Dispatcher.register((action) => {
switch(action.actionType) {
case ActionTypes.CREATE_AUTHOR:
AuthorStoreInstance.addAuthor(action.author);
break;
case ActionTypes.INITIALIZE:
AuthorStoreInstance.setAuthors(action.initialData.authors);
break;
default:
//do nothing
}
});
AuthorStoreInstance.init();
export default AuthorStoreInstance;
```
Notice how the init function is not a part of the constructor. This is because when the authorStore is constructed, the callback for the `AuthorActions.initAuthors` has not been registered with the dispatcher.
Initialization should happen after callbacks have been registered with the dispatcher.
edit: For clarity, `initAuthors` could look something like this:
```
initAuthors() {
var authors = AuthorAPI.getAllAuthors();
Dispatcher.dispatch({
actionType: ActionTypes.INITIALIZE,
initialData: {
authors: authors
}
});
}
``` |
28,958,290 | We have recently switched over to React + Flux from Angular to build a rather complex business application.
Taking the approach of having one container component that passes all state as properties down the component tree isn't a practical way to develop the app for us as the app makes use of large page-like modals. Enough state does get passed down to the modals for them to load their data into their stores.
The problem I have is I need to get some initial state (passed down as props) into the modal component's store. In [this post](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) the good guys over at Facebook say it's ok to use props for initial state when synchronization is not the goal.
This is how I get the initial state into my store currently:
```
var ABC = React.createClass({
...
getInitialState: function() {
return ABCStore.getInitialABCState(this.props.initialA);
},
...
var ABCStore = Reflux.createStore({
...
init: function() {
_state = {
a: null,
b: 'B init',
c: 'C init'
};
},
getInitialABCState: function(initialA) {
_state.a = initialA;
return _state;
},
getABCState: function() {
return _state;
}
...
```
I am unsure what the best practice is to do this, or whether this is a Flux anti-pattern? | 2015/03/10 | [
"https://Stackoverflow.com/questions/28958290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525096/"
] | [`Reflux.listenTo`](https://github.com/spoike/refluxjs/#sending-initial-state-with-the-listento-function) does this when you provide a third argument and `Reflux.connect` mixin factory (that uses `Reflux.listenTo` under the hood) handles this for you automatically. Here is an example:
```
var Actions = Reflux.createActions({"doIt"});
var Store = Reflux.createStore({
listenables: [Actions],
init: function() {
this.state = "I like to";
},
onDoIt: function() {
this.state = "Do it";
this.trigger(this.state);
},
getInitialState: function() {
return this.state;
}
});
var DoItButton = React.createClass({
mixins: [Reflux.connect(Store, "label")],
onClick: function() {
Actions.doIt();
},
render: function() {
return (<div onClick={this.onClick}>{this.state.label}</div>);
}
});
``` | Like other posters have said, the best thing to do is to trigger an action in `componentWillMount`. In ES6, this is usually done with a `constructor`.
Below is an example on how to do this with ES6:
(note that `AuthorActions.initAuthors()` is dependent on implementation, this is just an example. This could get initial state from database. Most importantly though, this action should dispatch the payload with the initial state to the dispatcher)
```
var _authors = [];
var AuthorStoreInstance;
class AuthorStore extends EventEmitter {
constructor(props) {
super(props);
}
init() {
AuthorActions.initAuthors();
this.emitChange();
}
addChangeListener(cb) {
this.on(CHANGE_EVENT, cb);
}
removeChangeListener(cb) {
this.removeListener(CHANGE_EVENT, cb);
}
emitChange() {
this.emit(CHANGE_EVENT);
}
getAllAuthors() {
return _authors;
}
addAuthor(author) {
_authors.push(author);
this.emitChange();
}
setAuthors(authors) {
_authors = authors;
}
};
AuthorStoreInstance = new AuthorStore();
Dispatcher.register((action) => {
switch(action.actionType) {
case ActionTypes.CREATE_AUTHOR:
AuthorStoreInstance.addAuthor(action.author);
break;
case ActionTypes.INITIALIZE:
AuthorStoreInstance.setAuthors(action.initialData.authors);
break;
default:
//do nothing
}
});
AuthorStoreInstance.init();
export default AuthorStoreInstance;
```
Notice how the init function is not a part of the constructor. This is because when the authorStore is constructed, the callback for the `AuthorActions.initAuthors` has not been registered with the dispatcher.
Initialization should happen after callbacks have been registered with the dispatcher.
edit: For clarity, `initAuthors` could look something like this:
```
initAuthors() {
var authors = AuthorAPI.getAllAuthors();
Dispatcher.dispatch({
actionType: ActionTypes.INITIALIZE,
initialData: {
authors: authors
}
});
}
``` |
35,281,379 | I have ElasticSearch 2.2 running on a linux VM. I'm running ManifoldCF 2.3 on another VM in the same netowrk. Using ManifoldCF's browser UI I added the ElasticSearch output connector and when I save it I get an error in the connector status:
```
Name: Elastic
Description: Elastic search
Connection type: ElasticSearch
Max connections: 10
Server Location (URL): http://<IP_ADDRESS>:9200
Index name: index
Index type: sharepoint
Use mapper-attachments: false
Content field name: contentfield
Connection status: ERROR "root_cause":["type":"illegal_argument_exception"
```
Any ideas? | 2016/02/08 | [
"https://Stackoverflow.com/questions/35281379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151200/"
] | You are passing an `array` of strings to jQuery's `append` method. Simply join it first:
```
jQuery('.place').append(top.join(''));
```
When you call `toString()` on an array (which is what jQuery is doing here when you try to `append` an array of strings) it casts each array element to a string and puts a comma between them:
```
[1,2,3].toString(); //"1,2,3"
[{a:"b"},2,3].toString(); //"[object Object],2,3"
``` | First of all it looks there's a problem using `top` as variable name, so I changed it to top1.
THEORY:
According to <http://api.jquery.com/append/> you can pass an array of DOM elements, or String(s) (or other things, but they're not related to the question). You seem to pass an array of strings, that is not an array of DOM elements, so it's being stringified, and the stringification of an array has commas between the elements. I'm pretty sure you also have a "[" before them and a "]" after them.
PRACTICE: Well, I don't seem to reproduce your problem (at least in Chrome, FF, Safari):
```js
var top1 = [];
for (var i = 0; i < 2; i++) {
var file = "<div>something[i]</div>";
top1.push(file);
}
$('#place').append(top1);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="place">
</div>
``` |
25,288 | We have made a installation of Sitecore Experience Platform v9.3.0 (rev. 003498) (details below):
* 2 servers as Content Management role
* 2 servers as Content Delivery role
* 2 servers as others roles (Processing, Reporting, Identity Server, XConnect, Identity Server, Marketing, Reference Data, Cortex)
* 3 servers as Solr
The application has been running for approximately 45 days, however, Experience Analytics and Experience Profile are not recording data (no data is displayed). we have checked the logs of all roles and found no errors that could help us fix the issue.
After some research we have changed the **"IndexAnonymousContactData"** tag to **true** in the **"{XCONNECT\_PATH}\App\_Data\jobs\continuous\IndexWorker\App\_Data\config\sitecore\SearchIndexer\sc.Xdb.Collection.IndexerSettings"** configuration file and rebuilt the indexes. However, it did not work.
Would anyone have any suggestions on what we could do to fix this issue?
Thank you in advance for your help | 2020/05/18 | [
"https://sitecore.stackexchange.com/questions/25288",
"https://sitecore.stackexchange.com",
"https://sitecore.stackexchange.com/users/6980/"
] | It turns out to be that the device detection rule config in sitecore 9.3 doesn't include Content Management Role by default so by patching this role solves the problem.
```
<?xml version="1.0" encoding="utf-8" ?>
<!--
Purpose: This include file configures the device detection rules component.
-->
<configuration xmlns:x="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
**<sitecore role:require="Standalone or ContentDelivery or Processing">**
<services>
<register
serviceType="Sitecore.CES.DeviceDetection.Rules.IRuleDeviceInformationManager, Sitecore.CES.DeviceDetection.Rules"
implementationType="Sitecore.CES.DeviceDetection.Rules.RuleDeviceInformationManager, Sitecore.CES.DeviceDetection.Rules"
lifetime="Singleton" />
</services>
</sitecore>
</configuration>
``` | It looks like you have a Sitecore rule for detecting device, some thing similar to what you can see in the following screenshot:
[](https://i.stack.imgur.com/50PtT.png)
Following what you can find when checking Sitecore documentation for device detection:
>
> From Sitecore 9.0 and later, Sitecore Device Detection is enabled to
> use Sitecore services and the database provided by 51Degrees by
> default
>
>
>
There are some configuration you can double check that you have them right in addition to verify that you server can access and download the database, following where you can find the details information:
1. <https://doc.sitecore.com/developers/93/sitecore-experience-manager/en/configure-sitecore-device-detection.html>
2. <https://labs.tadigital.com/index.php/2018/11/05/device-detection-in-sitecore/> |
33,307,860 | I have a list of years, as follows:
```
year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']
```
I am trying to create a series of XML tags enclosed within another pre-existing tag, like so:
```
<intro>
<exposures>
<exposure year = "2005"></exposure>
<exposure year = "2006"></exposure>
<exposure year = "2007"></exposure>
<exposure year = "2008"></exposure>
etc.
<exposures>
</intro>
```
Later on I'll populate things within the tags. Right now I'm trying to loop through `year` and add them to the tag and then enclose it within the tag.
I've been trying to loop through the 'year' list and append each value to the tag as an attribute:
```
testsoup = BeautifulSoup(testxml, 'xml')
intro_tag = testsoup.intro('intro')
exp_tag = testsoup.exposures('exposures')
year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']
exposure_tag = testsoup.new_tag('exposure', year = '')
for x in year:
exposure_tag['year'] = x
exp_tag.append(exposure_tag)
intro_tag.append(exp_tag)
```
Unfortunately this only seems to append the last value in the list:
```
<intro><exposures><exposure year="2013"/></exposures></intro>
```
Is this just a feature of BeautifulSoup? Can you only add one tag and not multiple ones? I'm using BeautifulSoup 4.4.0.
Incidentally, is BeautifulSoup the best way to do this? I see a lot of posts praising BS4 and lxml for their webscraping abilities but neither seem to be useful for generating XML (that's not a bad thing, just something I've noticed). Is there a better package for automating XML generation? | 2015/10/23 | [
"https://Stackoverflow.com/questions/33307860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5199451/"
] | I suspect that the issue is this line: `exposure_tag = testsoup.new_tag('exposure', year = '')`. You have one tag and you are trying to append it to the same parent multiple times. Try this instead.
```
for x in year:
exposure_tag = testsoup.new_tag('exposure', year = x)
exp_tag.append(exposure_tag)
intro_tag.append(exp_tag)
``` | I have not looked into BS source code, but think the behaviour is this: when you calling `exp_tag.append(smth)` you actually add pointer to `smth` object. So as you instantiate `exposure_tag` only once, you got bunch of pointers to the same object. When you modify that object in `exposure_tag['year'] = x`, it affects all elements of internal list structure of BS.
So, the solution is to create new object instance in every step:
```
testsoup = BeautifulSoup(testxml, 'xml')
intro_tag = testsoup.intro('intro')
exp_tag = testsoup.exposures('exposures')
year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']
for x in year:
exposure_tag = testsoup.new_tag('exposure', year = x)
exp_tag.append(exposure_tag)
intro_tag.append(exp_tag) # BTW: Are you sure you need this here?
``` |
21,239 | I'm setting up a projection map for a non-profit that will have images projected onto angular and unusually shaped walls. I use modul8 on my mac in the past, but this case is different. They use PC (in fact their whole show runs off of a laptop) and they want the ability to change the images based on the theme of the show. They have an A/V guy, but I don't want to suggest complex software that is going to be hard for a beginner to use. What software should I recommend and then use to set up their show so they don't have to keep calling little old expensive me?
EDIT: I should also mention that this is a small non-profit, so free or really cheap would benefit them greatly. | 2017/04/20 | [
"https://avp.stackexchange.com/questions/21239",
"https://avp.stackexchange.com",
"https://avp.stackexchange.com/users/18709/"
] | It is certainly possible to use FCPX and AfterEffects as part of the same workflow. To do this effectively, you will need to use an intermediate codec that preserves image quality across successive generations. ProRes HQ 422 is a good baseline as an intermediate codec. There are higher quality ProRes codecs (XQ 4444) and lower quality ones (ProRes LT 422). But ProRes HQ should be a good starting place. | While Adobe and Apple each link their editing software with their own respective compositing software, saying 'AE is to Premiere as Motion is to FCPX' glosses over the strengths and differences of each package.
Sure, AE is a powerful compositing app, and it's dynamic link to Premiere is convenient, but Adobe is still playing catch up to Apple when it comes to application interoperability.
Say, for instance, you'd like to make a transition between two clips, and you'd like this transition to be a stylistic element of your production which you can re-use as often as you like. This is something at which Motion excels and at which AE struggles.
After Effects is more powerful when it comes to a lot of VFX work, and its scriptability is a powerful feature which is unmatched in Motion. However, I would argue that the "bond" between FCPX and Motion is stronger than the one between Premiere and AE. But when you're talking about using FCPX with AE, there is NO link and you have to render bi-directionally. |
74,240,319 | I am trying to set my machines javac version to 11 from 18.0.2 and I'm doing the following steps
1. open ~/.zshenv
2. export JAVA\_HOME=$(/usr/libexec/java\_home -v11)
3. source ~/.zshenv
When I check the version, I still get it as 18.0.2. Not sure what I am doing wrong here.
Could someone please help me with this? Been stuck on this forever. | 2022/10/28 | [
"https://Stackoverflow.com/questions/74240319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6466023/"
] | What works like a charme for me is using jenv: <https://www.jenv.be/>
With jenv you can also switch between different Java versions.
Before using jenv, I relied on the Maven toolchains plugin: <https://maven.apache.org/plugins/maven-toolchains-plugin/>
Thus, I actually never really worried about `JAVA_HOME` on MacOS. Maybe one of these options also is an alternative for you. | ```
export JAVA_HOME=`/usr/libexec/java_home -v 11`
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | The easiest way is to avoid `length`:
```
myButLast (x : _ : []) = x -- base case
myButLast (_ : xs) = myButLast xs
```
The definitive reference on patterns in Haskell is the language report: <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17>
GHC implements a few extensions described at <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html#pattern-guards>. | Exploiting `zip`:
```
\l -> fst . last $ zip l (tail l)
```
Also available in a pointless, obfuscated style:
```
fst . last . (zip <*> tail)
```
or even without parentheses (thanks to @melpomene):
```
fst . last . ap zip tail
```
Other variants:
```
last . ap (zipWith const) tail
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | what about
```
myButLast [] = error "oho"
myButLast [x,_] = x
myButLast (_:xs) = myButLast xs
``` | Another solution:
```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | what about
```
myButLast [] = error "oho"
myButLast [x,_] = x
myButLast (_:xs) = myButLast xs
``` | Another zip-based solution, without exlicitly zipping. Throw in some safety for good measure.
```
import Data.Maybe
g :: Int -> [a] -> Maybe a
g i = (head <$>) . listToMaybe . reverse -- quick'n'dirty safe-last
. getZipList . traverse ZipList
. sequence [id, drop i]
g 1 [1..10] => Just 9
g 3 [1..10] => Just 7
g 13 [1..10] => Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | The easiest way is to avoid `length`:
```
myButLast (x : _ : []) = x -- base case
myButLast (_ : xs) = myButLast xs
```
The definitive reference on patterns in Haskell is the language report: <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17>
GHC implements a few extensions described at <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html#pattern-guards>. | Here is my solution using the tail function from prelude
```
myButLast :: [Int] -> Maybe Int
myButLast (x:xs) | ((null xs) || null (tail xs)) = Just x
| otherwise = myButLast(xs)
myButLast [] = Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | The easiest way is to avoid `length`:
```
myButLast (x : _ : []) = x -- base case
myButLast (_ : xs) = myButLast xs
```
The definitive reference on patterns in Haskell is the language report: <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17>
GHC implements a few extensions described at <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html#pattern-guards>. | Another zip-based solution, without exlicitly zipping. Throw in some safety for good measure.
```
import Data.Maybe
g :: Int -> [a] -> Maybe a
g i = (head <$>) . listToMaybe . reverse -- quick'n'dirty safe-last
. getZipList . traverse ZipList
. sequence [id, drop i]
g 1 [1..10] => Just 9
g 3 [1..10] => Just 7
g 13 [1..10] => Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | Another solution:
```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs
``` | Here is my solution using the tail function from prelude
```
myButLast :: [Int] -> Maybe Int
myButLast (x:xs) | ((null xs) || null (tail xs)) = Just x
| otherwise = myButLast(xs)
myButLast [] = Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | The easiest way is to avoid `length`:
```
myButLast (x : _ : []) = x -- base case
myButLast (_ : xs) = myButLast xs
```
The definitive reference on patterns in Haskell is the language report: <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17>
GHC implements a few extensions described at <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html#pattern-guards>. | Another solution:
```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | Another solution:
```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs
``` | Another zip-based solution, without exlicitly zipping. Throw in some safety for good measure.
```
import Data.Maybe
g :: Int -> [a] -> Maybe a
g i = (head <$>) . listToMaybe . reverse -- quick'n'dirty safe-last
. getZipList . traverse ZipList
. sequence [id, drop i]
g 1 [1..10] => Just 9
g 3 [1..10] => Just 7
g 13 [1..10] => Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | Exploiting `zip`:
```
\l -> fst . last $ zip l (tail l)
```
Also available in a pointless, obfuscated style:
```
fst . last . (zip <*> tail)
```
or even without parentheses (thanks to @melpomene):
```
fst . last . ap zip tail
```
Other variants:
```
last . ap (zipWith const) tail
``` | Another zip-based solution, without exlicitly zipping. Throw in some safety for good measure.
```
import Data.Maybe
g :: Int -> [a] -> Maybe a
g i = (head <$>) . listToMaybe . reverse -- quick'n'dirty safe-last
. getZipList . traverse ZipList
. sequence [id, drop i]
g 1 [1..10] => Just 9
g 3 [1..10] => Just 7
g 13 [1..10] => Nothing
``` |
33,068,428 | Consider the following function for finding the second-to-last element of a list:
```
myButLast (x:xs) = if length xs > 1 then myButLast xs else x
```
This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)? | 2015/10/11 | [
"https://Stackoverflow.com/questions/33068428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | Exploiting `zip`:
```
\l -> fst . last $ zip l (tail l)
```
Also available in a pointless, obfuscated style:
```
fst . last . (zip <*> tail)
```
or even without parentheses (thanks to @melpomene):
```
fst . last . ap zip tail
```
Other variants:
```
last . ap (zipWith const) tail
``` | Another solution:
```
myButLast [] = error "List is empty"
myButLast [x] = error "List is a singleton"
myButLast xs = last $ init xs
``` |
7,756,437 | Is that possible to get notification when Home button is pressed or Home Screen is launched?
In [Android Overriding home key](https://stackoverflow.com/questions/5039500/android-overriding-home-key) thread i read that "it will be notified when the home screen is about to be launched". So is that possible, if yes how?
Thank you | 2011/10/13 | [
"https://Stackoverflow.com/questions/7756437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992888/"
] | >
> Is that possible to get notification when Home button is pressed or Home Screen is launched?
>
>
>
Only by being a home screen. | You can simply add this on your activity:
```
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
// Do something
}
return super.onKeyDown(keyCode, event);
}
``` |
7,756,437 | Is that possible to get notification when Home button is pressed or Home Screen is launched?
In [Android Overriding home key](https://stackoverflow.com/questions/5039500/android-overriding-home-key) thread i read that "it will be notified when the home screen is about to be launched". So is that possible, if yes how?
Thank you | 2011/10/13 | [
"https://Stackoverflow.com/questions/7756437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992888/"
] | >
> Is that possible to get notification when Home button is pressed or Home Screen is launched?
>
>
>
Only by being a home screen. | You can `Detect Home Screen is running or not`.
You can see [this page](http://andytsui.wordpress.com/2012/08/02/detect-home-screen-is-running-or-not-android/) for more details,Or you can see [this answer](https://stackoverflow.com/a/6562223/1043882).It propose use `isScreenOn ()` from `PowerManager`(Returns whether the screen is currently on. The screen could be bright or dim):
```
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
``` |
2,347,497 | >
> Let $R$ be a ring. If $I\_1,\ldots, I\_k$ are ideals of $R$ and for all $i$:
>
>
> $$I\_i + \bigcap\_{j\neq i} I\_j = R$$
>
>
> then for all $a\_1,\ldots,a\_k \in R$, there exists some $a \in R$ such that for all $i$, $a \equiv a\_i \pmod{I\_i}$
>
>
>
I could prove this for $k=2$: for $a\_1,a\_2 \in R$, $a\_1 - a\_2 \in I\_1 + I\_2$, so there are $i\_i \in I\_i$ such that $a\_1 - a\_2 = -i\_1 + i\_2$. Hence $a\_1 + i\_1 = a\_2 + i\_2 = a$, and $a \equiv a\_i \pmod{I\_i}$ for $i=1,2$.
I couldn't prove the general case. Any help? | 2017/07/05 | [
"https://math.stackexchange.com/questions/2347497",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/360858/"
] | **Hint for the inductive step:**
Suppose $I\_1,\dots, I\_k,I\_{k+1}$ are ideals in $R$ such that for any $1\le i \le k+1$,
$$I\_i+\bigcap\_{\substack{1\le j \le k+1\\j\ne i}}I\_j=R. $$
Then, *a fortiori*, we have for any $1\le i \le k$,
$$I\_i+\bigcap\_{\substack{1\le j \le k\\j\ne i}}I\_j=R. $$
So, given $a\_1, \dots, a\_k, a\_{k+1}\in R$, there exists some $a\in R$ such that
$$a\equiv a\_i\mod I\_i\quad(1\le i\le k)$$
and $a$ is unique mod. $\displaystyle\bigcap\_{j=1}^k I\_j$.
Can you end the inductive step?
*Some more details*:
Note that if $J=\displaystyle\bigcap\_{j=1}^k I\_j $, we have $J+I\_{k+1}=R$.
So we have to find $A\in R$ such that \begin{cases}A\equiv a& \mkern-12mu\bmod J\\A\equiv a\_{k+1},&\mkern-12mu\bmod I\_{k+1}.\end{cases}
which is possible by the case $k=2$, and the solution is unique modulo $J\cap I\_{k+1} =\displaystyle\bigcap\_{j=1}^{k+1} I\_j$. | **Hint** $ $ It is easy if we view the solutions as "vectors" in the product ring $\, (R/I\_1,\ldots, R/I\_k).\,$ Then every such congruence is solvable iff the natural image of $R$ in the product ring is onto iff the image contains all unit vectors $e\_j$ with $1$ in the $j$'th component and $0$ in all others, since they *span*, e.g. $$(a\_1,a\_2,a\_3) = a\_1(1,0,0)+a\_2(0,1,0)+ a\_3(0,0,1) = a\_1 e\_1 + a\_2 e\_2+ a\_3 e\_3$$
But the hypotheses imply that unit vector systems are solveable, since by hypothes $\,a+b = 1\,$ for $\,a\in I\_j,\ b\in I\_i, \forall\, i\neq j$ so $\,e\_j := 1\!-\!a = b\,$ $\,\Rightarrow\,e\_j\equiv 1\pmod{I\_j},\ $ $e\_j\equiv 0\pmod{I\_i},\forall\,i\ne j$
**Remark** $ $ The classical CRT formula for integers is a special case, where the unit vectors are constructed by the formula
$\qquad e\_j := M\_j(M\_j^{-1} \bmod m\_j)\,$ where $M\_j$ is the product of all moduli except $m\_j$
Note $\,M\_j \equiv 1\pmod{m\_j}\,$ and $\,M\_j\equiv 0\,$ mod other moduli since they divide $\,M\_j$ |
6,637,219 | Let's say I accidentally evaluate an enormous variable--a list with a ba-jillion elements, or whatever. As they scroll down my screen and my computer crawls to a halt, is there a good way to interrupt this *without* killing my `*Python*` buffer? I'm using IPython via `python-mode.el` and `ipython.el` in emacs24 on Mac OS X Leopard--
Thoughts appreciated,
a. | 2011/07/09 | [
"https://Stackoverflow.com/questions/6637219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37772/"
] | Could you not just use the [DisplayAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx "DisplayAttribute")? | Why don't you just use @Html.Label("Business name")? |
6,637,219 | Let's say I accidentally evaluate an enormous variable--a list with a ba-jillion elements, or whatever. As they scroll down my screen and my computer crawls to a halt, is there a good way to interrupt this *without* killing my `*Python*` buffer? I'm using IPython via `python-mode.el` and `ipython.el` in emacs24 on Mac OS X Leopard--
Thoughts appreciated,
a. | 2011/07/09 | [
"https://Stackoverflow.com/questions/6637219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37772/"
] | Could you not just use the [DisplayAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx "DisplayAttribute")? | You need a new metadataprovider which can inherit from the default one like this:
```
using System;
using System.Web.Mvc;
using System.Collections.Generic;
public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (metadata.DisplayName == null)
metadata.DisplayName = GetDisplayNameFromDBName(propertyName);
return metadata;
}
private string GetDisplayNameFromDBName(string propertyName)
{
return ...;
}
}
```
Register it in global.asax like this:
```
ModelMetadataProviders.Current = new MyMetadataProvider();
```
You just need to provide the implementation of GetDisplayNameFromDBName to provide the correct display name given the property name |
6,637,219 | Let's say I accidentally evaluate an enormous variable--a list with a ba-jillion elements, or whatever. As they scroll down my screen and my computer crawls to a halt, is there a good way to interrupt this *without* killing my `*Python*` buffer? I'm using IPython via `python-mode.el` and `ipython.el` in emacs24 on Mac OS X Leopard--
Thoughts appreciated,
a. | 2011/07/09 | [
"https://Stackoverflow.com/questions/6637219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37772/"
] | You need a new metadataprovider which can inherit from the default one like this:
```
using System;
using System.Web.Mvc;
using System.Collections.Generic;
public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (metadata.DisplayName == null)
metadata.DisplayName = GetDisplayNameFromDBName(propertyName);
return metadata;
}
private string GetDisplayNameFromDBName(string propertyName)
{
return ...;
}
}
```
Register it in global.asax like this:
```
ModelMetadataProviders.Current = new MyMetadataProvider();
```
You just need to provide the implementation of GetDisplayNameFromDBName to provide the correct display name given the property name | Why don't you just use @Html.Label("Business name")? |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Tested with latest **Firebase iOS SDK i.e. 4.0.0** and **Xcode 8.3**
Firstly , remove this key `FirebaseAppDelegateProxyEnabled` from info.plist. This is not needed.
Now in **AppDelegate.swift** add following functions
```
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
//At time of production it will be set to .prod
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let firebaseAuth = Auth.auth()
if (firebaseAuth.canHandleNotification(userInfo)){
print(userInfo)
return
}
}*
```
**Send a verification code to the user's phone:**
In the class where you want to integrate Phone Authentication write :
**Note** : I have added `+91` as its country code for India. You can add country code according to your region.
```
PhoneAuthProvider.provider().verifyPhoneNumber("+919876543210") { (verificationID, error) in
if ((error) != nil) {
// Verification code not sent.
print(error)
} else {
// Successful. User gets verification code
// Save verificationID in UserDefaults
UserDefaults.standard.set(verificationID, forKey: "firebase_verification")
UserDefaults.standard.synchronize()
//And show the Screen to enter the Code.
}
```
**Sign in the user with the verification code**:
```
let verificationID = UserDefaults.standard.value(forKey: "firebase_verification")
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID! as! String, verificationCode: self.txtEmailID.text!)
Auth.auth().signIn(with: credential, completion: {(_ user: User, _ error: Error?) -> Void in
if error != nil {
// Error
}else {
print("Phone number: \(user.phoneNumber)")
var userInfo: Any? = user.providerData[0]
print(userInfo)
}
} as! AuthResultCallback)
``` | Double check that the app bundle ID in Xcode matches the bundle ID in Firebase **exactly**. And by **exactly**, make sure their case matches - Xcode likes to use mixed case by default for the app name part of the bundle ID.
If you end up changing the bundle ID in Xcode, make sure to manually delete the provisioning profile for the app before generating a new one in Xcode, or it will repeatedly fail (Apple apparently ignores case on profile names). |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Tested with latest **Firebase iOS SDK i.e. 4.0.0** and **Xcode 8.3**
Firstly , remove this key `FirebaseAppDelegateProxyEnabled` from info.plist. This is not needed.
Now in **AppDelegate.swift** add following functions
```
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
//At time of production it will be set to .prod
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let firebaseAuth = Auth.auth()
if (firebaseAuth.canHandleNotification(userInfo)){
print(userInfo)
return
}
}*
```
**Send a verification code to the user's phone:**
In the class where you want to integrate Phone Authentication write :
**Note** : I have added `+91` as its country code for India. You can add country code according to your region.
```
PhoneAuthProvider.provider().verifyPhoneNumber("+919876543210") { (verificationID, error) in
if ((error) != nil) {
// Verification code not sent.
print(error)
} else {
// Successful. User gets verification code
// Save verificationID in UserDefaults
UserDefaults.standard.set(verificationID, forKey: "firebase_verification")
UserDefaults.standard.synchronize()
//And show the Screen to enter the Code.
}
```
**Sign in the user with the verification code**:
```
let verificationID = UserDefaults.standard.value(forKey: "firebase_verification")
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID! as! String, verificationCode: self.txtEmailID.text!)
Auth.auth().signIn(with: credential, completion: {(_ user: User, _ error: Error?) -> Void in
if error != nil {
// Error
}else {
print("Phone number: \(user.phoneNumber)")
var userInfo: Any? = user.providerData[0]
print(userInfo)
}
} as! AuthResultCallback)
``` | In my case it was the apns token type that was wrong:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)
```
should have been:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
``` |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Tested with latest **Firebase iOS SDK i.e. 4.0.0** and **Xcode 8.3**
Firstly , remove this key `FirebaseAppDelegateProxyEnabled` from info.plist. This is not needed.
Now in **AppDelegate.swift** add following functions
```
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
//At time of production it will be set to .prod
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let firebaseAuth = Auth.auth()
if (firebaseAuth.canHandleNotification(userInfo)){
print(userInfo)
return
}
}*
```
**Send a verification code to the user's phone:**
In the class where you want to integrate Phone Authentication write :
**Note** : I have added `+91` as its country code for India. You can add country code according to your region.
```
PhoneAuthProvider.provider().verifyPhoneNumber("+919876543210") { (verificationID, error) in
if ((error) != nil) {
// Verification code not sent.
print(error)
} else {
// Successful. User gets verification code
// Save verificationID in UserDefaults
UserDefaults.standard.set(verificationID, forKey: "firebase_verification")
UserDefaults.standard.synchronize()
//And show the Screen to enter the Code.
}
```
**Sign in the user with the verification code**:
```
let verificationID = UserDefaults.standard.value(forKey: "firebase_verification")
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID! as! String, verificationCode: self.txtEmailID.text!)
Auth.auth().signIn(with: credential, completion: {(_ user: User, _ error: Error?) -> Void in
if error != nil {
// Error
}else {
print("Phone number: \(user.phoneNumber)")
var userInfo: Any? = user.providerData[0]
print(userInfo)
}
} as! AuthResultCallback)
``` | Well, in my case I have sending wrong `self.verificationID` to `FIRAuthCredential`.
If you are having this error, then please print your `verificationID` and check, is that the same one you are sending to `FIRAuthCredential`.
Here is my code in `objC` :
```
[[FIRPhoneAuthProvider provider] verifyPhoneNumber:self.phoneNumberTextField.text
UIDelegate:nil
completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
if (error) {
NSLog(@"error %@", error.localizedDescription);
return;
}
NSLog(@"verificationID %@", verificationID);
self.verificationID = [NSString stringWithFormat:@"%@", verificationID];
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// [defaults setObject:verificationID forKey:@"authVerificationID"];
// NSString *verificationID = [defaults stringForKey:@"authVerificationID"];
// Sign in using the verificationID and the code sent to the user
// ...
}];
```
I accidentally send wrong verificationID here :
`self.verificationID = [NSString stringWithFormat:@"verificationID",];`
Right one is this :
`self.verificationID = [NSString stringWithFormat:@"%@", verificationID];`
And then I send it to `FIRAuthCredential` like this :
```
FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider]
credentialWithVerificationID:self.verificationID
verificationCode:self.pinCodeTextField.text];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRUser *user, NSError *error) {
if (error) {
NSLog(@"error %@", error);
return;
}
NSLog(@"Success");
// User successfully signed in. Get user data from the FIRUser object
// ...
}];
```
Which return `success` successfully. Hope it will help to others. |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Tested with latest **Firebase iOS SDK i.e. 4.0.0** and **Xcode 8.3**
Firstly , remove this key `FirebaseAppDelegateProxyEnabled` from info.plist. This is not needed.
Now in **AppDelegate.swift** add following functions
```
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
//At time of production it will be set to .prod
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let firebaseAuth = Auth.auth()
if (firebaseAuth.canHandleNotification(userInfo)){
print(userInfo)
return
}
}*
```
**Send a verification code to the user's phone:**
In the class where you want to integrate Phone Authentication write :
**Note** : I have added `+91` as its country code for India. You can add country code according to your region.
```
PhoneAuthProvider.provider().verifyPhoneNumber("+919876543210") { (verificationID, error) in
if ((error) != nil) {
// Verification code not sent.
print(error)
} else {
// Successful. User gets verification code
// Save verificationID in UserDefaults
UserDefaults.standard.set(verificationID, forKey: "firebase_verification")
UserDefaults.standard.synchronize()
//And show the Screen to enter the Code.
}
```
**Sign in the user with the verification code**:
```
let verificationID = UserDefaults.standard.value(forKey: "firebase_verification")
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID! as! String, verificationCode: self.txtEmailID.text!)
Auth.auth().signIn(with: credential, completion: {(_ user: User, _ error: Error?) -> Void in
if error != nil {
// Error
}else {
print("Phone number: \(user.phoneNumber)")
var userInfo: Any? = user.providerData[0]
print(userInfo)
}
} as! AuthResultCallback)
``` | i am solve it easy make type .sandbox
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
}
```
and remove this line from code
```
Auth.auth().settings.isAppVerificationDisabledForTesting = TRUE
``` |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | In my case it was the apns token type that was wrong:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)
```
should have been:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
``` | Double check that the app bundle ID in Xcode matches the bundle ID in Firebase **exactly**. And by **exactly**, make sure their case matches - Xcode likes to use mixed case by default for the app name part of the bundle ID.
If you end up changing the bundle ID in Xcode, make sure to manually delete the provisioning profile for the app before generating a new one in Xcode, or it will repeatedly fail (Apple apparently ignores case on profile names). |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Double check that the app bundle ID in Xcode matches the bundle ID in Firebase **exactly**. And by **exactly**, make sure their case matches - Xcode likes to use mixed case by default for the app name part of the bundle ID.
If you end up changing the bundle ID in Xcode, make sure to manually delete the provisioning profile for the app before generating a new one in Xcode, or it will repeatedly fail (Apple apparently ignores case on profile names). | Well, in my case I have sending wrong `self.verificationID` to `FIRAuthCredential`.
If you are having this error, then please print your `verificationID` and check, is that the same one you are sending to `FIRAuthCredential`.
Here is my code in `objC` :
```
[[FIRPhoneAuthProvider provider] verifyPhoneNumber:self.phoneNumberTextField.text
UIDelegate:nil
completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
if (error) {
NSLog(@"error %@", error.localizedDescription);
return;
}
NSLog(@"verificationID %@", verificationID);
self.verificationID = [NSString stringWithFormat:@"%@", verificationID];
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// [defaults setObject:verificationID forKey:@"authVerificationID"];
// NSString *verificationID = [defaults stringForKey:@"authVerificationID"];
// Sign in using the verificationID and the code sent to the user
// ...
}];
```
I accidentally send wrong verificationID here :
`self.verificationID = [NSString stringWithFormat:@"verificationID",];`
Right one is this :
`self.verificationID = [NSString stringWithFormat:@"%@", verificationID];`
And then I send it to `FIRAuthCredential` like this :
```
FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider]
credentialWithVerificationID:self.verificationID
verificationCode:self.pinCodeTextField.text];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRUser *user, NSError *error) {
if (error) {
NSLog(@"error %@", error);
return;
}
NSLog(@"Success");
// User successfully signed in. Get user data from the FIRUser object
// ...
}];
```
Which return `success` successfully. Hope it will help to others. |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | Double check that the app bundle ID in Xcode matches the bundle ID in Firebase **exactly**. And by **exactly**, make sure their case matches - Xcode likes to use mixed case by default for the app name part of the bundle ID.
If you end up changing the bundle ID in Xcode, make sure to manually delete the provisioning profile for the app before generating a new one in Xcode, or it will repeatedly fail (Apple apparently ignores case on profile names). | i am solve it easy make type .sandbox
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
}
```
and remove this line from code
```
Auth.auth().settings.isAppVerificationDisabledForTesting = TRUE
``` |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | In my case it was the apns token type that was wrong:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)
```
should have been:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
``` | Well, in my case I have sending wrong `self.verificationID` to `FIRAuthCredential`.
If you are having this error, then please print your `verificationID` and check, is that the same one you are sending to `FIRAuthCredential`.
Here is my code in `objC` :
```
[[FIRPhoneAuthProvider provider] verifyPhoneNumber:self.phoneNumberTextField.text
UIDelegate:nil
completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
if (error) {
NSLog(@"error %@", error.localizedDescription);
return;
}
NSLog(@"verificationID %@", verificationID);
self.verificationID = [NSString stringWithFormat:@"%@", verificationID];
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// [defaults setObject:verificationID forKey:@"authVerificationID"];
// NSString *verificationID = [defaults stringForKey:@"authVerificationID"];
// Sign in using the verificationID and the code sent to the user
// ...
}];
```
I accidentally send wrong verificationID here :
`self.verificationID = [NSString stringWithFormat:@"verificationID",];`
Right one is this :
`self.verificationID = [NSString stringWithFormat:@"%@", verificationID];`
And then I send it to `FIRAuthCredential` like this :
```
FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider]
credentialWithVerificationID:self.verificationID
verificationCode:self.pinCodeTextField.text];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRUser *user, NSError *error) {
if (error) {
NSLog(@"error %@", error);
return;
}
NSLog(@"Success");
// User successfully signed in. Get user data from the FIRUser object
// ...
}];
```
Which return `success` successfully. Hope it will help to others. |
44,091,666 | I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN.
So I wrote this:
```
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in
if error != nil {
print("Verification code not sent \(error!)")
} else {
print ("Successful.")
}
```
And I get:
```
Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 500;
message = "<null>";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
```
Any idea? Should I file a bug against firebase?
I am using iOS SDK 4.0.0 (latest zip I could find.)
**UPDATE:**
I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO`
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
Auth.auth().setAPNSToken(deviceToken, type: .prod)
}
``` | 2017/05/20 | [
"https://Stackoverflow.com/questions/44091666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666818/"
] | In my case it was the apns token type that was wrong:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)
```
should have been:
```
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
``` | i am solve it easy make type .sandbox
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth.
let firebaseAuth = Auth.auth()
//At development time we use .sandbox
firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
}
```
and remove this line from code
```
Auth.auth().settings.isAppVerificationDisabledForTesting = TRUE
``` |
50,488,521 | I am looking for a solution to convert my string to `camelcaps` by the `dot` it contains.
here is my string: `'sender.state'`
I am expecting the result as : `'senderState'`;
I tried this: `'sender.state'.replace(/\./g, '');` it removes the `.` but how to handle the `camel caps` stuff? | 2018/05/23 | [
"https://Stackoverflow.com/questions/50488521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218349/"
] | You can pass a function to `.replace()`:
```
'sender.state'.replace(/\.([a-z])/g, (match, letter) => letter.toUpperCase());
``` | Without `regex` - this might help :
```
var str = "bad.unicron";
var temp = str.split(".");
return temp[0]+temp[1].charAt(0).toUpperCase() + temp[1].slice(1);
```
I'll try to come up with `regex` |
51,094,339 | I need to measure the execution time of a Python program having the following structure:
```
import numpy
import pandas
def func1():
code
def func2():
code
if __name__ == '__main__':
func1()
func2()
```
If I want to use "time.time()", where should I put them in the code? I want to get the execution time for the whole program.
Alternative 1:
```
import time
start = time.time()
import numpy
import pandas
def func1():
code
def func2():
code
if __name__ == '__main__':
func1()
func2()
end = time.time()
print("The execution time is", end - start)
```
Alternative 2:
```
import numpy
import pandas
def func1():
code
def func2():
code
if __name__ == '__main__':
import time
start = time.time()
func1()
func2()
end = time.time()
print("The execution time is", end - start)
``` | 2018/06/29 | [
"https://Stackoverflow.com/questions/51094339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9668218/"
] | In linux: you could run this file test.py using the time command
>
> time python3 test.py
>
>
>
After your program runs it will give you the following output:
real 0m0.074s
user 0m0.004s
sys 0m0.000s
[this link](https://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1) will tell the difference between the three times you get | The whole program:
```
import time
t1 = time.time()
import numpy
import pandas
def func1():
code
def func2():
code
if __name__ == '__main__':
func1()
func2()
t2 = time.time()
print("The execution time is", t2 - t1)
``` |
38,659,379 | I've been experiencing an irritating issue that I cant get around.
I am trying to `vagrant up` a centos7 system in this environment:
* Windows 10
* Hyper-V (not anniversary update version)
* Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7"
* OpenSSH installed, private key configured
The contents of my Vagrantfile:
```
Vagrant.configure("2") do |config|
#config.vm.box = "serveit/centos-7"
config.vm.box = "bluefedora/hyperv-alpha-centos7"
config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.forward_agent = true
end
```
I am getting this error when doing a `vagrant up`:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant up
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
==> default: Importing a Hyper-V instance
default: Cloning virtual hard drive...
default: Creating and registering the VM...
default: Successfully imported a VM with name: vagrantbox
==> default: Starting the machine...
==> default: Waiting for the machine to report its IP address...
default: Timeout: 120 seconds
default: IP: 192.168.137.6
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 192.168.137.6:22
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
```
I can do an `vagrant ssh-config`:
```
Host default
HostName 192.168.137.6
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
```
I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work.
I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected.
Also `vagrant ssh` works with password:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant ssh
[email protected]'s password:
[vagrant@localhost ~]$
```
So because I could SSH, I decided to check the `.ssh/authorized_keys` file:
[vagrant@localhost ~]$ cat .ssh/authorized\_keys
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz
UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4
47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd
n2Hr158Jy83A9CslQPbT vagrant
```
***Dafuq is this key?!?!***
I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
Furthermore, if I update my `Vagrantfile` to use my system private key:
```
#config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.private_key_path = "~/.ssh/id_rsa"
```
I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub):
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own.
***HELP!***
Can anyone help me find out why this is happening? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38659379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951942/"
] | Turns out, there is a known bug in Vagrant 1.8.5 (Will be fixed in 1.8.6):
Details [here](https://github.com/mitchellh/vagrant/issues/7610)
If you are using 1.8.5, you can download the updated version from PR [#7611](https://github.com/mitchellh/vagrant/pull/7611) using PowerShell:
`[IO.File]::WriteAllLines("C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb", (Invoke-WebRequest -Uri https://raw.githubusercontent.com/Poohblah/vagrant/41063204ca540c44f9555bd11ba9e76c7307bec5/plugins/guests/linux/cap/public_key.rb).Content)` | SSH into the vagrant machine and give this privilege.
vagrant@localhost:chmod 600 ~/.ssh/authorized\_keys.
exit out comeback to the host and hit "vagrant reload"
It works!!! |
38,659,379 | I've been experiencing an irritating issue that I cant get around.
I am trying to `vagrant up` a centos7 system in this environment:
* Windows 10
* Hyper-V (not anniversary update version)
* Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7"
* OpenSSH installed, private key configured
The contents of my Vagrantfile:
```
Vagrant.configure("2") do |config|
#config.vm.box = "serveit/centos-7"
config.vm.box = "bluefedora/hyperv-alpha-centos7"
config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.forward_agent = true
end
```
I am getting this error when doing a `vagrant up`:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant up
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
==> default: Importing a Hyper-V instance
default: Cloning virtual hard drive...
default: Creating and registering the VM...
default: Successfully imported a VM with name: vagrantbox
==> default: Starting the machine...
==> default: Waiting for the machine to report its IP address...
default: Timeout: 120 seconds
default: IP: 192.168.137.6
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 192.168.137.6:22
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
```
I can do an `vagrant ssh-config`:
```
Host default
HostName 192.168.137.6
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
```
I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work.
I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected.
Also `vagrant ssh` works with password:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant ssh
[email protected]'s password:
[vagrant@localhost ~]$
```
So because I could SSH, I decided to check the `.ssh/authorized_keys` file:
[vagrant@localhost ~]$ cat .ssh/authorized\_keys
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz
UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4
47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd
n2Hr158Jy83A9CslQPbT vagrant
```
***Dafuq is this key?!?!***
I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
Furthermore, if I update my `Vagrantfile` to use my system private key:
```
#config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.private_key_path = "~/.ssh/id_rsa"
```
I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub):
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own.
***HELP!***
Can anyone help me find out why this is happening? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38659379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951942/"
] | Turns out, there is a known bug in Vagrant 1.8.5 (Will be fixed in 1.8.6):
Details [here](https://github.com/mitchellh/vagrant/issues/7610)
If you are using 1.8.5, you can download the updated version from PR [#7611](https://github.com/mitchellh/vagrant/pull/7611) using PowerShell:
`[IO.File]::WriteAllLines("C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb", (Invoke-WebRequest -Uri https://raw.githubusercontent.com/Poohblah/vagrant/41063204ca540c44f9555bd11ba9e76c7307bec5/plugins/guests/linux/cap/public_key.rb).Content)` | Inside `public_key.rb` file find those at line 56 and append `chmod 0600 ~/.ssh/authorized_keys` like so:
```
if test -f ~/.ssh/authorized_keys; then
grep -v -x -f '#{remote_path}' ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.tmp
mv ~/.ssh/authorized_keys.tmp ~/.ssh/authorized_keys
chmod 0600 ~/.ssh/authorized_keys
fi
rm -f '#{remote_path}'
```
Path for Windows: `C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb`
Path for mac: `/opt/vagrant/embedded/gems/gems/vagrant-1.8.5/plugins/guests/linux/cap/public_key.rb` |
38,659,379 | I've been experiencing an irritating issue that I cant get around.
I am trying to `vagrant up` a centos7 system in this environment:
* Windows 10
* Hyper-V (not anniversary update version)
* Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7"
* OpenSSH installed, private key configured
The contents of my Vagrantfile:
```
Vagrant.configure("2") do |config|
#config.vm.box = "serveit/centos-7"
config.vm.box = "bluefedora/hyperv-alpha-centos7"
config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.forward_agent = true
end
```
I am getting this error when doing a `vagrant up`:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant up
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
==> default: Importing a Hyper-V instance
default: Cloning virtual hard drive...
default: Creating and registering the VM...
default: Successfully imported a VM with name: vagrantbox
==> default: Starting the machine...
==> default: Waiting for the machine to report its IP address...
default: Timeout: 120 seconds
default: IP: 192.168.137.6
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 192.168.137.6:22
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
```
I can do an `vagrant ssh-config`:
```
Host default
HostName 192.168.137.6
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
```
I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work.
I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected.
Also `vagrant ssh` works with password:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant ssh
[email protected]'s password:
[vagrant@localhost ~]$
```
So because I could SSH, I decided to check the `.ssh/authorized_keys` file:
[vagrant@localhost ~]$ cat .ssh/authorized\_keys
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz
UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4
47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd
n2Hr158Jy83A9CslQPbT vagrant
```
***Dafuq is this key?!?!***
I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
Furthermore, if I update my `Vagrantfile` to use my system private key:
```
#config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.private_key_path = "~/.ssh/id_rsa"
```
I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub):
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own.
***HELP!***
Can anyone help me find out why this is happening? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38659379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951942/"
] | Turns out, there is a known bug in Vagrant 1.8.5 (Will be fixed in 1.8.6):
Details [here](https://github.com/mitchellh/vagrant/issues/7610)
If you are using 1.8.5, you can download the updated version from PR [#7611](https://github.com/mitchellh/vagrant/pull/7611) using PowerShell:
`[IO.File]::WriteAllLines("C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb", (Invoke-WebRequest -Uri https://raw.githubusercontent.com/Poohblah/vagrant/41063204ca540c44f9555bd11ba9e76c7307bec5/plugins/guests/linux/cap/public_key.rb).Content)` | check permissions inside vagrant instance:
```
chmod 600 /vagrant/.ssh/authorized_keys
chmod 700 /vagrant/.ssh
chmod 700 /vagrant # important too! (for me that was a reason of same error)
```
ssh keys will be used only with right permissions.
Also, as *workaround*, you can add to the Vagrantfile:
```
config.ssh.username = "vagrant"
config.ssh.password = "vagrant"
``` |
38,659,379 | I've been experiencing an irritating issue that I cant get around.
I am trying to `vagrant up` a centos7 system in this environment:
* Windows 10
* Hyper-V (not anniversary update version)
* Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7"
* OpenSSH installed, private key configured
The contents of my Vagrantfile:
```
Vagrant.configure("2") do |config|
#config.vm.box = "serveit/centos-7"
config.vm.box = "bluefedora/hyperv-alpha-centos7"
config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.forward_agent = true
end
```
I am getting this error when doing a `vagrant up`:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant up
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
==> default: Importing a Hyper-V instance
default: Cloning virtual hard drive...
default: Creating and registering the VM...
default: Successfully imported a VM with name: vagrantbox
==> default: Starting the machine...
==> default: Waiting for the machine to report its IP address...
default: Timeout: 120 seconds
default: IP: 192.168.137.6
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 192.168.137.6:22
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
```
I can do an `vagrant ssh-config`:
```
Host default
HostName 192.168.137.6
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
```
I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work.
I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected.
Also `vagrant ssh` works with password:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant ssh
[email protected]'s password:
[vagrant@localhost ~]$
```
So because I could SSH, I decided to check the `.ssh/authorized_keys` file:
[vagrant@localhost ~]$ cat .ssh/authorized\_keys
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz
UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4
47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd
n2Hr158Jy83A9CslQPbT vagrant
```
***Dafuq is this key?!?!***
I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
Furthermore, if I update my `Vagrantfile` to use my system private key:
```
#config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.private_key_path = "~/.ssh/id_rsa"
```
I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub):
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own.
***HELP!***
Can anyone help me find out why this is happening? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38659379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951942/"
] | Inside `public_key.rb` file find those at line 56 and append `chmod 0600 ~/.ssh/authorized_keys` like so:
```
if test -f ~/.ssh/authorized_keys; then
grep -v -x -f '#{remote_path}' ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.tmp
mv ~/.ssh/authorized_keys.tmp ~/.ssh/authorized_keys
chmod 0600 ~/.ssh/authorized_keys
fi
rm -f '#{remote_path}'
```
Path for Windows: `C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb`
Path for mac: `/opt/vagrant/embedded/gems/gems/vagrant-1.8.5/plugins/guests/linux/cap/public_key.rb` | SSH into the vagrant machine and give this privilege.
vagrant@localhost:chmod 600 ~/.ssh/authorized\_keys.
exit out comeback to the host and hit "vagrant reload"
It works!!! |
38,659,379 | I've been experiencing an irritating issue that I cant get around.
I am trying to `vagrant up` a centos7 system in this environment:
* Windows 10
* Hyper-V (not anniversary update version)
* Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7"
* OpenSSH installed, private key configured
The contents of my Vagrantfile:
```
Vagrant.configure("2") do |config|
#config.vm.box = "serveit/centos-7"
config.vm.box = "bluefedora/hyperv-alpha-centos7"
config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.forward_agent = true
end
```
I am getting this error when doing a `vagrant up`:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant up
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
==> default: Importing a Hyper-V instance
default: Cloning virtual hard drive...
default: Creating and registering the VM...
default: Successfully imported a VM with name: vagrantbox
==> default: Starting the machine...
==> default: Waiting for the machine to report its IP address...
default: Timeout: 120 seconds
default: IP: 192.168.137.6
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 192.168.137.6:22
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
```
I can do an `vagrant ssh-config`:
```
Host default
HostName 192.168.137.6
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
```
I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work.
I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected.
Also `vagrant ssh` works with password:
```
PS C:\Programs\vagrant_stuff\centos7> vagrant ssh
[email protected]'s password:
[vagrant@localhost ~]$
```
So because I could SSH, I decided to check the `.ssh/authorized_keys` file:
[vagrant@localhost ~]$ cat .ssh/authorized\_keys
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz
UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4
47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd
n2Hr158Jy83A9CslQPbT vagrant
```
***Dafuq is this key?!?!***
I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this:
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
Furthermore, if I update my `Vagrantfile` to use my system private key:
```
#config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key"
config.ssh.private_key_path = "~/.ssh/id_rsa"
```
I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub):
```
[vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H
ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi
lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd
K8jlqm8tehUc9c9WhQ== vagrant insecure public key
```
I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own.
***HELP!***
Can anyone help me find out why this is happening? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38659379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951942/"
] | check permissions inside vagrant instance:
```
chmod 600 /vagrant/.ssh/authorized_keys
chmod 700 /vagrant/.ssh
chmod 700 /vagrant # important too! (for me that was a reason of same error)
```
ssh keys will be used only with right permissions.
Also, as *workaround*, you can add to the Vagrantfile:
```
config.ssh.username = "vagrant"
config.ssh.password = "vagrant"
``` | SSH into the vagrant machine and give this privilege.
vagrant@localhost:chmod 600 ~/.ssh/authorized\_keys.
exit out comeback to the host and hit "vagrant reload"
It works!!! |
4,778,743 | I created a wordpress blog (http://raptor.hk), but i am unable to set the right sidebar into correct position. i think i have missed something in CSS. the DIV is named "rightbar". I would like the DIV to be positioned right next to the content, within the white wrapper. Also, support of fluid layout (not moving on browser resize) is needed.
the problem is solved (see my answer), but anybody can give better solutions? | 2011/01/24 | [
"https://Stackoverflow.com/questions/4778743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188331/"
] | You can use the [Users API](http://code.google.com/appengine/docs/python/users/) to authenticate users - either using Google accounts, or OpenID. If you want sessions without user login, there are a number of libraries, such as [gaesessions](https://github.com/dound/gae-sessions). | Yes, this is for me the easiest way using Python 2.7.
```
import Cookie
value_session = "userid (encrypted);time of login"
name_cookie = "sessioncookie"
expires = 2629743 # 1 month in seconds
D = Cookie.SimpleCookie()
D["name_cookie"] = value_session
D["name_cookie"]["path"] = "/"
D["name_cookie"]["expires"] = expires
print(D)
``` |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | Make `random` return `string`. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a `for` loop.
```
string random(string names[]){
int randNum = 0;
randNum = rand() % 20 + 1;
return names[randNum];
}
```
Then, in the `main` function, assign a `string` variable to the return value of the `random` function.
```
int main() {
srand( time(NULL) ); // seed number generator once
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
string randomWord = random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
``` | I'm not super familiar with strings, but you should be able to just declare random() as a string function.
Ex:
string random (string names[]); |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | Additionally srand(time(NULL)) should be called only one time, on the beginning of main() function. | I'm not super familiar with strings, but you should be able to just declare random() as a string function.
Ex:
string random (string names[]); |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | In your question as well as in the previous answer, you are running out of bounds accessing the names array:
```
int randNum = rand() % 20 + 1;
return names[randNum];
```
You are never accessing names[0] but instead reach behind the array when addressing names[20]. | I'm not super familiar with strings, but you should be able to just declare random() as a string function.
Ex:
string random (string names[]); |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | Make `random` return `string`. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a `for` loop.
```
string random(string names[]){
int randNum = 0;
randNum = rand() % 20 + 1;
return names[randNum];
}
```
Then, in the `main` function, assign a `string` variable to the return value of the `random` function.
```
int main() {
srand( time(NULL) ); // seed number generator once
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
string randomWord = random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
``` | Additionally srand(time(NULL)) should be called only one time, on the beginning of main() function. |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | Make `random` return `string`. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a `for` loop.
```
string random(string names[]){
int randNum = 0;
randNum = rand() % 20 + 1;
return names[randNum];
}
```
Then, in the `main` function, assign a `string` variable to the return value of the `random` function.
```
int main() {
srand( time(NULL) ); // seed number generator once
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
string randomWord = random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
``` | In your question as well as in the previous answer, you are running out of bounds accessing the names array:
```
int randNum = rand() % 20 + 1;
return names[randNum];
```
You are never accessing names[0] but instead reach behind the array when addressing names[20]. |
36,967,907 | i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
```
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
``` | 2016/05/01 | [
"https://Stackoverflow.com/questions/36967907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058648/"
] | In your question as well as in the previous answer, you are running out of bounds accessing the names array:
```
int randNum = rand() % 20 + 1;
return names[randNum];
```
You are never accessing names[0] but instead reach behind the array when addressing names[20]. | Additionally srand(time(NULL)) should be called only one time, on the beginning of main() function. |
24,587,704 | So am trying to do some end to end testing in specflow using entity framework 6.
I have code migrations enabled and my seed method written. I have a context factory to generate my context with a connection string that in influenced by a step definition.
What I want to be able to do is in a Feature I want to create a background step like the following
```
Given I create a database "Admin-Test"
```
In this test i want to drop all connections to a database and then drop it, followed by leaning on EF6 code migration to then recreate it and seed it with a known set of data (the default data for the application).
This all works great for the first scenario in the feature but for the rest when the database is droppde the code migrations do not run to repopulate it.
I have tried inheriting from `DropCreateDatabaseAlways<DbContext>` And this gets hit in the first but not subsequent.
The first problem i was getting was the database not getting created, if i do that manually the seed stuff is still not being run (I read something on msdn about ef not creating the db anymore as it was confusing users).
so my question is this:
How can i get code migrations to trigger per scenario?
I suspect the question people may be able to answer easier is: how can i trigger the automatic code migration stuff manually in a unit test to force it to run?
The bonus question is this: recreating the database each scenario is inefficient - i noticed the migration generates a lot of db up and down methods. How can i run those manually and then the seed code? | 2014/07/05 | [
"https://Stackoverflow.com/questions/24587704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109347/"
] | I personally see your bonus question as part of a potential overall approach.
I dont see why `SEED` and `Migration` need to be so tightly coupled.
A basic pattern that works with Multiple DBs.
a) By default Use Context against a DB with No initializer
```
Database.SetInitializer(new ContextInitializerNone<MYDbContext>());
var context = new MYDbContext((Tools.GetDbConnection(DataSource,DbName )),true); // pass in connection to db
```
b) on demand Migrate. For me this means adminsitrative trigger
```
public override void MigrateDb() {
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMigrationConfiguration>());
Context.Database.Initialize(true);
}
```
c) Control Drops separately - Admin trigger
You can use EF for this. I personally prefer SQL script triggered from code.
d) Trigger seed routines - Admin trigger.
Using a rountine that can be called by a tool that just called Migrate for example.
I dont like trying to launch this from inside EF migrations.
Some scenarios for me that it caused headaches having EF orchestrating when seed got called.
A single Admin step could of course combine as required.
I use a custom built Migration Workbench (WPF) that can do any or all of the above on any DB.
Including New DBs. | An approach that I have used for this is to declare a `[BeforeScenario]` method and create the database and run the migrations in here, and then in an `[AfterScenario]` method I delete the database. Its often better to put these in a seperate class specifically for setup. As long as its marked as a `[Binding]` class then specflow will find it and run the methods.
in the `[BeforeScenario]` I create by db context (`ApplicationDB`) and then create the database
```
container = TestContainerFactory.SetupContainer(id);
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDb, Configuration>());
var applicationDb = container.GetInstance<ApplicationDb>();
if (applicationDb.Database.Exists()) //just in case the previous test didn't delete the old db
{
applicationDb.Database.Delete();
}
applicationDb.Database.Initialize(true);
```
in the `[AfterScenario]` I delete the database
```
var applicationDb = container.GetInstance<ApplicationDb>();
applicationDb.Database.Delete();
applicationDb.Dispose();
```
The only issues I've had with this are when I am running it with a multi threaded testrunner like NCrunch, when I have had to ensure a new database gets created and deleted for each scenario and that these database all have a unique name, which I generate with a GUID.
this served me well for a while until I had too many tests that the feedback cycle became too long, at that point I allowed the tests to mock the database by having in memory collections behind the IQueryable interface of the IDbSet stuff. I made this switchable in config so that I could run the tests fast most of the time that NCrunch was running them, btu the switch back to actually running them against the database to check that that stuff still actually worked correctly. |
9,272,270 | Hi I've an input button like
```
<input id="btnDelete" type="button" value="Delete" name="btnDelete" runat="server" onclick="return confirm('Are you sure you wish to delete these records?');" />
and my serverside code is
Private Sub btnDelete_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.ServerClick
' my code here
End Sub
```
but when I click on delete button I'm getting confirm msg box, but after that it is not going to server side event.
Anything wrong in this?
Thank you | 2012/02/14 | [
"https://Stackoverflow.com/questions/9272270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225264/"
] | USE [OnClientClick](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx#Y570) for your client side javascript validation
```
<asp:BUTTON id="btnDelete" name="btnDelete" value="Delete" onclick="btnDelete_ServerClick"
OnClientClick="return confirm('Are you sure you wish to delete these records?');"/>
```
IF you are using HTML control then this may be helpful: [How to call code behind server method from a client side javascript function?](https://stackoverflow.com/questions/5828803/how-to-call-code-behind-server-method-from-a-client-side-javascript-function)
CHECK THIS OUT ALSO [\_doPostBack()](http://wiki.asp.net/404.aspx?aspxerrorpath=/themes/fan/pages/page.aspx/1082/dopostback-function/) | Maybe because its not a type=submit button?
```
<form name="frmPerson" action="/dome.asp">
some form fields here
.
.
<input id="btnDelete" type="submit" name="btnDelete" value="Delete" />
</form>
``` |
53,834,396 | Assuming that I have a QPushButton named `button`, I successfully do the following to allow **click** event:
```
class UI(object):
def setupUi(self, Dialog):
# ...
self.button.clicked.connect(self.do_something)
def do_something(self):
# Something here
```
My question is: how can I call `do_something()` when `the tab` key is pressed? For instance, if I have a QlineEdit named `tb_id`, after entering a value and press tab key, `do_something()` method should be called in the same way as what `clicked` does above. How can I do that using `pyqt5`?
Thank you so much. | 2018/12/18 | [
"https://Stackoverflow.com/questions/53834396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9923495/"
] | To get what you want there are many methods but before pointing it by observing your code I see that you have generated it with Qt Designer so that code should not be modified but create another class that uses that code so I will place the base code:
```
from PyQt5 import QtCore, QtWidgets
class UI(object):
def setupUi(self, Dialog):
self.button = QtWidgets.QPushButton("Press Me")
lay = QtWidgets.QVBoxLayout(Dialog)
lay.addWidget(self.button)
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
@QtCore.pyqtSlot()
def do_something(self):
print("do_something")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
```
Also, I recommend you read the difference between event and signal in the world of Qt in [What are the differences between event and signal in Qt](https://stackoverflow.com/questions/9323888/what-are-the-differences-between-event-and-signal-in-qt) since you speak of *click event* but in the world of Qt one must say *clicked signal*.
Now if going to the point there are the following options:
* Using keyPressEvent:
---
```
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
@QtCore.pyqtSlot()
def do_something(self):
print("do_something")
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Tab:
self.do_something()
```
* Using an event filter:
---
```
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
@QtCore.pyqtSlot()
def do_something(self):
print("do_something")
def eventFilter(self, obj, event):
if obj is self and event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Tab:
self.do_something()
return super(Dialog, self).eventFilter(obj, event)
```
* Using activated signal of QShorcut:
---
```
class Dialog(QtWidgets.QDialog, UI):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.button.clicked.connect(self.do_something)
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self)
shortcut.activated.connect(self.do_something)
@QtCore.pyqtSlot()
def do_something(self):
print("do_something")
```
From the previous methods I prefer the latter because you do not need to overwrite anything and you can connect to several functions.
On the other hand, only events are detected when the focus is in the Qt window. | I assume you put your widget in QDialog widget, so if you want to implement your own key press event, you should override the **keyPressEvent** of your Dialog widget,
then it can behave as you like.
Here's an example,
```
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
class UI(QDialog):
def __init__(self):
super(UI, self).__init__()
# ...
self.button.clicked.connect(self.do_something)
def do_something(self):
# Something here
def keyPressEvent(self, event):
# when press key is Tab call your function
if event.key() == Qt.Key_Tab:
self.do_something()
``` |
62,910,520 | I tried to run `flutter pub get` and I got this error:
```
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷
1 │
│ ^
╵
pub upgrade failed (65; ╵)
``` | 2020/07/15 | [
"https://Stackoverflow.com/questions/62910520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753831/"
] | The file pubspec.lock is a generated file, so you can delete it and then regenerate it.
Delete **pubspec.lock**.
Run the following command:
```
flutter pub get
```
or
```
flutter pub upgrade
```
Notes on [pub upgrade](https://dart.dev/tools/pub/cmd/pub-upgrade) (you could probably skip the delete step). | Delete the file at flutter/packages/flutter\_tools/pubspec.lock then try flutter pub upgrade again.
You may have interrupted the upgrade process before it finished hence the file became invalid. |
62,910,520 | I tried to run `flutter pub get` and I got this error:
```
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷
1 │
│ ^
╵
pub upgrade failed (65; ╵)
``` | 2020/07/15 | [
"https://Stackoverflow.com/questions/62910520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753831/"
] | The file pubspec.lock is a generated file, so you can delete it and then regenerate it.
Delete **pubspec.lock**.
Run the following command:
```
flutter pub get
```
or
```
flutter pub upgrade
```
Notes on [pub upgrade](https://dart.dev/tools/pub/cmd/pub-upgrade) (you could probably skip the delete step). | I took the same error,
but this error was coming from my main folder.
in this path "C:\Users"yourusername"\AppData\Local\Pub\Cache\global\_packages\devtools"
I deleted the file and I started app. file has been by itself created and problem solved. |
62,910,520 | I tried to run `flutter pub get` and I got this error:
```
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷
1 │
│ ^
╵
pub upgrade failed (65; ╵)
``` | 2020/07/15 | [
"https://Stackoverflow.com/questions/62910520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753831/"
] | The file pubspec.lock is a generated file, so you can delete it and then regenerate it.
Delete **pubspec.lock**.
Run the following command:
```
flutter pub get
```
or
```
flutter pub upgrade
```
Notes on [pub upgrade](https://dart.dev/tools/pub/cmd/pub-upgrade) (you could probably skip the delete step). | I got the same error while working.
I deleted **pubspec.lock** file.
then I ran command
`flutter pub get`
It created new **pubspec.lock** file.
Now application runs without any errors. |
62,910,520 | I tried to run `flutter pub get` and I got this error:
```
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷
1 │
│ ^
╵
pub upgrade failed (65; ╵)
``` | 2020/07/15 | [
"https://Stackoverflow.com/questions/62910520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753831/"
] | Delete the file at flutter/packages/flutter\_tools/pubspec.lock then try flutter pub upgrade again.
You may have interrupted the upgrade process before it finished hence the file became invalid. | I took the same error,
but this error was coming from my main folder.
in this path "C:\Users"yourusername"\AppData\Local\Pub\Cache\global\_packages\devtools"
I deleted the file and I started app. file has been by itself created and problem solved. |
62,910,520 | I tried to run `flutter pub get` and I got this error:
```
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷
1 │
│ ^
╵
pub upgrade failed (65; ╵)
``` | 2020/07/15 | [
"https://Stackoverflow.com/questions/62910520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753831/"
] | Delete the file at flutter/packages/flutter\_tools/pubspec.lock then try flutter pub upgrade again.
You may have interrupted the upgrade process before it finished hence the file became invalid. | I got the same error while working.
I deleted **pubspec.lock** file.
then I ran command
`flutter pub get`
It created new **pubspec.lock** file.
Now application runs without any errors. |
877,690 | How does a 3D model handled unit wise ?
When i have a random model that i want to fit in my view port i dunno if it is too big or not, if i need to translate it to be in the middle...
I think a 3d object might have it's own origine. | 2009/05/18 | [
"https://Stackoverflow.com/questions/877690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | You need to find a bounding volume, a shape that encloses all the object's vertices, for your object that is easier to work with than the object itself. Spheres are often used for this. Either the artist can define the sphere as part of the model information or you can work it out at run time. Calculating the optimal sphere is very hard, but you can get a good approximation using the following:
```
determine the min and max value of each point's x, y and z
for each vertex
min_x = min (min_x, vertex.x)
max_x = max (max_x, vertex.x)
min_y = min (min_y, vertex.y)
max_y = max (max_y, vertex.y)
min_z = min (min_z, vertex.z)
max_z = max (max_z, vertex.z)
sphere centre = (max_x + min_x) / 2, (max_y + min_y) / 2, (max_z + min_z) / 2
sphere radius = distance from centre to (max_x, max_y, max_z)
```
Using this sphere, determine the a world position that allows the sphere to be viewed in full - simple geometry will determine this. | Sorry, your question is very unclear. I suppose you want to center a 3D model to a viewport. You can achieve this by calculating the model's bounding box. To do this, traverse all polygons and get the minimum/maximum X/Y/Z coordinates. The bounding box given by the points `(min_x,min_y,min_z)` and `(max_x,max_y,max_z)` will contain the whole model. Now you can center the model by looking at the center of this box. With some further calculations (depending on your FOV) you can also get the left/right/upper/lower borders inside your viewport. |
877,690 | How does a 3D model handled unit wise ?
When i have a random model that i want to fit in my view port i dunno if it is too big or not, if i need to translate it to be in the middle...
I think a 3d object might have it's own origine. | 2009/05/18 | [
"https://Stackoverflow.com/questions/877690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | You need to find a bounding volume, a shape that encloses all the object's vertices, for your object that is easier to work with than the object itself. Spheres are often used for this. Either the artist can define the sphere as part of the model information or you can work it out at run time. Calculating the optimal sphere is very hard, but you can get a good approximation using the following:
```
determine the min and max value of each point's x, y and z
for each vertex
min_x = min (min_x, vertex.x)
max_x = max (max_x, vertex.x)
min_y = min (min_y, vertex.y)
max_y = max (max_y, vertex.y)
min_z = min (min_z, vertex.z)
max_z = max (max_z, vertex.z)
sphere centre = (max_x + min_x) / 2, (max_y + min_y) / 2, (max_z + min_z) / 2
sphere radius = distance from centre to (max_x, max_y, max_z)
```
Using this sphere, determine the a world position that allows the sphere to be viewed in full - simple geometry will determine this. | "so i tried to scale it down"
The best thing to do in this situation is not to transform your model at all! Leave it be. What you want to change is your camera.
First calculate the bounding box of your model somewhere in 3D space.
Next calculate the radius of it by taking the max( aabb.max.x-aabb.min.x, aabb.max.y-aabb.min.y, aabb.max.z-aabb.min.z ). It's crude but it gets the job done.
To center the object in the viewport place the camera at the object position. If Y is your forward axis subtract the radius from Y. If Z is the forward axis then subtract radius from it instead. Subtract a fudge factor to get you past the pesky near plane so your model doesn't clip out. I use quaternions in my engine with a nice lookat() method. So call lookat() and pass in the center of the bounding box. Voila! You're object is centered in the viewport regardless of where it is in the world.
This always places the camera axis aligned so you might want to get fancy and transform the camera into model space instead, subtract off the radius, then lookat() the center again. Then you're always looking at the back of the model. The key is always the lookat().
Here's some example code from my engine. It checks to see if we're trying to frame a chunk of static terrain, if so look down from a height, or a light or a static mesh. A visual is anything that draws in the scene and there are dozens of different types. A Visual::Instance is a copy of the visual, or where to draw it.
```
void EnvironmentView::frameSelected(){
if( m_tSelection.toInstance() ){
Visual::Instance& I = m_tSelection.toInstance().cast();
Visual* pVisual = I.toVisual();
if( pVisual->isa( StaticTerrain::classid )){
toEditorCamera().toL2W().setPosition( pt3( 0, 0, 50000 ));
toEditorCamera().lookat( pt3( 0 ));
}else if( I.toFlags()->bIsLight ){
Visual::LightInstance& L = static_cast<Visual::LightInstance&>( I );
qst3& L2W = L.toL2W();
const sphere s( L2W.toPosition(), L2W.toScale() );
const f32 y =-(s.toCenter()+s.toRadius()).y();
const f32 z = (s.toCenter()+s.toRadius()).y();
qst3& camL2W = toEditorCamera().toL2W();
camL2W.setPosition(s.toCenter()+pt3( 0, y, z ));//45 deg above
toEditorCamera().lookat( s.toCenter() );
}else{
Mesh::handle hMesh = pVisual->getMesh();
if( hMesh ){
qst3& L2W = m_tSelection.toInstance()->toL2W();
vec4x4 M;
L2W.getMatrix( M );
aabb3 b0 = hMesh->toBounds();
b0.min = M * b0.min;
b0.max = M * b0.max;
aabb3 b1;
b1 += b0.min;
b1 += b0.max;
const sphere s( b1.toSphere() );
const f32 y =-(s.toCenter()+s.toRadius()*2.5f).y();
const f32 z = (s.toCenter()+s.toRadius()*2.5f).y();
qst3& camL2W = toEditorCamera().toL2W();
camL2W.setPosition( L2W.toPosition()+pt3( 0, y, z ));//45 deg above
toEditorCamera().lookat( b1.toOrigin() );
}
}
}
}
``` |
32,747,720 | I have a table called Product. I need to select all product records that have the MAX ManufatureDate.
Here is a sample of the table data:
```
Id ProductName ManufactureDate
1 Car 01-01-2015
2 Truck 05-01-2015
3 Computer 05-01-2015
4 Phone 02-01-2015
5 Chair 03-01-2015
```
This is what the result should be since the max date of all the records is 05-01-2015 and these 2 records have this max date:
```
Id ProductName ManufactureDate
2 Truck 05-01-2015
3 Computer 05-01-2015
```
The only way I can think of doing this is by first doing a query on the entire table to find out what the max date is and then store it in a variable @MaxManufatureDate. Then do a second query where ManufactureDate=@MaxManufactureDate. Something tells me there is a better way.
There are 1 million+ records in this table:
**Here is the way I am currently doing it:**
```
@MaxManufactureDate = select max(ManufactureDate) from Product
select * from Product where ManufactureDate = @MaxManufactureDate
```
If figure this is a lot better then doing a subselect in a where clause. Or is this the same exact thing as doing a subselect in a where clause? I am not sure if the query gets ran for each row regardless or if sqlserver stored the variable value in memory. | 2015/09/23 | [
"https://Stackoverflow.com/questions/32747720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5150565/"
] | ```
select * from product
where manufactureDate = (select max(manufactureDate) from product)
```
The inner select-statements selects the maximum date, the outer all products which have the date. | You can use a subQuery
```
SELECT *
FROM Product
WHERE ManufactureDate = (
SELECT ManufactureDate
FROM Product
ORDER BY ManufactureDate
LIMIT 1
);`
```
You may need to use `ASC` or `DESC` to collect the right order |
32,747,720 | I have a table called Product. I need to select all product records that have the MAX ManufatureDate.
Here is a sample of the table data:
```
Id ProductName ManufactureDate
1 Car 01-01-2015
2 Truck 05-01-2015
3 Computer 05-01-2015
4 Phone 02-01-2015
5 Chair 03-01-2015
```
This is what the result should be since the max date of all the records is 05-01-2015 and these 2 records have this max date:
```
Id ProductName ManufactureDate
2 Truck 05-01-2015
3 Computer 05-01-2015
```
The only way I can think of doing this is by first doing a query on the entire table to find out what the max date is and then store it in a variable @MaxManufatureDate. Then do a second query where ManufactureDate=@MaxManufactureDate. Something tells me there is a better way.
There are 1 million+ records in this table:
**Here is the way I am currently doing it:**
```
@MaxManufactureDate = select max(ManufactureDate) from Product
select * from Product where ManufactureDate = @MaxManufactureDate
```
If figure this is a lot better then doing a subselect in a where clause. Or is this the same exact thing as doing a subselect in a where clause? I am not sure if the query gets ran for each row regardless or if sqlserver stored the variable value in memory. | 2015/09/23 | [
"https://Stackoverflow.com/questions/32747720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5150565/"
] | ```
select * from product
where manufactureDate = (select max(manufactureDate) from product)
```
The inner select-statements selects the maximum date, the outer all products which have the date. | Try this pattern:
```
SELECT Id, ProductName, ManufactureDate
FROM (
SELECT Id, ProductName, ManufactureDate, MAX(ManufactureDate)OVER() AS MaxManufactureDate
FROM Product P
) P
WHERE P.MaxManufactureDate = P.ManufactureDate
```
Essentially, use a window function to get the data you're looking for in the inline view, then use the where clause in the outer query to match them. |
68,118,208 | ```
CREATE TABLE
mydataset.newtable (transaction_id INT64, transaction_date DATE)
PARTITION BY
transaction_date
AS SELECT transaction_id, transaction_date FROM mydataset.mytable
```
The docs don't specify whether the PARTITION BY clause supports "required". | 2021/06/24 | [
"https://Stackoverflow.com/questions/68118208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381013/"
] | Solved it finally by displaying more logs on the error message.
The key action is to update Gradle in my project level build.gradle file,
I changed:
```
classpath 'com.android.tools.build:gradle:4.0.2'
```
To:
```
classpath 'com.android.tools.build:gradle:4.2.1'
``` | I had a similar problem (yet not related to the NDK so I gave your solution a shot). I just want to preface that your answer helped me realize something that was horribly wrong with my installation of Android Studio in terms of configuration.
Uninstalling and Reinstalling the IDE helped me find the true culprit as to why Android Studio just wouldn't compile: Inadequate [SFML configuration for Android](https://github.com/SFML/SFML/wiki/Tutorial:-Building-SFML-for-Android) in my case. I don't have enough reputation points as this is a new account, or I'd upvote your answer for helping me realize what I did wrong.
Thank you! |
68,118,208 | ```
CREATE TABLE
mydataset.newtable (transaction_id INT64, transaction_date DATE)
PARTITION BY
transaction_date
AS SELECT transaction_id, transaction_date FROM mydataset.mytable
```
The docs don't specify whether the PARTITION BY clause supports "required". | 2021/06/24 | [
"https://Stackoverflow.com/questions/68118208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381013/"
] | Solved it finally by displaying more logs on the error message.
The key action is to update Gradle in my project level build.gradle file,
I changed:
```
classpath 'com.android.tools.build:gradle:4.0.2'
```
To:
```
classpath 'com.android.tools.build:gradle:4.2.1'
``` | **first** go to your pc dir wich android sdk is installed
```
in my pc dir is -> C:\Users\lotka-pc\AppData\Local\Android\Sdk\cmake
```
and delete the older version
**second** in your gradle file **module** you should change the version of cmake
```
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.18.1'
}
}
```
**third** - you should check dir
```
src/main/cpp/CmakeList.txt
```
and check the version
```
cmake_minimum_required(VERSION 3.10.2)
```
these will work :) |
68,118,208 | ```
CREATE TABLE
mydataset.newtable (transaction_id INT64, transaction_date DATE)
PARTITION BY
transaction_date
AS SELECT transaction_id, transaction_date FROM mydataset.mytable
```
The docs don't specify whether the PARTITION BY clause supports "required". | 2021/06/24 | [
"https://Stackoverflow.com/questions/68118208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381013/"
] | **first** go to your pc dir wich android sdk is installed
```
in my pc dir is -> C:\Users\lotka-pc\AppData\Local\Android\Sdk\cmake
```
and delete the older version
**second** in your gradle file **module** you should change the version of cmake
```
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.18.1'
}
}
```
**third** - you should check dir
```
src/main/cpp/CmakeList.txt
```
and check the version
```
cmake_minimum_required(VERSION 3.10.2)
```
these will work :) | I had a similar problem (yet not related to the NDK so I gave your solution a shot). I just want to preface that your answer helped me realize something that was horribly wrong with my installation of Android Studio in terms of configuration.
Uninstalling and Reinstalling the IDE helped me find the true culprit as to why Android Studio just wouldn't compile: Inadequate [SFML configuration for Android](https://github.com/SFML/SFML/wiki/Tutorial:-Building-SFML-for-Android) in my case. I don't have enough reputation points as this is a new account, or I'd upvote your answer for helping me realize what I did wrong.
Thank you! |
29,808,109 | So, I am trying to read in a text file using VB.NET and add the values of each line into a SQL Server database table. The code I have this far reads in the first line but keeps trying to read in the same line and fails. It adds the first, but like I stated it fails after the first one. I am quite sure the problem is in my loop and/or mysplit() array values. Any help in the right direction would be greatly appreciated. Thank you
```
Public Sub addTxtMember()
'Dim fileName As String
' fileName = Application.StartupPath + "c:\users\james needham\documents\visual studio 2013\projects\textfiletutorial1\textfiletutorial1\textfile1.txt"
Dim fileName As Integer = FreeFile()
'If File.Exists(fileName) Then
'Dim iofile As New StreamReader(fileName)
FileOpen(fileName, "TextFile1.txt", OpenMode.Input)
Dim ioline As String
'Dim iolines() As String
Dim eID, fName, lName, email, phone
Dim i As Integer = 0
ioline = LineInput(fileName)
'Do Until EOF(fileName)
While Not ioline = ""
' Dim endsplit = Split(ioline, "")
Dim mysplit = Split(ioline, ",")
eID = mysplit(0)
fName = mysplit(1)
lName = mysplit(2)
phone = mysplit(3)
email = mysplit(4)
' try
Dim strInsert As String = "INSERT INTO Employees1 (eID, fName, lName, phone, email) " & _
"VALUES (" & _
"'" & eID & "'," & _
"'" & fName & "', " & _
"'" & lName & "', " & _
"'" & phone & "', " & _
"'" & email & "')"
'MsgBox(strInsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strInsert, SQLCon)
'has to be non when inserting, updating, or deleting
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
' Catch ex As Exception
'MsgBox(ex.Message)
'End Try
End While
FileClose(fileName)
'Else
'MsgBox("fILE NOT FOUND")
' FileClose(fileName)
'End If
End Sub
``` | 2015/04/22 | [
"https://Stackoverflow.com/questions/29808109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3889163/"
] | Do the selection of the friend ID in a subquery, then join that with `users`.
```
SELECT u.firstname, u.lastname
FROM users as u
JOIN (SELECT DISTINCT IF(friends.sender = 75, friends.recipient, friends.sender) AS friend
FROM friends
WHERE 75 in (sender, recipient)) AS f
ON f.friend = u.id
``` | If I understood your question, you want to list all users first and lastname that received from user 75, if it's the case, this will work for you :
```
SELECT u.id,u.firstname,u.lastname FROM users u
JOIN friends f
ON u.id = f.sender OR u.id = f.recipient
WHERE f.sender=75
AND u.id<>75
```
And the `AND u.id<>75` does all the job so you get only the friends names. |
2,937,395 | I have a JavaScript class that has a method:
```
function someClass() {
this.someMethod = someClass_someMethod;
}
function someClass_someMethod() {
// make an AJAX request
}
```
The problem is that `someClass_someMethod()` needs to return the value of the AJAX request.
I'm using jQuery's `$.getJSON()` method to fetch the data. The data needs to be returned but it seems the only way to get the data is through a callback.
How can this be done? | 2010/05/30 | [
"https://Stackoverflow.com/questions/2937395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193619/"
] | Make your special view its own UIWindow. Set the UIWindow's windowLevel to UIWindowLevelStatusBar. If it still isn't on top, you can use bringSubviewToFront: on the UIWindow (remember, a UIWindow is a UIView) to bring it to the top of that level. | Answer here:
[Add UIView Above All Other Views, Including StatusBar](https://stackoverflow.com/questions/2666792/add-uiview-above-all-other-views-including-statusbar)
Have to create a UIWindow and set it's windowLevel property to statusBarLevel. |
276,080 | Given all variables are in $\mathbb{R}$, and $\{ a, d\} \neq 0$, solve for $\theta$:
$$a \sin^2 \theta + b \sin \theta + c + d \cos^2 \theta + e \cos \theta + f = 0$$
as posed in [this question](https://math.stackexchange.com/questions/4577312/solving-quadratic-function-of-sine-and-cosine#4577312).
The straightforward approach does not work:
```
Assuming[a != 0 \[And] b != 0,
Solve[a Sin[\[Theta]]^2 + b Sin[\[Theta]] + c + d Cos[\[Theta]]^2 +
e Cos[\[Theta]] + f == 0, \[Theta]]]
```
One can force "smart" substitutions, as given in the solution to the linked source problem. Is there a direct way to get the solution using *Mathematica*? | 2022/11/15 | [
"https://mathematica.stackexchange.com/questions/276080",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9735/"
] | Mathematica has no trouble solving
```
eqn = a Sin[θ]^2 + b Sin[θ] + c + d Cos[θ]^2 +
e Cos[θ] + f == 0;
subs = {Sin[θ] -> sin, Cos[θ] -> cos};
solution = Solve[(eqn /. subs) && sin^2 + cos^2 == 1, {sin, cos}];
```
though the solution is rather large, and may not be useful to you. | I think Weirstaß-substitution isn't "awkward" and gives a clear direct solution:
Transforming the equation using Weirstaß-substitution `\[Theta] -> 2 ArcTan[u\[Theta]]` gives
```
eqW = a Sin[\[Theta]]^2 + b Sin[\[Theta]] + c + d Cos[\[Theta]]^2 +
e Cos[\[Theta]] + f /. \[Theta] -> 2 ArcTan[u\[Theta]] // TrigExpand // Collect[#, {a, b, c, d, e, f}, Simplify] &
```
$$
\frac{4 a \text{u$\theta $}^2}{\left(\text{u$\theta$}^2+1\right)^2}+\frac{2 b \text{u$\theta $}}{\text{u$\theta$}^2+1}+c+\frac{d \left(\text{u$\theta$}^2-1\right)^2}{\left(\text{u$\theta$}^2+1\right)^2}+\frac{e \left(1-\text{u$\theta$}^2\right)}{\text{u$\theta $}^2+1}+f
$$
Mathematica
```
Solve[eqW == 0, u\[Theta], Reals] /. u\[Theta] -> Tan[\[Theta]/2];
```
finds four solutions in the form of Root objects
`{Tan[\[Theta]/2] ->Root[c + d + e + f + 2 b #1 + (4 a + 2 c - 2 d + 2 f) #1^2 + 2 b #1^3 + (c + d - e + f) #1^4 &, 1]}`
Solutions are lengthy. |
49,124,177 | I have a class where written is a function creating my button:
LoginButton.swift
```
func createButton() {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(Foo().buttonPressed(_:)), for: .touchUpInside)
}()
}
```
Now in my second class, Foo.swift, I have a function that just prints a statement
Foo.swift
```
@objc func buttonPressed(_ sender: UIButton) {
print("button was pressed")
}
```
When ran I get no errors except when I try to press the button, nothing happens. Nothing prints, the `UIButton` doesn't react in any way. Really not sure where the error occurs because Xcode isn't printing out any type of error or warning message. | 2018/03/06 | [
"https://Stackoverflow.com/questions/49124177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9449419/"
] | The action method is called in the target object. Thus, you have either to move `buttonPressed` to the class which contains `createButton` or to pass an instance of `Foo` as a target object.
But note that a button is not the owner of its targets. So, if you just write:
```
button.addTarget(Foo(), action: #selector(buttonPressed(_:)), for: .touchUpInside)
```
This will not work, because the `Foo` object is immediately released after that line. You must have a strong reference (e.g. a property) to `Foo()` like
```
let foo = Foo()
func createButton() {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(foo, action: #selector(buttonPressed(_:)), for: .touchUpInside)
}()
}
``` | Just pass `Selector` as function argument.
```
func createButtonWith(selector: Selector) {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: selector), for: .touchUpInside)
}()
}
```
And call this function like below...
```
createButtonWith(selector: #selector(Foo().buttonPressed(_:)))
``` |
49,124,177 | I have a class where written is a function creating my button:
LoginButton.swift
```
func createButton() {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(Foo().buttonPressed(_:)), for: .touchUpInside)
}()
}
```
Now in my second class, Foo.swift, I have a function that just prints a statement
Foo.swift
```
@objc func buttonPressed(_ sender: UIButton) {
print("button was pressed")
}
```
When ran I get no errors except when I try to press the button, nothing happens. Nothing prints, the `UIButton` doesn't react in any way. Really not sure where the error occurs because Xcode isn't printing out any type of error or warning message. | 2018/03/06 | [
"https://Stackoverflow.com/questions/49124177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9449419/"
] | You are missing with target. So make instant of target globally and make use of it as target for button action handler.
```
class ViewController: UIViewController {
let foo = Foo()
override func viewDidLoad() {
super.viewDidLoad()
createButton()
}
func createButton() {
let myButton: UIButton = {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = UIColor.red
button.setTitle("Tap me", for: .normal)
button.addTarget(self.foo, action: #selector(self.foo.buttonPressed(_:)), for: .touchUpInside)
return button
}()
myButton.center = self.view.center
self.view.addSubview(myButton)
}
}
```
Class Foo:
```
class Foo {
@objc func buttonPressed(_ sender: UIButton) {
print("button was pressed")
}
}
``` | Just pass `Selector` as function argument.
```
func createButtonWith(selector: Selector) {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: selector), for: .touchUpInside)
}()
}
```
And call this function like below...
```
createButtonWith(selector: #selector(Foo().buttonPressed(_:)))
``` |
32,173,907 | I am new to Apache. I have 2 jboss (Jboss as 7.1.1) and apache httpd server. I am using mod\_cluster for load balancing. I wish to hide the jboss url from user and wish to show the user clean urls.
for e.g.
www.mydomain.com will be having my static website.
subdomain.mydomain.com should go to mydomain.com:8080/myapp
subdomain.mydomain.com/mypage.xhtml should go to mydomain.com:8080/myapp/mypage.xhtml
sumdomain.mydomain.com/myservice should go to mydomain.com:8080/myapp/service.xhtml?name=myservice
I have tried many things with no success. Can some one tell me if it is possible or not. And if possible what are the things I should do.
Thanks a lot in advance.
Regards. | 2015/08/24 | [
"https://Stackoverflow.com/questions/32173907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392795/"
] | You could roll your own without too much coding using `do.call`:
```
partial <- function(f, ...) {
l <- list(...)
function(...) {
do.call(f, c(l, list(...)))
}
}
```
Basically `partial` returns a function that stores `f` as well as the originally provided arguments (stored in list `l`). When this function is called, it is passed both the arguments in `l` and any additional arguments. Here it is in action:
```
f <- function(a, b, c, d) a+b+c+d
p <- partial(f, a=2, c=3)
p(b=0, d=1)
# [1] 6
``` | You have also `Curry` from package `functional`:
```
library(functional)
f <- function(a, b, c, d) a+b+c+d
ff = Curry(f, a=2, c=10)
ff(1,5)
#[1] 18
ff(b=1,d=5)
#[1] 18
``` |
32,173,907 | I am new to Apache. I have 2 jboss (Jboss as 7.1.1) and apache httpd server. I am using mod\_cluster for load balancing. I wish to hide the jboss url from user and wish to show the user clean urls.
for e.g.
www.mydomain.com will be having my static website.
subdomain.mydomain.com should go to mydomain.com:8080/myapp
subdomain.mydomain.com/mypage.xhtml should go to mydomain.com:8080/myapp/mypage.xhtml
sumdomain.mydomain.com/myservice should go to mydomain.com:8080/myapp/service.xhtml?name=myservice
I have tried many things with no success. Can some one tell me if it is possible or not. And if possible what are the things I should do.
Thanks a lot in advance.
Regards. | 2015/08/24 | [
"https://Stackoverflow.com/questions/32173907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392795/"
] | There are functions in the `pryr` package that can handle this, namely `partial()`
```
f <- function(a, b, c, d) a + b + c + d
pryr::partial(f, a = 1, c = 2)
# function (...)
# f(a = 1, c = 2, ...)
```
So you can use it like this -
```
new_fun <- pryr::partial(f, a = 1, c = 2)
new_fun(b = 2, d = 5)
# [1] 10
## or if you are daring ...
new_fun(2, 5)
# [1] 10
```
You could also simply change `f()`'s formal arguments with
```
f <- function(a, b, c, d) a + b + c + d
formals(f)[c("a", "c")] <- list(1, 2)
f
# function (a = 1, b, c = 2, d)
# a + b + c + d
f(b = 2, d = 5)
# [1] 10
```
But with the latter, you **must** name the `b` and `d` arguments in `f()` to avoid an error when you want to leave `a` and `c` as their default values. | You have also `Curry` from package `functional`:
```
library(functional)
f <- function(a, b, c, d) a+b+c+d
ff = Curry(f, a=2, c=10)
ff(1,5)
#[1] 18
ff(b=1,d=5)
#[1] 18
``` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | Does the button need to be absolutely positioned? If so, you could specify a width and then a negative left margin:
```
.btn-bot{
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
bottom:0px;
}
```
[fiddle](http://jsfiddle.net/3QguR/8/) | I know this has been answered a long time ago, but I couldn't use display:table on the parent container so I had to find another way around.
It turned out that this worked just fine:
```
.container{
position:absolute;
}
.button{
position:absolute;
bottom: 5px;
left: 0%;
right: 0%;
text-align: center;
}
```
Edit: This works if your button is a `<div>`, not for an actual `<button>` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | Does the button need to be absolutely positioned? If so, you could specify a width and then a negative left margin:
```
.btn-bot{
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
bottom:0px;
}
```
[fiddle](http://jsfiddle.net/3QguR/8/) | You can use [`align-items: flex-end`](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) like so:
```css
html,
body {
height: 100%;
}
.flex-container {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.center {
width: 200px;
height: 200px;
background: #0088cc;
display: flex;
align-items: flex-end;
}
.btn-bot {
margin: 0 auto;
display: block;
}
```
```html
<div class="flex-container">
<div class="center">
<button class="btn-bot">Bottom button</button>
</div>
</div>
``` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | Give the parent element…
```
display: table; text-align: center;
```
…and its child element…
```
display: table-cell; vertical-align: bottom;
```
This way you do not need to know the width of the child element in case it changes, thus requiring no negative margins or workarounds. | One way of doing this would be to give it an absolute width and then a margin half of that:
```
width: 250px;
margin-left: -125px;
```
Another way would be to give the `div` the following line-height and remove all styles from the `button`:
```
line-height: 398px;
``` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | Give the parent element…
```
display: table; text-align: center;
```
…and its child element…
```
display: table-cell; vertical-align: bottom;
```
This way you do not need to know the width of the child element in case it changes, thus requiring no negative margins or workarounds. | For example write like this if you have position absolute:
```
.btn-bot{
position:absolute;
margin-left:-50px;
left:50%;
width:100px;
bottom:0px;
}
```
Note: give margin-left half of the width of the button.
[JSFiddle demo](http://jsfiddle.net/3QguR/12/) |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | For example write like this if you have position absolute:
```
.btn-bot{
position:absolute;
margin-left:-50px;
left:50%;
width:100px;
bottom:0px;
}
```
Note: give margin-left half of the width of the button.
[JSFiddle demo](http://jsfiddle.net/3QguR/12/) | This is what worked for me and I think is what several people were trying to get at.
Just use a full width wrapper div with the button centered inside it.
```
<div class="outer">
<div class="inner-button-container">
<a href="#">The Button</a>
</div>
</div>
.outer{
position:relative;
height:200px;
width:500px;
background-color:lightgreen;
}
.inner-button-container{
background-color:grey;
position:absolute;
bottom:0;
right:0;
left:0;
text-align:center;
}
a{
margin:auto;
background-color:white;
}
```
Result:
[](https://i.stack.imgur.com/nl5YX.png)
[Fiddle](http://jsfiddle.net/s157fa98/) |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | One way of doing this would be to give it an absolute width and then a margin half of that:
```
width: 250px;
margin-left: -125px;
```
Another way would be to give the `div` the following line-height and remove all styles from the `button`:
```
line-height: 398px;
``` | You can use [`align-items: flex-end`](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) like so:
```css
html,
body {
height: 100%;
}
.flex-container {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.center {
width: 200px;
height: 200px;
background: #0088cc;
display: flex;
align-items: flex-end;
}
.btn-bot {
margin: 0 auto;
display: block;
}
```
```html
<div class="flex-container">
<div class="center">
<button class="btn-bot">Bottom button</button>
</div>
</div>
``` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | For example write like this if you have position absolute:
```
.btn-bot{
position:absolute;
margin-left:-50px;
left:50%;
width:100px;
bottom:0px;
}
```
Note: give margin-left half of the width of the button.
[JSFiddle demo](http://jsfiddle.net/3QguR/12/) | I used `table-row` to combine text and button in one container:
```
#out{
display:table;
position:absolute;
}
#out div#textContainer{
display:table-row;
}
#out div#text{
display:table-cell;
vertical-align:top;
}
#out div#buttonContainer{
display:table-row;
text-align:center;
}
#out div#button{
display:table-cell;
vertical-align:bottom;
}
```
[CodePen](https://codepen.io/mortalis/pen/eygBPG) |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | For example write like this if you have position absolute:
```
.btn-bot{
position:absolute;
margin-left:-50px;
left:50%;
width:100px;
bottom:0px;
}
```
Note: give margin-left half of the width of the button.
[JSFiddle demo](http://jsfiddle.net/3QguR/12/) | I know this has been answered a long time ago, but I couldn't use display:table on the parent container so I had to find another way around.
It turned out that this worked just fine:
```
.container{
position:absolute;
}
.button{
position:absolute;
bottom: 5px;
left: 0%;
right: 0%;
text-align: center;
}
```
Edit: This works if your button is a `<div>`, not for an actual `<button>` |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | For example write like this if you have position absolute:
```
.btn-bot{
position:absolute;
margin-left:-50px;
left:50%;
width:100px;
bottom:0px;
}
```
Note: give margin-left half of the width of the button.
[JSFiddle demo](http://jsfiddle.net/3QguR/12/) | Does the button need to be absolutely positioned? If so, you could specify a width and then a negative left margin:
```
.btn-bot{
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
bottom:0px;
}
```
[fiddle](http://jsfiddle.net/3QguR/8/) |
22,162,560 | How to make a button be at the bottom of div and at the center of it at the same time?
```css
.Center {
width: 200px;
height: 200px;
background: #0088cc;
margin: auto;
padding: 2%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.btn-bot {
position: absolute;
bottom: 0px;
}
```
```html
<div class=Center align='center'>
<button class='btn-bot'>Bottom button</button>
</div>
``` | 2014/03/04 | [
"https://Stackoverflow.com/questions/22162560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789810/"
] | One way of doing this would be to give it an absolute width and then a margin half of that:
```
width: 250px;
margin-left: -125px;
```
Another way would be to give the `div` the following line-height and remove all styles from the `button`:
```
line-height: 398px;
``` | I know this has been answered a long time ago, but I couldn't use display:table on the parent container so I had to find another way around.
It turned out that this worked just fine:
```
.container{
position:absolute;
}
.button{
position:absolute;
bottom: 5px;
left: 0%;
right: 0%;
text-align: center;
}
```
Edit: This works if your button is a `<div>`, not for an actual `<button>` |
60,878,489 | When I generate the production version of my PWA built with VueJS I got this error in Google Chrome after deploying it to my server:
* `Uncaught SyntaxError: Unexpected token '<'` in app.21fde857.js:1
* `Uncaught SyntaxError: Unexpected token '<'` in chunk-vendors.d1f8f63f.js:1
I take a look in the Network tab of the console and in both files `chunk-vendors.d1f8f63f.js` and `app.21fde857.js` the `index.html` is coming back with a status 200.
Why this occurs?
**OBS:** Locally this works perfectly. | 2020/03/27 | [
"https://Stackoverflow.com/questions/60878489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12542704/"
] | Here is a solution that doesn't require hand-editing your dist assets.
Simply add the following property to the exports of your vue.config.js:
`publicPath: './'` | 1. Add <%= BASE\_URL %> on all links in index.html
(Example: `<link href="<%= BASE_URL %>favicon/apple-icon-144x144.png">`)
2. And add the **base** tag (Example: `<base href="https://mywebsite.com" />`) in the **head** tag, and now this works perfectly.
**Old answer**
I found a solution. I have to add a manually a `.` in every `src` in the **index.html** file in the `dist/` folder. (Example: `<link href=./js/chunk-vendors.d1f8f63f.js rel=preload as=script>`)
In the **index.html** of the source code, I have added **<%= BASE\_URL %>** in every link, (Example: `<link rel="apple-touch-icon" sizes="144x144" href="<%= BASE_URL %>favicon/apple-icon-144x144.png">`), as well as in [this question](https://stackoverflow.com/questions/51210795/vue-cli-uncaught-syntaxerror-unexpected-token), but this doesn't work, I think that this error occurs because of it. |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Just use specifc CSS rules as:
```
.yellow:hover ~ #slider {
background: yellow !important;
}
```
[SEE jsFiddle](http://jsfiddle.net/GJQA5/1/) | My approach:
**Working:**
<http://jsfiddle.net/skozz/YW24L/1/>
**Pro tip:**
You can refactor this code using array + each/for loop.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
});
$('.blue').hover()
$( ".blue" ).hover(
function() {
$( '#slider' ).css( "background", "blue" );
}
);
$( ".orange" ).hover(
function() {
$( '#slider' ).css( "background", "orange" );
}
);
$( ".yellow" ).hover(
function() {
$( '#slider' ).css( "background", "yellow" );
}
);
$( ".lime" ).hover(
function() {
$( '#slider' ).css( "background", "lime" );
}
);
});
``` |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Just use specifc CSS rules as:
```
.yellow:hover ~ #slider {
background: yellow !important;
}
```
[SEE jsFiddle](http://jsfiddle.net/GJQA5/1/) | Here is something much more simple: [Fiddle](http://jsfiddle.net/tomanow/GJQA5/7/)
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
$slider.css('background', $(this).parent().prop('class'));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
$slider.css('background', 'red');
});
});
``` |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Just use specifc CSS rules as:
```
.yellow:hover ~ #slider {
background: yellow !important;
}
```
[SEE jsFiddle](http://jsfiddle.net/GJQA5/1/) | Here is the update code:
**new CSS**
```
#slider.blue {
background-color: blue;
}
#slider.orange {
background-color: orange;
}
#slider.yellow {
background-color: yellow;
}
#slider.lime {
background-color: lime;
}
```
**JS COde**
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth,
}).addClass($(this).parent().attr('class'));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
}).removeAttr('class');
});
});
```
[**Updated Fiddle**](http://jsfiddle.net/GJQA5/6/) |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Just use specifc CSS rules as:
```
.yellow:hover ~ #slider {
background: yellow !important;
}
```
[SEE jsFiddle](http://jsfiddle.net/GJQA5/1/) | I like the CSS solution of A.Wolff best, but here's an alternative.
The changes are only made in your jQuery code.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origColor", $slider.css("background-color"))
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
elColor = $el.css("color");
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
}).css('background-color', $el.css("color"));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
}).css('background-color', $slider.data("origColor"));;
});
});
```
Check your [**updated Fiddle**](http://jsfiddle.net/GJQA5/8/). |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Here is something much more simple: [Fiddle](http://jsfiddle.net/tomanow/GJQA5/7/)
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
$slider.css('background', $(this).parent().prop('class'));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
$slider.css('background', 'red');
});
});
``` | My approach:
**Working:**
<http://jsfiddle.net/skozz/YW24L/1/>
**Pro tip:**
You can refactor this code using array + each/for loop.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
});
$('.blue').hover()
$( ".blue" ).hover(
function() {
$( '#slider' ).css( "background", "blue" );
}
);
$( ".orange" ).hover(
function() {
$( '#slider' ).css( "background", "orange" );
}
);
$( ".yellow" ).hover(
function() {
$( '#slider' ).css( "background", "yellow" );
}
);
$( ".lime" ).hover(
function() {
$( '#slider' ).css( "background", "lime" );
}
);
});
``` |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | Here is the update code:
**new CSS**
```
#slider.blue {
background-color: blue;
}
#slider.orange {
background-color: orange;
}
#slider.yellow {
background-color: yellow;
}
#slider.lime {
background-color: lime;
}
```
**JS COde**
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth,
}).addClass($(this).parent().attr('class'));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
}).removeAttr('class');
});
});
```
[**Updated Fiddle**](http://jsfiddle.net/GJQA5/6/) | My approach:
**Working:**
<http://jsfiddle.net/skozz/YW24L/1/>
**Pro tip:**
You can refactor this code using array + each/for loop.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
});
$('.blue').hover()
$( ".blue" ).hover(
function() {
$( '#slider' ).css( "background", "blue" );
}
);
$( ".orange" ).hover(
function() {
$( '#slider' ).css( "background", "orange" );
}
);
$( ".yellow" ).hover(
function() {
$( '#slider' ).css( "background", "yellow" );
}
);
$( ".lime" ).hover(
function() {
$( '#slider' ).css( "background", "lime" );
}
);
});
``` |
22,094,668 | I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606389/"
] | I like the CSS solution of A.Wolff best, but here's an alternative.
The changes are only made in your jQuery code.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origColor", $slider.css("background-color"))
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
elColor = $el.css("color");
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
}).css('background-color', $el.css("color"));
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
}).css('background-color', $slider.data("origColor"));;
});
});
```
Check your [**updated Fiddle**](http://jsfiddle.net/GJQA5/8/). | My approach:
**Working:**
<http://jsfiddle.net/skozz/YW24L/1/>
**Pro tip:**
You can refactor this code using array + each/for loop.
```
$(function() {
$("#example-one").append("<div id='slider'></div>");
var $slider = $("#slider");
$slider
.width($(".current_page").width())
.css("left", $(".current_page a").position().left)
.data("origLeft", $slider.position().left)
.data("origWidth", $slider.width());
$("#example-one div").find("a").hover(function() {
$el = $(this);
leftPos = $el.position().left;
newWidth = $el.parent().width();
$slider.stop().animate({
left: leftPos,
width: newWidth
});
}, function() {
$slider.stop().animate({
left: $slider.data("origLeft"),
width: $slider.data("origWidth")
});
});
$('.blue').hover()
$( ".blue" ).hover(
function() {
$( '#slider' ).css( "background", "blue" );
}
);
$( ".orange" ).hover(
function() {
$( '#slider' ).css( "background", "orange" );
}
);
$( ".yellow" ).hover(
function() {
$( '#slider' ).css( "background", "yellow" );
}
);
$( ".lime" ).hover(
function() {
$( '#slider' ).css( "background", "lime" );
}
);
});
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.