input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Resetting a setTimeout
<p>I have the following:</p>
<pre><code>window.setTimeout(function() {
window.location.href = 'file.php';
}, 115000);
</code></pre>
<p>How can I, via a .click function, reset the counter midway through the countdown?</p> | <p>You can store a reference to that timeout, and then call <a href="https://developer.mozilla.org/en/DOM/window.clearTimeout" rel="noreferrer"><code>clearTimeout</code></a> on that reference.</p>
<pre><code>// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);
// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);
// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);
</code></pre> | {
"question_id": 1472705,
"question_date": "2009-09-24T16:12:11.833Z",
"question_score": 207,
"tags": "javascript|jquery",
"answer_id": 1472717,
"answer_date": "2009-09-24T16:15:08.550Z",
"answer_score": 310
} |
Please answer the following Stack Overflow question:
Title: How to suppress Pandas Future warning ?
<p>When I run the program, Pandas gives 'Future warning' like below every time.</p>
<pre><code>D:\Python\lib\site-packages\pandas\core\frame.py:3581: FutureWarning: rename with inplace=True will return None from pandas 0.11 onward
" from pandas 0.11 onward", FutureWarning)
</code></pre>
<p>I got the msg, but I just want to stop Pandas showing such msg again and again, is there any buildin parameter that I can set to let Pandas not pop up the 'Future warning' ?</p> | <p>Found this on <a href="https://github.com/pydata/pandas/issues/2841" rel="noreferrer">github</a>...</p>
<pre><code>import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
</code></pre> | {
"question_id": 15777951,
"question_date": "2013-04-03T02:37:48.730Z",
"question_score": 207,
"tags": "python|pandas|suppress-warnings|future-warning",
"answer_id": 15778297,
"answer_date": "2013-04-03T03:19:42.940Z",
"answer_score": 428
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Trap and Interrupt?
<p>What is the difference between Trap and Interrupt?</p>
<p>If the terminology is different for different systems, then what do they mean on x86?</p> | <p>A <strong><a href="http://en.wikipedia.org/wiki/Kernel_trap" rel="noreferrer">trap</a></strong> is an exception in a user process. It's caused by division by zero or invalid memory access. It's also the usual way to invoke a kernel routine (a <a href="http://en.wikipedia.org/wiki/System_call" rel="noreferrer">system call</a>) because those run with a higher priority than user code. Handling is synchronous (so the user code is suspended and continues afterwards). In a sense they are "active" - most of the time, the code expects the trap to happen and relies on this fact.</p>
<p>An <strong><a href="http://en.wikipedia.org/wiki/Interrupt" rel="noreferrer">interrupt</a></strong> is something generated by the hardware (devices like the hard disk, graphics card, I/O ports, etc). These are asynchronous (i.e. they don't happen at predictable places in the user code) or "passive" since the interrupt handler has to wait for them to happen eventually.</p>
<p>You can also see a trap as a kind of CPU-internal interrupt since the handler for trap handler looks like an interrupt handler (registers and stack pointers are saved, there is a context switch, execution can resume in some cases where it left off).</p> | {
"question_id": 3149175,
"question_date": "2010-06-30T12:23:24.907Z",
"question_score": 207,
"tags": "x86|operating-system|kernel|interrupt|cpu-architecture",
"answer_id": 3149217,
"answer_date": "2010-06-30T12:28:26.973Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Visual Studio opens the default browser instead of Internet Explorer
<p>When I debug in Visual Studio, Firefox opens and that is annoying because of the hookups that Internet Explorer and Visual Studio have, such as when you close the Internet Explorer browser that starting debug opened, Visual Studio stops debugging. How can I get Visual Studio to open Internet Explorer instead without having to set Internet Explorer as my default browser?</p> | <p>Scott Guthrie has made a post on <a href="http://weblogs.asp.net/scottgu/archive/2005/11/18/430943.aspx" rel="noreferrer">how to change Visual Studio's default browser</a>:</p>
<blockquote>
<p>1) Right click on a .aspx page in your
solution explorer</p>
<p>2) Select the "browse with" context
menu option</p>
<p>3) In the dialog you can select or add
a browser. If you want Firefox in the
list, click "add" and point to the
firefox.exe filename</p>
<p>4) Click the "Set as Default" button
to make this the default browser when
you run any page on the site.</p>
</blockquote>
<p>I however dislike the fact that this isn't as straightforward as it should be.</p> | {
"question_id": 79954,
"question_date": "2008-09-17T04:23:35.510Z",
"question_score": 207,
"tags": "visual-studio|internet-explorer",
"answer_id": 79965,
"answer_date": "2008-09-17T04:24:58.083Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Copy values from one column to another in the same table
<p>How can I make a copy values from one column to another?</p>
<p>I have:</p>
<pre><code>Database name: list
-------------------
number | test
-------------------
123456 | somedata
123486 | somedata1
232344 | 34
</code></pre>
<p>I want to have:</p>
<pre><code>Database name: list
----------------
number | test
----------------
123456 | 123456
123486 | 123486
232344 | 232344
</code></pre>
<p>What MySQL query should I have?</p> | <p>Short answer for the code in question is:</p>
<pre><code>UPDATE `table` SET test=number
</code></pre>
<p>Here <code>table</code> is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to <a href="https://stackoverflow.com/questions/7857278/what-is-the-meaning-of-grave-accent-aka-backtick-quoted-characters-in-mysql">escape keywords</a> (and <code>TABLE</code> is a keyword in that case).</p>
<hr />
<h1>BEWARE!</h1>
<p>This is pretty dangerous query which will <strong>wipe everything</strong> in column <code>test</code> in every row of your table replacing it by the <code>number</code> (regardless of it's value)</p>
<p>It is more common to use <code>WHERE</code> clause to limit your query to only specific set of rows:</p>
<pre><code>UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
</code></pre> | {
"question_id": 9001939,
"question_date": "2012-01-25T11:28:38.163Z",
"question_score": 207,
"tags": "mysql|database",
"answer_id": 9001957,
"answer_date": "2012-01-25T11:30:06.680Z",
"answer_score": 431
} |
Please answer the following Stack Overflow question:
Title: Creating a segue programmatically
<p>I have a common <code>UIViewController</code> that all my <code>UIViewsControllers</code> extend to reuse some common operations.</p>
<p>I want to set up a segue on this "Common" <code>UIViewController</code> so that all the other <code>UIViewControllers</code> inherit. </p>
<p>I am trying to figure out how do I do that programmatically.</p>
<p>I guess that the question could also be how do I set a <code>segue</code> for all my <code>UIViewControllers</code> without going into the story board and do them by hand.</p> | <p>By definition a segue can't really exist independently of a storyboard. It's even there in the name of the class: <code>UIStoryboardSegue</code>. You don't create segues programmatically - it is the storyboard runtime that creates them for you. You can normally call <code>performSegueWithIdentifier:</code> in your view controller's code, but this relies on having a segue already set up in the storyboard to reference.</p>
<p>What I think you are asking though is how you can create a method in your common view controller (base class) that will transition to a new view controller, and will be inherited by all derived classes. You could do this by creating a method like this one to your base class view controller:</p>
<pre><code>- (IBAction)pushMyNewViewController
{
MyNewViewController *myNewVC = [[MyNewViewController alloc] init];
// do any setup you need for myNewVC
[self presentModalViewController:myNewVC animated:YES];
}
</code></pre>
<p>and then in your derived class, call that method when the appropriate button is clicked or table row is selected or whatever.</p> | {
"question_id": 9674685,
"question_date": "2012-03-12T20:56:06.867Z",
"question_score": 207,
"tags": "ios|objective-c|segue",
"answer_id": 9675186,
"answer_date": "2012-03-12T21:38:55.557Z",
"answer_score": 170
} |
Please answer the following Stack Overflow question:
Title: How to sort Counter by value? - python
<p>Other than doing list comprehensions of reversed list comprehension, is there a pythonic way to sort Counter by value? If so, it is faster than this:</p>
<pre><code>>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('b', 3), ('a', 5), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 7), ('a', 5), ('b', 3)
</code></pre> | <p>Use the <a href="http://docs.python.org/library/collections.html#collections.Counter.most_common" rel="noreferrer"><code>Counter.most_common()</code> method</a>, it'll sort the items <em>for you</em>:</p>
<pre><code>>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
</code></pre>
<p>It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a <code>heapq</code> is used instead of a straight sort:</p>
<pre><code>>>> x.most_common(1)
[('c', 7)]
</code></pre>
<p>Outside of counters, sorting can always be adjusted based on a <code>key</code> function; <code>.sort()</code> and <code>sorted()</code> both take callable that lets you specify a value on which to sort the input sequence; <code>sorted(x, key=x.get, reverse=True)</code> would give you the same sorting as <code>x.most_common()</code>, but only return the keys, for example:</p>
<pre><code>>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
</code></pre>
<p>or you can sort on only the value given <code>(key, value)</code> pairs:</p>
<pre><code>>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
</code></pre>
<p>See the <a href="http://docs.python.org/howto/sorting.html" rel="noreferrer">Python sorting howto</a> for more information.</p> | {
"question_id": 20950650,
"question_date": "2014-01-06T13:02:52.040Z",
"question_score": 207,
"tags": "python|sorting|collections|counter",
"answer_id": 20950686,
"answer_date": "2014-01-06T13:05:18.577Z",
"answer_score": 381
} |
Please answer the following Stack Overflow question:
Title: Work on a remote project with Eclipse via SSH
<p>I have the following boxes:</p>
<p>a) A Windows box with Eclipse CDT,<br />
b) A Linux box, accessible for me only via SSH.</p>
<p>Both the compiler and the hardware required to build and run my project is only on machine B.</p>
<p>I'd like to work "transparently" from a Windows box on that project using Eclipse CDT and be able to build, run and debug the project remotely from within the IDE.</p>
<p>How do I set up that:</p>
<ul>
<li>The building will work? Any simpler solutions than writing a local makefile which would <code>rsync</code> the project and then call a remote makefile to initiate the actual build? Does Eclipse managed build have a feature for that?</li>
<li>The debugging will work?</li>
<li>Preferably - the Eclipse CDT code indexing will work? Do I have to copy all required header files from machine B to machine A and add them to include path manually?</li>
</ul> | <p>Try the <a href="http://tmober.blogspot.com/2006/11/remote-system-explorer-10-is-released.html">Remote System Explorer</a> (RSE). It's a set of plug-ins to do exactly what you want. </p>
<p>RSE may already be included in your current Eclipse installation. To check in Eclipse Indigo go to <strong>Window</strong> > <strong>Open Perspective</strong> > <strong>Other...</strong> and choose <strong>Remote System Explorer</strong> from the <em>Open Perspective</em> dialog to open the RSE perspective.</p>
<p>To create an SSH remote project from the RSE perspective in Eclipse:</p>
<ol>
<li>Define a new connection and choose SSH Only from the Select Remote System Type screen in the New Connection dialog.</li>
<li>Enter the connection information then choose Finish.</li>
<li>Connect to the new host. (Assumes SSH keys are already setup.)</li>
<li>Once connected, drill down into the host's <em>Sftp Files</em>, choose a folder and select <strong>Create Remote Project</strong> from the item's context menu. (Wait as the remote project is created.)</li>
</ol>
<p>If done correctly, there should now be a new remote project accessible from the Project Explorer and other perspectives within eclipse. With the SSH connection set-up correctly passwords can be made an optional part of the normal SSH authentication process. A remote project with Eclipse via SSH is now created.</p> | {
"question_id": 4216822,
"question_date": "2010-11-18T16:00:19.300Z",
"question_score": 207,
"tags": "c|eclipse|ssh|eclipse-cdt|remote-debugging",
"answer_id": 4216878,
"answer_date": "2010-11-18T16:06:39.743Z",
"answer_score": 230
} |
Please answer the following Stack Overflow question:
Title: How to highlight a current menu item?
<p>Does AngularJS help in any way with setting an <code>active</code> class on the link for the current page?</p>
<p>I imagine there is some magical way this is done, but I can't seem to find.</p>
<p>My menu looks like:</p>
<pre><code> <ul>
<li><a class="active" href="/tasks">Tasks</a>
<li><a href="/actions">Tasks</a>
</ul>
</code></pre>
<p>and I have controllers for each of them in my routes: <code>TasksController</code> and <code>ActionsController</code>.</p>
<p>But I can't figure out a way to bind the "active" class on the <code>a</code> links to the controllers.</p>
<p>Any hints?</p> | <p>on view</p>
<pre><code><a ng-class="getClass('/tasks')" href="/tasks">Tasks</a>
</code></pre>
<p>on controller</p>
<pre><code>$scope.getClass = function (path) {
return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}
</code></pre>
<p>With this the tasks link will have the active class in any url that starts with '/tasks'(e.g. '/tasks/1/reports')</p> | {
"question_id": 12592472,
"question_date": "2012-09-25T23:18:57.440Z",
"question_score": 207,
"tags": "angularjs",
"answer_id": 12592693,
"answer_date": "2012-09-25T23:46:44.670Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: Replace multiple whitespaces with single whitespace in JavaScript string
<p>I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?</p> | <p>Something like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)</code></pre>
</div>
</div>
</p> | {
"question_id": 6163169,
"question_date": "2011-05-28T17:16:57.070Z",
"question_score": 207,
"tags": "javascript|string|trim",
"answer_id": 6163180,
"answer_date": "2011-05-28T17:18:54.270Z",
"answer_score": 388
} |
Please answer the following Stack Overflow question:
Title: RabbitMQ / AMQP: single queue, multiple consumers for same message?
<p>I am just starting to use RabbitMQ and AMQP in general.</p>
<ul>
<li>I have a queue of messages</li>
<li>I have multiple consumers, which I would like to do different things with the <strong>same message</strong>. </li>
</ul>
<p>Most of the RabbitMQ documentation seems to be focused on round-robin, ie where a single message is consumed by a single consumer, with the load being spread between each consumer. This is indeed the behavior I witness. </p>
<p>An example: the producer has a single queue, and send messages every 2 sec:</p>
<pre><code>var amqp = require('amqp');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
var count = 1;
connection.on('ready', function () {
var sendMessage = function(connection, queue_name, payload) {
var encoded_payload = JSON.stringify(payload);
connection.publish(queue_name, encoded_payload);
}
setInterval( function() {
var test_message = 'TEST '+count
sendMessage(connection, "my_queue_name", test_message)
count += 1;
}, 2000)
})
</code></pre>
<p>And here's a consumer:</p>
<pre><code>var amqp = require('amqp');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
connection.on('ready', function () {
connection.queue("my_queue_name", function(queue){
queue.bind('#');
queue.subscribe(function (message) {
var encoded_payload = unescape(message.data)
var payload = JSON.parse(encoded_payload)
console.log('Recieved a message:')
console.log(payload)
})
})
})
</code></pre>
<p>If I start the consumer twice, <strong>I can see that each consumer is consuming alternate messages in round-robin behavior. Eg, I'll see messages 1, 3, 5 in one terminal, 2, 4, 6 in the other</strong>.</p>
<p>My question is: </p>
<ul>
<li><p>Can I have each consumer receive the same messages? Ie, both consumers get message 1, 2, 3, 4, 5, 6? What is this called in AMQP/RabbitMQ speak? How is it normally configured?</p></li>
<li><p>Is this commonly done? Should I just have the exchange route the message into two separate queues, with a single consumer, instead? </p></li>
</ul> | <p><strong>Can I have each consumer receive the same messages? Ie, both consumers get message 1, 2, 3, 4, 5, 6? What is this called in AMQP/RabbitMQ speak? How is it normally configured?</strong></p>
<p>No, not if the consumers are on the same queue. From RabbitMQ's <a href="http://www.rabbitmq.com/tutorials/amqp-concepts.html" rel="noreferrer">AMQP Concepts</a> guide:</p>
<blockquote>
<p>it is important to understand that, in AMQP 0-9-1, messages are load balanced between consumers.</p>
</blockquote>
<p>This seems to imply that <strong>round-robin behavior within a queue is a given</strong>, and not configurable. Ie, separate queues are required in order to have the same message ID be handled by multiple consumers.</p>
<p><strong>Is this commonly done? Should I just have the exchange route the message into two separate queues, with a single consumer, instead?</strong></p>
<p>No it's not, single queue/multiple consumers with each consumer handling the same message ID isn't possible. Having the exchange route the message onto into two separate queues is indeed better.</p>
<p>As I don't require too complex routing, a <strong>fanout exchange</strong> will handle this nicely. I didn't focus too much on Exchanges earlier as node-amqp has the concept of a 'default exchange' allowing you to publish messages to a connection directly, however most AMQP messages are published to a specific exchange.</p>
<p>Here's my fanout exchange, both sending and receiving:</p>
<pre><code>var amqp = require('amqp');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
var count = 1;
connection.on('ready', function () {
connection.exchange("my_exchange", options={type:'fanout'}, function(exchange) {
var sendMessage = function(exchange, payload) {
console.log('about to publish')
var encoded_payload = JSON.stringify(payload);
exchange.publish('', encoded_payload, {})
}
// Recieve messages
connection.queue("my_queue_name", function(queue){
console.log('Created queue')
queue.bind(exchange, '');
queue.subscribe(function (message) {
console.log('subscribed to queue')
var encoded_payload = unescape(message.data)
var payload = JSON.parse(encoded_payload)
console.log('Recieved a message:')
console.log(payload)
})
})
setInterval( function() {
var test_message = 'TEST '+count
sendMessage(exchange, test_message)
count += 1;
}, 2000)
})
})
</code></pre> | {
"question_id": 10620976,
"question_date": "2012-05-16T14:43:08.350Z",
"question_score": 207,
"tags": "node.js|messaging|rabbitmq|amqp|node-amqp",
"answer_id": 10621516,
"answer_date": "2012-05-16T15:14:13.767Z",
"answer_score": 156
} |
Please answer the following Stack Overflow question:
Title: How to enumerate a range of numbers starting at 1
<p>I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0):</p>
<pre><code>[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
</code></pre>
<p>I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot...</p>
<p>Using Python 2.5:</p>
<pre><code>>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]
</code></pre>
<p>Does anyone know a way to get that desired result in Python 2.5?</p> | <p>As you already mentioned, this is straightforward to do in Python 2.6 or newer:</p>
<pre><code>enumerate(range(2000, 2005), 1)
</code></pre>
<p>Python 2.5 and older do not support the <code>start</code> parameter so instead you could create two range objects and zip them:</p>
<pre><code>r = xrange(2000, 2005)
r2 = xrange(1, len(r) + 1)
h = zip(r2, r)
print h
</code></pre>
<p>Result:</p>
<pre>
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
</pre>
<p>If you want to create a generator instead of a list then you can use <a href="http://docs.python.org/library/itertools.html#itertools.izip" rel="noreferrer">izip</a> instead.</p> | {
"question_id": 3303608,
"question_date": "2010-07-21T20:37:35.457Z",
"question_score": 207,
"tags": "python",
"answer_id": 3303640,
"answer_date": "2010-07-21T20:41:11.657Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: Vuex - passing multiple parameters to mutation
<p>I am trying to authenticate a user using vuejs and laravel's passport.<br><br><strong>I am not able to figure out how to send multiple parameters to the vuex mutation via an action.</strong><br><br>
<strong>- store -</strong></p>
<pre><code>export default new Vuex.Store({
state: {
isAuth: !!localStorage.getItem('token')
},
getters: {
isLoggedIn(state) {
return state.isAuth
}
},
mutations: {
authenticate(token, expiration) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
}
},
actions: {
authenticate: ({
commit
}, token, expiration) => commit('authenticate', token, expiration)
}
})
</code></pre>
<p><strong>- login method -</strong></p>
<pre><code>login() {
var data = {
client_id: 2,
client_secret: '**************************',
grant_type: 'password',
username: this.email,
password: this.password
}
// send data
this.$http.post('oauth/token', data)
.then(response => {
// send the parameters to the action
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
})
}
</code></pre>
<p>I would be very thankful for any kind of help!</p> | <p>Mutations expect two arguments: <code>state</code> and <code>payload</code>, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.</p>
<p>The easiest way to <a href="https://www.karltarvas.com/2017/09/07/vuex-passing-multiple-parameters-to-an-action.html" rel="noreferrer">pass a number of parameters</a> is to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring" rel="noreferrer">destruct them</a>:</p>
<pre class="lang-js prettyprint-override"><code>mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
</code></pre>
<p>Then later on in your actions you can simply</p>
<pre class="lang-js prettyprint-override"><code>store.commit('authenticate', {
token,
expiration,
});
</code></pre> | {
"question_id": 46097687,
"question_date": "2017-09-07T13:29:26.833Z",
"question_score": 207,
"tags": "vue.js|vuejs2|vuex",
"answer_id": 46097834,
"answer_date": "2017-09-07T13:36:56.287Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: How to enable Bootstrap tooltip on disabled button?
<p>I need to display a tooltip on a disabled button and remove it on an enabled button. Currently, it works in reverse.</p>
<p>What is the best way to invert this behaviour?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('[rel=tooltip]').tooltip();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<hr>
<button class="btn" disabled rel="tooltip" data-title="Dieser Link führt zu Google">button disabled</button>
<button class="btn" rel="tooltip" data-title="Dieser Link führt zu Google">button not disabled</button></code></pre>
</div>
</div>
</p>
<p>Here is a <a href="http://jsfiddle.net/BA4zM/68/" rel="noreferrer">demo</a></p>
<p>P.S.: I want to keep the <code>disabled</code> attribute.</p> | <p>Here is some working code: <a href="http://jsfiddle.net/mihaifm/W7XNU/200/" rel="noreferrer">http://jsfiddle.net/mihaifm/W7XNU/200/</a></p>
<pre><code>$('body').tooltip({
selector: '[rel="tooltip"]'
});
$(".btn").click(function(e) {
if (! $(this).hasClass("disabled"))
{
$(".disabled").removeClass("disabled").attr("rel", null);
$(this).addClass("disabled").attr("rel", "tooltip");
}
});
</code></pre>
<p>The idea is to add the tooltip to a parent element with the <code>selector</code> option, and then add/remove the <code>rel</code> attribute when enabling/disabling the button.</p> | {
"question_id": 13311574,
"question_date": "2012-11-09T16:03:51.650Z",
"question_score": 207,
"tags": "javascript|jquery|html|twitter-bootstrap|twitter-bootstrap-tooltip",
"answer_id": 13316157,
"answer_date": "2012-11-09T21:17:59.623Z",
"answer_score": 19
} |
Please answer the following Stack Overflow question:
Title: How to generate serial version UID in Intellij
<p>When I used <strong><em>Eclipse</em></strong> it had a nice feature to generate serial version UID.</p>
<p>But what to do in IntelliJ? </p>
<p><strong><em>How to choose or generate identical serial version UID in IntelliJ?</em></strong></p>
<p>And what to do when you modify old class?</p>
<p>If you haven't specify the <code>id</code>, it is generated at runtime...</p> | <p>Without any plugins:</p>
<p>You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)</p>
<blockquote>
<p>File -> Settings -> Editor -> Inspections -> Java -> Serialization issues -> Serializable class without 'serialVersionUID' - set flag and click 'OK'.
(For Macs, Settings is under IntelliJ IDEA -> Preferences...)</p>
</blockquote>
<p>For Idea v. 2022.1 (Community and Ultimate) it's on:</p>
<blockquote>
<p>File -> Settings -> Editor -> Inspections -> JVM Languages -> Serializable class without 'serialVersionUID' - set flag and click 'OK'</p>
</blockquote>
<p>Now, if your class implements <code>Serializable</code>, you will see highlight and alt+Enter on class name will ask you to generate <code>private static final long serialVersionUID</code>.</p>
<p>UPD: a faster way to find this setting - you might use hotkey <code>Ctrl+Shift+A</code> (find action), type <code>Serializable class without 'serialVersionUID'</code> - the first is the one.</p> | {
"question_id": 24573643,
"question_date": "2014-07-04T11:50:55.730Z",
"question_score": 207,
"tags": "java|serialization|intellij-idea",
"answer_id": 36007392,
"answer_date": "2016-03-15T09:35:09.317Z",
"answer_score": 446
} |
Please answer the following Stack Overflow question:
Title: Intellij IDEA Java classes not auto compiling on save
<p>Yesterday I switched to IntelliJ IDEA from Eclipse. </p>
<p>I am using JRebel with WebSphere Server 7 as well.</p>
<p>Everything now seems to be working somewhat fine, except that <strong>when I modify</strong> a Java file, and <strong>hit save</strong>, IntelliJ <strong>does not</strong> re-compile the file, in order for JRebel to pick it up. </p>
<p>The Eclipse "<strong>Build Automatically</strong>" feature resolved this issue. </p>
<p>In IntelliJ IDEA, I have to hit <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>9</kbd> to re-compile the relevant class for JRebel to pick it up. If changes are done across <strong>two files</strong>, I have <strong>to do this on each and one of</strong> them and since IntelliJ uses the save all mechanism, its pretty hard to know what to recompile manually which I am not really interested in doing either.</p>
<p>Isn't there a way to make IntelliJ to <strong>do this on its own</strong>?</p> | <h1>UPDATED</h1>
<p>For IntelliJ IDEA 12+ releases we can build automatically the edited sources if we are using the external compiler option. The only thing needed is to check the option "<em>Build project automatically</em>", located under "<em>Compiler</em>" settings:</p>
<p><a href="https://i.stack.imgur.com/Wj0TX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Wj0TX.png" alt="Compiler Settings" /></a></p>
<p>Also, if you would like to hot deploy, while the application is running or if you are using spring boot devtools you should enable the <code>compiler.automake.allow.when.app.running</code> from registry too. This will automatically compile your changes.</p>
<p>For versions greater than 2021.2, we need check 'Allow auto-make to start even id the development application is currently running' option:
<a href="https://i.stack.imgur.com/Spv3R.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Spv3R.png" alt="enter image description here" /></a></p>
<p>For versions older than 2021.2:</p>
<p>Using <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>A</kbd> (or <kbd>⌘</kbd>+<kbd>Shift</kbd>+<kbd>A</kbd> on Mac) type <code>Registry</code> once the registry windows is open, locate and enable <code>compiler.automake.allow.when.app.running</code>, see here:</p>
<p><a href="https://i.stack.imgur.com/piDMv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/piDMv.png" alt="enter image description here" /></a></p>
<hr>
For versions older than 12, you can use the *EclipseMode* plugin to make IDEA automatically compile the saved files.
<p>For more tips see the <a href="https://www.jetbrains.com/help/idea/migrating-from-eclipse-to-intellij-idea.html" rel="noreferrer">"Migrating From Eclipse to IntelliJ IDEA"</a> guide.</p> | {
"question_id": 12744303,
"question_date": "2012-10-05T10:27:24.683Z",
"question_score": 207,
"tags": "java|jakarta-ee|intellij-idea|jrebel",
"answer_id": 12744431,
"answer_date": "2012-10-05T10:35:56.670Z",
"answer_score": 286
} |
Please answer the following Stack Overflow question:
Title: Parse JSON in C#
<p>I'm trying to parse some JSON data from the Google AJAX Search API. I have <a href="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=cheese&rsz=large" rel="noreferrer">this URL</a> and I'd like to break it down so that the results are displayed. I've currently written this code, but I'm pretty lost in regards of what to do next, although there are a number of examples out there with simplified JSON strings.</p>
<p>Being new to C# and .NET in general I've struggled to get a genuine text output for my ASP.NET page so I've been recommended to give JSON.NET a try. Could anyone point me in the right direction to just simply writing some code that'll take in JSON from the Google AJAX Search API and print it out to the screen?</p>
<hr>
<p><strong>EDIT:</strong> ALL FIXED! All results are working fine. Thank you again Dreas Grech!</p>
<pre><code>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GoogleSearchResults g1 = new GoogleSearchResults();
const string json = @"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}";
g1 = JSONHelper.Deserialise<GoogleSearchResults>(json);
Response.Write(g1.content);
}
}
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
ms.Close();
return obj;
}
}
/// Deserialise from JSON
[Serializable]
public class GoogleSearchResults
{
public GoogleSearchResults() { }
public GoogleSearchResults(string _unescapedUrl, string _url, string _visibleUrl, string _cacheUrl, string _title, string _titleNoFormatting, string _content)
{
this.unescapedUrl = _unescapedUrl;
this.url = _url;
this.visibleUrl = _visibleUrl;
this.cacheUrl = _cacheUrl;
this.title = _title;
this.titleNoFormatting = _titleNoFormatting;
this.content = _content;
}
string _unescapedUrl;
string _url;
string _visibleUrl;
string _cacheUrl;
string _title;
string _titleNoFormatting;
string _content;
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
[DataMember]
public string url
{
get { return _url; }
set { _url = value; }
}
[DataMember]
public string visibleUrl
{
get { return _visibleUrl; }
set { _visibleUrl = value; }
}
[DataMember]
public string cacheUrl
{
get { return _cacheUrl; }
set { _cacheUrl = value; }
}
[DataMember]
public string title
{
get { return _title; }
set { _title = value; }
}
[DataMember]
public string titleNoFormatting
{
get { return _titleNoFormatting; }
set { _titleNoFormatting = value; }
}
[DataMember]
public string content
{
get { return _content; }
set { _content = value; }
}
}
</code></pre>
<p>The code currently compiles and runs perfectly, but isn't returning any results. Could someone help me with returning what I require, the results ready to print out to the screen?</p>
<p><strong>Edit:</strong></p>
<p>Json.NET works using the same JSON and classes as the example above.</p>
<pre><code>GoogleSearchResults g1 = JsonConvert.DeserializeObject<GoogleSearchResults>(json);
</code></pre>
<p>Link: <a href="http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm" rel="noreferrer">Serializing and Deserializing JSON with Json.NET</a></p>
<h2>Related</h2>
<p><a href="https://stackoverflow.com/questions/802766/c-parsing-json-formatted-data-into-nested-hashtables">C# - parsing json formatted data into nested hashtables</a><br>
<a href="https://stackoverflow.com/questions/854028/parse-json-array">Parse JSON array</a></p> | <p><strong>[Update]</strong><br/>
I've just realized why you weren't receiving results back... you have a missing line in your <code>Deserialize</code> method. You were forgetting to assign the results to your <code>obj</code> :</p>
<pre><code>public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
</code></pre>
<p>Also, just for reference, here is the <code>Serialize</code> method : </p>
<pre><code>public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
</code></pre>
<hr>
<p><strong>Edit</strong></p>
<p>If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..</p>
<p>Deserialize:</p>
<pre><code>JsonConvert.DeserializeObject<T>(string json);
</code></pre>
<p>Serialize:</p>
<pre><code>JsonConvert.SerializeObject(object o);
</code></pre>
<p>This are already part of Json.NET so you can just call them on the JsonConvert class.</p>
<p><strong>Link: <a href="http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm" rel="noreferrer">Serializing and Deserializing JSON with Json.NET</a></strong></p>
<hr>
<p><br/>Now, the reason you're getting a StackOverflow is because of your <code>Properties</code>.</p>
<p>Take for example this one : </p>
<pre><code>[DataMember]
public string unescapedUrl
{
get { return unescapedUrl; } // <= this line is causing a Stack Overflow
set { this.unescapedUrl = value; }
}
</code></pre>
<p>Notice that in the <code>getter</code>, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.</p>
<hr>
<p>Properties (in 2.0) should be defined like such : </p>
<pre><code>string _unescapedUrl; // <= private field
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
</code></pre>
<p>You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.</p>
<hr>
<p>Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that : </p>
<pre><code>public string unescapedUrl { get; set;}
</code></pre> | {
"question_id": 1212344,
"question_date": "2009-07-31T12:45:07.740Z",
"question_score": 207,
"tags": "c#|asp.net|json|parsing|json.net",
"answer_id": 1218902,
"answer_date": "2009-08-02T13:32:38.003Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: Android ViewPager with bottom dots
<p>I want to add 3 bottom dots to my ViewPager, like this.</p>
<p><img src="https://i.stack.imgur.com/jg9SL.png" alt="3 bottom dots">
<img src="https://i.stack.imgur.com/7ML5B.png" alt="3 bottom dots">
<img src="https://i.stack.imgur.com/ACHh7.png" alt="3 bottom dots"></p>
<p>I use FragmentActivity and support library ViewPager.</p> | <p><strong>No need for that much code.</strong></p>
<p>You can do all this stuff without coding so much by using only <strong><code>viewpager</code></strong> with <strong><code>tablayout</code></strong>.</p>
<p><strong>Your main Layout:</strong></p>
<pre class="lang-xml prettyprint-override"><code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:id="@+id/tabDots"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"/>
</RelativeLayout>
</code></pre>
<p>Hook up your UI elements inactivity or fragment as follows:</p>
<p><strong>Java Code:</strong><br></p>
<pre class="lang-java prettyprint-override"><code>mImageViewPager = (ViewPager) findViewById(R.id.pager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabDots);
tabLayout.setupWithViewPager(mImageViewPager, true);
</code></pre>
<p>That's it, you are good to go.</p>
<p>You will need to create the following xml resource file in the <strong>drawable</strong> folder.</p>
<p><strong>tab_indicator_selected.xml</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent"/>
</shape>
</code></pre>
<p><strong>tab_indicator_default.xml</strong><br></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="oval"
android:thickness="2dp"
android:useLevel="false">
<solid android:color="@android:color/darker_gray"/>
</shape>
</code></pre>
<p><strong>tab_selector.xml</strong></p>
<pre class="lang-xml prettyprint-override"><code> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_indicator_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/tab_indicator_default"/>
</selector>
</code></pre>
<p>Feeling as lazy as I am? Well, all the above code is converted into a library!
<strong>Usage</strong>
Add the following in your gradle:
<code>implementation 'com.chabbal:slidingdotsplash:1.0.2'</code>
Add the following to your Activity or Fragment layout.</p>
<pre class="lang-xml prettyprint-override"><code><com.chabbal.slidingdotsplash.SlidingSplashView
android:id="@+id/splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:imageResources="@array/img_id_arr"/>
</code></pre>
<p>Create an integer array in <code>strings.xml</code> e.g.</p>
<pre class="lang-xml prettyprint-override"><code><integer-array name="img_id_arr">
<item>@drawable/img1</item>
<item>@drawable/img2</item>
<item>@drawable/img3</item>
<item>@drawable/img4</item>
</integer-array>
</code></pre>
<p><em>Done!</em>
<strong>Extra</strong> in order to listen page changes use <code>addOnPageChangeListener(listener);</code>
Github <a href="https://github.com/Chabbal/slidingdotsplash" rel="noreferrer">link</a>.</p> | {
"question_id": 20586619,
"question_date": "2013-12-14T18:14:53.337Z",
"question_score": 207,
"tags": "android|user-interface|android-viewpager|android-fragmentactivity|viewpagerindicator",
"answer_id": 40047719,
"answer_date": "2016-10-14T16:15:05.307Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: Pass a parameter to a fixture function
<p>I am using py.test to test some DLL code wrapped in a python class MyTester.
For validating purpose I need to log some test data during the tests and do more processing afterwards. As I have many test_... files I want to reuse the tester object creation (instance of MyTester) for most of my tests.</p>
<p>As the tester object is the one which got the references to the DLL's variables and functions I need to pass a list of the DLL's variables to the tester object for each of the test files (variables to be logged are the same for a test_... file).
The content of the list is used to log the specified data.</p>
<p>My idea is to do it somehow like this:</p>
<pre><code>import pytest
class MyTester():
def __init__(self, arg = ["var0", "var1"]):
self.arg = arg
# self.use_arg_to_init_logging_part()
def dothis(self):
print "this"
def dothat(self):
print "that"
# located in conftest.py (because other test will reuse it)
@pytest.fixture()
def tester(request):
""" create tester object """
# how to use the list below for arg?
_tester = MyTester()
return _tester
# located in test_...py
# @pytest.mark.usefixtures("tester")
class TestIt():
# def __init__(self):
# self.args_for_tester = ["var1", "var2"]
# # how to pass this list to the tester fixture?
def test_tc1(self, tester):
tester.dothis()
assert 0 # for demo purpose
def test_tc2(self, tester):
tester.dothat()
assert 0 # for demo purpose
</code></pre>
<p>Is it possible to achieve it like this or is there even a more elegant way?</p>
<p>Usually I could do it for each test method with some kind of setup function (xUnit-style). But I want to gain some kind of reuse. Does anyone know if this is possible with fixtures at all?</p>
<p>I know I can do something like this: (from the docs)</p>
<pre><code>@pytest.fixture(scope="module", params=["merlinux.eu", "mail.python.org"])
</code></pre>
<p>But I need to the parametrization directly in the test module.
<strong>Is it possible to access the params attribute of the fixture from the test module?</strong></p> | <p><strong>Update:</strong> Since this the accepted answer to this question and still gets upvoted sometimes, I should add an update. Although my original answer (below) was the only way to do this in older versions of pytest as <a href="https://stackoverflow.com/a/33879151/982257">others</a> have <a href="https://stackoverflow.com/a/60148972/982257">noted</a> pytest now supports indirect parametrization of fixtures. For example you can do something like this (via @imiric):</p>
<pre><code># test_parameterized_fixture.py
import pytest
class MyTester:
def __init__(self, x):
self.x = x
def dothis(self):
assert self.x
@pytest.fixture
def tester(request):
"""Create tester object"""
return MyTester(request.param)
class TestIt:
@pytest.mark.parametrize('tester', [True, False], indirect=['tester'])
def test_tc1(self, tester):
tester.dothis()
assert 1
</code></pre>
<pre><code>$ pytest -v test_parameterized_fixture.py
================================================================================= test session starts =================================================================================
platform cygwin -- Python 3.6.8, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: .
collected 2 items
test_parameterized_fixture.py::TestIt::test_tc1[True] PASSED [ 50%]
test_parameterized_fixture.py::TestIt::test_tc1[False] FAILED
</code></pre>
<p>However, although this form of indirect parametrization is explicit, as @Yukihiko Shinoda <a href="https://stackoverflow.com/a/60148972/982257">points out</a> it now supports a form of implicit indirect parametrization (though I couldn't find any obvious reference to this in the official docs):</p>
<pre><code># test_parameterized_fixture2.py
import pytest
class MyTester:
def __init__(self, x):
self.x = x
def dothis(self):
assert self.x
@pytest.fixture
def tester(tester_arg):
"""Create tester object"""
return MyTester(tester_arg)
class TestIt:
@pytest.mark.parametrize('tester_arg', [True, False])
def test_tc1(self, tester):
tester.dothis()
assert 1
</code></pre>
<pre><code>$ pytest -v test_parameterized_fixture2.py
================================================================================= test session starts =================================================================================
platform cygwin -- Python 3.6.8, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: .
collected 2 items
test_parameterized_fixture2.py::TestIt::test_tc1[True] PASSED [ 50%]
test_parameterized_fixture2.py::TestIt::test_tc1[False] FAILED
</code></pre>
<p>I don't know exactly what are the semantics of this form, but it seems that <code>pytest.mark.parametrize</code> recognizes that although the <code>test_tc1</code> method does not take an argument named <code>tester_arg</code>, the <code>tester</code> fixture that it's using does, so it passes the parametrized argument on through the <code>tester</code> fixture.</p>
<hr>
<p>I had a similar problem--I have a fixture called <code>test_package</code>, and I later wanted to be able to pass an optional argument to that fixture when running it in specific tests. For example:</p>
<pre><code>@pytest.fixture()
def test_package(request, version='1.0'):
...
request.addfinalizer(fin)
...
return package
</code></pre>
<p>(It doesn't matter for these purposes what the fixture does or what type of object the returned <code>package</code>) is.</p>
<p>It would then be desirable to somehow use this fixture in a test function in such a way that I can also specify the <code>version</code> argument to that fixture to use with that test. This is currently not possible, though might make a nice feature.</p>
<p>In the meantime it was easy enough to make my fixture simply return a <em>function</em> that does all the work the fixture previously did, but allows me to specify the <code>version</code> argument:</p>
<pre><code>@pytest.fixture()
def test_package(request):
def make_test_package(version='1.0'):
...
request.addfinalizer(fin)
...
return test_package
return make_test_package
</code></pre>
<p>Now I can use this in my test function like:</p>
<pre><code>def test_install_package(test_package):
package = test_package(version='1.1')
...
assert ...
</code></pre>
<p>and so on.</p>
<p>The OP's attempted solution was headed in the right direction, and as @hpk42's <a href="https://stackoverflow.com/a/18098713/982257">answer</a> suggests, the <code>MyTester.__init__</code> could just store off a reference to the request like:</p>
<pre><code>class MyTester(object):
def __init__(self, request, arg=["var0", "var1"]):
self.request = request
self.arg = arg
# self.use_arg_to_init_logging_part()
def dothis(self):
print "this"
def dothat(self):
print "that"
</code></pre>
<p>Then use this to implement the fixture like:</p>
<pre><code>@pytest.fixture()
def tester(request):
""" create tester object """
# how to use the list below for arg?
_tester = MyTester(request)
return _tester
</code></pre>
<p>If desired the <code>MyTester</code> class could be restructured a bit so that its <code>.args</code> attribute can be updated after it has been created, to tweak the behavior for individual tests.</p> | {
"question_id": 18011902,
"question_date": "2013-08-02T08:11:46.260Z",
"question_score": 207,
"tags": "python|fixtures|pytest",
"answer_id": 28570677,
"answer_date": "2015-02-17T20:36:40.410Z",
"answer_score": 179
} |
Please answer the following Stack Overflow question:
Title: With Spring can I make an optional path variable?
<p>With Spring 3.0, can I have an optional path variable?</p>
<p>For example</p>
<pre><code>@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return new TestBean();
}
</code></pre>
<p>Here I would like <code>/json/abc</code> or <code>/json</code> to call the same method. <br/>
One obvious workaround declare <code>type</code> as a request parameter: </p>
<pre><code>@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@RequestParam(value = "type", required = false) String type,
@RequestParam("track") String track) {
return new TestBean();
}
</code></pre>
<p>and then <code>/json?type=abc&track=aa</code> or <code>/json?track=rr</code> will work</p> | <p>You can't have optional path variables, but you can have two controller methods which call the same service code:</p>
<pre><code>@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return getTestBean(type);
}
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
HttpServletRequest req,
@RequestParam("track") String track) {
return getTestBean();
}
</code></pre> | {
"question_id": 4904092,
"question_date": "2011-02-04T23:58:11.430Z",
"question_score": 207,
"tags": "spring|rest",
"answer_id": 4904139,
"answer_date": "2011-02-05T00:06:56.207Z",
"answer_score": 209
} |
Please answer the following Stack Overflow question:
Title: What exactly does big Ө notation represent?
<p>I'm really confused about the differences between big O, big Omega, and big Theta notation. </p>
<p>I understand that big O is the upper bound and big Omega is the lower bound, but what exactly does big Ө (theta) represent? </p>
<p>I have read that it means <strong><em>tight bound</em></strong>, but what does that mean?</p> | <p>It means that the algorithm is both big-O and big-Omega in the given function. </p>
<p>For example, if it is <code>Ө(n)</code>, then there is some constant <code>k</code>, such that your function (run-time, whatever), is larger than <code>n*k</code> for sufficiently large <code>n</code>, and some other constant <code>K</code> such that your function is smaller than <code>n*K</code> for sufficiently large <code>n</code>. </p>
<p>In other words, for sufficiently large <code>n</code>, it is sandwiched between two linear functions :</p>
<p>For <code>k < K</code> and <code>n</code> sufficiently large, <code>n*k < f(n) < n*K</code></p> | {
"question_id": 10376740,
"question_date": "2012-04-29T22:56:19.830Z",
"question_score": 207,
"tags": "algorithm|computer-science|notation|big-o",
"answer_id": 10376776,
"answer_date": "2012-04-29T23:03:05.717Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: How can I get zoom functionality for images?
<p>Is there a common way to show a big image and enable the user to zoom in and out and pan the image?</p>
<p>Until now I found two ways: </p>
<ol>
<li>overwriting ImageView, that seems a little bit too much for such a common problem. </li>
<li>using a webview but with less control over the overall layout etc.</li>
</ol> | <p>I used a WebView and loaded the image from the memory via</p>
<pre><code>webview.loadUrl("file://...")
</code></pre>
<p>The WebView handles all the panning zooming and scrolling. If you use wrap_content the webview won't be bigger then the image and no white areas are shown.
The WebView is the better ImageView ;)</p> | {
"question_id": 2537238,
"question_date": "2010-03-29T10:36:30.247Z",
"question_score": 207,
"tags": "android|imageview|zooming",
"answer_id": 2538606,
"answer_date": "2010-03-29T14:23:04.180Z",
"answer_score": 60
} |
Please answer the following Stack Overflow question:
Title: jQuery: keyPress Backspace won't fire?
<p>I wonder what I'm doing wrong:</p>
<pre><code>$(".s").keypress(function(e) {
switch (e.keyCode) {
case 8: // Backspace
//console.log('backspace');
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
doSearch();
}
});
</code></pre>
<p>I want my <code>doSearch()</code> function also to be fired when I hit the <kbd>Backspace</kbd> key. At the moment absolutely nothing happens when I press <kbd>Backspace</kbd> in Chrome and Safari.</p>
<p>any ideas?</p> | <p>Use <code>keyup</code> instead of <code>keypress</code>. This gets all the key codes when the user presses something</p> | {
"question_id": 4690330,
"question_date": "2011-01-14T11:01:41.197Z",
"question_score": 207,
"tags": "jquery|keypress|backspace",
"answer_id": 4690368,
"answer_date": "2011-01-14T11:05:29.103Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: Programmatically scrolling to the end of a ListView
<p>I have a scrollable <code>ListView</code> where the number of items can change dynamically. Whenever a new item is added to the end of the list, I would like to programmatically scroll the <code>ListView</code> to the end. (e.g., something like a chat message list where new messages can be added at the end)</p>
<p>My guess is that I would need to create a <code>ScrollController</code> in my <code>State</code> object and pass it manually to the <code>ListView</code> constructor, so I can later call <code>animateTo()</code> / <code>jumpTo()</code> method on the controller. However, since I cannot easily determine the maximum scroll offset, it seems impossible to simply perform a <code>scrollToEnd()</code> type of operation (whereas I can easily pass <code>0.0</code> to make it scroll to the initial position).</p>
<p>Is there an easy way to achieve this?</p>
<p>Using <code>reverse: true</code> is not a perfect solution for me, because I would like the items to be aligned at the top when there are only a small number of items that fit within the <code>ListView</code> viewport.</p> | <p>If you use a shrink-wrapped <code>ListView</code> with <code>reverse: true</code>, scrolling it to 0.0 will do what you want.</p>
<pre><code>import 'dart:collection';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Example',
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> _messages = <Widget>[new Text('hello'), new Text('world')];
ScrollController _scrollController = new ScrollController();
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Container(
decoration: new BoxDecoration(backgroundColor: Colors.blueGrey.shade100),
width: 100.0,
height: 100.0,
child: new Column(
children: [
new Flexible(
child: new ListView(
controller: _scrollController,
reverse: true,
shrinkWrap: true,
children: new UnmodifiableListView(_messages),
),
),
],
),
),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
onPressed: () {
setState(() {
_messages.insert(0, new Text("message ${_messages.length}"));
});
_scrollController.animateTo(
0.0,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
}
),
);
}
}
</code></pre> | {
"question_id": 43485529,
"question_date": "2017-04-19T02:55:36.633Z",
"question_score": 207,
"tags": "flutter|flutter-layout|flutter-animation",
"answer_id": 43486389,
"answer_date": "2017-04-19T04:28:12.757Z",
"answer_score": 164
} |
Please answer the following Stack Overflow question:
Title: getActivity() returns null in Fragment function
<p>I have a fragment (F1) with a public method like this</p>
<pre><code>public void asd() {
if (getActivity() == null) {
Log.d("yes","it is null");
}
}
</code></pre>
<p>and yes when I call it (from the Activity), it is null...</p>
<pre><code>FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();
</code></pre>
<p>It must be something that I am doing very wrong, but I don't know what that is.</p> | <p><code>commit</code> schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready. </p>
<p>I'd suggest adding an </p>
<pre><code>onAttach(Activity activity)
</code></pre>
<p>method to your <code>Fragment</code> and putting a break point on it and seeing when it is called relative to your call to <code>asd()</code>. You'll see that it is called after the method where you make the call to <code>asd()</code> exits. The <code>onAttach</code> call is where the <code>Fragment</code> is attached to its activity and from this point <code>getActivity()</code> will return non-null (nb there is also an <code>onDetach()</code> call).</p> | {
"question_id": 6215239,
"question_date": "2011-06-02T13:33:46.503Z",
"question_score": 207,
"tags": "android|android-fragments|android-activity|null|android-context",
"answer_id": 6225044,
"answer_date": "2011-06-03T09:03:51.180Z",
"answer_score": 172
} |
Please answer the following Stack Overflow question:
Title: Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?
<p>In multiple courses, books, and jobs, I have seen text fields defined as VARCHAR(255) as kind of the default for "shortish" text. Is there any good reason that a length of 255 is chosen so often, other than being <a href="https://stackoverflow.com/questions/164432/what-real-life-bad-habits-has-programming-given-you/164556#164556">a nice round number</a>? Is it a holdout from some time in the past when there was a good reason (whether or not it applies today)?</p>
<p>I realize, of course, that a tighter limit would be more ideal, if you somehow know the maximum length of the string. But if you are using VARCHAR(255) that probably indicates that you don't know the max length, only that it is a "shortish" string.</p>
<hr>
<p>Note: I found this question (<a href="https://stackoverflow.com/questions/143933/varchar255-v-tinyblob-v-tinytext">varchar(255) v tinyblob v tinytext</a>), which says that VARCHAR(<em>n</em>) requires <em>n</em>+1 bytes of storage for <em>n</em><=255, <em>n</em>+2 bytes of storage for <em>n</em>>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).</p> | <p>Historically, 255 characters has often been the maximum length of a <code>VARCHAR</code> in some DBMSes, and it sometimes still winds up being the effective maximum if you want to use UTF-8 and have the column indexed (because of index length limitations).</p> | {
"question_id": 1217466,
"question_date": "2009-08-01T20:51:10.367Z",
"question_score": 207,
"tags": "database|database-design|types|varchar",
"answer_id": 1217477,
"answer_date": "2009-08-01T20:57:31.850Z",
"answer_score": 128
} |
Please answer the following Stack Overflow question:
Title: Converting Integer to String with comma for thousands
<p>I want to convert an Integer 35634646 to have the thousand "," so it should be 35,634,646.</p>
<p>What would be the quickest way to doing that? </p> | <pre><code>System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
</code></pre>
<pre><code>Output: 35,634,646
</code></pre> | {
"question_id": 7070209,
"question_date": "2011-08-15T20:10:37.620Z",
"question_score": 207,
"tags": "java|string|integer",
"answer_id": 7070301,
"answer_date": "2011-08-15T20:17:18.403Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: linux: kill background task
<p>How do I kill the last spawned background task in linux?</p>
<p>Example:</p>
<pre><code>doSomething
doAnotherThing
doB &
doC
doD
#kill doB
????
</code></pre> | <p>There's a special variable for this in bash:</p>
<pre><code>kill $!
</code></pre>
<p>$! expands to the PID of the last process executed in the background.</p> | {
"question_id": 1624691,
"question_date": "2009-10-26T13:10:45.330Z",
"question_score": 207,
"tags": "linux|bash|unix|kill|job-control",
"answer_id": 1624713,
"answer_date": "2009-10-26T13:14:39.530Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: Android Eclipse - Could not find *.apk
<p>I know this question has been asked before and I have seen a plethora of solutions out there, yet none seem to work for me. I was able to build my apk without issues until this error started cropping up. I have tried cleaning my project, removing it from the workspace and reimporting it, removing "Java Builder" from my Builders for the project, building the project manually, reordering my java build path. I have no visible compiler issues and no problems exist in my workspace. </p>
<p>I did experience this issue before and solved it once by removing the project form my workspace and re-importing it and another time I solved it by removing "Java Builder" from my java build path. None seem to work this time. I currently have most of the settings set back to default (i.e. java build is checked again).</p>
<p>I am running windows 7 (64 bit) and using jdk1.6.0_21 via Eclipse 3.6. </p>
<p>Any suggestions would be greatly appreciated as I have lost loads of development time troubleshooting this already.</p>
<p>[Update] My locale is English & I have tried removing the debug.keystore, United States as related to <a href="http://code.google.com/p/android/issues/detail?id=834" rel="noreferrer">issue 834</a></p> | <p>Please follow these steps; this might help you out:</p>
<ol>
<li><p>Right-click your app project and go to Properties</p></li>
<li><p>Select Android from left-hand side list</p></li>
<li><p>Uncheck the "Is Library" checkbox</p></li>
</ol>
<p>If your app project relies on library projects which are in your workspace, those of course need to have the "Is Library" box checked.</p> | {
"question_id": 4778113,
"question_date": "2011-01-24T02:36:12.117Z",
"question_score": 207,
"tags": "java|android|eclipse",
"answer_id": 6450971,
"answer_date": "2011-06-23T07:55:53.373Z",
"answer_score": 603
} |
Please answer the following Stack Overflow question:
Title: Upgrade python packages from requirements.txt using pip command
<p>How do I upgrade all my python packages from requirements.txt file using pip command?</p>
<p>tried with below command</p>
<pre><code>$ pip install --upgrade -r requirements.txt
</code></pre>
<p>Since, the python packages are suffixed with the version number (<code>Django==1.5.1</code>) they don't seem to upgrade. Is there any better approach than manually editing requirements.txt file?</p>
<p><strong>EDIT</strong></p>
<p>As Andy mentioned in his answer packages are pinned to a specific version, hence it is not possible to upgrade packages through pip command.</p>
<p>But, we can achieve this with <code>pip-tools</code> using the following command.</p>
<pre><code>$ pip-review --auto
</code></pre>
<p>this will automatically upgrade all packages from requirements.txt (make sure to install <code>pip-tools</code> using pip install command).</p> | <p>No. Your requirements file has been <a href="http://nvie.com/posts/pin-your-packages/">pinned</a> to specific versions. If your requirements are set to that version, you should not be trying to upgrade beyond those versions. If you <strong>need</strong> to upgrade, then you need to switch to unpinned versions in your requirements file.</p>
<p>Example:</p>
<pre><code>lxml>=2.2.0
</code></pre>
<p>This would upgrade lxml to any version newer than 2.2.0</p>
<pre><code>lxml>=2.2.0,<2.3.0
</code></pre>
<p>This would upgrade lxml to the most recent version between 2.2.0 and 2.3.0.</p> | {
"question_id": 24764549,
"question_date": "2014-07-15T17:32:03.360Z",
"question_score": 207,
"tags": "python|pip|package|requirements.txt",
"answer_id": 24764628,
"answer_date": "2014-07-15T17:37:14.467Z",
"answer_score": 69
} |
Please answer the following Stack Overflow question:
Title: HTML-parser on Node.js
<p>Is there something like Ruby's <a href="http://nokogiri.org">nokogiri</a> on nodejs?
I mean a user-friendly HTML-parser.</p>
<p>I'd seen on Node.js modules page some parsers, but I can't find something pretty and fresh.</p> | <p>If you want to build <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="nofollow noreferrer">DOM</a> you can use <a href="https://github.com/tmpvar/jsdom" rel="nofollow noreferrer">jsdom</a>.</p>
<p>There's also <a href="https://github.com/MatthewMueller/cheerio" rel="nofollow noreferrer">cheerio</a>, it has the <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.</p>
<p>You might wanna have a look at <a href="https://github.com/fb55/htmlparser2" rel="nofollow noreferrer">htmlparser2</a>, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.</p>
<p><a href="https://github.com/inikulin/parse5" rel="nofollow noreferrer">parse5</a> also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in <a href="https://github.com/tmpvar/jsdom" rel="nofollow noreferrer">jsdom</a>, <a href="https://github.com/angular/angular" rel="nofollow noreferrer">Angular</a>, and <a href="https://github.com/Polymer/polymer" rel="nofollow noreferrer">Polymer</a>.</p>
<p>If the website you're trying to scrape is <a href="http://en.wikipedia.org/wiki/Dynamic_web_page" rel="nofollow noreferrer">dynamic</a> then you should be using a <a href="https://en.wikipedia.org/wiki/Headless_browser" rel="nofollow noreferrer">headless browser</a> like <a href="http://phantomjs.org/" rel="nofollow noreferrer">phantomjs</a>. Also have a look at <a href="http://casperjs.org/" rel="nofollow noreferrer">casperjs</a>, if you're considering phantomjs. And you can control casperjs from node with <a href="https://github.com/WaterfallEngineering/SpookyJS" rel="nofollow noreferrer">SpookyJS</a>.</p>
<p>Beside phantomjs there's <a href="http://zombie.labnotes.org/" rel="nofollow noreferrer">zombiejs</a>. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.</p>
<p>There's a <a href="http://net.tutsplus.com/tutorials/javascript-ajax/web-scraping-with-node-js/" rel="nofollow noreferrer">nettuts+ toturial</a> for the latter solutions.</p> | {
"question_id": 7977945,
"question_date": "2011-11-02T09:16:50.157Z",
"question_score": 207,
"tags": "html|parsing|node.js|nokogiri",
"answer_id": 7978072,
"answer_date": "2011-11-02T09:27:49.633Z",
"answer_score": 456
} |
Please answer the following Stack Overflow question:
Title: How to set my phpmyadmin user session to not time out so quickly?
<p>I work on my wamp for localhost backend development everyday. </p>
<p>I feel annoyed by phpmyadmin auto log out out quickly. Is there any way I could get rid of this or extend the timeout?</p>
<p>Where can I set this timeout value?</p> | <p>To increase the <code>phpMyAdmin</code> <strong>Session Timeout</strong>, open <code>config.inc.php</code> in the root <code>phpMyAdmin</code> directory and add this setting (anywhere).</p>
<pre><code>$cfg['LoginCookieValidity'] = <your_new_timeout>;
</code></pre>
<p>Where <code><your_new_timeout></code> is some number larger than 1800.</p>
<p><strong>Note</strong>:</p>
<p>Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.</p> | {
"question_id": 18886740,
"question_date": "2013-09-19T05:23:17.770Z",
"question_score": 207,
"tags": "phpmyadmin|timeout|settings",
"answer_id": 18886833,
"answer_date": "2013-09-19T05:32:20.593Z",
"answer_score": 291
} |
Please answer the following Stack Overflow question:
Title: How to update React Context from inside a child component?
<p>I have the language settings in the context as like below </p>
<pre><code>class LanguageProvider extends Component {
static childContextTypes = {
langConfig: PropTypes.object,
};
getChildContext() {
return { langConfig: 'en' };
}
render() {
return this.props.children;
}
}
export default LanguageProvider;
</code></pre>
<p>My application code will be something like below </p>
<pre><code><LanguageProvider>
<App>
<MyPage />
</App>
</LanguageProvider>
</code></pre>
<p>My Page is having a component to switch the language </p>
<pre><code><MyPage>
<LanguageSwitcher/>
</MyPage>
</code></pre>
<p><code>LanguageSwitcher</code> in this <code>MyPage</code> need to update the context to change the language into 'jp' as below </p>
<pre><code>class LanguageSwitcher extends Component {
static contextTypes = {
langConfig: PropTypes.object,
};
updateLanguage() {
//Here I need to update the langConfig to 'jp'
}
render() {
return <button onClick={this.updateLanguage}>Change Language</button>;
}
}
export default LanguageSwitcher;
</code></pre>
<p>How can I update the context from inside the LanguageSwitcher component ?</p> | <h1>Using hooks</h1>
<p>Hooks were introduced in 16.8.0 so the following code requires a minimum version of 16.8.0 (scroll down for the class components example). <a href="https://codesandbox.io/s/react-context-4c174" rel="noreferrer">CodeSandbox Demo</a></p>
<h2>1. Setting parent state for dynamic context</h2>
<p>Firstly, in order to have a dynamic context which can be passed to the consumers, I'll use the parent's state. This ensures that I've a single source of truth going forth. For example, my parent App will look like this:</p>
<pre><code>const App = () => {
const [language, setLanguage] = useState("en");
const value = { language, setLanguage };
return (
...
);
};
</code></pre>
<p>The <code>language</code> is stored in the state. We will pass both <code>language</code> and the setter function <code>setLanguage</code> via context later.</p>
<h2>2. Creating a context</h2>
<p>Next, I created a language context like this:</p>
<pre><code>// set the defaults
const LanguageContext = React.createContext({
language: "en",
setLanguage: () => {}
});
</code></pre>
<p>Here I'm setting the defaults for <code>language</code> ('en') and a <code>setLanguage</code> function which will be sent by the context provider to the consumer(s). These are only defaults and I'll provide their values when using the provider component in the parent <code>App</code>.</p>
<p>Note: the <code>LanguageContext</code> remains same whether you use hooks or class based components.</p>
<h2>3. Creating a context consumer</h2>
<p>In order to have the language switcher set the language, it should have the access to the language setter function via context. It can look something like this:</p>
<pre><code>const LanguageSwitcher = () => {
const { language, setLanguage } = useContext(LanguageContext);
return (
<button onClick={() => setLanguage("jp")}>
Switch Language (Current: {language})
</button>
);
};
</code></pre>
<p>Here I'm just setting the language to 'jp' but you may have your own logic to set languages for this.</p>
<h2>4. Wrapping the consumer in a provider</h2>
<p>Now I'll render my language switcher component in a <code>LanguageContext.Provider</code> and pass in the values which have to be sent via context to any level deeper. Here's how my parent <code>App</code> look like:</p>
<pre><code>const App = () => {
const [language, setLanguage] = useState("en");
const value = { language, setLanguage };
return (
<LanguageContext.Provider value={value}>
<h2>Current Language: {language}</h2>
<p>Click button to change to jp</p>
<div>
{/* Can be nested */}
<LanguageSwitcher />
</div>
</LanguageContext.Provider>
);
};
</code></pre>
<p>Now, whenever the language switcher is clicked it updates the context dynamically.</p>
<p><a href="https://codesandbox.io/s/react-context-4c174" rel="noreferrer">CodeSandbox Demo</a></p>
<h1>Using class components</h1>
<p>The latest <a href="https://reactjs.org/docs/context.html" rel="noreferrer">context API</a> was introduced in React 16.3 which provides a great way of having a dynamic context. The following code requires a minimum version of 16.3.0. <a href="https://codesandbox.io/s/x7xrmnr954" rel="noreferrer">CodeSandbox Demo</a></p>
<h2>1. Setting parent state for dynamic context</h2>
<p>Firstly, in order to have a dynamic context which can be passed to the consumers, I'll use the parent's state. This ensures that I've a single source of truth going forth. For example, my parent App will look like this:</p>
<pre><code>class App extends Component {
setLanguage = language => {
this.setState({ language });
};
state = {
language: "en",
setLanguage: this.setLanguage
};
...
}
</code></pre>
<p>The <code>language</code> is stored in the state along with a language setter method, which you may keep outside the state tree.</p>
<h2>2. Creating a context</h2>
<p>Next, I created a language context like this:</p>
<pre><code>// set the defaults
const LanguageContext = React.createContext({
language: "en",
setLanguage: () => {}
});
</code></pre>
<p>Here I'm setting the defaults for <code>language</code> ('en') and a <code>setLanguage</code> function which will be sent by the context provider to the consumer(s). These are only defaults and I'll provide their values when using the provider component in the parent <code>App</code>.</p>
<h2>3. Creating a context consumer</h2>
<p>In order to have the language switcher set the language, it should have the access to the language setter function via context. It can look something like this:</p>
<pre><code>class LanguageSwitcher extends Component {
render() {
return (
<LanguageContext.Consumer>
{({ language, setLanguage }) => (
<button onClick={() => setLanguage("jp")}>
Switch Language (Current: {language})
</button>
)}
</LanguageContext.Consumer>
);
}
}
</code></pre>
<p>Here I'm just setting the language to 'jp' but you may have your own logic to set languages for this.</p>
<h2>4. Wrapping the consumer in a provider</h2>
<p>Now I'll render my language switcher component in a <code>LanguageContext.Provider</code> and pass in the values which have to be sent via context to any level deeper. Here's how my parent <code>App</code> look like:</p>
<pre><code>class App extends Component {
setLanguage = language => {
this.setState({ language });
};
state = {
language: "en",
setLanguage: this.setLanguage
};
render() {
return (
<LanguageContext.Provider value={this.state}>
<h2>Current Language: {this.state.language}</h2>
<p>Click button to change to jp</p>
<div>
{/* Can be nested */}
<LanguageSwitcher />
</div>
</LanguageContext.Provider>
);
}
}
</code></pre>
<p>Now, whenever the language switcher is clicked it updates the context dynamically.</p>
<p><a href="https://codesandbox.io/s/x7xrmnr954" rel="noreferrer">CodeSandbox Demo</a></p> | {
"question_id": 41030361,
"question_date": "2016-12-08T01:35:05.917Z",
"question_score": 207,
"tags": "javascript|reactjs|react-context",
"answer_id": 51573816,
"answer_date": "2018-07-28T17:46:58.587Z",
"answer_score": 536
} |
Please answer the following Stack Overflow question:
Title: Sound alarm when code finishes
<p>I am in a situation where my code takes extremely long to run and I don't want to be staring at it all the time but want to know when it is done.</p>
<p>How can I make the (Python) code sort of sound an "alarm" when it is done? I was contemplating making it play a .wav file when it reaches the end of the code... </p>
<p>Is this even a feasible idea?
If so, how could I do it?</p> | <h2>On Windows</h2>
<pre><code>import winsound
duration = 1000 # milliseconds
freq = 440 # Hz
winsound.Beep(freq, duration)
</code></pre>
<p>Where freq is the frequency in Hz and the duration is in milliseconds.</p>
<h2>On Linux and Mac</h2>
<pre><code>import os
duration = 1 # seconds
freq = 440 # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
</code></pre>
<p>In order to use this example, you must install <code>sox</code>.</p>
<p>On Debian / Ubuntu / Linux Mint, run this in your terminal:</p>
<pre><code>sudo apt install sox
</code></pre>
<p>On Mac, run this in your terminal (using macports):</p>
<pre><code>sudo port install sox
</code></pre>
<h2>Speech on Mac</h2>
<pre><code>import os
os.system('say "your program has finished"')
</code></pre>
<h2>Speech on Linux</h2>
<pre><code>import os
os.system('spd-say "your program has finished"')
</code></pre>
<p>You need to install the <code>speech-dispatcher</code> package in Ubuntu (or the corresponding package on other distributions):</p>
<pre><code>sudo apt install speech-dispatcher
</code></pre> | {
"question_id": 16573051,
"question_date": "2013-05-15T19:04:57.500Z",
"question_score": 207,
"tags": "python|alarm|audio",
"answer_id": 16573339,
"answer_date": "2013-05-15T19:23:23.917Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: getting the index of a row in a pandas apply function
<p>I am trying to access the index of a row in a function applied across an entire <code>DataFrame</code> in Pandas. I have something like this:</p>
<pre><code>df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df
a b c
0 1 2 3
1 4 5 6
</code></pre>
<p>and I'll define a function that access elements with a given row</p>
<pre><code>def rowFunc(row):
return row['a'] + row['b'] * row['c']
</code></pre>
<p>I can apply it like so:</p>
<pre><code>df['d'] = df.apply(rowFunc, axis=1)
>>> df
a b c d
0 1 2 3 7
1 4 5 6 34
</code></pre>
<p>Awesome! Now what if I want to incorporate the index into my function?
The index of any given row in this <code>DataFrame</code> before adding <code>d</code> would be <code>Index([u'a', u'b', u'c', u'd'], dtype='object')</code>, but I want the 0 and 1. So I can't just access <code>row.index</code>.</p>
<p>I know I could create a temporary column in the table where I store the index, but I'm wondering if it is stored in the row object somewhere.</p> | <p>To access the index in this case you access the <code>name</code> attribute:</p>
<pre><code>In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
</code></pre>
<p>Note that if this is really what you are trying to do that the following works and is much faster:</p>
<pre><code>In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop
</code></pre>
<p><strong>EDIT</strong></p>
<p>Looking at this question 3+ years later, you could just do:</p>
<pre><code>In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
</code></pre>
<p>but assuming it isn't as trivial as this, whatever your <code>rowFunc</code> is really doing, you should look to use the vectorised functions, and then use them against the df index:</p>
<pre><code>In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
</code></pre> | {
"question_id": 26658240,
"question_date": "2014-10-30T16:22:13.837Z",
"question_score": 207,
"tags": "python|pandas|dataframe",
"answer_id": 26658301,
"answer_date": "2014-10-30T16:25:18.800Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: Best way to pretty print a hash
<p>I have a large hash with nested arrays and hashes. I would like to simply print it out so it 'readable' to the user.</p>
<p>I would like it to be sort of like to_yaml - that's pretty readable - but still too tech looking. </p>
<p>Ultimately its going to be end users who need to read these data chunks so they need to be formatted cleanly.</p>
<p>Any suggestions?</p> | <pre><code>require 'pp'
pp my_hash
</code></pre>
<p>Use <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/pp/rdoc/index.html" rel="noreferrer"><code>pp</code></a> if you need a built-in solution and just want reasonable line breaks.</p>
<p>Use <a href="https://github.com/awesome-print/awesome_print" rel="noreferrer">awesome_print</a> if you can install a gem. (Depending on your users, you may wish to use the <code>index:false</code> option to turn off displaying array indices.)</p> | {
"question_id": 8842546,
"question_date": "2012-01-12T21:26:48.943Z",
"question_score": 207,
"tags": "ruby|ruby-on-rails-3",
"answer_id": 8842685,
"answer_date": "2012-01-12T21:35:49.203Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: Define css class in django Forms
<p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p> | <p>Answered my own question. <em>Sigh</em></p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs</a></p>
<p>I didn't realize it was passed into the widget constructor.</p> | {
"question_id": 401025,
"question_date": "2008-12-30T18:18:41.343Z",
"question_score": 207,
"tags": "python|django|django-forms",
"answer_id": 401030,
"answer_date": "2008-12-30T18:20:28.533Z",
"answer_score": 96
} |
Please answer the following Stack Overflow question:
Title: Create a string of variable length, filled with a repeated character
<p>So, my question has been asked by someone else in it's Java form here: <a href="https://stackoverflow.com/questions/1802915/java-create-a-new-string-instance-with-specified-length-and-filled-with-specif">Java - Create a new String instance with specified length and filled with specific character. Best solution?</a></p>
<p>. . . but I'm looking for its JavaScript equivalent.</p>
<p>Basically, I'm wanting to dynamically fill text fields with "#" characters, based on the "maxlength" attribute of each field. So, if an input has has <code>maxlength="3"</code>, then the field would be filled with "###".</p>
<p>Ideally there would be something like the Java <code>StringUtils.repeat("#", 10);</code>, but, so far, the best option that I can think of is to loop through and append the "#" characters, one at a time, until the max length is reached. I can't shake the feeling that there is a more efficient way to do it than that.</p>
<p>Any ideas?</p>
<p>FYI - I can't simply set a default value in the input, because the "#" characters need to clear on focus, and, if the user didn't enter a value, will need to be "refilled" on blur. It's the "refill" step that I'm concerned with</p> | <p>The best way to do this (that I've seen) is </p>
<pre><code>var str = new Array(len + 1).join( character );
</code></pre>
<p>That creates an array with the given length, and then joins it with the given string to repeat. The <code>.join()</code> function honors the array length regardless of whether the elements have values assigned, and undefined values are rendered as empty strings.</p>
<p>You have to add 1 to the desired length because the separator string goes <em>between</em> the array elements.</p> | {
"question_id": 14343844,
"question_date": "2013-01-15T17:57:43.037Z",
"question_score": 207,
"tags": "javascript|html|string",
"answer_id": 14343876,
"answer_date": "2013-01-15T17:59:54.493Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app
<p>Trying to create a react-native project on Android 4.4.2 I get this error screen</p>
<p><a href="https://i.stack.imgur.com/WGu6C.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WGu6C.png" alt="said error"></a></p>
<p>and couldn't find any way to resolve it. I tried restarting packager, reconnecting device, even reinstalling react native and starting new project. On 6.0.0 and later versions it works just fine.</p> | <p>A possible solution for this is that you most probably not bundling your application first, perform the following steps and then deploy your app-debug.apk to your device</p>
<pre><code>$ cd myproject
$ react-native start > /dev/null 2>&1 &
$ curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"
</code></pre>
<p>(if the folder <code>assets</code> does not exists create it)</p>
<p>Then run from project root</p>
<pre><code>$> (cd android/ && ./gradlew assembleDebug)
</code></pre>
<p>install the created apk to you device, from location: <code>android/app/build/outputs/apk/app-debug.apk</code></p>
<p>let me know if that fixes your issue</p>
<p><strong>EDIT</strong>:</p>
<p>You can simply put it to your package.json as a script to automate it, I believe it will be fixed in upcoming releases of react-native and will be executed prior assembling the final APK, hence this won't be needed (I hope as well)</p>
<p>put :</p>
<pre><code>"scripts": {
"build": "(cd android/ && ./gradlew assembleDebug)",
"start": "node node_modules/react-native/local-cli/cli.js start",
"bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --sourcemap-output android/app/src/main/assets/index.android.map --assets-dest android/app/src/main/res/"
},
</code></pre>
<p>or as mentioned the curl equivalent, but for most cases the above is more robust</p> | {
"question_id": 38870710,
"question_date": "2016-08-10T10:24:32.163Z",
"question_score": 207,
"tags": "android|react-native",
"answer_id": 38874952,
"answer_date": "2016-08-10T13:33:09.653Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: Is it possible to dynamically compile and execute C# code fragments?
<p>I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would compile fine within any Main() block, is it possible to compile and/or execute this code? I would prefer to compile it for performance reasons.</p>
<p>At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.</p> | <p>The best solution in C#/all static .NET languages is to use the <a href="http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx" rel="noreferrer">CodeDOM</a> for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)</p>
<p>Here's a nice short example take from <a href="http://blogs.msdn.com/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx" rel="noreferrer">LukeH's blog</a>, which uses some LINQ too just for fun.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
</code></pre>
<p>The class of primary importance here is the <code>CSharpCodeProvider</code> which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.</p>
<p><a href="https://simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/" rel="noreferrer">Here</a> is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the <code>System.Reflection</code> namespace.</p> | {
"question_id": 826398,
"question_date": "2009-05-05T18:55:34.513Z",
"question_score": 207,
"tags": "c#|compilation|dynamic-compilation",
"answer_id": 826435,
"answer_date": "2009-05-05T19:03:40.173Z",
"answer_score": 198
} |
Please answer the following Stack Overflow question:
Title: How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?
<p>I have a <code>FILE *</code>, returned by a call to <code>fopen()</code>. I need to get a file descriptor from it, to make calls like <code>fsync(fd)</code> on it. What's the function to get a file descriptor from a file pointer?</p> | <p>The proper function is <code>int fileno(FILE *stream)</code>. It can be found in <code><stdio.h></code>, and is a POSIX standard but not standard C.</p> | {
"question_id": 3167298,
"question_date": "2010-07-02T16:01:28.230Z",
"question_score": 207,
"tags": "c|linux|unix|file|posix",
"answer_id": 3167301,
"answer_date": "2010-07-02T16:02:06.530Z",
"answer_score": 252
} |
Please answer the following Stack Overflow question:
Title: How do I move a redis database from one server to another?
<p>I currently have a live redis server running on a cloud instance and I want to migrate this redis server to a new cloud instance and use that instance as my new redis server. If it were MySQL, I would export the DB from the old server and import it into the new server. How should I do this with redis? </p>
<p>P.S.: I'm not looking to set-up replication. I want to completely migrate the redis server to a new instance.</p> | <p>First, create a dump on server A.</p>
<pre><code>A$ redis-cli
127.0.0.1:6379> CONFIG GET dir
1) "dir"
2) "/var/lib/redis/"
127.0.0.1:6379> SAVE
OK
</code></pre>
<p>This ensures <code>dump.rdb</code> is completely up-to-date, and shows us where it is stored (<code>/var/lib/redis/dump.rdb</code> in this case). <code>dump.rdb</code> is also periodically written to disk automatically.</p>
<p>Next, copy it to server B:</p>
<pre><code>A$ scp /var/lib/redis/dump.rdb myuser@B:/tmp/dump.rdb
</code></pre>
<p>Stop the Redis server on B, copy dump.rdb (ensuring permissions are the same as before), then start.</p>
<pre><code>B$ sudo service redis-server stop
B$ sudo cp /tmp/dump.rdb /var/lib/redis/dump.rdb
B$ sudo chown redis: /var/lib/redis/dump.rdb
B$ sudo service redis-server start
</code></pre>
<p>The version of Redis on B must be greater or equal than that of A, or you may hit <a href="https://github.com/sripathikrishnan/redis-rdb-tools/blob/master/docs/RDB_Version_History.textile" rel="noreferrer">compatibility issues</a>.</p> | {
"question_id": 6004915,
"question_date": "2011-05-14T21:31:32.953Z",
"question_score": 207,
"tags": "database|redis|data-migration|database-migration",
"answer_id": 22024286,
"answer_date": "2014-02-25T19:31:05.750Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: Where does gcc look for C and C++ header files?
<p>On a Unix system, where does gcc look for header files?</p>
<p>I spent a little time this morning looking for some system header files, so I thought this would be good information to have here.</p> | <pre><code>`gcc -print-prog-name=cc1plus` -v
</code></pre>
<p>This command asks gcc which <strong>C++</strong> preprocessor it is using, and then asks that preprocessor where it looks for includes.</p>
<p>You will get a reliable answer for your specific setup.</p>
<p>Likewise, for the <strong>C</strong> preprocessor:</p>
<pre><code>`gcc -print-prog-name=cpp` -v
</code></pre> | {
"question_id": 344317,
"question_date": "2008-12-05T16:02:35.207Z",
"question_score": 207,
"tags": "c|gcc|header",
"answer_id": 344525,
"answer_date": "2008-12-05T17:02:48.487Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: How to programmatically skip a test in mocha?
<p>I have a code where certain tests will always fail in CI environment. I would like to disable them based on an environment condition.</p>
<p>How to programmatically skip a test in mocha during the runtime execution?</p> | <h3>Use Mocha's <a href="https://mochajs.org/#inclusive-tests" rel="noreferrer"><code>skip()</code></a> function</h3>
<p>It can be used to either statically to disable a test or entire suite, or dynamically skip it at runtime.</p>
<p>Here's an example runtime usage:</p>
<pre class="lang-js prettyprint-override"><code>it('should only test in the correct environment', function() {
if (/* check test environment */) {
// make assertions
} else {
this.skip();
}
});
</code></pre> | {
"question_id": 32723167,
"question_date": "2015-09-22T17:26:51.363Z",
"question_score": 207,
"tags": "mocha.js",
"answer_id": 32820119,
"answer_date": "2015-09-28T09:52:16.003Z",
"answer_score": 149
} |
Please answer the following Stack Overflow question:
Title: Android failed to load JS bundle
<p>I'm trying to run AwesomeProject on my Nexus5 (android 5.1.1).</p>
<p>I'm able to build the project and install it on the device. But when I run it, I got a red screen saying</p>
<blockquote>
<p>Unable to download JS bundle. Did you forget to start the development server or connect your device?</p>
</blockquote>
<p>In react native iOS, I can choose to load jsbundle offline. How can I do the same thing for Android? (Or at least, where can I configure the server address?)</p>
<h2>Update</h2>
<h3>To run with local server, run the following commands under your react-native project root directory</h3>
<ol>
<li><code>react-native start > /dev/null 2>&1 &</code></li>
<li><code>adb reverse tcp:8081 tcp:8081</code></li>
</ol>
<p>please take a look at dsissitka's answer for more details.</p>
<h3>To run without a server, bundle the jsfile into the apk by running:</h3>
<ol>
<li>create an assets folder under <code>android/app/src/main</code></li>
<li><code>curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"</code></li>
</ol>
<p>please take a look at kzzzf's answer for more details.</p> | <p>To bundle JS file into your apk while having your server running (<code>react-native start</code>) download bundle into assets directory of your app:</p>
<pre><code>curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"
</code></pre>
<p>With the next release (0.12) we'll fix <code>react-native bundle</code> command to work with android projects as expected.</p> | {
"question_id": 32572399,
"question_date": "2015-09-14T19:25:17.020Z",
"question_score": 207,
"tags": "android|react-native",
"answer_id": 32621060,
"answer_date": "2015-09-17T01:02:38.837Z",
"answer_score": 111
} |
Please answer the following Stack Overflow question:
Title: What is the advantage of using heredoc in PHP?
<p>What is the advantage of using <a href="http://php.net/heredoc" rel="noreferrer">heredoc</a> in PHP, and can you show an example?</p> | <p>The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:</p>
<pre><code>$sql = <<<SQL
select *
from $tablename
where id in [$order_ids_list]
and product_name = "widgets"
SQL;
</code></pre>
<p>To me this has a lower probability of introducing a syntax error than using quotes:</p>
<pre><code>$sql = "
select *
from $tablename
where id in [$order_ids_list]
and product_name = \"widgets\"
";
</code></pre>
<p>Another point is to avoid escaping double quotes in your string:</p>
<pre><code>$x = "The point of the \"argument" was to illustrate the use of here documents";
</code></pre>
<p>The problem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:</p>
<pre><code>$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;
</code></pre>
<p>It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:</p>
<ul>
<li><strong>Single</strong> quotes are used when the string is a constant like <code>'no variables here'</code></li>
<li><strong>Double</strong> quotes when I can put the string on a single line and require variable interpolation or an embedded single quote <code>"Today is ${user}'s birthday"</code></li>
<li><strong>Here</strong> documents for multi-line strings that require formatting and variable interpolation.</li>
</ul> | {
"question_id": 5673269,
"question_date": "2011-04-15T06:48:14.540Z",
"question_score": 207,
"tags": "php|heredoc",
"answer_id": 5673478,
"answer_date": "2011-04-15T07:12:19.870Z",
"answer_score": 229
} |
Please answer the following Stack Overflow question:
Title: When vectors are allocated, do they use memory on the heap or the stack?
<p>Are all of the following statements true?</p>
<pre><code>vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack
vector<Type*> vect; //vect will be on stack and Type* will be on heap.
</code></pre>
<p>How is the memory allocated internally for <code>Type</code> in a <code>vector</code> or any other STL container?</p> | <pre><code>vector<Type> vect;
</code></pre>
<p>will allocate the <code>vector</code>, i.e. the header info, on the stack, but the elements on the free store ("heap").</p>
<pre><code>vector<Type> *vect = new vector<Type>;
</code></pre>
<p>allocates everything on the free store.</p>
<pre><code>vector<Type*> vect;
</code></pre>
<p>will allocate the <code>vector</code> on the stack and a bunch of pointers on the free store, but where these point is determined by how you use them (you could point element 0 to the free store and element 1 to the stack, say).</p> | {
"question_id": 8036474,
"question_date": "2011-11-07T12:25:35.093Z",
"question_score": 207,
"tags": "c++|vector|stl|heap-memory|stack-memory",
"answer_id": 8036528,
"answer_date": "2011-11-07T12:29:33.037Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: Dynamic type languages versus static type languages
<p>What are the advantages and limitations of dynamic type languages compared to static type languages?</p>
<p><strong>See also</strong>: <a href="https://stackoverflow.com/questions/42934/whats-with-the-love-of-dynamic-languages">whats with the love of dynamic languages</a> (a far more argumentative thread...)</p> | <p>The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).</p>
<p>A good take on the issue is from <a href="http://www.ics.uci.edu/~lopes/teaching/inf212W12/readings/rdl04meijer.pdf" rel="noreferrer">Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages</a> by Erik Meijer and Peter Drayton at Microsoft:</p>
<blockquote>
<p>Advocates of static typing argue that
the advantages of static typing
include earlier detection of
programming mistakes (e.g. preventing
adding an integer to a boolean),
better documentation in the form of
type signatures (e.g. incorporating
number and types of arguments when
resolving names), more opportunities
for compiler optimizations (e.g.
replacing virtual calls by direct
calls when the exact type of the
receiver is known statically),
increased runtime efficiency (e.g. not
all values need to carry a dynamic
type), and a better design time
developer experience (e.g. knowing the
type of the receiver, the IDE can
present a drop-down menu of all
applicable members). Static typing
fanatics try to make us believe that
“well-typed programs cannot go wrong”.
While this certainly sounds
impressive, it is a rather vacuous
statement. Static type checking is a
compile-time abstraction of the
runtime behavior of your program, and
hence it is necessarily only partially
sound and incomplete. This means that
programs can still go wrong because of
properties that are not tracked by the
type-checker, and that there are
programs that while they cannot go
wrong cannot be type-checked. The
impulse for making static typing less
partial and more complete causes type
systems to become overly complicated
and exotic as witnessed by concepts
such as “phantom types” [11] and
“wobbly types” [10]. This is like
trying to run a marathon with a ball
and chain tied to your leg and
triumphantly shouting that you nearly
made it even though you bailed out
after the first mile.</p>
<p>Advocates of dynamically typed
languages argue that static typing is
too rigid, and that the softness of
dynamically languages makes them
ideally suited for prototyping systems
with changing or unknown requirements,
or that interact with other systems
that change unpredictably (data and
application integration). Of course,
dynamically typed languages are
indispensable for dealing with truly
dynamic program behavior such as
method interception, dynamic loading,
mobile code, runtime reflection, etc.
In the mother of all papers on
scripting [16], John Ousterhout argues
that statically typed systems
programming languages make code less
reusable, more verbose, not more safe,
and less expressive than dynamically
typed scripting languages. This
argument is parroted literally by many
proponents of dynamically typed
scripting languages. We argue that
this is a fallacy and falls into the
same category as arguing that the
essence of declarative programming is
eliminating assignment. Or as John
Hughes says [8], it is a logical
impossibility to make a language more
powerful by omitting features.
Defending the fact that delaying all
type-checking to runtime is a good
thing, is playing ostrich tactics with
the fact that errors should be caught
as early in the development process as
possible.</p>
</blockquote> | {
"question_id": 125367,
"question_date": "2008-09-24T04:05:00.947Z",
"question_score": 207,
"tags": "programming-languages|dynamic-languages|type-systems",
"answer_id": 125379,
"answer_date": "2008-09-24T04:10:22.073Z",
"answer_score": 140
} |
Please answer the following Stack Overflow question:
Title: How to rename AWS S3 Bucket
<p>After all the tough work of migration etc, I just realised that I need to serve the content using CNAME (e.g media.abc.com). The bucket name needs to start with media.abc.com/S3/amazon.com to ensure it works perfectly.</p>
<p>I just realised that S3 doesn't allow direct rename from the console.</p>
<p>Is there any way to work around this?</p> | <p>I think only way is to create a new bucket with correct name and then copy all your objects from old bucket to new bucket. You can do it using Aws CLI.</p> | {
"question_id": 41511034,
"question_date": "2017-01-06T17:30:54.610Z",
"question_score": 207,
"tags": "amazon-web-services|amazon-s3|cname",
"answer_id": 41515547,
"answer_date": "2017-01-06T22:40:54.857Z",
"answer_score": 129
} |
Please answer the following Stack Overflow question:
Title: String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?
<p>Which would be better code:</p>
<pre><code>int index = fileName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase);
</code></pre>
<p>or</p>
<pre><code>int index = fileName.LastIndexOf(".", StringComparison.OrdinalIgnoreCase);
</code></pre> | <p>If you really want to match only the dot, then <code>StringComparison.Ordinal</code> would be fastest, as there is no case-difference. </p>
<p>"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a <code>.</code>.</p> | {
"question_id": 2749662,
"question_date": "2010-05-01T11:00:08.033Z",
"question_score": 207,
"tags": "c#|string",
"answer_id": 2749752,
"answer_date": "2010-05-01T11:38:50.970Z",
"answer_score": 53
} |
Please answer the following Stack Overflow question:
Title: How to determine if one array contains all elements of another array
<p>Given:</p>
<pre><code>a1 = [5, 1, 6, 14, 2, 8]
</code></pre>
<p>I would like to determine if it contains all elements of:</p>
<pre><code>a2 = [2, 6, 15]
</code></pre>
<p>In this case the result is <code>false</code>.</p>
<p>Are there any built-in Ruby/Rails methods to identify such array inclusion?</p>
<p>One way to implement this is:</p>
<pre><code>a2.index{ |x| !a1.include?(x) }.nil?
</code></pre>
<p>Is there a better, more readable, way?</p> | <pre><code>a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]
a - b
# => [5, 1, 14, 8]
b - a
# => [15]
(b - a).empty?
# => false
</code></pre> | {
"question_id": 7387937,
"question_date": "2011-09-12T12:34:12.913Z",
"question_score": 207,
"tags": "ruby-on-rails|arrays|ruby",
"answer_id": 7388004,
"answer_date": "2011-09-12T12:39:17.607Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: How to get the name of enumeration value in Swift?
<p>If I have an enumeration with raw <code>Integer</code> values:</p>
<pre><code>enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
</code></pre>
<p>How can I convert a <code>city</code> value to a string <code>Melbourne</code>? Is this kind of a type name introspection available in the language?</p>
<p>Something like (this code will not work):</p>
<pre><code>println("Your city is \(city.magicFunction)")
> Your city is Melbourne
</code></pre> | <p>As of Xcode 7 beta 5 (Swift version 2) you can now print type names and enum cases by default using <code>print(_:)</code>, or convert to <code>String</code> using <code>String</code>'s <code>init(_:)</code> initializer or string interpolation syntax. So for your example:</p>
<pre><code>enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
print(city)
// prints "Melbourne"
let cityName = "\(city)" // or `let cityName = String(city)`
// cityName contains "Melbourne"
</code></pre>
<p>So there is no longer a need to define & maintain a convenience function that switches on each case to return a string literal. In addition, this works automatically for any enum, even if no raw-value type is specified.</p>
<p><code>debugPrint(_:)</code> & <code>String(reflecting:)</code> can be used for a fully-qualified name:</p>
<pre><code>debugPrint(city)
// prints "App.City.Melbourne" (or similar, depending on the full scope)
let cityDebugName = String(reflecting: city)
// cityDebugName contains "App.City.Melbourne"
</code></pre>
<p>Note that you can customise what is printed in each of these scenarios:</p>
<pre><code>extension City: CustomStringConvertible {
var description: String {
return "City \(rawValue)"
}
}
print(city)
// prints "City 1"
extension City: CustomDebugStringConvertible {
var debugDescription: String {
return "City (rawValue: \(rawValue))"
}
}
debugPrint(city)
// prints "City (rawValue: 1)"
</code></pre>
<p><em>(I haven't found a way to call into this "default" value, for example, to print "The city is Melbourne" without resorting back to a switch statement. Using <code>\(self)</code> in the implementation of <code>description</code>/<code>debugDescription</code> causes an infinite recursion.)</em></p>
<p><br>
The comments above <code>String</code>'s <code>init(_:)</code> & <code>init(reflecting:)</code> initializers describe exactly what is printed, depending on what the reflected type conforms to:</p>
<pre><code>extension String {
/// Initialize `self` with the textual representation of `instance`.
///
/// * If `T` conforms to `Streamable`, the result is obtained by
/// calling `instance.writeTo(s)` on an empty string s.
/// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
/// result is `instance`'s `description`
/// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
/// the result is `instance`'s `debugDescription`
/// * Otherwise, an unspecified result is supplied automatically by
/// the Swift standard library.
///
/// - SeeAlso: `String.init<T>(reflecting: T)`
public init<T>(_ instance: T)
/// Initialize `self` with a detailed textual representation of
/// `subject`, suitable for debugging.
///
/// * If `T` conforms to `CustomDebugStringConvertible`, the result
/// is `subject`'s `debugDescription`.
///
/// * Otherwise, if `T` conforms to `CustomStringConvertible`, the result
/// is `subject`'s `description`.
///
/// * Otherwise, if `T` conforms to `Streamable`, the result is
/// obtained by calling `subject.writeTo(s)` on an empty string s.
///
/// * Otherwise, an unspecified result is supplied automatically by
/// the Swift standard library.
///
/// - SeeAlso: `String.init<T>(T)`
public init<T>(reflecting subject: T)
}
</code></pre>
<p><br>
See the <a href="https://developer.apple.com/library/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc7_release_notes.html#//apple_ref/doc/uid/TP40001051-CH5-SW29" rel="noreferrer">release notes</a> for info about this change.</p> | {
"question_id": 24113126,
"question_date": "2014-06-09T03:04:27.100Z",
"question_score": 207,
"tags": "swift|enumeration",
"answer_id": 31893968,
"answer_date": "2015-08-08T14:13:15.577Z",
"answer_score": 170
} |
Please answer the following Stack Overflow question:
Title: CFNetwork SSLHandshake failed iOS 9
<p>has anyone with the iOS 9 beta 1 had this issue? </p>
<p>I use standard NSURLConnection to connect to a webservice and as soon as a call is made to the webservice i get the below error. This is currently working in iOS 8.3</p>
<p>Possible beta bug? any ideas or thoughts would be great ! I know its very early in iOS 9 development</p>
<p>Here is the full error:</p>
<blockquote>
<p>CFNetwork SSLHandshake failed (-9824)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)</p>
</blockquote>
<pre><code> NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://mywebserviceurl"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
</code></pre> | <p>iOS 9 and OSX 10.11 require TLSv1.2 SSL for all hosts you plan to request data from unless you specify exception domains in your app's Info.plist file.</p>
<p>The syntax for the Info.plist configuration looks like this:</p>
<pre><code><key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow insecure HTTP requests-->
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
</code></pre>
<p>If your application (a third-party web browser, for instance) needs to connect to arbitrary hosts, you can configure it like this:</p>
<pre><code><key>NSAppTransportSecurity</key>
<dict>
<!--Connect to anything (this is probably BAD)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</code></pre>
<p>If you're having to do this, it's probably best to update your servers to use TLSv1.2 and SSL, if they're not already doing so. This should be considered a temporary workaround.</p>
<p>As of today, the prerelease documentation makes no mention of any of these configuration options in any specific way. Once it does, I'll update the answer to link to the relevant documentation.</p> | {
"question_id": 30720813,
"question_date": "2015-06-08T23:44:59.887Z",
"question_score": 207,
"tags": "ios|ssl|nsurlconnection|ios9",
"answer_id": 30720929,
"answer_date": "2015-06-08T23:58:56.327Z",
"answer_score": 310
} |
Please answer the following Stack Overflow question:
Title: Android Room - Get the id of new inserted row with auto-generate
<p>This is how I am inserting data into database using Room Persistence Library:</p>
<p>Entity:</p>
<pre><code>@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
</code></pre>
<p>Data access object:</p>
<pre><code>@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
</code></pre>
<p>Is it possible to return the id of User once the insertion is completed in the above method itself without writing a separate select query?</p> | <p>Based on the documentation <a href="https://developer.android.com/training/data-storage/room/accessing-data#convenience-insert" rel="noreferrer">here</a> (below the code snippet)</p>
<p>A method annotated with the <code>@Insert</code> annotation can return:</p>
<blockquote>
<ul>
<li><code>long</code> for single insert operation</li>
<li><code>long[]</code> or <code>Long[]</code> or <code>List<Long></code> for multiple insert operations</li>
<li><code>void</code> if you don't care about the inserted id(s)</li>
</ul>
</blockquote> | {
"question_id": 44364240,
"question_date": "2017-06-05T07:55:00.080Z",
"question_score": 207,
"tags": "android|persistent-storage|android-room",
"answer_id": 44364516,
"answer_date": "2017-06-05T08:12:30.983Z",
"answer_score": 286
} |
Please answer the following Stack Overflow question:
Title: single command to stop and remove docker container
<p>Is there any command which can combine the <code>docker stop</code> and <code>docker rm</code> command together ? Each time I want to delete a running container, I need to execute 2 commands sequentially, I wonder if there is a combined command can simplify this process.</p>
<pre><code>docker stop CONTAINER_ID
docker rm CONTATINER_ID
</code></pre> | <p>You can use :</p>
<pre><code>docker rm -f CONTAINER_ID
</code></pre>
<p>It will remove the container even if it is still running.</p>
<p><a href="https://docs.docker.com/engine/reference/commandline/rm/" rel="nofollow noreferrer">https://docs.docker.com/engine/reference/commandline/rm/</a></p>
<p>You can also run your containers with <code>--rm</code> option (e.g. <code>docker run --rm -it alpine</code>), it will be automatically removed when stopped.</p>
<p><a href="https://docs.docker.com/engine/reference/run/#clean-up---rm" rel="nofollow noreferrer">https://docs.docker.com/engine/reference/run/#clean-up---rm</a></p>
<p><strong>Edit:</strong> The <code>rm -f</code> might be dangerous for your data and is best suited for test or development containers. @Bernard's comment on this subject is worth reading.</p> | {
"question_id": 35122773,
"question_date": "2016-02-01T03:53:59.607Z",
"question_score": 207,
"tags": "docker",
"answer_id": 35122815,
"answer_date": "2016-02-01T03:59:22.110Z",
"answer_score": 333
} |
Please answer the following Stack Overflow question:
Title: Rails find_or_create_by more than one attribute?
<p>There is a handy dynamic attribute in active-record called find_or_create_by:</p>
<p><code>Model.find_or_create_by_<attribute>(:<attribute> => "")</code></p>
<p>But what if I need to find_or_create by more than one attribute?</p>
<p>Say I have a model to handle a M:M relationship between Group and Member called GroupMember. I could have many instances where member_id = 4, but I don't ever want more than once instance where member_id = 4 and group_id = 7. I'm trying to figure out if it's possible to do something like this:</p>
<pre><code>GroupMember.find_or_create(:member_id => 4, :group_id => 7)
</code></pre>
<p>I realize there may be better ways to handle this, but I like the convenience of the idea of find_or_create.</p> | <p>Multiple attributes can be connected with an <code>and</code>:</p>
<pre><code>GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
</code></pre>
<p>(use <code>find_or_initialize_by</code> if you don't want to save the record right away)</p>
<p><strong>Edit:</strong> The above method is deprecated in Rails 4. The new way to do it will be:</p>
<pre><code>GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
</code></pre>
<p>and</p>
<pre><code>GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
</code></pre>
<p><strong>Edit 2:</strong> Not all of these were factored out of rails just the attribute specific ones. </p>
<p><a href="https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md" rel="noreferrer">https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md</a></p>
<p>Example </p>
<pre><code>GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
</code></pre>
<p>became </p>
<pre><code>GroupMember.find_or_create_by(member_id: 4, group_id: 7)
</code></pre> | {
"question_id": 3046607,
"question_date": "2010-06-15T15:27:00.700Z",
"question_score": 207,
"tags": "ruby-on-rails|activerecord|model|many-to-many|dynamic-attributes",
"answer_id": 3046645,
"answer_date": "2010-06-15T15:31:13.410Z",
"answer_score": 478
} |
Please answer the following Stack Overflow question:
Title: Why git can't remember my passphrase under Windows
<p>I have just start using git and i can't get it to remember my passphrase I'm using cmd.exe elevated and my git host is github and i have create a ssh key like that guide on github</p>
<p>but i still get </p>
<pre><code>*\subnus.mvc>git push origin master
Enter passphrase for key '/c/Users/Subnus/.ssh/id_rsa':
</code></pre> | <p>I realize that this question is coming up on two years old, but I had the same issue and several answers here did not completely answer the question for me. Here are three step-by-step solutions, depending on whether you use TortoiseGit in addition to msysgit or not.</p>
<p><strong>First solution</strong> Assumes Windows, msysgit, and PuTTY.</p>
<ol>
<li><p>Install msysgit and PuTTY as instructed.</p>
</li>
<li><p>(Optional) Add PuTTY to your path. <em>(If you do not do this, then any references to PuTTY commands below must be prefixed with the full path to the appropriate executable.)</em></p>
</li>
<li><p>If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.</p>
</li>
<li><p>Again, if you have not already done so, convert your key for use with PuTTY's pageant.exe using <strong>puttygen.exe</strong>. Instructions are in PuTTY's documentation, in <a href="http://www.electrictoolbox.com/putty-rsa-dsa-keys/" rel="noreferrer">this helpful guide</a>, and several other places in cyberspace.</p>
</li>
<li><p>Run PuTTY's <strong>pageant.exe</strong>, open your .ppk file ("Add Key"), and provide your passphrase for your key.</p>
</li>
<li><p>Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:</p>
<p>GIT_SSH=C:\full\path\to\plink.exe</p>
<p>Replace "C:\full\path\to" with the full installation path to PuTTY, where plink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to plink.exe matches the path you use for Pageant (pageant.exe). In some cases, you may have several installations of PuTTY because it might be installed along with other applications. Using plink.exe from one installation and pageant.exe from another will likely cause you trouble.</p>
</li>
<li><p>Open a command prompt.</p>
</li>
<li><p>If you are trying to connect to a git repository hosted at Github.com then run the following command:</p>
<p>plink.exe [email protected]</p>
<p>If the git repository you are trying to connect to is hosted somewhere else, then replace <em>[email protected]</em> with an appropriate user name and URL. (Assuming Github) You should be informed that the server's host key is not cached, and asked if you trust it. Answer with a <strong>y</strong>. This will add the server's host key to PuTTY's list of known hosts. Without this step, git commands will not work properly. After hitting enter, Github informs you that Github does not provide shell access. That's fine...we don't need it. (If you are connecting to some other host, and it gives you shell access, it is probably best to terminate the link without doing anything else.)</p>
</li>
<li><p>All done! Git commands should now work from the command line. You may want to have pageant.exe <a href="http://blog.shvetsov.com/2010/03/making-pageant-automatically-load-keys.html" rel="noreferrer">load your .ppk file automatically at boot time</a>, depending on how often you'll be needing it.</p>
</li>
</ol>
<p><strong>Second solution</strong> Assumes Windows, msysgit, and TortoiseGit.</p>
<p>TortoiseGit comes with PuTTY executables and a specially modified version of plink (called TortoisePlink.exe) that will make things easier.</p>
<ol>
<li><p>Install msysgit and TortoiseGit as instructed.</p>
</li>
<li><p>If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.</p>
</li>
<li><p>Again, if you have not already done so, convert your key for use with TortoiseGit's pageant.exe using TortoiseGit's <strong>puttygen.exe</strong>. Instructions are in PuTTY's documentation, in the helpful guide linked to in the first solution, and in several other places in cyberspace.</p>
</li>
<li><p>Run TortoiseGit's <strong>pageant.exe</strong>, open your .ppk file ("Add Key") and provide your passphrase for your key.</p>
</li>
<li><p>Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:</p>
<p>GIT_SSH=C:\full\path\to\TortoisePlink.exe</p>
<p>Replace "C:\full\path\to" with the full installation path to TortoiseGit, where TortoisePlink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to TortoisePlink.exe matches the path you use for Pageant (pageant.exe). In some cases, you may have several installations of PuTTY because it might be installed along with other applications. Using TortoisePlink.exe from the TortoiseGit installation and pageant.exe from another installation of a different application (or from a standalone PuTTY installation) will likely cause you trouble.</p>
</li>
<li><p>All done! Git commands should now work from the command line. The first time you try to connect to your git repository you will probably be informed that the server's host key is not cached, and asks if you trust the server. Click on "Yes". (This is TortoisePlink.exe in action.)</p>
<p>You may want to have pageant.exe <a href="http://blog.shvetsov.com/2010/03/making-pageant-automatically-load-keys.html" rel="noreferrer">load your .ppk file automatically at boot time</a>, depending on how often you'll be needing it.</p>
</li>
</ol>
<p><strong>Third solution</strong> Assumes Windows, msysgit, and the native command prompt.</p>
<ol>
<li>Install msysgit</li>
<li>Make sure to allow git to be used on the MS-DOS command prompt</li>
<li>Run <code>start-ssh-agent</code></li>
<li>Enter SSH passphrases</li>
<li>All done! Git commands should now work in the native command prompt.</li>
</ol> | {
"question_id": 370030,
"question_date": "2008-12-15T23:12:26.647Z",
"question_score": 207,
"tags": "windows|git|ssh|cmd",
"answer_id": 4356869,
"answer_date": "2010-12-05T01:24:03.597Z",
"answer_score": 221
} |
Please answer the following Stack Overflow question:
Title: DeprecationWarning: invalid escape sequence - what to use instead of \d?
<p>I've met a problem with <code>re</code> module in Python 3.6.5.
I have this pattern in my regular expression:</p>
<pre><code>'\\nRevision: (\d+)\\n'
</code></pre>
<p>But when I run it, I'm getting a <code>DeprecationWarning</code>.</p>
<p>I searched for <a href="https://stackoverflow.com/search?q=DeprecationWarning%3A%20invalid%20escape%20sequence%20%5Cd">the problem on SO</a>, and haven't found the answer, actually - what should I use instead of <code>\d+</code>? Just <code>[0-9]+</code> or maybe something else?</p> | <p>Python 3 interprets string literals as Unicode strings, and therefore your <code>\d</code> is treated as an escaped Unicode character.</p>
<p>Declare your RegEx pattern as a raw string instead by prepending <code>r</code>, as below:</p>
<pre><code>r'\nRevision: (\d+)\n'
</code></pre>
<p>This also means you can drop the escapes for <code>\n</code> as well since these will just be parsed as newline characters by <code>re</code>.</p> | {
"question_id": 50504500,
"question_date": "2018-05-24T08:27:43.030Z",
"question_score": 207,
"tags": "python|regex|python-3.x",
"answer_id": 50504635,
"answer_date": "2018-05-24T08:33:45.763Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Rails :dependent => :destroy VS :dependent => :delete_all
<p>In rails guides it's described like this:</p>
<blockquote>
<p>Objects will be in addition destroyed if they’re associated with <code>:dependent => :destroy</code>, and deleted if they’re associated with <code>:dependent => :delete_all</code></p>
</blockquote>
<p>Right, cool. But what's the difference between being destroyed and being deleted?
I tried both and it seems to do the same thing.</p> | <p>The difference is with the callback.</p>
<p>The <code>:delete_all</code> is made directly in your application and deletes by SQL :</p>
<pre><code>DELETE * FROM users where compagny_id = XXXX
</code></pre>
<p>With the <code>:destroy</code>, there is an instantiation of all of your children. So, if you can't destroy it or if each has their own <code>:dependent</code>, its callbacks can be called.</p> | {
"question_id": 2797339,
"question_date": "2010-05-09T10:27:23.920Z",
"question_score": 207,
"tags": "ruby-on-rails|ruby|model|associations",
"answer_id": 2797358,
"answer_date": "2010-05-09T10:36:01.207Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: What does "Mass Assignment" mean in Laravel?
<p>When I went through Laravel Document about Eloquent ORM topic part, I got a new term "Mass Assignment".</p>
<p>Document show How to do Mass Assignment and the <code>$fillable</code> or <code>$guarded</code> properties settings. But after went through that, I didn't have a clearly understand about "Mass Assignment" and how it works.</p>
<p>In my past experience in CodeIgniter, I also didn't hear about this term.</p>
<p>Does anyone have a simple explanation about that?</p> | <p>Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like:</p>
<pre><code>$user = new User(request()->all());
</code></pre>
<p>(This is instead of explicitly setting each value on the model separately.) </p>
<p>You can use <code>fillable</code> to protect which fields you want this to actually allow for updating.</p>
<p>You can also block all fields from being mass-assignable by doing this:</p>
<pre><code>protected $guarded = ['*'];
</code></pre>
<p>Let's say in your user table you have a field that is <code>user_type</code> and that can have values of user / admin</p>
<p>Obviously, you don't want users to be able to update this value. In theory, if you used the above code, someone could inject into a form a new field for <code>user_type</code> and send 'admin' along with the other form data, and easily switch their account to an admin account... bad news.</p>
<p>By adding:</p>
<pre><code>$fillable = ['name', 'password', 'email'];
</code></pre>
<p>You are ensuring that only those values can be updated using <code>mass assignment</code></p>
<p>To be able to update the <code>user_type</code> value, you need to explicitly set it on the model and save it, like this:</p>
<pre><code>$user->user_type = 'admin';
$user->save();
</code></pre> | {
"question_id": 22279435,
"question_date": "2014-03-09T07:14:28.970Z",
"question_score": 207,
"tags": "php|laravel|eloquent|mass-assignment",
"answer_id": 22279580,
"answer_date": "2014-03-09T07:33:14.543Z",
"answer_score": 264
} |
Please answer the following Stack Overflow question:
Title: Approximate cost to access various caches and main memory?
<p>Can anyone give me the approximate time (in nanoseconds) to access L1, L2 and L3 caches, as well as main memory on Intel i7 processors?</p>
<p>While this isn't specifically a programming question, knowing these kinds of speed details is neccessary for some low-latency programming challenges. </p> | <p><a href="https://web.archive.org/web/20160315021718/https://software.intel.com/sites/products/collateral/hpc/vtune/performance_analysis_guide.pdf" rel="nofollow noreferrer">Here is a Performance Analysis Guide</a> for the i7 and Xeon range of processors. I should stress, this has what you need and more (for example, check page 22 for some timings & cycles for example).</p>
<p>Additionally, <a href="http://software.intel.com/en-us/forums/showthread.php?t=77966" rel="nofollow noreferrer">this page</a> has some details on clock cycles etc. The second link served the following numbers:</p>
<pre><code>Core i7 Xeon 5500 Series Data Source Latency (approximate) [Pg. 22]
local L1 CACHE hit, ~4 cycles ( 2.1 - 1.2 ns )
local L2 CACHE hit, ~10 cycles ( 5.3 - 3.0 ns )
local L3 CACHE hit, line unshared ~40 cycles ( 21.4 - 12.0 ns )
local L3 CACHE hit, shared line in another core ~65 cycles ( 34.8 - 19.5 ns )
local L3 CACHE hit, modified in another core ~75 cycles ( 40.2 - 22.5 ns )
remote L3 CACHE (Ref: Fig.1 [Pg. 5]) ~100-300 cycles ( 160.7 - 30.0 ns )
local DRAM ~60 ns
remote DRAM ~100 ns
</code></pre>
<p><strong><code>EDIT2</code></strong>:
<br>The most important is the notice under the cited table, saying:<br></p>
<blockquote>
<p><sub>"NOTE: THESE VALUES ARE ROUGH APPROXIMATIONS. <strong>THEY DEPEND ON
CORE AND UNCORE FREQUENCIES, MEMORY SPEEDS, BIOS SETTINGS,
NUMBERS OF DIMMS</strong>, ETC,ETC..<strong>YOUR MILEAGE MAY VARY.</strong>"</sub></p>
</blockquote>
<p>EDIT: I should highlight that, as well as timing/cycle information, the above intel document addresses much more (extremely) useful details of the i7 and Xeon range of processors (from a performance point of view).</p> | {
"question_id": 4087280,
"question_date": "2010-11-03T13:02:38.807Z",
"question_score": 207,
"tags": "performance|memory|latency|cpu-cache|low-latency",
"answer_id": 4087331,
"answer_date": "2010-11-03T13:09:22.023Z",
"answer_score": 88
} |
Please answer the following Stack Overflow question:
Title: Unable to export Apple production push SSL certificate in .p12 format
<p>I am using Urban airship in my application for push notification. So, I need to download the push SSL certificate from Apple developer portal. After downloading, I added that in keychain access. But no private key was created for the certificate. When I tried to right click and export the certificate, I was not able to export that as <em>.p12</em> file as the <em>.p12</em> file extension was disabled while saving. I am unable to attach the screenshots here due to lesser reputation.</p>
<p>Someone please tell me where is the issue here. How should I do that?</p> | <p>Turns out all you have to do is select "My Certificates" on the left panel and it enables the .p12 option.</p>
<p><a href="https://i.stack.imgur.com/uLlex.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uLlex.png" alt="enter image description here" /></a></p> | {
"question_id": 15662377,
"question_date": "2013-03-27T15:13:30.540Z",
"question_score": 207,
"tags": "ios",
"answer_id": 19502944,
"answer_date": "2013-10-21T19:22:04.173Z",
"answer_score": 673
} |
Please answer the following Stack Overflow question:
Title: NumPy or Pandas: Keeping array type as integer while having a NaN value
<p>Is there a preferred way to keep the data type of a <code>numpy</code> array fixed as <code>int</code> (or <code>int64</code> or whatever), while still having an element inside listed as <code>numpy.NaN</code>?</p>
<p>In particular, I am converting an in-house data structure to a Pandas DataFrame. In our structure, we have integer-type columns that still have NaN's (but the dtype of the column is int). It seems to recast everything as a float if we make this a DataFrame, but we'd really like to be <code>int</code>.</p>
<p>Thoughts?</p>
<p><strong>Things tried:</strong></p>
<p>I tried using the <code>from_records()</code> function under pandas.DataFrame, with <code>coerce_float=False</code> and this did not help. I also tried using NumPy masked arrays, with NaN fill_value, which also did not work. All of these caused the column data type to become a float.</p> | <p>This capability has been added to pandas (beginning with version 0.24):
<a href="https://pandas.pydata.org/pandas-docs/version/0.24/whatsnew/v0.24.0.html#optional-integer-na-support" rel="noreferrer">https://pandas.pydata.org/pandas-docs/version/0.24/whatsnew/v0.24.0.html#optional-integer-na-support</a></p>
<p>At this point, it requires the use of extension dtype Int64 (capitalized), rather than the default dtype int64 (lowercase).</p> | {
"question_id": 11548005,
"question_date": "2012-07-18T18:30:02.887Z",
"question_score": 207,
"tags": "python|numpy|int|pandas|type-conversion",
"answer_id": 51997100,
"answer_date": "2018-08-24T03:36:20.830Z",
"answer_score": 106
} |
Please answer the following Stack Overflow question:
Title: MySQL OR vs IN performance
<p>I am wondering if there is any difference with regards to performance between the following</p>
<pre><code>SELECT ... FROM ... WHERE someFIELD IN(1,2,3,4)
SELECT ... FROM ... WHERE someFIELD between 0 AND 5
SELECT ... FROM ... WHERE someFIELD = 1 OR someFIELD = 2 OR someFIELD = 3 ...
</code></pre>
<p>or will MySQL optimize the SQL in the same way compilers optimize code?</p>
<hr />
<h3>EDIT</h3>
<p>Changed the <code>AND</code>'s to <code>OR</code>'s for the reason stated in the comments.</p> | <p>The accepted answer doesn't explain the reason. </p>
<p>Below are quoted from High Performance MySQL, 3rd Edition.</p>
<blockquote>
<p>In many database servers, IN() is just a synonym for multiple OR clauses, because the two are logically equivalent. Not so in MySQL, which sorts the values in the IN() list and uses a fast binary search to see whether a value is in the list. This is O(Log n) in the size of the list, whereas an equivalent series of OR clauses is O(n) in the size of the list (i.e., much slower for large lists)</p>
</blockquote> | {
"question_id": 782915,
"question_date": "2009-04-23T18:16:52.883Z",
"question_score": 207,
"tags": "mysql|sql|performance|optimization",
"answer_id": 51833230,
"answer_date": "2018-08-14T03:16:56.927Z",
"answer_score": 60
} |
Please answer the following Stack Overflow question:
Title: What does @: (at symbol colon) mean in a Makefile?
<p>What does the following do in a Makefile?</p>
<pre><code>rule: $(deps)
@:
</code></pre>
<p>I can't seem to find this in the make manual.</p> | <p>It means "don't echo this command on the output." So this rule is saying "execute the shell command <code>:</code> and don't echo the output.</p>
<p>Of course the shell command <code>:</code> is a no-op, so this is saying "do nothing, and don't tell."</p>
<p><em>Why?</em></p>
<p>The trick here is that you've got an obscure combination of two different syntaxes. The <em>make(1)</em> syntax is the use of an action starting with @, which is simply not to echo the command. So a rule like </p>
<pre><code>always:
@echo this always happens
</code></pre>
<p>won't emit</p>
<pre><code> echo this always happens
this always happens
</code></pre>
<p>Now, the action part of a rule can be <em>any</em> shell command, including <code>:</code>. Bash help explains this as well as anywhere:</p>
<pre><code>$ help :
:: :
Null command.
No effect; the command does nothing.
Exit Status:
Always succeeds.
</code></pre> | {
"question_id": 8610799,
"question_date": "2011-12-22T23:21:19.687Z",
"question_score": 207,
"tags": "makefile|gnu-make",
"answer_id": 8610814,
"answer_date": "2011-12-22T23:23:32.207Z",
"answer_score": 275
} |
Please answer the following Stack Overflow question:
Title: How can I call a custom Django manage.py command directly from a test driver?
<p>I want to write a unit test for a Django manage.py command that does a backend operation on a database table. How would I invoke the management command directly from code? </p>
<p>I don't want to execute the command on the Operating System's shell from tests.py because I can't use the test environment set up using manage.py test (test database, test dummy email outbox, etc...)</p> | <p>The best way to test such things - extract needed functionality from command itself to standalone function or class. It helps to abstract from "command execution stuff" and write test without additional requirements.</p>
<p>But if you by some reason cannot decouple logic form command you can call it from any code using <a href="https://docs.djangoproject.com/en/2.0/ref/django-admin/#running-management-commands-from-your-code" rel="noreferrer">call_command</a> method like this:</p>
<pre><code>from django.core.management import call_command
call_command('my_command', 'foo', bar='baz')
</code></pre> | {
"question_id": 907506,
"question_date": "2009-05-25T17:39:05.703Z",
"question_score": 207,
"tags": "django|unit-testing",
"answer_id": 907743,
"answer_date": "2009-05-25T19:04:02.023Z",
"answer_score": 373
} |
Please answer the following Stack Overflow question:
Title: What's the difference between a Python "property" and "attribute"?
<p>I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences. </p> | <p>Properties are a special kind of attribute. Basically, when Python encounters the following code:</p>
<pre><code>spam = SomeObject()
print(spam.eggs)
</code></pre>
<p>it looks up <code>eggs</code> in <code>spam</code>, and then examines <code>eggs</code> to see if it has a <code>__get__</code>, <code>__set__</code>, or <code>__delete__</code> method — if it does, it's a property. If it <em>is</em> a property, instead of just returning the <code>eggs</code> object (as it would for any other attribute) it will call the <code>__get__</code> method (since we were doing lookup) and return whatever that method returns.</p>
<p>More information about <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="noreferrer">Python's data model and descriptors</a>.</p> | {
"question_id": 7374748,
"question_date": "2011-09-10T21:15:34.447Z",
"question_score": 207,
"tags": "python",
"answer_id": 7377013,
"answer_date": "2011-09-11T07:56:36.833Z",
"answer_score": 232
} |
Please answer the following Stack Overflow question:
Title: What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface?
<p>Looking at ASP.NET Identity (new membership implementation in ASP.NET), I came across this interface when implementing my own <code>UserStore</code>:</p>
<pre><code>//Microsoft.AspNet.Identity.Core.dll
namespace Microsoft.AspNet.Identity
{
public interface IUserSecurityStampStore<TUser> :
{
// Methods
Task<string> GetSecurityStampAsync(TUser user);
Task SetSecurityStampAsync(TUser user, string stamp);
}
}
</code></pre>
<p><code>IUserSecurityStampStore</code> is implemented by the default <code>EntityFramework.UserStore<TUser></code> which essentially get and set the <code>TUser.SecurityStamp</code> property.</p>
<p>After some more digging, it appears that a <code>SecurityStamp</code> is a <code>Guid</code> that is newly generated at key points in the <code>UserManager</code> (for example, changing passwords).</p>
<p>I can't really decipher much beyond this since I'm examining this code in <strong>Reflector</strong>. Almost all the symbol and async information has been optimized out.</p>
<p>Also, Google hasn't been much help.</p>
<h1>Questions are:</h1>
<ul>
<li>What is a <code>SecurityStamp</code> in ASP.NET Identity and what is it used for?</li>
<li>Does the <code>SecurityStamp</code> play any role when authentication cookies are created?</li>
<li>Are there any security ramifications or precautions that need to be taken with this? For example, don't send this value downstream to clients?</li>
</ul>
<hr>
<h2>Update (9/16/2014)</h2>
<p>Source code available here:</p>
<ul>
<li><a href="https://github.com/aspnet/Identity/">https://github.com/aspnet/Identity/</a></li>
<li><a href="https://github.com/aspnet/Security/">https://github.com/aspnet/Security/</a></li>
</ul> | <p>This is meant to represent the current snapshot of your user's credentials. So if nothing changes, the stamp will stay the same. But if the user's password is changed, or a login is removed (unlink your google/fb account), the stamp will change. This is needed for things like automatically signing users/rejecting old cookies when this occurs, which is a feature that's coming in 2.0.</p>
<p>Identity is not open source yet, its currently in the pipeline still.</p>
<p><strong>Edit: Updated for 2.0.0.</strong> So the primary purpose of the <code>SecurityStamp</code> is to enable sign out everywhere. The basic idea is that whenever something security related is changed on the user, like a password, it is a good idea to automatically invalidate any existing sign in cookies, so if your password/account was previously compromised, the attacker no longer has access.</p>
<p>In 2.0.0 we added the following configuration to hook the <code>OnValidateIdentity</code> method in the <code>CookieMiddleware</code> to look at the <code>SecurityStamp</code> and reject cookies when it has changed. It also automatically refreshes the user's claims from the database every <code>refreshInterval</code> if the stamp is unchanged (which takes care of things like changing roles etc)</p>
<pre><code>app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider {
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
</code></pre>
<p>If your app wants to trigger this behavior explicitly, it can call:</p>
<pre><code>UserManager.UpdateSecurityStampAsync(userId);
</code></pre> | {
"question_id": 19487322,
"question_date": "2013-10-21T06:09:05.787Z",
"question_score": 207,
"tags": "asp.net|asp.net-mvc|asp.net-mvc-5|asp.net-identity",
"answer_id": 19505060,
"answer_date": "2013-10-21T21:26:45.217Z",
"answer_score": 250
} |
Please answer the following Stack Overflow question:
Title: How to use R's ellipsis feature when writing your own function?
<p>The R language has a nifty feature for defining functions that can take a variable number of arguments. For example, the function <code>data.frame</code> takes any number of arguments, and each argument becomes the data for a column in the resulting data table. Example usage:</p>
<pre><code>> data.frame(letters=c("a", "b", "c"), numbers=c(1,2,3), notes=c("do", "re", "mi"))
letters numbers notes
1 a 1 do
2 b 2 re
3 c 3 mi
</code></pre>
<p>The function's signature includes an ellipsis, like this:</p>
<pre><code>function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
stringsAsFactors = default.stringsAsFactors())
{
[FUNCTION DEFINITION HERE]
}
</code></pre>
<p>I would like to write a function that does something similar, taking multiple values and consolidating them into a single return value (as well as doing some other processing). In order to do this, I need to figure out how to "unpack" the <code>...</code> from the function's arguments within the function. I don't know how to do this. The relevant line in the function definition of <code>data.frame</code> is <code>object <- as.list(substitute(list(...)))[-1L]</code>, which I can't make any sense of.</p>
<p>So how can I convert the ellipsis from the function's signature into, for example, a list?</p>
<p>To be more specific, how can I write <code>get_list_from_ellipsis</code> in the code below?</p>
<pre><code>my_ellipsis_function(...) {
input_list <- get_list_from_ellipsis(...)
output_list <- lapply(X=input_list, FUN=do_something_interesting)
return(output_list)
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
</code></pre>
<hr />
<h2>Edit</h2>
<p>It seems there are two possible ways to do this. They are <code>as.list(substitute(list(...)))[-1L]</code> and <code>list(...)</code>. However, these two do not do exactly the same thing. (For differences, see examples in the answers.) Can anyone tell me what the practical difference between them is, and which one I should use?</p> | <p>I read answers and comments and I see that few things weren't mentioned:</p>
<ol>
<li><p><code>data.frame</code> uses <code>list(...)</code> version. Fragment of the code:</p>
<pre><code>object <- as.list(substitute(list(...)))[-1L]
mrn <- is.null(row.names)
x <- list(...)
</code></pre>
<p><code>object</code> is used to do some magic with column names, but <code>x</code> is used to create final <code>data.frame</code>.<br>
For use of unevaluated <code>...</code> argument look at <code>write.csv</code> code where <code>match.call</code> is used.</p></li>
<li><p>As you write in comment result in Dirk answer is not a list of lists. Is a list of length 4, which elements are <code>language</code> type. First object is a <code>symbol</code> - <code>list</code>, second is expression <code>1:10</code> and so on. That explain why <code>[-1L]</code> is needed: it removes expected <code>symbol</code> from provided arguments in <code>...</code> (cause it is always a list).<br>
As Dirk states <code>substitute</code> returns "parse tree the unevaluated expression".<br>
When you call <code>my_ellipsis_function(a=1:10,b=11:20,c=21:30)</code> then <code>...</code> "creates" a list of arguments: <code>list(a=1:10,b=11:20,c=21:30)</code> and <code>substitute</code> make it a list of four elements:</p>
<pre><code>List of 4
$ : symbol list
$ a: language 1:10
$ b: language 11:20
$ c: language 21:30
</code></pre>
<p>First element doesn't have a name and this is <code>[[1]]</code> in Dirk answer. I achieve this results using:</p>
<pre><code>my_ellipsis_function <- function(...) {
input_list <- as.list(substitute(list(...)))
str(input_list)
NULL
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
</code></pre></li>
<li><p>As above we can use <code>str</code> to check what objects are in a function.</p>
<pre><code>my_ellipsis_function <- function(...) {
input_list <- list(...)
output_list <- lapply(X=input_list, function(x) {str(x);summary(x)})
return(output_list)
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
int [1:10] 1 2 3 4 5 6 7 8 9 10
int [1:10] 11 12 13 14 15 16 17 18 19 20
int [1:10] 21 22 23 24 25 26 27 28 29 30
$a
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 3.25 5.50 5.50 7.75 10.00
$b
Min. 1st Qu. Median Mean 3rd Qu. Max.
11.0 13.2 15.5 15.5 17.8 20.0
$c
Min. 1st Qu. Median Mean 3rd Qu. Max.
21.0 23.2 25.5 25.5 27.8 30.0
</code></pre>
<p>It's ok. Lets see <code>substitute</code> version:</p>
<pre><code> my_ellipsis_function <- function(...) {
input_list <- as.list(substitute(list(...)))
output_list <- lapply(X=input_list, function(x) {str(x);summary(x)})
return(output_list)
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
symbol list
language 1:10
language 11:20
language 21:30
[[1]]
Length Class Mode
1 name name
$a
Length Class Mode
3 call call
$b
Length Class Mode
3 call call
$c
Length Class Mode
3 call call
</code></pre>
<p>Isn't what we needed. You will need additional tricks to deal with these kind of objects (as in <code>write.csv</code>).</p></li>
</ol>
<p>If you want use <code>...</code> then you should use it as in Shane answer, by <code>list(...)</code>.</p> | {
"question_id": 3057341,
"question_date": "2010-06-16T21:31:41.897Z",
"question_score": 207,
"tags": "r|function|parameters|ellipsis|variadic",
"answer_id": 3083193,
"answer_date": "2010-06-21T08:50:26.133Z",
"answer_score": 121
} |
Please answer the following Stack Overflow question:
Title: What is the best way to force yourself to master vi?
<p>A good while ago, I read <a href="http://www.viemu.com/a-why-vi-vim.html" rel="noreferrer">an article by the creator of viemu</a>, clearing up a lot of the misconceptions about vi, as well as explaining why it's a good idea (and why it's been very popular for the last 30 years+). The same guy also has <a href="http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html" rel="noreferrer">a great set of graphical cheat sheets</a> that teach the basics a few bits at a time.</p>
<p>I'm convinced.</p>
<p>I've been convinced for the past 2 years in fact. But I still really haven't gotten around to force myself to learn vi as my primary editor, the learning curve is just too high. When I get down to work, acceptable but immediate productivity (using my current editor) has so far won over tremendous productivity farther down the line (using vi).</p>
<p>Does anybody have any good tips to help get past the learning curve? It can be straight out tips, some other tutorial or article, whatever.</p>
<p>Edit: Note that I'm aware of the <a href="http://www.vim.org/" rel="noreferrer">vim/gVim</a>, <a href="http://cream.sourceforge.net/" rel="noreferrer">Cream</a> and <a href="http://code.google.com/p/macvim/" rel="noreferrer">MacVim</a> (etc.) variants of vi. I kept my question about vi to refer to the vi family as a whole. Thanks for all the great answers.</p>
<h3>Update (April 2009)</h3>
<p>I've been using Vim (more precisely, MacVim) in my day to day professional life since last December. I'm not going back :-)</p>
<p>Good luck to everyone in their Vim mastery.</p> | <p>First of all, you may want to pick up Vim; it has a vastly superior feature set along with everything vi has.</p>
<p>That said, it takes discipline to learn. If you have a job and can't afford the productivity hit (without getting fired), I'd suggest taking on a weekend project for the sole purpose of learning the editor. Keep its documentation open as you work, and be disciplined enough not to chicken out. As you learn more, become efficient and start relying on muscle memory, it won't be as hard to stick with it.</p>
<p>I've been using Vim for so long that I don't even think about what keys to press to search or navigate or save. And my hands never leave the keyboard. To use Vim is one of the best choices I've made in my programming career.</p> | {
"question_id": 74625,
"question_date": "2008-09-16T17:08:38.957Z",
"question_score": 207,
"tags": "vim|editor|text-editor|vi",
"answer_id": 74672,
"answer_date": "2008-09-16T17:13:36.043Z",
"answer_score": 126
} |
Please answer the following Stack Overflow question:
Title: What is the difference between JavaConverters and JavaConversions in Scala?
<p>In <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.package"><code>scala.collection</code></a>, there are two very similar objects <a href="http://www.scala-lang.org/api/current/scala/collection/JavaConversions%24.html"><code>JavaConversions</code></a> and <a href="http://www.scala-lang.org/api/current/scala/collection/JavaConverters%24.html"><code>JavaConverters</code></a>. </p>
<ul>
<li>What is the difference between these two objects? </li>
<li>Why do they both exist?</li>
<li>When do I want to use one vs. the other?</li>
</ul> | <p>EDIT: <code>Java Conversions</code> got <code>@deprecated</code> in Scala 2.13.0. Use <a href="https://www.scala-lang.org/api/2.13.0/scala/jdk/CollectionConverters$.html" rel="noreferrer">scala.jdk.CollectionConverters</a> instead.</p>
<p><code>JavaConversions</code> provide a series of implicit methods that convert between a Java collection and the closest corresponding Scala collection, and vice versa. This is done by creating wrappers that implement either the Scala interface and forward the calls to the underlying Java collection, or the Java interface, forwarding the calls to the underlying Scala collection.</p>
<p><code>JavaConverters</code> uses the pimp-my-library pattern to “add” the <code>asScala</code> method to the Java collections and the <code>asJava</code> method to the Scala collections, which return the appropriate wrappers discussed above. It is newer (since version 2.8.1) than <code>JavaConversions</code> (since 2.8) and makes the conversion between Scala and Java collection explicit. Contrary to what David writes in his answer, I'd recommend you make it a habit to use <code>JavaConverters</code> as you'll be much less likely to write code that makes a lot of implicit conversions, as you can control the only spot where that will happen: where you write <code>.asScala</code> or <code>.asJava</code>.</p>
<p>Here's the conversion methods that <code>JavaConverters</code> provide:</p>
<pre><code>Pimped Type | Conversion Method | Returned Type
=================================================================================================
scala.collection.Iterator | asJava | java.util.Iterator
scala.collection.Iterator | asJavaEnumeration | java.util.Enumeration
scala.collection.Iterable | asJava | java.lang.Iterable
scala.collection.Iterable | asJavaCollection | java.util.Collection
scala.collection.mutable.Buffer | asJava | java.util.List
scala.collection.mutable.Seq | asJava | java.util.List
scala.collection.Seq | asJava | java.util.List
scala.collection.mutable.Set | asJava | java.util.Set
scala.collection.Set | asJava | java.util.Set
scala.collection.mutable.Map | asJava | java.util.Map
scala.collection.Map | asJava | java.util.Map
scala.collection.mutable.Map | asJavaDictionary | java.util.Dictionary
scala.collection.mutable.ConcurrentMap | asJavaConcurrentMap | java.util.concurrent.ConcurrentMap
—————————————————————————————————————————————————————————————————————————————————————————————————
java.util.Iterator | asScala | scala.collection.Iterator
java.util.Enumeration | asScala | scala.collection.Iterator
java.lang.Iterable | asScala | scala.collection.Iterable
java.util.Collection | asScala | scala.collection.Iterable
java.util.List | asScala | scala.collection.mutable.Buffer
java.util.Set | asScala | scala.collection.mutable.Set
java.util.Map | asScala | scala.collection.mutable.Map
java.util.concurrent.ConcurrentMap | asScala | scala.collection.mutable.ConcurrentMap
java.util.Dictionary | asScala | scala.collection.mutable.Map
java.util.Properties | asScala | scala.collection.mutable.Map[String, String]
</code></pre>
<p>To use the conversions directly from Java, though, you're better off calling methods from <code>JavaConversions</code> directly; e.g.:</p>
<pre><code>List<String> javaList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
System.out.println(javaList); // [a, b, c]
Buffer<String> scalaBuffer = JavaConversions.asScalaBuffer(javaList);
System.out.println(scalaBuffer); // Buffer(a, b, c)
List<String> javaListAgain = JavaConversions.bufferAsJavaList(scalaBuffer);
System.out.println(javaList == javaListAgain); // true
</code></pre> | {
"question_id": 8301947,
"question_date": "2011-11-28T20:34:10.957Z",
"question_score": 207,
"tags": "scala|scala-collections|scala-java-interop",
"answer_id": 8302493,
"answer_date": "2011-11-28T21:21:36.227Z",
"answer_score": 264
} |
Please answer the following Stack Overflow question:
Title: Is REST DELETE really idempotent?
<p>DELETE is supposed to be idempotent.</p>
<p>If I DELETE <a href="http://example.com/account/123">http://example.com/account/123</a> it's going to delete the account.</p>
<p>If I do it again would I expect a 404, since the account no longer exists? What if I attempt to DELETE an account that has never existed?</p> | <h3>Idempotence refers to the state of the system after the request has completed</h3>
<p><br></p>
<p>In all cases (apart from the error issues - see below), the account no longer exists. </p>
<p>From <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">here</a></p>
<blockquote>
<p>"Methods can also have the property of
"idempotence" in that (<strong>aside from
error or expiration issues</strong>) the
side-effects of N > 0 identical
requests is the same as for a single
request. The methods GET, HEAD, PUT
and DELETE share this property. Also,
the methods OPTIONS and TRACE SHOULD
NOT have side effects, and so are
inherently idempotent. "</p>
</blockquote>
<p><br>
The key bit there is the <i>side-effects of N > 0 identical requests is the same as for a single request.</i></p>
<p>You would be correct to expect that the status code would be different but this does not affect the <b>core concept of idempotency - you can send the request more than once without additional changes to the state of the server.</b></p> | {
"question_id": 4088350,
"question_date": "2010-11-03T14:55:33.363Z",
"question_score": 207,
"tags": "http|rest|http-headers",
"answer_id": 4088451,
"answer_date": "2010-11-03T15:06:01.100Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: Test whether a Ruby class is a subclass of another class
<p>I would like to test whether a class inherits from another class, but there doesn't seem to exist a method for that.</p>
<pre><code>class A
end
class B < A
end
B.is_a? A
=> false
B.superclass == A
=> true
</code></pre>
<p>A trivial implementation of what I want would be:</p>
<pre><code>class Class
def is_subclass_of?(clazz)
return true if superclass == clazz
return false if self == Object
superclass.is_subclass_of?(clazz)
end
end
</code></pre>
<p>but I would expect this to exist already.</p> | <p>Just use the <a href="http://www.ruby-doc.org/core/Module.html#method-i-3C" rel="noreferrer"><code><</code></a> operator</p>
<pre><code>B < A # => true
A < A # => false
</code></pre>
<p>or use the <code><=</code> operator</p>
<pre><code>B <= A # => true
A <= A # => true
</code></pre> | {
"question_id": 4545518,
"question_date": "2010-12-28T11:00:39.917Z",
"question_score": 207,
"tags": "ruby|inheritance|subclass|superclass",
"answer_id": 4545583,
"answer_date": "2010-12-28T11:11:45.753Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: Convert RGB to RGBA over white
<p>I have a hex color, e.g. <code>#F4F8FB</code> (or <code>rgb(244, 248, 251)</code>) that I want converted into an <em>as-transparent-as-possible</em> rgba color (when displayed over white). Make sense? I'm looking for an algorithm, or at least idea of an algorithm for how to do so.</p>
<p>For Example:</p>
<pre><code>rgb( 128, 128, 255 ) --> rgba( 0, 0, 255, .5 )
rgb( 152, 177, 202 ) --> rgba( 50, 100, 150, .5 ) // can be better(lower alpha)
</code></pre>
<p>Ideas?</p>
<hr />
<p>FYI solution based on Guffa's answer:</p>
<pre class="lang-js prettyprint-override"><code>function RGBtoRGBA(r, g, b){
if((g == null) && (typeof r === 'string')){
var hex = r.replace(/^\s*#|\s*$/g, '');
if(hex.length === 3){
hex = hex.replace(/(.)/g, '$1$1');
}
r = parseInt(hex.substr(0, 2), 16);
g = parseInt(hex.substr(2, 2), 16);
b = parseInt(hex.substr(4, 2), 16);
}
var min, a = (255 - (min = Math.min(r, g, b))) / 255;
return {
r : r = 0|(r - min) / a,
g : g = 0|(g - min) / a,
b : b = 0|(b - min) / a,
a : a = (0|1000*a)/1000,
rgba : 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'
};
}
RGBtoRGBA(204, 153, 102) == RGBtoRGBA('#CC9966') == RGBtoRGBA('C96') ==
{
r : 170,
g : 85 ,
b : 0 ,
a : 0.6,
rgba : 'rgba(170, 85, 0, 0.6)'
}
</code></pre> | <p>Take the lowest color component, and convert that to an alpha value. Then scale the color components by subtracting the lowest, and dividing by the alpha value.</p>
<p>Example:</p>
<pre><code>152 converts to an alpha value of (255 - 152) / 255 ~ 0.404
152 scales using (152 - 152) / 0.404 = 0
177 scales using (177 - 152) / 0.404 ~ 62
202 scales using (202 - 152) / 0.404 ~ 123
</code></pre>
<p>So, <code>rgb(152, 177, 202)</code> displays as <code>rgba(0, 62, 123, .404)</code>.</p>
<p>I have verified in Photoshop that the colors actually match perfectly.</p> | {
"question_id": 6672374,
"question_date": "2011-07-12T23:20:57.060Z",
"question_score": 207,
"tags": "javascript|colors|css|rgba",
"answer_id": 6672545,
"answer_date": "2011-07-12T23:44:00.270Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: What do the following phrases mean in C++: zero-, default- and value-initialization?
<p>What do the following phrases mean in C++:</p>
<ul>
<li><p>zero-initialization,</p></li>
<li><p>default-initialization, and</p></li>
<li><p>value-initialization</p></li>
</ul>
<p>What should a C++ developer know about them?</p> | <p>One thing to realize is that 'value-initialization' is new with the C++ 2003 standard - it doesn't exist in the original 1998 standard (I think it might be the only difference that's more than a clarification). See <a href="https://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializati/1613383#1613383">Kirill V. Lyadvinsky's answer</a> for the definitions straight from the standard.</p>
<p>See this previous answer about the behavior of <code>operator new</code> for details on the the different behavior of these type of initialization and when they kick in (and when they differ from c++98 to C++03):</p>
<ul>
<li><a href="https://stackoverflow.com/questions/620137/syntax-of-new/620402#620402">Do the parentheses after the type name make a difference with new?</a></li>
</ul>
<p>The main point of the answer is:</p>
<blockquote>
<p>Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD, or if it's a class that contains POD members and is using a compiler-generated default constructor.</p>
<ul>
<li>In C++1998 there are 2 types of initialization: zero and default</li>
<li>In C++2003 a 3rd type of initialization, value initialization was added.</li>
</ul>
</blockquote>
<p>To say they least, it's rather complex and when the different methods kick in are subtle.</p>
<p>One thing to certainly be aware of is that MSVC follows the C++98 rules, even in VS 2008 (VC 9 or cl.exe version 15.x).</p>
<p>The following snippet shows that MSVC and Digital Mars follow C++98 rules, while GCC 3.4.5 and Comeau follow the C++03 rules:</p>
<pre><code>#include <cstdio>
#include <cstring>
#include <new>
struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m
int main()
{
char buf[sizeof(B)];
std::memset( buf, 0x5a, sizeof( buf));
// use placement new on the memset'ed buffer to make sure
// if we see a zero result it's due to an explicit
// value initialization
B* pB = new(buf) B(); //C++98 rules - pB->m is uninitialized
//C++03 rules - pB->m is set to 0
std::printf( "m is %d\n", pB->m);
return 0;
}
</code></pre> | {
"question_id": 1613341,
"question_date": "2009-10-23T13:14:45.477Z",
"question_score": 207,
"tags": "c++|initialization|c++-faq",
"answer_id": 1613578,
"answer_date": "2009-10-23T13:48:46.657Z",
"answer_score": 67
} |
Please answer the following Stack Overflow question:
Title: Under what circumstances is an SqlConnection automatically enlisted in an ambient TransactionScope Transaction?
<p>What does it mean for an SqlConnection to be "enlisted" in a transaction? Does it simply mean that commands I execute on the connection will participate in the transaction?</p>
<p>If so, under what circumstances is an SqlConnection <em>automatically</em> enlisted in an ambient TransactionScope Transaction?</p>
<p>See questions in code comments. My guess to each question's answer follows each question in parenthesis.</p>
<h2>Scenario 1: Opening connections INSIDE a transaction scope</h2>
<pre><code>using (TransactionScope scope = new TransactionScope())
using (SqlConnection conn = ConnectToDB())
{
// Q1: Is connection automatically enlisted in transaction? (Yes?)
//
// Q2: If I open (and run commands on) a second connection now,
// with an identical connection string,
// what, if any, is the relationship of this second connection to the first?
//
// Q3: Will this second connection's automatic enlistment
// in the current transaction scope cause the transaction to be
// escalated to a distributed transaction? (Yes?)
}
</code></pre>
<h2>Scenario 2: Using connections INSIDE a transaction scope that were opened OUTSIDE of it</h2>
<pre><code>//Assume no ambient transaction active now
SqlConnection new_or_existing_connection = ConnectToDB(); //or passed in as method parameter
using (TransactionScope scope = new TransactionScope())
{
// Connection was opened before transaction scope was created
// Q4: If I start executing commands on the connection now,
// will it automatically become enlisted in the current transaction scope? (No?)
//
// Q5: If not enlisted, will commands I execute on the connection now
// participate in the ambient transaction? (No?)
//
// Q6: If commands on this connection are
// not participating in the current transaction, will they be committed
// even if rollback the current transaction scope? (Yes?)
//
// If my thoughts are correct, all of the above is disturbing,
// because it would look like I'm executing commands
// in a transaction scope, when in fact I'm not at all,
// until I do the following...
//
// Now enlisting existing connection in current transaction
conn.EnlistTransaction( Transaction.Current );
//
// Q7: Does the above method explicitly enlist the pre-existing connection
// in the current ambient transaction, so that commands I
// execute on the connection now participate in the
// ambient transaction? (Yes?)
//
// Q8: If the existing connection was already enlisted in a transaction
// when I called the above method, what would happen? Might an error be thrown? (Probably?)
//
// Q9: If the existing connection was already enlisted in a transaction
// and I did NOT call the above method to enlist it, would any commands
// I execute on it participate in it's existing transaction rather than
// the current transaction scope. (Yes?)
}
</code></pre> | <p>I've done some tests since asking this question and found most if not all answers on my own, since no one else replied. Please let me know if I've missed anything.</p>
<blockquote>
<p>Q1: Is connection automatically enlisted in transaction?</p>
</blockquote>
<p>Yes, unless <code>enlist=false</code> is specified in the connection string. The connection pool finds a usable connection. A usable connection is one that's not enlisted in a transaction or one that's enlisted in the same transaction.</p>
<blockquote>
<p>Q2: If I open (and run commands on) a second connection now, with an identical connection string, what, if any, is the relationship of this second connection to the first?</p>
</blockquote>
<p>The second connection is an independent connection, which participates in the same transaction. I'm not sure about the interaction of commands on these two connections, since they're running against the same database, but I think errors can occur if commands are issued on both at the same time: errors like <a href="https://stackoverflow.com/questions/2858750/what-is-the-reason-of-transaction-context-in-use-by-another-session/2885059#2885059">"Transaction context in use by another session"</a></p>
<blockquote>
<p>Q3: Will this second connection's automatic enlistment in the current transaction scope cause the transaction to be escalated to a distributed transaction?</p>
</blockquote>
<p>Yes, it gets escalated to a distributed transaction, so enlisting more than one connection, even with the same connection string, causes it to become a distributed transaction, which can be confirmed by checking for a non-null GUID at <code>Transaction.Current.TransactionInformation.DistributedIdentifier</code>.</p>
<p>*<em>Update: I read somewhere that this is fixed in SQL Server 2008, so that MSDTC is not used when the same connection string is used for both connections (as long as both connections are not open at the same time). That allows you to open a connection and close it multiple times within a transaction, which could make better use of the connection pool by opening connections as late as possible and closing them as soon as possible.</em></p>
<blockquote>
<p>Q4: If I start executing commands on the connection now, will it automatically become enlisted in the current transaction scope?</p>
</blockquote>
<p>No. A connection opened when no transaction scope was active, will not be automatically enlisted in a newly created transaction scope.</p>
<blockquote>
<p>Q5: If not enlisted, will commands I execute on the connection now participate in the ambient transaction?</p>
</blockquote>
<p>No. Unless you open a connection in the transaction scope, or enlist an existing connection in the scope, there basically is NO TRANSACTION. Your connection must be automatically or manually enlisted in the transaction scope in order for your commands to participate in the transaction.</p>
<blockquote>
<p>Q6: If commands on this connection are not participating in the current transaction, will they be committed even if rollback the current transaction scope?</p>
</blockquote>
<p>Yes, commands on a connection not participating in a transaction are committed as issued, even though the code happens to have executed in a transaction scope block that got rolled back. If the connection is not enlisted in the current transaction scope, it's not participating in the transaction, so committing or rolling back the transaction will have no effect on commands issued on a connection not enlisted in the transaction scope... as <a href="https://stackoverflow.com/questions/1707566/data-committed-even-though-system-transactions-transactionscope-commit-not-call">this guy found out</a>. That's a very hard one to spot unless you understand the automatic enlistment process: it occurs only when a connection is opened <em>inside</em> an active transaction scope.</p>
<blockquote>
<p>Q7: Does the above method explicitly enlist the pre-existing connection in the current ambient transaction, so that commands I execute on the connection now participate in the ambient transaction?</p>
</blockquote>
<p>Yes. An existing connection can be explicitly enlisted in the current transaction scope by calling <code>EnlistTransaction(Transaction.Current)</code>. You can also enlist a connection on a separate thread in the transaction by using a DependentTransaction, but like before, I'm not sure how two connections involved in the same transaction against the same database may interact... and errors may occur, and of course the second enlisted connection causes the transaction to escalate to a distributed transaction.</p>
<blockquote>
<p>Q8: If the existing connection was already enlisted in a transaction when I called the above method, what would happen? Might an error be thrown?</p>
</blockquote>
<p>An error may be thrown. If <code>TransactionScopeOption.Required</code> was used, and the connection was already enlisted in a transaction scope transaction, then there is no error; in fact, there's no new transaction created for the scope, and the transaction count (<code>@@trancount</code>) does not increase. If, however, you use <code>TransactionScopeOption.RequiresNew</code>, then you get a helpful error message upon attempting to enlist the connection in the new transaction scope transaction: "Connection currently has transaction enlisted. Finish current transaction and retry." And yes, if you complete the transaction the connection is enlisted in, you can safely enlist the connection in a new transaction.</p>
<p>*<em>Update: If you previously called <code>BeginTransaction</code> on the connection, a slightly different error is thrown when you try to enlist in a new transaction scope transaction: "Cannot enlist in the transaction because a local transaction is in progress on the connection. Finish local transaction and retry." On the other hand, you can safely call <code>BeginTransaction</code> on the <code>SqlConnection</code> while its enlisted in a transaction scope transaction, and that will actually increase <code>@@trancount</code> by one, unlike using the Required option of a nested transaction scope, which does not cause it to increase. Interestingly, if you then go on to create another nested transaction scope with the <code>Required</code> option, you will not get an error, because nothing changes as a result of already having an active transaction scope transaction (remember <code>@@trancount</code> is not increased when a transaction scope transaction is already active and the <code>Required</code> option is used).</em></p>
<blockquote>
<p>Q9: If the existing connection was already enlisted in a transaction and I did NOT call the above method to enlist it, would any commands I execute on it participate in its existing transaction rather than the current transaction scope?</p>
</blockquote>
<p>Yes. Commands participate in whatever transaction the connection is enlisted in, regardless of what the active transaction scope is in the C# code.</p> | {
"question_id": 2884863,
"question_date": "2010-05-21T19:13:10.277Z",
"question_score": 207,
"tags": "c#|ado.net|transactionscope|sqlconnection|sqlcommand",
"answer_id": 2886326,
"answer_date": "2010-05-21T23:57:52.990Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Are there pronounceable names for common Haskell operators?
<p>I'm reading <a href="http://learnyouahaskell.com" rel="noreferrer"><em>Learn You a Haskell for Great Good</em></a>, and I never know how to pronounce the Haskell operators. Do they have "real" names? ?</p>
<p>For instance, how do you read aloud an expression like this one?</p>
<pre><code>Just (+3) <*> Just 9
</code></pre>
<p>I know that <code>>>=</code> is "bind", but what about the others? Since Google doesn't take non-alphanumeric characters into account, it's kind of hard to do an efficient search...</p>
<p>I realize you can create your own operators, so of course not all operators can have names, but I expect that the common ones (e.g. those defined in <code>Applicative</code> or <code>Monad</code>) must have names...</p> | <p>Here is how I pronounce them:</p>
<pre>
>>= bind
>> then
*> then
-> to <i>a -> b: a to b</i>
<- bind <i>(as it desugars to >>=)</i>
<$> (f)map
<$ map-replace by <i>0 <$ f: "f map-replace by 0"</i>
<*> ap(ply) <i>(as it is the same as Control.Monad.ap)</i>
$ <i>(none, just as " " [whitespace])</i>
. pipe to <i>a . b: "b pipe-to a"</i>
!! index
! index / strict <i>a ! b: "a index b", foo !x: foo strict x</i>
<|> or / alternative <i>expr <|> term: "expr or term"</i>
++ concat / plus / append
[] empty list
: cons
:: of type / as <i>f x :: Int: f x of type Int</i>
\ lambda
@ as <i>go ll@(l:ls): go ll as l cons ls</i>
~ lazy <i>go ~(a,b): go lazy pair a, b</i>
</pre> | {
"question_id": 7746894,
"question_date": "2011-10-12T21:35:27.277Z",
"question_score": 207,
"tags": "haskell|operators",
"answer_id": 7747115,
"answer_date": "2011-10-12T21:58:47.327Z",
"answer_score": 201
} |
Please answer the following Stack Overflow question:
Title: String was not recognized as a valid DateTime " format dd/MM/yyyy"
<p>I am trying to convert my string formatted value to date type with format <code>dd/MM/yyyy</code>.</p>
<pre><code>this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
</code></pre>
<p>What is the problem ?
It has a second override which asks for <code>IFormatProvider</code>. What is this? <em>Do</em> I need to pass this also? If Yes how to use it for this case?</p>
<p><strong>Edit</strong> </p>
<p>What are the differences between <code>Parse</code> and <code>ParseExact</code>?</p>
<p><strong>Edit 2</strong></p>
<p>Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.</p>
<p>Which answer is better considering all aspects like type saftey, performance or something you feel like</p> | <p>Use <code>DateTime.ParseExact</code>.</p>
<pre><code>this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
</code></pre> | {
"question_id": 2193012,
"question_date": "2010-02-03T15:24:29.530Z",
"question_score": 206,
"tags": "c#|.net|datetime|types|casting",
"answer_id": 2193037,
"answer_date": "2010-02-03T15:27:40.990Z",
"answer_score": 298
} |
Please answer the following Stack Overflow question:
Title: Correct way to pause a Python program
<p>I've been using the <code>input</code> function as a way to pause my scripts:</p>
<pre><code>print("something")
wait = input("Press Enter to continue.")
print("something")
</code></pre>
<p>Is there a formal way to do this?</p> | <p>It <em>seems</em> fine to me (or <code>raw_input()</code> in Python 2.X). Alternatively, you could use <code>time.sleep()</code> if you want to pause for a certain number of seconds.</p>
<pre><code>import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
</code></pre> | {
"question_id": 11552320,
"question_date": "2012-07-19T00:28:17.843Z",
"question_score": 206,
"tags": "python|sleep",
"answer_id": 11552350,
"answer_date": "2012-07-19T00:32:24.190Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: CSS: background image on background color
<p>I have panel which I colored blue if this panel is being selected (clicked on it). Additionally, I add a small sign (<code>.png</code> image) to that panel, which indicates that the selected panel has been already selected before.</p>
<p>So if the user sees for example 10 panels and 4 of them have this small sign, he knows that he has already clicked on those panels before. This work fine so far. The problem is now that I can't display the small sign and make the panel blue at the same time.</p>
<p>I set the panel to blue with the css <code>background: #6DB3F2;</code> and the background image with <code>background-image: url('images/checked.png')</code>. But it seems that the background color is above the image so you cannot see the sign.</p>
<p>Is it therefore possible to set <code>z-index</code>es for the background color and the background image?</p> | <p>You need to use the full property name for each:</p>
<pre><code>background-color: #6DB3F2;
background-image: url('images/checked.png');
</code></pre>
<p>Or, you can use the background shorthand and specify it all in one line:</p>
<pre><code>background: url('images/checked.png'), #6DB3F2;
</code></pre> | {
"question_id": 8195215,
"question_date": "2011-11-19T15:58:23.553Z",
"question_score": 206,
"tags": "css|background|background-image|background-color",
"answer_id": 8195272,
"answer_date": "2011-11-19T16:05:37.637Z",
"answer_score": 378
} |
Please answer the following Stack Overflow question:
Title: href image link download on click
<p>I generate normal links like: <code><a href="/path/to/image"><img src="/path/to/image" /></a></code> in a web app.</p>
<p>When I click on the link, it displays the picture in a new page. If you want to save the picture, then you need to right click on it and select "save as"</p>
<p>I don't want this behaviour, I would like to have a download box popping out when I click on the link, is that possible just with html or javascript? How?</p>
<p>If not I guess I would have to write a download.php script and call it into the href with the file name as parameter...?</p> | <pre><code><a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
<img alt="ImageName" src="/path/to/image">
</a>
</code></pre>
<p>It's not yet fully supported <a href="http://caniuse.com/#feat=download" rel="noreferrer">caniuse</a>, but you can use with <a href="https://modernizr.com/download/?adownload-setclasses" rel="noreferrer">modernizr</a> (<em>under Non-core detects</em>) to check the support of the browser.</p> | {
"question_id": 2408146,
"question_date": "2010-03-09T10:09:29.083Z",
"question_score": 206,
"tags": "html|image|download|href",
"answer_id": 16302092,
"answer_date": "2013-04-30T14:15:03.263Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Error: could not find function ... in R
<blockquote>
<p><em>This is meant to be a FAQ question, so please be as complete as possible. The answer is a community answer, so feel free to edit if you think something is missing.</em></p>
<p><em><a href="https://meta.stackexchange.com/questions/101892/community-wiki-with-common-error-messages-allowed">This question was discussed and approved on meta.</a></em></p>
</blockquote>
<p>I am using R and tried <code>some.function</code> but I got following error message:</p>
<pre><code>Error: could not find function "some.function"
</code></pre>
<p>This question comes up very regularly. When you get this type of error in R, how can you solve it?</p> | <p>There are a few things you should check :</p>
<ol>
<li>Did you write the name of your function correctly? Names are case sensitive.</li>
<li>Did you install the package that contains the function? <code>install.packages("thePackage")</code> (this only needs to be done once)</li>
<li>Did you attach that package to the workspace ?
<code>require(thePackage)</code> (and check its return value) or <code>library(thePackage)</code> (this should be done every time you start a new R session)</li>
<li>Are you using an older R version where this function didn't exist yet?</li>
<li>Are you using a different version of the specific <em>package</em>? This could be in either direction: functions are added and removed over time, and it's possible the code you're referencing is expecting a newer or older version of the package than what you have installed.</li>
</ol>
<p>If you're not sure in which package that function is situated, you can do a few things.</p>
<ol>
<li>If you're sure you installed and attached/loaded the right package, type <code>help.search("some.function")</code> or <code>??some.function</code> to get an information box that can tell you in which package it is contained.</li>
<li><code>find</code> and <code>getAnywhere</code> can also be used to locate functions.</li>
<li>If you have no clue about the package, you can use <code>findFn</code> in the <code>sos</code> package as explained in <a href="https://stackoverflow.com/questions/7004710/lapply-is-part-of-what-package-in-r">this answer</a>.</li>
<li><code>RSiteSearch("some.function")</code> or searching with <a href="https://www.rdocumentation.org" rel="noreferrer">rdocumentation</a> or <a href="http://rseek.org/" rel="noreferrer">rseek</a> are alternative ways to find the function.</li>
</ol>
<p>Sometimes you need to use an older version of R, but run code created for a newer version. Newly added functions (eg hasName in R 3.4.0) won't be found then. If you use an older R version and want to use a newer function, you can use the package <a href="https://cran.r-project.org/package=backports" rel="noreferrer">backports</a> to make such functions available. You also find a list of functions that need to be backported on the <a href="https://github.com/r-lib/backports/blob/master/README.md" rel="noreferrer">git repo of backports</a>. Keep in mind that R versions older than R3.0.0 are incompatible with packages built for R3.0.0 and later versions.</p> | {
"question_id": 7027288,
"question_date": "2011-08-11T14:04:19.110Z",
"question_score": 206,
"tags": "r|function|error-handling|r-faq",
"answer_id": 7027332,
"answer_date": "2011-08-11T14:07:23.913Z",
"answer_score": 140
} |
Please answer the following Stack Overflow question:
Title: How can I render a list select box (dropdown) with bootstrap?
<p>Is there anything out of the box that bootstrap supports to render a "regular" defacto drop down list select box? That is, where the drop down box is a list of values and if selected populate the contents of the list box?</p>
<p>Something similar to this functionality?</p>
<p><a href="http://bootstrapformhelpers.com/select/">http://bootstrapformhelpers.com/select/</a></p>
<p><img src="https://i.stack.imgur.com/eWw4u.png" alt="enter image description here"></p> | <p>Bootstrap 3 uses the <code>.form-control</code> class to style form components. </p>
<pre><code><select class="form-control">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
</code></pre>
<p><a href="http://getbootstrap.com/css/#forms-controls">http://getbootstrap.com/css/#forms-controls</a></p> | {
"question_id": 18150954,
"question_date": "2013-08-09T16:00:27.893Z",
"question_score": 206,
"tags": "twitter-bootstrap",
"answer_id": 18151311,
"answer_date": "2013-08-09T16:20:41.143Z",
"answer_score": 424
} |
Please answer the following Stack Overflow question:
Title: Does Android keep the .apk files? if so where?
<p>After android installs an application from the Marketplace, does it keep the .apk file?</p>
<p>Is there a standard location where Android would keep such files?</p> | <p>Preinstalled applications are in <code>/system/app</code> folder. User installed applications are in <code>/data/app</code>. I guess you can't access unless you have a rooted phone.
I don't have a rooted phone here but try this code out:</p>
<pre><code>public class Testing extends Activity {
private static final String TAG = "TEST";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File appsDir = new File("/data/app");
String[] files = appsDir.list();
for (int i = 0 ; i < files.length ; i++ ) {
Log.d(TAG, "File: "+files[i]);
}
}
</code></pre>
<p>It does lists the apks in my rooted htc magic and in the emu.</p> | {
"question_id": 2507960,
"question_date": "2010-03-24T13:26:11.673Z",
"question_score": 206,
"tags": "android|package|apk|installation",
"answer_id": 2508110,
"answer_date": "2010-03-24T13:48:37.273Z",
"answer_score": 130
} |
Please answer the following Stack Overflow question:
Title: resize2fs: Bad magic number in super-block while trying to open
<p>I am trying to resize a logical volume on CentOS7 but am running into the following error:</p>
<pre><code>resize2fs 1.42.9 (28-Dec-2013)
resize2fs: Bad magic number in super-block while trying to open /dev/mapper/centos-root
Couldn't find valid filesystem superblock.
</code></pre>
<p>I have tried adding a new partition (using fdisk) and using vgextend to extend the volume group, then resizing.
Resize worked fine for the logical volume using lvextend, but it failed at resize2fs.</p>
<p>I have also tried deleting an existing partition (using fdisk) and recreating it with a larger end block, then resizing the physical volume using lvm pvresize, followed by a resize of the logical volume using lvm lvresize. Again everything worked fine up to this point.</p>
<p>Once I tried to use resize2fs, using both methods as above, I received the exact same error.</p>
<p>Hopefully some of the following will shed some light.</p>
<p>fdisk -l</p>
<pre><code>[root@server~]# fdisk -l
Disk /dev/xvda: 32.2 GB, 32212254720 bytes, 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0009323a
Device Boot Start End Blocks Id System
/dev/xvda1 * 2048 1026047 512000 83 Linux
/dev/xvda2 1026048 41943039 20458496 8e Linux LVM
/dev/xvda3 41943040 62914559 10485760 8e Linux LVM
Disk /dev/mapper/centos-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/mapper/centos-root: 29.5 GB, 29532094464 bytes, 57679872 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
</code></pre>
<p>pvdisplay</p>
<pre><code>[root@server ~]# pvdisplay
--- Physical volume ---
PV Name /dev/xvda2
VG Name centos
PV Size 19.51 GiB / not usable 2.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 4994
Free PE 0
Allocated PE 4994
PV UUID 7bJOPh-OUK0-dGAs-2yqL-CAsV-TZeL-HfYzCt
--- Physical volume ---
PV Name /dev/xvda3
VG Name centos
PV Size 10.00 GiB / not usable 4.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 2559
Free PE 0
Allocated PE 2559
PV UUID p0IClg-5mrh-5WlL-eJ1v-t6Tm-flVJ-gsJOK6
</code></pre>
<p>vgdisplay</p>
<pre><code>[root@server ~]# vgdisplay
--- Volume group ---
VG Name centos
System ID
Format lvm2
Metadata Areas 2
Metadata Sequence No 6
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 2
Act PV 2
VG Size 29.50 GiB
PE Size 4.00 MiB
Total PE 7553
Alloc PE / Size 7553 / 29.50 GiB
Free PE / Size 0 / 0
VG UUID FD7k1M-koJt-2veW-sizL-Srsq-Y6zt-GcCfz6
</code></pre>
<p>lvdisplay</p>
<pre><code>[root@server ~]# lvdisplay
--- Logical volume ---
LV Path /dev/centos/swap
LV Name swap
VG Name centos
LV UUID KyokrR-NGsp-6jVA-P92S-QE3X-hvdp-WAeACd
LV Write Access read/write
LV Creation host, time localhost, 2014-10-09 08:28:42 +0100
LV Status available
# open 2
LV Size 2.00 GiB
Current LE 512
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 8192
Block device 253:0
--- Logical volume ---
LV Path /dev/centos/root
LV Name root
VG Name centos
LV UUID ugCOcT-sTDK-M8EV-3InM-hjIg-2nwS-KeAOnq
LV Write Access read/write
LV Creation host, time localhost, 2014-10-09 08:28:42 +0100
LV Status available
# open 1
LV Size 27.50 GiB
Current LE 7041
Segments 2
Allocation inherit
Read ahead sectors auto
- currently set to 8192
Block device 253:1
</code></pre>
<p>I've probably done something stupid, so any help would be greatly appreciated!</p> | <p>After a bit of trial and error... as mentioned in the possible answers, it turned out to require <code>xfs_growfs</code> rather than <code>resize2fs</code>.</p>
<p>CentOS 7,</p>
<pre><code>fdisk /dev/xvda
</code></pre>
<p>Create new primary partition, set type as <code>linux lvm</code>.</p>
<pre><code>n
p
3
t
8e
w
</code></pre>
<p>Create a new primary volume and extend the volume group to the new volume.</p>
<pre><code>partprobe
pvcreate /dev/xvda3
vgextend /dev/centos /dev/xvda3
</code></pre>
<p>Check the physical volume for free space, extend the logical volume with the free space.</p>
<pre><code>vgdisplay -v
lvextend -l+288 /dev/centos/root
</code></pre>
<p>Finally perform an online resize to resize the logical volume, then check the available space.</p>
<pre><code>xfs_growfs /dev/centos/root
df -h
</code></pre> | {
"question_id": 26305376,
"question_date": "2014-10-10T18:00:05.997Z",
"question_score": 206,
"tags": "lvm|centos7",
"answer_id": 26320277,
"answer_date": "2014-10-11T23:21:53.567Z",
"answer_score": 410
} |
Please answer the following Stack Overflow question:
Title: How to get the element clicked (for the whole document)?
<p>I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:</p>
<pre><code>$(document).click(function () {
alert($(this).text());
});
</code></pre>
<p>But very strangely, I get the text of the whole(!) document, not the clicked element.</p>
<p>How to get only the element I clicked on?</p>
<h3>Example</h3>
<pre><code><body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
</code></pre>
<p>If I click on the "test" text, I would like to be able to read the attribute with <code>$(this).attr("myclass"</code>) in jQuery.</p> | <p>You need to use the <a href="http://api.jquery.com/event.target/" rel="noreferrer"><code>event.target</code></a> which is the element which originally triggered the event. The <code>this</code> in your example code refers to <code>document</code>.</p>
<p>In jQuery, that's...</p>
<pre><code>$(document).click(function(event) {
var text = $(event.target).text();
});
</code></pre>
<p>Without jQuery...</p>
<pre><code>document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
</code></pre>
<p>Also, ensure if you need to support < IE9 that you use <code>attachEvent()</code> instead of <code>addEventListener()</code>.</p> | {
"question_id": 9012537,
"question_date": "2012-01-26T00:37:28.410Z",
"question_score": 206,
"tags": "javascript|jquery|html|dom",
"answer_id": 9012576,
"answer_date": "2012-01-26T00:41:52.753Z",
"answer_score": 308
} |
Please answer the following Stack Overflow question:
Title: How do I create a unique ID in Java?
<p>I'm looking for the best way to create a unique ID as a String in Java.</p>
<p>Any guidance appreciated, thanks.</p>
<p>I should mention I'm using Java 5.</p> | <p>Create a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/UUID.html" rel="noreferrer">UUID</a>.</p>
<pre><code>String uniqueID = UUID.randomUUID().toString();
</code></pre> | {
"question_id": 1389736,
"question_date": "2009-09-07T14:48:31.740Z",
"question_score": 206,
"tags": "java|uniqueidentifier",
"answer_id": 1389747,
"answer_date": "2009-09-07T14:51:01.363Z",
"answer_score": 417
} |
Please answer the following Stack Overflow question:
Title: String.format() to format double in Java
<p>How can I use <code>String.format(format, args)</code> to format a double like below?</p>
<p><code>2354548.235</code> -> <code>2,354,548.23</code></p> | <pre><code>String.format("%1$,.2f", myDouble);
</code></pre>
<p><code>String.format</code> automatically uses the default locale.</p> | {
"question_id": 4885254,
"question_date": "2011-02-03T10:54:45.247Z",
"question_score": 206,
"tags": "java",
"answer_id": 4885329,
"answer_date": "2011-02-03T11:04:18.950Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How to sort the letters in a string alphabetically in Python
<p>Is there an easy way to sort the letters in a string alphabetically in Python?</p>
<p>So for:</p>
<pre><code>a = 'ZENOVW'
</code></pre>
<p>I would like to return:</p>
<pre><code>'ENOVWZ'
</code></pre> | <p>You can do:</p>
<pre><code>>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
</code></pre> | {
"question_id": 15046242,
"question_date": "2013-02-23T22:00:04.827Z",
"question_score": 206,
"tags": "python|string",
"answer_id": 15046263,
"answer_date": "2013-02-23T22:02:27.353Z",
"answer_score": 348
} |
Please answer the following Stack Overflow question:
Title: How to add new item to hash
<p>I'm new to Ruby and don't know how to add new item to already existing hash. For example, first I construct hash:</p>
<pre><code>hash = {item1: 1}
</code></pre>
<p>after that a want to add item2 so after this I have hash like this:</p>
<pre><code>{item1: 1, item2: 2}
</code></pre>
<p>I don't know what method to do on hash, could someone help me?</p> | <p>Create the hash:</p>
<pre><code>hash = {:item1 => 1}
</code></pre>
<p>Add a new item to it:</p>
<pre><code>hash[:item2] = 2
</code></pre> | {
"question_id": 9571768,
"question_date": "2012-03-05T18:17:44.480Z",
"question_score": 206,
"tags": "ruby|hash",
"answer_id": 9571786,
"answer_date": "2012-03-05T18:19:34.777Z",
"answer_score": 338
} |
Please answer the following Stack Overflow question:
Title: Convert String to System.IO.Stream
<p>I need to convert a String to System.IO.Stream type to pass to another method.</p>
<p>I tried this unsuccessfully.</p>
<pre><code>Stream stream = new StringReader(contents);
</code></pre> | <p>Try this:</p>
<pre><code>// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
</code></pre>
<p>and</p>
<pre><code>// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
</code></pre> | {
"question_id": 8047064,
"question_date": "2011-11-08T07:13:57.460Z",
"question_score": 206,
"tags": "c#",
"answer_id": 8047081,
"answer_date": "2011-11-08T07:16:31.317Z",
"answer_score": 433
} |
Please answer the following Stack Overflow question:
Title: How do I remove background-image in css?
<p>I have a general rule which gives all DIVs a background image.<br>
I have one div (with id='a') which I don't want it to have the background image.<br>
What css rule do I have to give it?</p> | <p>Try:</p>
<pre><code>div#a {
background-image:none
}
</code></pre> | {
"question_id": 1461077,
"question_date": "2009-09-22T16:15:48.080Z",
"question_score": 206,
"tags": "html|css",
"answer_id": 1461087,
"answer_date": "2009-09-22T16:17:23.480Z",
"answer_score": 369
} |
Please answer the following Stack Overflow question:
Title: How do I make the return type of a method generic?
<p>Is there a way to make this method generic so I can return a string, bool, int, or double? Right now, it's returning a string, but if it's able find "true" or "false" as the configuration value, I'd like to return a bool for example.</p>
<pre><code> public static string ConfigSetting(string settingName)
{
return ConfigurationManager.AppSettings[settingName];
}
</code></pre> | <p>You need to make it a generic method, like this:</p>
<pre><code>public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
</code></pre>
<p>But the <em>caller</em> will have to specify the type they expect. You could then potentially use <a href="http://msdn.microsoft.com/en-us/library/dtb69x08.aspx"><code>Convert.ChangeType</code></a>, assuming that all the relevant types are supported:</p>
<pre><code>public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
</code></pre>
<p>I'm not entirely convinced that all this is a good idea, mind you...</p> | {
"question_id": 9808035,
"question_date": "2012-03-21T15:44:20.153Z",
"question_score": 206,
"tags": "c#|.net|generics|return-type",
"answer_id": 9808070,
"answer_date": "2012-03-21T15:46:10.820Z",
"answer_score": 433
} |
Please answer the following Stack Overflow question:
Title: Convert row names into first column
<p>I have a data frame like this: </p>
<pre><code>df
VALUE ABS_CALL DETECTION P-VALUE
1007_s_at "957.729231881542" "P" "0.00486279317241156"
1053_at "320.632701283368" "P" "0.0313356324173416"
117_at "429.842323161046" "P" "0.0170004527476119"
121_at "2395.7364289242" "P" "0.0114473584876183"
1255_g_at "116.493632746934" "A" "0.39799368200131"
1294_at "739.927122116896" "A" "0.0668649772942343"
</code></pre>
<p>I want to convert the row names into the first column. Currently I use something like this to make row names as the first column:</p>
<pre><code> d <- df
names <- rownames(d)
rownames(d) <- NULL
data <- cbind(names,d)
</code></pre>
<p>Is there a single line to do this?</p> | <p>Or you can use <code>tibble</code>'s <code>rownames_to_column</code> which does the same thing as David's answer:</p>
<pre><code>library(tibble)
df <- tibble::rownames_to_column(df, "VALUE")
</code></pre>
<p>Note: The earlier function called <code>add_rownames()</code> has been deprecated and is being replaced by <code>tibble::rownames_to_column()</code></p> | {
"question_id": 29511215,
"question_date": "2015-04-08T09:45:47.903Z",
"question_score": 206,
"tags": "r|dataframe|col|rowname",
"answer_id": 29511626,
"answer_date": "2015-04-08T10:04:41.193Z",
"answer_score": 209
} |
Please answer the following Stack Overflow question:
Title: ERROR Error: No value accessor for form control with unspecified name attribute on switch
<p>Here is my Angular component:</p>
<pre class="lang-ts prettyprint-override"><code>@Component( {
selector: 'input-extra-field',
template: `
<div class="form-group" [formGroup]="formGroup" >
<switch [attr.title]="field.etiquette"
[attr.value]="field.valeur" [(ngModel)]="field.valeur"
[formControl]="fieldControl" [attr.id]="name" [attr.disabled]="disabled">
</switch>
<error-messages [control]="name"></error-messages>
</div>
`
} )
</code></pre>
<p>Here is my Class:</p>
<pre class="lang-ts prettyprint-override"><code>export class SwitchExtraField extends ExtraField {
@Input() field: ExtraFormField;
@Input() entity: { fields: Object };
@Input() formGroup: FormGroup;
constructor( formDir: NgForm ) {
super( null, null, formDir );
}
get disabled(): string {
if ( this.field && !!this.field.saisissable && !this.field.saisissable ) {
return 'disabled';
}
return null;
}
}
</code></pre>
<p>This is the error I get when compiling:</p>
<pre class="lang-none prettyprint-override"><code>ERROR Error: No value accessor for form control with unspecified name attribute
at _throwError (forms.es5.js:1918)
at setUpControl (forms.es5.js:1828)
at FormControlDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormControlDirective.ngOnChanges (forms.es5.js:4617)
</code></pre>
<p>When I change the element switch to input it works, knowing that I'm using the same structure to other components and it works fine.</p> | <p>I fixed this error by adding the <code>name="fieldName" ngDefaultControl</code> attributes to the element that carries the <code>[(ngModel)]</code> attribute.</p> | {
"question_id": 46422007,
"question_date": "2017-09-26T08:59:13.703Z",
"question_score": 206,
"tags": "angular|form-control",
"answer_id": 47795277,
"answer_date": "2017-12-13T14:22:05.373Z",
"answer_score": 276
} |
Please answer the following Stack Overflow question:
Title: Negation in Python
<p>I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this?</p>
<pre><code>if (!os.path.exists("/usr/share/sounds/blues")):
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
</code></pre> | <p>The negation operator in Python is <code>not</code>. Therefore just replace your <code>!</code> with <code>not</code>.</p>
<p>For your example, do this:</p>
<pre><code>if not os.path.exists("/usr/share/sounds/blues") :
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
</code></pre>
<hr>
<p>For your specific example (as Neil said in the comments), you don't have to use the <code>subprocess</code> module, you can simply use <a href="http://docs.python.org/2/library/os.html#os.mkdir" rel="noreferrer"><code>os.mkdir()</code></a> to get the result you need, with added exception handling goodness.</p>
<p>Example:</p>
<pre><code>blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
try:
os.mkdir(blues_sounds_path)
except OSError:
# Handle the case where the directory could not be created.
</code></pre> | {
"question_id": 6117733,
"question_date": "2011-05-24T22:38:35.487Z",
"question_score": 206,
"tags": "python|negation",
"answer_id": 6117762,
"answer_date": "2011-05-24T22:41:50.727Z",
"answer_score": 280
} |
Please answer the following Stack Overflow question:
Title: Is there a max array length limit in C++?
<p>Is there a max length for an array in C++?</p>
<p>Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?</p>
<p>Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?</p>
<p>What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?</p>
<p>I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.</p> | <p>There are two limits, both not enforced by C++ but rather by the hardware.</p>
<p>The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's <code>std::size_t</code> can take. This data type is large enough to contain the size in bytes of any object</p>
<p>The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a <code>vector<int></code> of a given size <em>n</em> typically takes multiple times as much memory as an array of type <code>vector<char></code> (minus a small constant value), since <code>int</code> is usually bigger than <code>char</code>. Therefore, a <code>vector<char></code> may contain more items than a <code>vector<int></code> before memory is full. The same counts for raw C-style arrays like <code>int[]</code> and <code>char[]</code>.</p>
<p>Additionally, this upper limit may be influenced by the type of <code>allocator</code> used to construct the <code>vector</code> because an <code>allocator</code> is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.</p>
<p>Apart from that, C++ doesn't enforce any limits.</p> | {
"question_id": 216259,
"question_date": "2008-10-19T10:39:11.103Z",
"question_score": 206,
"tags": "c++|arrays",
"answer_id": 216266,
"answer_date": "2008-10-19T10:44:37.880Z",
"answer_score": 173
} |
Please answer the following Stack Overflow question:
Title: How do I concatenate strings in Swift?
<p>How to concatenate string in Swift?</p>
<p>In <code>Objective-C</code> we do like</p>
<pre><code>NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];
</code></pre>
<p>or</p>
<pre><code>NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];
</code></pre>
<p>But I want to do this in Swift-language.</p> | <p>You can concatenate strings a number of ways:</p>
<pre><code>let a = "Hello"
let b = "World"
let first = a + ", " + b
let second = "\(a), \(b)"
</code></pre>
<p>You could also do:</p>
<pre><code>var c = "Hello"
c += ", World"
</code></pre>
<p>I'm sure there are more ways too.</p>
<p><strong>Bit of description</strong></p>
<p><code>let</code> creates a constant. (sort of like an <code>NSString</code>). You can't change its value once you have set it. You can still add it to other things and create new variables though.</p>
<p><code>var</code> creates a variable. (sort of like <code>NSMutableString</code>) so you can change the value of it. But this has been answered several times on Stack Overflow, (see <em><a href="https://stackoverflow.com/q/24002092/61654">difference between let and var</a></em>).</p>
<p><strong>Note</strong></p>
<p>In reality <code>let</code> and <code>var</code> are <em>very different</em> from <code>NSString</code> and <code>NSMutableString</code> but it helps the analogy.</p> | {
"question_id": 24034174,
"question_date": "2014-06-04T09:49:15.007Z",
"question_score": 206,
"tags": "string|swift|concat|string-concatenation",
"answer_id": 24034334,
"answer_date": "2014-06-04T09:55:44.483Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: Difference between two dates in MySQL
<p>How to calculate the difference between two dates, in the format <code>YYYY-MM-DD hh: mm: ss</code> and to get the result in seconds or milliseconds?</p> | <pre><code>SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59, the difference in HH:MM:SS format
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
-- result: 79259 the difference in seconds
</code></pre>
<p>So, you can use <code>TIMESTAMPDIFF</code> for your purpose.</p> | {
"question_id": 4759248,
"question_date": "2011-01-21T13:23:08.207Z",
"question_score": 206,
"tags": "mysql|sql|date|datetime",
"answer_id": 4760637,
"answer_date": "2011-01-21T15:39:07.363Z",
"answer_score": 387
} |
Please answer the following Stack Overflow question:
Title: How to format Joda-Time DateTime to only mm/dd/yyyy?
<p>I have a string "<code>11/15/2013 08:00:00</code>", I want to format it to "<code>11/15/2013</code>", what is the correct <code>DateTimeFormatter</code> pattern?</p>
<p>I've tried many and googled and still unable to find the correct pattern.</p>
<p>edit: I am looking for <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormatter.html" rel="noreferrer"><code>DateTimeFormatter</code></a>, not Java's SimpleDateFormat..</p> | <p><em>Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE ≥ 8 way of formatting date and time, see below.</em></p>
<h3>Joda time</h3>
<p><strong>Create a <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormatter.html" rel="noreferrer"><code>DateTimeFormatter</code></a> using <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html#forPattern%28java.lang.String%29" rel="noreferrer"><code>DateTimeFormat.forPattern(String)</code></a></strong></p>
<p>Using Joda time you would do it like this:</p>
<pre><code>String dateTime = "11/15/2013 08:00:00";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");
// Printing the date
System.out.println(dtfOut.print(jodatime));
</code></pre>
<hr />
<h3>Standard Java ≥ 8</h3>
<p>Java 8 introduced a <a href="http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html" rel="noreferrer">new Date and Time library</a>, making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer">DateTimeFormatter</a>. Since you don't have a time zone in your <code>String</code>, a <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html" rel="noreferrer">java.time.LocalDateTime</a> or a <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="noreferrer">LocalDate</a>, otherwise the time zoned varieties <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html" rel="noreferrer">ZonedDateTime</a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDate.html" rel="noreferrer">ZonedDate</a> could be used.</p>
<pre><code>// Format for input
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
LocalDate date = LocalDate.parse(dateTime, inputFormat);
// Format for output
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
// Printing the date
System.out.println(date.format(outputFormat));
</code></pre>
<hr />
<h3>Standard Java < 8</h3>
<p>Before Java 8, you would use the a <a href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer">java.util.Date</a></p>
<pre><code>String dateTime = "11/15/2013 08:00:00";
// Format for input
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Parsing the date
Date date7 = dateParser.parse(dateTime);
// Format for output
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Printing the date
System.out.println(dateFormatter.format(date7));
</code></pre> | {
"question_id": 20331163,
"question_date": "2013-12-02T14:53:02.597Z",
"question_score": 206,
"tags": "java|jodatime|date-format",
"answer_id": 20331243,
"answer_date": "2013-12-02T14:57:27.470Z",
"answer_score": 416
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.