id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50,937,362 | Multiprocessing on Python 3 Jupyter | <p>I come here because I have an issue with my Jupiter's Python3 notebook.
I need to create a function that uses the multiprocessing library.
Before to implement it, I make some tests.
I found a looooot of different examples but the issue is everytime the same : my code is executed but nothing happens in the notebook's interface :</p>
<p><img src="https://i.stack.imgur.com/1kWUH.png" alt="enter image description here"></p>
<p>The code i try to run on jupyter is this one : </p>
<pre><code>import os
from multiprocessing import Process, current_process
def doubler(number):
"""
A doubling function that can be used by a process
"""
result = number * 2
proc_name = current_process().name
print('{0} doubled to {1} by: {2}'.format(
number, result, proc_name))
return result
if __name__ == '__main__':
numbers = [5, 10, 15, 20, 25]
procs = []
proc = Process(target=doubler, args=(5,))
for index, number in enumerate(numbers):
proc = Process(target=doubler, args=(number,))
proc2 = Process(target=doubler, args=(number,))
procs.append(proc)
procs.append(proc2)
proc.start()
proc2.start()
proc = Process(target=doubler, name='Test', args=(2,))
proc.start()
procs.append(proc)
for proc in procs:
proc.join()
</code></pre>
<p>It's OK when I just run my code without Jupyter but with the command "python my_progrem.py" and I can see the logs :
<img src="https://i.stack.imgur.com/9CVuo.png" alt="enter image description here"></p>
<p>Is there, for my example, and in Jupyter, a way to catch the results of my two tasks (proc1 and proc2 which both call thefunction "doubler") in a variable/object that I could use after ?
If "yes", how can I do it?</p> | 53,162,557 | 4 | 0 | null | 2018-06-19 21:46:32.553 UTC | 4 | 2022-05-19 20:00:13.91 UTC | 2020-02-04 09:55:54.097 UTC | null | 1,185,254 | null | 9,533,185 | null | 1 | 25 | multiprocessing|jupyter-notebook|python-3.6 | 46,472 | <p>Another way of running multiprocessing jobs in a Jupyter notebook is to use one of the approaches supported by the <a href="https://github.com/micahscopes/nbmultitask" rel="nofollow noreferrer">nbmultitask</a> package.</p> |
39,931,316 | What is the PID in the host, of a process running inside a Docker container? | <p>There are several processes running in a Docker container, their PIDs are isolated in the container namespace, is there a way to figure out what are their PIDs on the Docker host?</p>
<p>For example there is an Apache web server running inside a Docker container,
(I use Apache+PHP image from <a href="https://hub.docker.com/_/php/" rel="noreferrer" title="Docker Hub">Docker Hub</a>), and the Apache, when it starts, creates more worker processes inside the container. Those worker processes are actually handling incoming requests. To view these processes I run <code>pstree</code> inside the docker container:</p>
<pre><code># pstree -p 1
apache2(1)-+-apache2(8)
|-apache2(9)
|-apache2(10)
|-apache2(11)
|-apache2(12)
`-apache2(20)
</code></pre>
<p>The parent Apache process runs on PID 1 inside of the container process namespace. However from the host's perspective it can be also accessed,
but its PID on the host is different and can be determined by running <code>docker compose</code> command:</p>
<pre><code> $ docker inspect --format '{{.State.Pid}}' container
17985
</code></pre>
<p>From this we can see that the PID 1 from within the container process namespace maps to PID 17985 on the host. So I can run <code>pstree</code> on the host, to list the children of the Apache process:</p>
<pre><code>$ pstree -p 17985
apache2(17985)─┬─apache2(18010)
├─apache2(18011)
├─apache2(18012)
├─apache2(18013)
├─apache2(18014)
└─apache2(18164)
</code></pre>
<p>From this I assume that the same way how PID 1 in the container maps to PID 17985 on the host, it also maps: </p>
<ul>
<li>PID 8 in container to PID 18010 on host, and</li>
<li>PID 9 to PID 18011;</li>
<li>PID 10 to PID 18012
and so on...</li>
</ul>
<p>(This allows me to debug the processes from docker container, using tools that are only available only on the host, and not the in the container, like strace)</p>
<p>The problem is that I don't know how safe is to assume that pstree lists the processes in the same order both in the container and in the host.</p>
<p>Would be great if someone could suggest a more reliable way to detect what is a PID on the host of a specific process running inside the Docker container.</p> | 39,932,796 | 3 | 1 | null | 2016-10-08 10:33:09.817 UTC | 9 | 2021-11-10 20:42:48.233 UTC | null | null | null | null | 296,988 | null | 1 | 29 | linux|docker|process|pid | 35,246 | <p>You can look at the <code>/proc/<pid>/status</code> file to determine the mapping between the namespace PID and the global PID. For example, if in a docker container I start several <code>sleep 900</code> processes, like this:</p>
<pre><code># docker run --rm -it alpine sh
/ # sleep 900 &
/ # sleep 900 &
/ # sleep 900 &
</code></pre>
<p>I can see them running in the container:</p>
<pre><code>/ # ps -fe
PID USER TIME COMMAND
1 root 0:00 sh
7 root 0:00 sleep 900
8 root 0:00 sleep 900
9 root 0:00 sleep 900
10 root 0:00 ps -fe
</code></pre>
<p>I can look at these on the host:</p>
<pre><code># ps -fe | grep sleep
root 10394 10366 0 09:11 pts/10 00:00:00 sleep 900
root 10397 10366 0 09:12 pts/10 00:00:00 sleep 900
root 10398 10366 0 09:12 pts/10 00:00:00 sleep 900
</code></pre>
<p>And for any one of those, I can look at the <code>status</code> file to see the namespace pid:</p>
<pre><code># grep -i pid /proc/10394/status
Pid: 10394
PPid: 10366
TracerPid: 0
NSpid: 10394 7
</code></pre>
<p>Looking at the <code>NSpid</code> line, I can see that within the PID namespace this process has pid 7. And indeed, if I kill process <code>10394</code> on the host:</p>
<pre><code># kill 10394
</code></pre>
<p>Then in the container I see that PID 7 is no longer running:</p>
<pre><code>/ # ps -fe
PID USER TIME COMMAND
1 root 0:00 sh
8 root 0:00 sleep 900
9 root 0:00 sleep 900
11 root 0:00 ps -fe
</code></pre> |
37,326,002 | Is it possible to make a trainable variable not trainable? | <p>I created a <em><strong>trainable</strong> variable</em> in a scope. Later, I entered the same scope, set the scope to <code>reuse_variables</code>, and used <code>get_variable</code> to retrieve the same variable. However, I cannot set the variable's trainable property to <code>False</code>. My <code>get_variable</code> line is like:</p>
<pre><code>weight_var = tf.get_variable('weights', trainable = False)
</code></pre>
<p>But the variable <code>'weights'</code> is still in the output of <code>tf.trainable_variables</code>.</p>
<p>Can I set a shared variable's <code>trainable</code> flag to <code>False</code> by using <code>get_variable</code>?</p>
<p>The reason I want to do this is that I'm trying to reuse the low-level filters pre-trained from VGG net in my model, and I want to build the graph like before, retrieve the weights variable, and assign VGG filter values to the weight variable, and then keep them fixed during the following training step. </p> | 37,327,561 | 4 | 1 | null | 2016-05-19 14:17:19.537 UTC | 20 | 2019-05-17 20:21:56 UTC | 2018-01-04 02:52:23.547 UTC | null | 3,924,118 | null | 1,913,898 | null | 1 | 38 | tensorflow|pre-trained-model | 32,165 | <p>After looking at the documentation and the code, I was <strong>not</strong> able to find a way to remove a Variable from the <code>TRAINABLE_VARIABLES</code>.</p>
<h3>Here is what happens:</h3>
<ul>
<li>The first time <code>tf.get_variable('weights', trainable=True)</code> is called, the variable is added to the list of <code>TRAINABLE_VARIABLES</code>.</li>
<li>The second time you call <code>tf.get_variable('weights', trainable=False)</code>, you get the same variable but the argument <code>trainable=False</code> has no effect as the variable is already present in the list of <code>TRAINABLE_VARIABLES</code> (and there is <strong>no way to remove it</strong> from there)</li>
</ul>
<h3>First solution</h3>
<p>When calling the <code>minimize</code> method of the optimizer (see <a href="https://www.tensorflow.org/api_guides/python/train#Optimizer" rel="noreferrer">doc.</a>), you can pass a <code>var_list=[...]</code> as argument with the variables you want to optimizer. </p>
<p>For instance, if you want to freeze all the layers of VGG except the last two, you can pass the weights of the last two layers in <code>var_list</code>.</p>
<h3>Second solution</h3>
<p>You can use a <code>tf.train.Saver()</code> to save variables and restore them later (see <a href="https://www.tensorflow.org/programmers_guide/variables" rel="noreferrer">this tutorial</a>).</p>
<ul>
<li>First you train your entire VGG model with <strong>all trainable</strong> variables. You save them in a checkpoint file by calling <code>saver.save(sess, "/path/to/dir/model.ckpt")</code>.</li>
<li>Then (in another file) you train the second version with <strong>non trainable</strong> variables. You load the variables previously stored with <code>saver.restore(sess, "/path/to/dir/model.ckpt")</code>.</li>
</ul>
<p>Optionally, you can decide to save only some of the variables in your checkpoint file. See the <a href="https://www.tensorflow.org/api_guides/python/state_ops#Saver" rel="noreferrer">doc</a> for more info.</p> |
25,848,879 | Difference between mod and rem operators in VHDL? | <p>I came across these statements in VHDL programming and could not understand the difference between the two operators mod and rem</p>
<pre><code> 9 mod 5
(-9) mod 5
9 mod (-5)
9 rem 5
(-9) rem 5
9 rem (-5)
</code></pre> | 25,850,139 | 2 | 1 | null | 2014-09-15 13:09:00.72 UTC | 6 | 2017-11-24 10:20:03.827 UTC | null | null | null | null | 2,828,316 | null | 1 | 17 | vhdl | 88,183 | <p>A way to see the different is to run a quick simulation in a test bench, for
example using a process like this:</p>
<pre><code>process is
begin
report " 9 mod 5 = " & integer'image(9 mod 5);
report " 9 rem 5 = " & integer'image(9 rem 5);
report " 9 mod (-5) = " & integer'image(9 mod (-5));
report " 9 rem (-5) = " & integer'image(9 rem (-5));
report "(-9) mod 5 = " & integer'image((-9) mod 5);
report "(-9) rem 5 = " & integer'image((-9) rem 5);
report "(-9) mod (-5) = " & integer'image((-9) mod (-5));
report "(-9) rem (-5) = " & integer'image((-9) rem (-5));
wait;
end process;
</code></pre>
<p>It shows the result to be:</p>
<pre><code># ** Note: 9 mod 5 = 4
# ** Note: 9 rem 5 = 4
# ** Note: 9 mod (-5) = -1
# ** Note: 9 rem (-5) = 4
# ** Note: (-9) mod 5 = 1
# ** Note: (-9) rem 5 = -4
# ** Note: (-9) mod (-5) = -4
# ** Note: (-9) rem (-5) = -4
</code></pre>
<p><a href="http://en.wikipedia.org/wiki/Modulo_operation">Wikipedia - Modulo operation</a>
has an elaborate description, including the rules:</p>
<ul>
<li>mod has sign of divisor, thus <code>n</code> in <code>a mod n</code></li>
<li>rem has sign of dividend, thus <code>a</code> in <code>a rem n</code></li>
</ul>
<p>The <code>mod</code> operator gives the residue for a division that rounds down (floored division), so <code>a = floor_div(a, n) * n + (a mod n)</code>. The advantage is that <code>a mod n</code> is a repeated sawtooth graph when <code>a</code> is increasing even through zero, which is important in some calculations.</p>
<p>The <code>rem</code> operator gives the remainder for the regular integer division <code>a / n</code> that rounds towards 0 (truncated division), so <code>a = (a / n) * n + (a rem n)</code>.</p> |
25,758,737 | vagrant login as root by default | <p>Problem: frequently the first command I type to my boxes is <code>su -</code>.</p>
<p>Question: how do I make <code>vagrant ssh</code> use the root user by default?</p>
<p>Version: vagrant 1.6.5</p> | 25,758,738 | 11 | 1 | null | 2014-09-10 06:31:20.003 UTC | 45 | 2022-02-02 15:22:24.853 UTC | null | null | null | null | 1,574,942 | null | 1 | 104 | authentication|ssh|vagrant|root | 179,126 | <p><strong>Solution:</strong> <br/>
Add the following to your <code>Vagrantfile</code>:</p>
<pre class="lang-ruby prettyprint-override"><code>config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'
</code></pre>
<p>When you <code>vagrant ssh</code> henceforth, you will login as <code>root</code> and should expect the following:</p>
<pre><code>==> mybox: Waiting for machine to boot. This may take a few minutes...
mybox: SSH address: 127.0.0.1:2222
mybox: SSH username: root
mybox: SSH auth method: password
mybox: Warning: Connection timeout. Retrying...
mybox: Warning: Remote connection disconnect. Retrying...
==> mybox: Inserting Vagrant public key within guest...
==> mybox: Key inserted! Disconnecting and reconnecting using new SSH key...
==> mybox: Machine booted and ready!
</code></pre>
<p><strong>Update 23-Jun-2015:</strong>
This works for version 1.7.2 as well. Keying security has improved since 1.7.0; this technique overrides back to the previous method which uses a known private key. This solution is not intended to be used for a box that is accessible publicly without proper security measures done prior to publishing.</p>
<p><strong>Reference:</strong><br/></p>
<ul>
<li><strong><a href="https://docs.vagrantup.com/v2/vagrantfile/ssh_settings.html" rel="noreferrer">https://docs.vagrantup.com/v2/vagrantfile/ssh_settings.html</a></strong></li>
</ul> |
30,685,623 | How to implement a Java stream? | <p>I want to implement a <code>Stream<T></code>.</p>
<p>I don't want to just use <code>implements Stream<T></code>, because I would have to implement a ton of methods.</p>
<p>Can this be avoided?</p>
<p>To be more concrete, how can I stream <code>t1</code>, <code>t2</code> and <code>t3</code> for example:</p>
<pre><code>class Foo<T> {
T t1, t2, t3;
Foo(T t1, T t2, T t3) {
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
}
</code></pre> | 30,685,799 | 5 | 2 | null | 2015-06-06 17:27:18.453 UTC | 15 | 2017-08-12 00:34:12.823 UTC | 2017-04-04 16:35:59.707 UTC | null | 3,453,226 | null | 1,022,707 | null | 1 | 39 | java|java-8|java-stream | 39,768 | <p>The JDK's standard implementation of <code>Stream</code> is the internal class <code>java.util.stream.ReferencePipeline</code>, you cannot instantiate it directly. </p>
<p>Instead you can use <code>java.util.stream.Stream.builder()</code>, <code>java.util.stream.StreamSupport.stream(Spliterator<T>, boolean)</code> and various<sup><a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#of-T...-" rel="noreferrer">1</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamSources" rel="noreferrer">2</a></sup> other static factory methods to create an instance of the default implementation.</p>
<p>Using a spliterator is probably the most powerful approach as it allows you to provide objects lazily while also enabling efficient parallelization if your source can be divided into multiple chunks.</p>
<p>Additionally you can also convert streams back into spliterators, wrap them in a custom spliterator and then convert them back into a stream if you need to implement your own <em>stateful intermediate operations</em> - e.g. due to shortcomings in the standard APIs - since most available intermediate ops <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#Statelessness" rel="noreferrer">are not allowed to be stateful</a>.<br>See <a href="https://stackoverflow.com/a/28363324/1362755">this SO answer</a> for an example.</p>
<p>In principle you could write your own implementation of the stream interface, but that would be quite tedious.</p> |
32,466,073 | Alamofire No Such Module (CocoaPods) | <p>Using Xcode 7</p>
<p>I am trying to install Alamofire in a sample project. Have used the instructions from <a href="http://www.raywenderlich.com/97014/use-cocoapods-with-swift" rel="noreferrer">Ray Wenderlich's page</a></p>
<p>Only change from above link is the podfile -- which is from GitHub page <a href="https://github.com/Alamofire/Alamofire/tree/swift-2.0" rel="noreferrer">here</a> because the version has been updated. I have also used the Swift 2.0 branch.</p>
<p>Below is the snapshop of the error, my pod file and my terminal post installing the pod</p>
<p><a href="https://i.stack.imgur.com/wEFlB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wEFlB.png" alt=""></a></p>
<p><strong>PODFILE</strong>
<a href="https://i.stack.imgur.com/W8PsP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W8PsP.png" alt="enter image description here"></a></p>
<p><strong>TERMINAL</strong>
<a href="https://i.stack.imgur.com/q6JnX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q6JnX.png" alt="enter image description here"></a></p>
<p>P.S: I want to use cocoapods to install Alamofire. I don't want to download it from github page</p> | 32,499,180 | 18 | 3 | null | 2015-09-08 19:48:47.613 UTC | 5 | 2021-10-07 06:02:10.57 UTC | 2018-03-18 14:50:34.243 UTC | null | 1,033,581 | null | 849,775 | null | 1 | 37 | ios|cocoapods|alamofire | 55,687 | <p>Try this one.</p>
<p>For Swift 2.0 there is no need to add Alamofire.xcodeproj into your xcode. Simply copy and paste source folder from <a href="https://github.com/Alamofire">https://github.com/Alamofire</a> and you are done.</p>
<p>or if you want to install Alamofire from Cocoapods then try below code.</p>
<pre><code> source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Alamofire', '~> 2.0'
</code></pre> |
36,553,274 | Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4 | <p>I'm moving from using the hacky JavaScript classes of old (functions and prototypes) to the new ES6 classes.</p>
<p>I'm probably doing something stupid but I'm not sure why I'm not allowed to do this:</p>
<pre><code>class Player{
constructor(playerNo){
this.playerNo = playerNo;
}
get playerNo(){
return this.playerNo;
}
set cards(playersCards){
this.cards = playersCards;
}
get cards(){
return this.cards;
}
}
var steve = new Player(1);
</code></pre>
<p>It gives me the error: <code>Uncaught TypeError: Cannot set property playerNo of # which has only a getter on line 4</code></p>
<p>So, I tried the below:</p>
<pre><code>class Player{
constructor(playerNo){
this.playerNo = playerNo;
}
set playerNo(no){
this.playerNo = no;
}
get playerNo(){
return this.playerNo;
}
set cards(playersCards){
this.cards = playersCards;
}
get cards(){
return this.cards;
}
}
var steve = new Player(1);
</code></pre>
<p>Which gives me: <code>Uncaught RangeError: Maximum call stack size exceeded on line 6</code> (which is the line <code>this.playerNo = no;</code>).</p>
<p>Any ideas?</p> | 36,553,360 | 3 | 3 | null | 2016-04-11 15:42:33.913 UTC | 6 | 2021-01-23 17:53:19.467 UTC | null | null | null | null | 2,953,666 | null | 1 | 33 | javascript|ecmascript-6 | 54,801 | <p>You have recursion with setting <code>playerNo</code>.</p>
<p>In the <code>playerNo</code> setter, try setting <code>this._playerNo = 0</code>.</p>
<p>In the rest of the code, continue to make a distinction between the name of the setter method and the internal property that stores the data. </p> |
34,607,841 | React router nav bar example | <p>I am a beginner in React JS and would like to develop a react router based navigation for my Dashboard. The mockup is as follows:</p>
<p><a href="https://i.stack.imgur.com/lwtCO.png"><img src="https://i.stack.imgur.com/lwtCO.png" alt="Mockup"></a></p>
<p>My app.js code which I created to try routing is as follows:</p>
<pre><code>import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link } from 'react-router'
import Login from './components/Login.js';
const App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/login">Login</Link></li>
<li><Link to="/inbox">Inbox</Link></li>
</ul>
{this.props.children}
</div>
)
}
})
render((
<li>
<Router>
<Route path="/" component={App}>
<Route path="login" component={Login} />
</Route>
</Router>
</li>
), document.getElementById('placeholder'))
</code></pre>
<p>How do I create the navigation as shown in the mockup ?</p> | 34,634,762 | 4 | 4 | null | 2016-01-05 09:10:22.927 UTC | 38 | 2022-05-29 18:14:00.957 UTC | 2016-01-05 17:05:41.363 UTC | null | 452,332 | null | 452,332 | null | 1 | 71 | reactjs|nav|react-router | 173,789 | <p>Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:</p>
<pre><code><Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
</code></pre>
<p>And the other components would look something like this:</p>
<pre><code>var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
</code></pre> |
6,821,755 | multi tenant with custom domain on rails | <p>I'm creating a multi tenant application like shopify and wanna know how can I create custom domain on server that points to the same application instance?
For example:</p>
<pre><code>app1.mysystem.com == www.mystore.com
app2.mystem.com == www.killerstore.com
</code></pre>
<p>I need to do that config on CNAME like Google Apps? If so, how can I do that? Is there some good paper showing how this works ? </p>
<p>PS: app1 AND app2 points to the same application!
Thanks</p> | 6,822,083 | 2 | 0 | null | 2011-07-25 20:12:45.99 UTC | 10 | 2016-04-06 15:48:15.313 UTC | null | null | null | null | 151,174 | null | 1 | 4 | ruby-on-rails|apache|multi-tenant | 1,862 | <p>I have a similar setup and am using nginX. What I did for ease of maintenance was accepted all the connections from nginx and did the filtering in my app.</p>
<pre><code># application_controller.rb
before_filter :current_client
private
def current_client
# I am using MongoDB with Mongoid, so change the syntax of query accordingly
@current_client ||= Client.where(:host => request.host).first
render('/public/404.html', :status => :not_found, :layout => false) unless @current_client
end
</code></pre>
<p>You can have your clients have a domain record with there domain/subdomain pointing to <code>you_ip</code> or <code>your_domain_pointing_to_your_ip.com</code> and capture that in a form and save in database. Then alter the query in <code>current_client</code> like:</p>
<pre><code>@current_client ||= Client.or(:host => request.host).or(:alias => request.host).first
</code></pre> |
6,322,127 | Can not find the tag library descriptor for http://java.sun.com/jsf/facelets | <p>I've a JSP with</p>
<pre><code><%@taglib uri="http://java.sun.com/jsf/facelets" prefix="ui" %>
</code></pre>
<p>However it errors with</p>
<blockquote>
<p>The absolute uri: <a href="http://java.sun.com/jsf/facelets" rel="nofollow">http://java.sun.com/jsf/facelets</a> cannot be resolved in either web.xml or the jar files deployed with this application</p>
</blockquote>
<p>I have libraries <code>facelets-lib.jar</code> and <code>jsf-facelets-1.1.10.jar</code>, which I suppose is Facelets, but they do not contain JSP taglib descriptors.</p>
<p>What file is correct?</p> | 6,322,355 | 2 | 0 | null | 2011-06-12 13:13:36.423 UTC | 9 | 2015-04-28 14:23:42.7 UTC | 2015-03-05 11:37:17.597 UTC | null | 157,882 | null | 779,098 | null | 1 | 13 | jsp|jsf|facelets|taglib | 39,112 | <p>Facelets is intented to <strong>replace</strong> JSP altogether. But yet you're attempting to declare it as a JSP taglib. This is never going to work. Both are distinct view technologies. Facelets is a XML based view technology which is designed to be a successor of JSP. In Java EE 6 which was released december 2009 it has already replaced JSP as standard view technology for JSF and JSP has since then been deprecated.</p>
<p>You need to rename file extension from <code>.jsp</code> to <code>.xhtml</code> and replace all JSP taglib declarations by XML namespace declarations and remove all <code><jsp:xxx></code> tags and all <code><% %></code> scriptlets.</p>
<p>So, for example the following basic JSP template <code>page.jsp</code></p>
<pre class="lang-xml prettyprint-override"><code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html>
<f:view>
<html lang="en">
<head>
<title>JSP page</title>
</head>
<body>
<h:outputText value="JSF components here." />
</body>
</html>
</f:view>
</code></pre>
<p>has to be rewritten as <code>page.xhtml</code></p>
<pre class="lang-xml prettyprint-override"><code><!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>Facelet page</title>
</head>
<body>
<h:outputText value="JSF components here." />
</body>
</html>
</code></pre>
<p>Finally, the mentioned JAR files are Facelets 1.x JARs while Facelets 2.x is already been out since 2009 as part of <a href="http://javaserverfaces.java.net/" rel="noreferrer">a JSF 2.x implementation</a>. If you can, I'd strongly recommend to just skip Facelets 1.x and continue with Facelets 2.x.</p>
<h3>See also:</h3>
<ul>
<li><a href="http://facelets.java.net/nonav/docs/dev/docbook.html" rel="noreferrer">Facelets Developer Documentation</a> (for Facelets 1.x)</li>
<li><a href="http://docs.oracle.com/javaee/6/tutorial/doc/giepx.html" rel="noreferrer">Java EE 6 tutorial - Facelets</a> (for Facelets 2.x)</li>
<li><a href="http://balusc.blogspot.com/2011/01/jsf-20-tutorial-with-eclipse-and.html" rel="noreferrer">JSF 2.0 tutorial with Eclipse and Glassfish</a> (to start from zero)</li>
<li><a href="https://stackoverflow.com/questions/4441713/migrating-from-jsf-1-2-to-jsf-2-0">Migrating from JSF 1.2 to JSF 2.0</a></li>
</ul> |
6,661,108 | Import WordNet In NLTK | <p>I want to import <em><code>wordnet</code></em> dictionary but when i import Dictionary form <em><code>wordnet</code></em> i see this error :</p>
<pre><code> for l in open(WNSEARCHDIR+'/lexnames').readlines():
IOError: [Errno 2] No such file or directory: 'C:\\Program Files\\WordNet\\2.0\\dict/lexnames'
</code></pre>
<p>I install wordnet2.1 in this directory but i cant import
please help me to solve this problem</p>
<pre><code>import nltk
from nltk import *
from nltk.corpus import wordnet
from wordnet import Dictionary
print '-----------------------------------------'
print Dictionary.length
</code></pre> | 6,662,494 | 2 | 0 | null | 2011-07-12 08:00:34.917 UTC | 6 | 2021-08-20 16:21:47.233 UTC | 2011-07-12 09:34:37 UTC | null | 166,749 | null | 838,242 | null | 1 | 15 | python|dictionary|nltk|wordnet|stemming | 41,933 | <p>The following works for me:</p>
<pre><code>>>> nltk.download()
# Download window opens, fetch wordnet
>>> from nltk.corpus import wordnet as wn
</code></pre>
<p>Now I've a <code>WordNetCorpusReader</code> called <code>wn</code>. I don't know why you're looking for a <code>Dictionary</code> class, since there's no such class listed in the <a href="http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.wordnet.WordNetCorpusReader-class.html" rel="noreferrer">docs</a>. The NLTK book, in <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html#wordnet_index_term" rel="noreferrer">section 2.5</a>, explains what you can do with the <code>nltk.corpus.wordnet</code> module.</p> |
6,634,077 | PHP SOAP client Tutorial/Recommendation? | <p>I need to build some integration with a SOAP service based on .NET 2.0. Im using PHP 5 and have never used SOAP. There doesn't appear to be any straight forward tutorials about how to talk to a soap service using PHP.</p>
<p>Does anyone know where to find some good tutorials or docs?</p> | 6,634,106 | 2 | 1 | null | 2011-07-09 09:59:54.3 UTC | 7 | 2015-06-15 11:34:11.407 UTC | 2013-08-09 15:33:46.07 UTC | null | 630,443 | null | 579,049 | null | 1 | 21 | php|soap|soap-client | 39,217 | <p>Have you tried <a href="http://php.net/manual/pl/class.soapclient.php" rel="noreferrer">SoapClient</a> which is already built into PHP?</p>
<p>There is one tutorial: <a href="http://www.codingfriends.com/index.php/2010/04/16/soap-client-calling-net-web-service/" rel="noreferrer">PHP - Soap Client calling .NET Web service</a></p>
<p><a href="http://devzone.zend.com/article/689" rel="noreferrer">Here</a> is another one, even though it was created for zend developers it should work fine.</p> |
6,567,724 | Matplotlib so log axis only has minor tick mark labels at specified points. Also change size of tick labels in colorbar | <p>I am trying to create a plot but I just want the ticklabels to show as shown where the log scale is shown as above. I only want the minor ticklabel for 50, 500 and 2000 to show. Is there anyway to specify the minor tick labels to show?? I have been trying to figure this out for a bit but haven't found a good solution. All I can think of is to get the minorticklabels() and set the fontsize to 0. This is shown below the first snippet of code. I was hoping there was a more clean solution.</p>
<p>The other thing is changing the size of the ticklabels in the colorbar which I haven't figured out. If anyone knows of a way to do this please let me know because I don't see a method in colorbar that easily does this.</p>
<p>First code:</p>
<pre><code>fig = figure(figto)
ax = fig.add_subplot(111)
actShape = activationTrace.shape
semitones = arange(actShape[1])
freqArray = arange(actShape[0])
X,Y = meshgrid(self.testFreqArray,self.testFreqArray)
Z = sum(activationTrace[:,:,beg:end],axis=2)
surf = ax.contourf(X,Y,Z, 8, cmap=cm.jet)
ax.set_position([0.12,0.15,.8,.8])
ax.set_ylabel('Log Frequency (Hz)')
ax.set_xlabel('Log Frequency (Hz)')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_minor_formatter(FormatStrFormatter('%d'))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both',reset=False,which='both',length=8,width=2)
self.plotSetAxisLabels(ax,22)
self.plotSetAxisTickLabels(ax,18)
cbar = fig.colorbar(surf, shrink=0.5, aspect=20, fraction=.12,pad=.02)
cbar.set_label('Activation',size=18)
return ax, cbar
</code></pre>
<p><img src="https://i.stack.imgur.com/WJMsE.png" alt="enter image description here"></p>
<p>Second Code:</p>
<pre><code>fig = figure(figto)
ax = fig.add_subplot(111)
actShape = activationTrace.shape
semitones = arange(actShape[1])
freqArray = arange(actShape[0])
X,Y = meshgrid(self.testFreqArray,self.testFreqArray)
Z = sum(activationTrace[:,:,beg:end],axis=2)
surf = ax.contourf(X,Y,Z, 8, cmap=cm.jet)
ax.set_position([0.12,0.15,.8,.8])
ax.set_ylabel('Log Frequency (Hz)')
ax.set_xlabel('Log Frequency (Hz)')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_minor_formatter(FormatStrFormatter('%d'))
ax.yaxis.set_minor_formatter(FormatStrFormatter('%d'))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both',reset=False,which='both',length=8,width=2)
self.plotSetAxisLabels(ax,22)
self.plotSetAxisTickLabels(ax,18)
cbar = fig.colorbar(surf, shrink=0.5, aspect=20, fraction=.12,pad=.02)
cbar.set_label('Activation',size=18)
count = 0
for i in ax.xaxis.get_minorticklabels():
if (count%4 == 0):
i.set_fontsize(12)
else:
i.set_fontsize(0)
count+=1
for i in ax.yaxis.get_minorticklabels():
if (count%4 == 0):
i.set_fontsize(12)
else:
i.set_fontsize(0)
count+=1
return ax, cbar
</code></pre>
<p><img src="https://i.stack.imgur.com/JoQsl.png" alt="enter image description here"></p>
<p>For the colorbar:
Another quick question if you don't mind because trying to figure it out but not entirely sure. I want to use scientific notation which I can get with ScalarFormatter. How do I set the number of decimal places and the multiplier?? I'd like it to be like 8x10^8 or .8x10^9 to save space instead of putting all those zeros. I figure there is multiple ways to do this inside the axes object but what do you reckon is the best way. I can't figure out how to change the notation when changing to the ScalarFormatter.</p>
<p>For the chart:
Also, my data has points starting at 46 and then at successive multiplies of that multiplied by 2^(1/12) so 46,49,50,55,58,61...3132. These are all rounded but lie close to the 2^(1/12). I decided it better to place major tickers close to these numbers. Is the best way to use the fixed formatter and use a ticker every 15 or so in the freqArray. Then use a minor ticker at every other frequency. Can I do this and still maintain a log axis??</p> | 6,568,248 | 2 | 0 | null | 2011-07-04 05:50:13.857 UTC | 14 | 2021-11-07 16:47:00.857 UTC | 2016-07-26 10:12:13.043 UTC | null | 2,666,859 | null | 748,357 | null | 1 | 22 | python|numpy|scipy|matplotlib | 25,311 | <ol>
<li>Use <code>FixedLocator</code> to statically define explicit tick locations.</li>
<li>Colorbar <code>cbar</code> will have an <code>.ax</code> attribute that will provide access to the usual axis methods including tick formatting. This is not a reference to an <code>axes</code> (e.g. <code>ax1</code>, <code>ax2</code>, etc.).</li>
</ol>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(10,3000,100)
y = np.arange(10,3000,100)
X,Y = np.meshgrid(x,y)
Z = np.random.random(X.shape)*8000000
surf = ax.contourf(X,Y,Z, 8, cmap=plt.cm.jet)
ax.set_ylabel('Log Frequency (Hz)')
ax.set_xlabel('Log Frequency (Hz)')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_minor_formatter(plt.FormatStrFormatter('%d'))
# defining custom minor tick locations:
ax.xaxis.set_minor_locator(plt.FixedLocator([50,500,2000]))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both',reset=False,which='both',length=8,width=2)
cbar = fig.colorbar(surf, shrink=0.5, aspect=20, fraction=.12,pad=.02)
cbar.set_label('Activation',size=18)
# access to cbar tick labels:
cbar.ax.tick_params(labelsize=5)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/eYWYZ.png" alt="enter image description here" /></p>
<p><strong>Edit</strong></p>
<p>If you want the tick marls, but you want to selectively show the labels, I see nothing wrong with your iteration, except I might use <code>set_visible</code> instead of making the fontsize zero.</p>
<p>You might enjoy finer control using a <code>FuncFormatter</code> where you can use the value or position of the tick to decide whether it gets shown:</p>
<pre><code>def show_only_some(x, pos):
s = str(int(x))
if s[0] in ('2','5'):
return s
return ''
ax.xaxis.set_minor_formatter(plt.FuncFormatter(show_only_some))
</code></pre> |
7,129,249 | Getting the floor value of a number in SQLite? | <p>I have a SQLite database with a table containing the scores of some league players in a bowling center. I'm trying to get the average of the Score column for each player ID. The problem with this is I only need the whole part of the average, and it should not be rounded (example: an average of 168.99 should return 168, not 169).</p>
<p>When trying to find something like this on Google, I only found solutions for SQL Server and some others, but not SQLite, so if anyone can help me with this, I'd really appreciate it!</p>
<p>So far, I'm using <code>ROUND(AVG(s1.Score),2)</code> and I'm truncating the extra part in my Java program that uses the database by converting it to a String, removing the unwanted part and then casting it to an Integer, but I'd rather do it all in SQL if possible.</p> | 7,129,253 | 3 | 0 | null | 2011-08-20 02:33:23.277 UTC | null | 2021-11-24 17:55:26.333 UTC | 2021-11-24 17:55:26.333 UTC | null | 9,449,426 | null | 804,929 | null | 1 | 29 | sql|sqlite|floor | 27,842 | <p>You can just use cast it to an integer. It will truncate it, which is equivalent to floor.</p> |
7,479,720 | Removing the first 16 bytes from a byte array | <p>In Java, how do I take a byte[] array and remove the first 16 bytes from the array? I know I might have to do this by copying the array into a new array. Any examples or help would be appreciated.</p> | 7,479,741 | 4 | 0 | null | 2011-09-20 03:18:31.18 UTC | null | 2021-01-16 02:49:53.45 UTC | 2011-09-20 04:17:50.653 UTC | null | 98,094 | null | 98,094 | null | 1 | 11 | java|bytearray | 38,356 | <p>See <code>Arrays</code> class in the <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#copyOfRange-byte:A-int-int-" rel="nofollow noreferrer">Java library</a>:</p>
<pre><code>Arrays.copyOfRange(byte[] original, int from, int to)
</code></pre>
<p><code>from</code> is inclusive, whereas <code>to</code> is exclusive. Both are zero based indices, so to remove the first 16 bytes do</p>
<pre><code>Arrays.copyOfRange(original, 16, original.length);
</code></pre> |
7,496,840 | Get Android shared preferences value in activity/normal class | <p>I have made a shared preference activity that store the user settings, now i want to get values in a activity or normal java class.please provide a solution or example i have already tried this code but failed.</p>
<pre><code>public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences channel=this.getSharedPreferences(strFile, Context.MODE_PRIVATE);
strChannel=channel.getString(keyChannel,"Default").toString();
Toast.makeText(getApplicationContext(), strChannel, Toast.LENGTH_LONG).show();
}
</code></pre>
<p>in this code <code>strfile</code> for eg. <code>com.android.pack.ClassName</code> is <code>SharedPreference Activity</code> from values to be fetched, and keyChannel is key that is same in <code>SharedPreference Activity</code>.</p>
<p>Kindly provide the solution.</p> | 7,497,079 | 4 | 2 | null | 2011-09-21 08:35:11.227 UTC | 11 | 2018-08-11 05:08:42.01 UTC | 2011-09-21 09:19:06.13 UTC | null | 213,550 | null | 921,653 | null | 1 | 41 | android|sharedpreferences | 118,214 | <p>If you have a SharedPreferenceActivity by which you have saved your values </p>
<pre><code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
</code></pre>
<p>if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.</p>
<pre><code>SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
</code></pre>
<p>and this is how you can retrieve the values.</p>
<pre><code>SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
</code></pre>
<p>Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.</p>
<pre><code>mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
</code></pre> |
7,869,405 | Opencv match contour image | <p>I'd like to know what would be the best strategy to compare a group of contours, in fact are edges resulting of a canny edges detection, from two pictures, in order to know which pair is more alike. </p>
<p>I have this image:</p>
<p><a href="http://i55.tinypic.com/10fe1y8.jpg" rel="noreferrer">http://i55.tinypic.com/10fe1y8.jpg</a></p>
<p>And I would like to know how can I calculate which one of these fits best to it:</p>
<p><a href="http://i56.tinypic.com/zmxd13.jpg" rel="noreferrer">http://i56.tinypic.com/zmxd13.jpg</a></p>
<p>(it should be the one on the right)</p>
<p>Is there anyway to compare the contours as a whole?
I can easily rotate the images but I don't know what functions to use in order to calculate that the reference image on the right is the best fit.</p>
<p>Here it is what I've already tried using opencv:</p>
<p>matchShapes function - I tried this function using 2 gray scales images and I always get the same result in every comparison image and the value seems wrong as it is 0,0002.</p>
<p>So what I realized about matchShapes, but I'm not sure it's the correct assumption, is that the function works with pairs of contours and not full images. Now this is a problem because although I have the contours of the images I want to compare, they are hundreds and I don't know which ones should be "paired up".</p>
<p>So I also tried to compare all the contours of the first image against the other two with a <em>for</em> iteration but I might be comparing,for example, the contour of the 5 against the circle contour of the two reference images and not the 2 contour.</p>
<p>Also tried simple cv::compare function and matchTemplate, none with success. </p> | 7,870,399 | 1 | 0 | null | 2011-10-23 21:39:01.173 UTC | 14 | 2011-10-24 16:52:29.123 UTC | null | null | null | null | 985,289 | null | 1 | 16 | opencv|contour | 20,547 | <p>Well, for this you have a couple of options depending on how robust you need your approach to be.</p>
<h2>Simple Solutions (with assumptions):</h2>
<p>For these methods, I'm assuming your the images you supplied are what you are working with (i.e., the objects are already segmented and approximately the same scale. Also, you will need to correct the rotation (at least in a coarse manner). You might do something like iteratively rotate the comparison image every 10, 30, 60, or 90 degrees, or whatever coarseness you feel you can get away with.</p>
<p>For example,</p>
<pre><code>for(degrees = 10; degrees < 360; degrees += 10)
coinRot = rotate(compareCoin, degrees)
// you could also try Cosine Similarity, or even matchedTemplate here.
metric = SAD(coinRot, targetCoin)
if(metric > bestMetric)
bestMetric = metric
coinRotation = degrees
</code></pre>
<hr>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Sum_of_absolute_differences" rel="noreferrer">Sum of Absolute Differences (SAD)</a>: This will allow you to quickly compare the images once you have determined an approximate rotation angle.</li>
<li><a href="http://en.wikipedia.org/wiki/Cosine_similarity" rel="noreferrer">Cosine Similarity</a>: This operates a bit differently by treating the image as a 1D vector, and then computes the the high-dimensional angle between the two vectors. The better the match the smaller the angle will be.</li>
</ul>
<h2>Complex Solutions (possibly more robust):</h2>
<p>These solutions will be more complex to implement, but will probably yield more robust classifications.</p>
<hr>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Hausdorff_distance" rel="noreferrer">Haussdorf Distance</a>: This <a href="https://stackoverflow.com/questions/7715407/how-do-i-compare-two-edge-images-in-opencv/7718768#7718768">answer</a> will give you an introduction on using this method. This solution will probably also need the rotation correction to work properly.</li>
<li><a href="http://students.ee.sun.ac.za/~riaanvdd/image_processing_tools.htm" rel="noreferrer">Fourier-Mellin Transform</a>: This method is an extension of Phase Correlation, which can extract the rotation, scale, and translation (RST) transform between two images.</li>
<li><a href="http://en.wikipedia.org/wiki/Feature_detection_%28computer_vision%29" rel="noreferrer">Feature Detection and Extraction</a>: This method involves detecting "robust" (i.e., scale and/or rotation invariant) features in the image and comparing them against a set of target features with RANSAC, LMedS, or simple least squares. OpenCV has a couple of samples using this technique in <a href="https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/matcher_simple.cpp" rel="noreferrer">matcher_simple.cpp</a> and <a href="https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/matching_to_many_images.cpp" rel="noreferrer">matching_to_many_images.cpp</a>. <strong>NOTE:</strong> With this method you will probably not want to binarize the image, so there are more detectable features available.</li>
</ul> |
2,083,923 | Empty textbox using Jquery | <p>I'm able to hide the 'tr' when 'Remove' is clicked. with the following code.</p>
<pre><code>$("a#minus").bind("click", function(e){
$(this).closest('tr').hide();
});
</code></pre>
<p>But I also want to clear the content of the 2 text boxes (id of the textbox's are dynamic [frm_Expense_expensesVO_<em>__strAmount and frm_Expense_expensesVO_</em>__memo] here '*' goes from 1 to infinity). Please help. Thanks</p>
<pre><code><table>
<tr>
<td>
Amount
</td>
<td>
Memo
</td>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
<input type="text" name="expensesVO[0].strAmount" value="2.30" id="frm_Expense_expensesVO_0__strAmount"/>
</td>
<td>
<input type="text" name="expensesVO[0].memo" value="Five" id="frm_Expense_expensesVO_0__memo"/>
</td>
<td>
<a id="minus" href="#">Remove</a>
</td>
</tr>
<tr>
<td>
<input type="text" name="expensesVO[1].strAmount" value="3.45" id="frm_Expense_expensesVO_1__strAmount"/>
</td>
<td>
<input type="text" name="expensesVO[1].memo" value="Six" id="frm_Expense_expensesVO_1__memo"/>
</td>
<td>
<a id="minus" href="#">Remove</a>
</td>
</tr>
<tr>
<td>
<input type="text" name="expensesVO[2].strAmount" value="" id="frm_Expense_expensesVO_2__strAmount"/>
</td>
<td>
<input type="text" name="expensesVO[2].memo" value="" id="frm_Expense_expensesVO_2__memo"/>
</td>
<td>
<input type="submit" id="frm_Expense_ExpenseAdd_plus" name="action:ExpenseAdd_plus" value="+"/>
</td>
</tr>
<tr>
<td>
<label id="frm_Expense_transactionVO_amount">5.75</label>
</td>
<td align="right">
<input type="submit" id="frm_Expense_Cancel" name="action:ExpenseAdd_cancel" value="Cancel"/>
</td>
<td align="left">
<input type="submit" id="frm_Expense_Save" name="action:ExpenseAdd_save" value="Save"/>
</td>
</tr>
</code></pre>
<p></p> | 2,083,938 | 4 | 0 | null | 2010-01-18 04:35:37.26 UTC | 2 | 2010-01-18 06:25:00.99 UTC | null | null | null | null | 234,110 | null | 1 | 6 | jquery|textbox | 58,325 | <pre><code>$("a#minus").bind("click", function(e){
$(this).closest('tr').hide().find('input:text').val('');
});
</code></pre>
<p><strong>Note:</strong> Also see <a href="https://stackoverflow.com/questions/2083923/empty-textbox-using-jquery/2083955#2083955">darmen's answer</a> on why the selector <code>a#minus</code> will not work as desired.</p> |
2,134,461 | Why can't indexed views have a MAX() aggregate? | <p>I have been trying out a few index views and am impressed but I nearly always need a max or a min as well and can not understand why it doesn't work with these, can anyone explain why?</p>
<p>I KNOW they are not allowed, I just can't understand why!!! Count etc. is allowed why not MIN/MAX, I'm looking for explanation...</p> | 2,134,890 | 4 | 0 | null | 2010-01-25 18:09:23.537 UTC | 4 | 2019-10-17 06:12:16.927 UTC | 2010-01-25 19:04:02.287 UTC | null | 40,725 | null | 234,457 | null | 1 | 51 | sql-server|view|indexing|aggregate | 16,833 | <p>These aggregates are not allowed because they cannot be recomputed solely based on the changed values.</p>
<p>Some aggregates, like <code>COUNT_BIG()</code> or <code>SUM()</code>, can be recomputed just by looking at the data that changed. These are allowed within an indexed view because, if an underlying value changes, the impact of that change can be directly calculated. </p>
<p>Other aggregates, like <code>MIN()</code> and <code>MAX()</code>, cannot be recomputed just by looking at the data that is being changed. If you delete the value that is currently the max or min, then the new max or min has to be searched for and found in the <em>entire</em> table. </p>
<p>The same principle applies to other aggregates, like <code>AVG()</code> or the standard variation aggregates. SQL cannot recompute them just from the values changed, but needs to re-scan the entire table to get the new value. </p> |
26,182,524 | Oracle: How to select current date (Today) before midnight? | <p>Using Oracle, how do you select current date (i.e. SYSDATE) at 11:59:59?</p>
<p>Take into account that the definition of midnight <a href="https://english.stackexchange.com/questions/6459/how-should-midnight-on-be-interpreted">might be a little ambiguous</a> (Midnight Thursday means Straddling Thursday and Friday or Straddling Wednesday and Thursday?).</p> | 26,182,525 | 3 | 1 | null | 2014-10-03 16:00:02.093 UTC | 6 | 2015-10-16 03:01:17.473 UTC | 2017-04-13 12:38:09.717 UTC | null | -1 | null | 2,658,613 | null | 1 | 11 | sql|database|oracle | 76,025 | <p>To select current date (Today) before midnight (one second before) you can use any of the following statements:</p>
<pre><code>SELECT TRUNC(SYSDATE + 1) - 1/(24*60*60) FROM DUAL
SELECT TRUNC(SYSDATE + 1) - INTERVAL '1' SECOND FROM DUAL;
</code></pre>
<p>What it does:</p>
<ol>
<li>Sum one day to <code>SYSDATE</code>: <code>SYSDATE + 1</code>, now the date is Tomorrow</li>
<li>Remove time part of the date with <code>TRUNC</code>, now the date is Tomorrow at 00:00</li>
<li>Subtract one second from the date: <code>- 1/(24*60*60)</code> or <code>- INTERVAL '1' SECOND FROM DUAL</code>, now the date is Today at 11:59:59</li>
</ol>
<p><strong>Note 1:</strong> If you want to check date intervals you might want to check @Allan answer below.</p>
<p><strong>Note 2:</strong> As an alternative you can use this other one (which is easier to read):</p>
<pre><code>SELECT TRUNC(SYSDATE) + INTERVAL '23:59:59' HOUR TO SECOND FROM DUAL;
</code></pre>
<ol>
<li>Remove time part of the current date with <code>TRUNC</code>, now the date is Today at 00:00</li>
<li>Add a time interval of <code>23:59:59</code>, now the date is Today at 11:59:59</li>
</ol>
<p><strong>Note 3:</strong> To check the results you might want to add format:</p>
<pre><code>SELECT TO_CHAR(TRUNC(SYSDATE + 1) - 1/(24*60*60),'yyyy/mm/dd hh24:mi:ss') FROM DUAL
SELECT TO_CHAR(TRUNC(SYSDATE + 1) - INTERVAL '1' SECOND,'yyyy/mm/dd hh24:mi:ss') FROM DUAL
SELECT TO_CHAR(TRUNC(SYSDATE) + INTERVAL '23:59:59','yyyy/mm/dd hh24:mi:ss') FROM DUAL
</code></pre> |
7,123,060 | Is there a predict function for plm in R? | <p>I have a small N large T panel which I am estimating via <code>plm::plm</code> (panel linear regression model), with fixed effects.</p>
<p>Is there any way to get predicted values for a new dataset? (I want to
estimate parameters on a subset of my sample, and then use these to
calculate model-implied values for the whole sample).</p> | 7,129,240 | 5 | 5 | null | 2011-08-19 14:28:17.17 UTC | 11 | 2022-04-17 22:22:25.577 UTC | 2022-04-17 22:22:25.577 UTC | null | 4,640,346 | null | 1,106,532 | null | 1 | 19 | r|panel-data|plm | 15,382 | <p>There are (at least) two methods in the package to produce estimates from plm objects: </p>
<p>-- fixef.plm: Extract the Fixed Effects</p>
<p>-- pmodel.response: A function to extract the model.response</p>
<p>It appears to me that the author(s) are not interested in providing estimates for the "random effects". It may be a matter of "if you don't know how to do it on your own, then we don't want to give you a sharp knife to cut yourself too deeply."</p> |
7,433,602 | How to center in JTable cell a value? | <p>How to center a value in <code>JTable</code> cell? I'm using Netbeans.</p> | 7,433,758 | 6 | 1 | null | 2011-09-15 15:41:39.297 UTC | 10 | 2017-08-12 16:59:26.313 UTC | 2011-09-15 18:09:28.133 UTC | null | 418,556 | null | 452,011 | null | 1 | 31 | java|swing|jtable | 95,530 | <p>You need to customize the renderer. To center the first column you can do:</p>
<pre><code>DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
</code></pre>
<p>To center all columns with String data you can do:</p>
<pre><code>DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.setDefaultRenderer(String.class, centerRenderer);
</code></pre> |
7,537,791 | Understanding Recursion to generate permutations | <p>I find recursion, apart from very straight forward ones like factorial, very difficult to understand. The following snippet prints all permutations of a string. Can anyone help me understand it. What is the way to go about to understand recursion properly.</p>
<pre><code>void permute(char a[], int i, int n)
{
int j;
if (i == n)
cout << a << endl;
else
{
for (j = i; j <= n; j++)
{
swap(a[i], a[j]);
permute(a, i+1, n);
swap(a[i], a[j]);
}
}
}
int main()
{
char a[] = "ABCD";
permute(a, 0, 3);
getchar();
return 0;
}
</code></pre> | 7,537,933 | 6 | 4 | null | 2011-09-24 08:00:40.993 UTC | 52 | 2020-04-11 00:13:54.71 UTC | 2011-09-24 10:15:50.72 UTC | null | 176,418 | null | 176,418 | null | 1 | 51 | c++|recursion | 80,207 | <p>PaulR has the right suggestion. You have to run through the code by "hand" (using whatever tools you want - debuggers, paper, logging function calls and variables at certain points) until you understand it. For an explanation of the code I'll refer you to quasiverse's excellent answer.</p>
<p>Perhaps this visualization of the call graph with a slightly smaller string makes it more obvious how it works:
<img src="https://i.stack.imgur.com/KkDTf.png" alt="Call graph"></p>
<p>The graph was made with <a href="http://www.graphviz.org/" rel="noreferrer">graphviz</a>. </p>
<pre><code>// x.dot
// dot x.dot -Tpng -o x.png
digraph x {
rankdir=LR
size="16,10"
node [label="permute(\"ABC\", 0, 2)"] n0;
node [label="permute(\"ABC\", 1, 2)"] n1;
node [label="permute(\"ABC\", 2, 2)"] n2;
node [label="permute(\"ACB\", 2, 2)"] n3;
node [label="permute(\"BAC\", 1, 2)"] n4;
node [label="permute(\"BAC\", 2, 2)"] n5;
node [label="permute(\"BCA\", 2, 2)"] n6;
node [label="permute(\"CBA\", 1, 2)"] n7;
node [label="permute(\"CBA\", 2, 2)"] n8;
node [label="permute(\"CAB\", 2, 2)"] n9;
n0 -> n1 [label="swap(0, 0)"];
n0 -> n4 [label="swap(0, 1)"];
n0 -> n7 [label="swap(0, 2)"];
n1 -> n2 [label="swap(1, 1)"];
n1 -> n3 [label="swap(1, 2)"];
n4 -> n5 [label="swap(1, 1)"];
n4 -> n6 [label="swap(1, 2)"];
n7 -> n8 [label="swap(1, 1)"];
n7 -> n9 [label="swap(1, 2)"];
}
</code></pre> |
7,190,965 | How to move (and overwrite) all files from one directory to another? | <p>I know of the <code>mv</code> command to move a file from one place to another, but how do I move all files from one directory into another (that has a bunch of other files), overwriting if the file already exists?</p> | 7,190,995 | 6 | 2 | null | 2011-08-25 13:12:35.02 UTC | 7 | 2019-11-12 13:43:52.47 UTC | 2011-08-25 16:39:11.61 UTC | null | 471,272 | null | 906,475 | null | 1 | 60 | linux|unix | 189,352 | <p>It's just <code>mv srcdir/* targetdir/</code>.</p>
<p>If there are too many files in <code>srcdir</code> you might want to try something like the following approach:</p>
<pre><code>cd srcdir
find -exec mv {} targetdir/ +
</code></pre>
<p>In contrast to <code>\;</code> the final <code>+</code> collects arguments in an <code>xargs</code> like manner instead of executing <code>mv</code> once for every file.</p> |
14,004,442 | Cannot apply indexing with [] to an expression of type `object' | <p><strong>H</strong>ere is my code: An ArrayList of ArrayList that returns a float:</p>
<pre><code>public ArrayList walls=new ArrayList();
public void Start()
{
walls[0] = ReturnInArrayList(279,275,0,0,90);
walls[1] = ReturnInArrayList(62,275,0,0,0);
walls[2] = ReturnInArrayList(62,275,62,0,90);
walls[3] = ReturnInArrayList(217,275,62,-62,0);
walls[4] = ReturnInArrayList(62,275,279,0,90);
walls[5] = ReturnInArrayList(41,275,279,0,0);
walls[6] = ReturnInArrayList(279,275,320,0,9);
walls[7] = ReturnInArrayList(320,275,0,-279,0);
for (int i = 0; i < walls.Length; i++) {
float a = (float)walls[i][0];
float b = (float)walls[i][1];
float c = (float)walls[i][2];
float d = (float)walls[i][3];
float e = (float)walls[i][4];
}
}
ArrayList ReturnInArrayList(float a,float b,float c, float d, float e)
{
ArrayList arrayList = new ArrayList();
arrayList.Add(a);
arrayList.Add(b);
arrayList.Add(c);
arrayList.Add(d);
arrayList.Add(e);
return arrayList;
}
</code></pre>
<p>It gives me the following error:</p>
<blockquote>
<p>error CS0021: Cannot apply indexing with [] to an expression of type
`object'</p>
</blockquote>
<p>I already did the casting, what is wrong? :(</p> | 14,004,488 | 4 | 4 | null | 2012-12-22 16:21:19.44 UTC | 2 | 2020-06-09 19:06:34.477 UTC | 2020-06-09 19:06:34.477 UTC | null | 1,646,928 | null | 1,646,928 | null | 1 | 16 | c#|object|arraylist|indexing | 83,190 | <p>The problem is that <code>paredes[i]</code> returns an <code>object</code> which is the return type of the <code>ArrayList</code> indexer. You need to cast this to an <code>ArrayList</code> to be able to access it:</p>
<pre><code>float a= (float)((ArrayList)paredes[i])[0];
</code></pre>
<p>A better solution though is to use generics and populate a <code>List<float></code> instead:</p>
<pre><code>List<float> RetornaEmList(float a,float b,float c, float d, float e)
{
return new List<float> { a, b, c, d, e };
}
</code></pre>
<p>then <code>paredes</code> is a <code>List<List<float>></code> and your accessor can be changed to:</p>
<pre><code>float a = paredes[i][0];
</code></pre> |
14,191,929 | Fingerprint Scanner using Camera | <p>Working on fingerprint scanner using camera or without, its possibility and its success rate?, I came across one of open source SDK named <a href="http://digitalpersona.com/fingerjetfx/">FingerJetFX</a> its provide feasibilty with android too.</p>
<p>The FingerJetFX OSE fingerprint feature extractor is platform-independent and can be built
for, with appropriate changes to the make files, and run in environments with or without
operating systems, including </p>
<ul>
<li>Linux</li>
<li>Android</li>
<li>Windows</li>
<li>Windows CE </li>
<li>various RTOSs</li>
</ul>
<p>but I'm not sure whether Fingerprint scanner possible or not, I download the SDK and digging but no luck, even didn't found any steps to integrate the SDK, so having few of question which listed below:</p>
<p>I'm looking for suggestion and guidance: </p>
<blockquote>
<ol>
<li>Fingerprint scanner can be possible in android using camera or without camera? </li>
<li>With the help of <code>FingerJetFX</code> can I achieve my goal?</li>
<li>If 2nd answer is yes, then can someone provide me any sort of steps to integrate SDK in android?</li>
</ol>
</blockquote>
<p>Your suggestion are appreciable.</p> | 14,205,345 | 2 | 1 | null | 2013-01-07 07:54:16.623 UTC | 25 | 2017-04-27 15:14:23.55 UTC | 2013-01-07 09:54:14.243 UTC | null | 903,469 | null | 646,806 | null | 1 | 43 | android|sdk|android-ndk|camera|fingerprint | 41,988 | <p><strong>Android Camera Based Solutions:</strong></p>
<p>As someone who's done significant research on this exact problem, I can tell you it's difficult to get a suitable image for templating (feature extraction) using a stock camera found on any current Android device. The main debilitating issue is achieving significant contrast between the finger's ridges and valleys. Commercial optical fingerprint scanners (which you are attempting to mimic) typically achieve the necessary contrast through frustrated total internal reflection in a prism. </p>
<p><img src="https://i.stack.imgur.com/nrIbc.png" alt="FTIR in Biometrics"></p>
<p>In this case, light from the ridges contacting the prism are transmitted to the CMOS sensor while light from the valleys are not. You're simply not going to reliably get the same kind of results from an Android camera, but that doesn't mean you can't get something useable under ideal conditions. </p>
<p>I took the image on the left with a commercial optical fingerprint scanner (Futronics FS80) and the right with a normal camera (15MP Cannon DSLR). After cropping, inverting (to match the other scanner's convention), contrasting, etc the camera image, we got the following results. </p>
<p><img src="https://i.stack.imgur.com/v0FFm.jpg" alt="enter image description here"> </p>
<p>The low contrast of the camera image is apparent.</p>
<p><img src="https://i.stack.imgur.com/AZy8A.jpg" alt="enter image description here"></p>
<p>But the software is able to accurately determine the ridge flow.</p>
<p><img src="https://i.stack.imgur.com/qqeyS.jpg" alt="enter image description here"></p>
<p>And we end up finding a decent number of matching minutia (marked with red circles.)</p>
<p>Here's the bad news. Taking these types of up close shots of the tip of a finger is difficult. I used a DSLR with a flash to achieve these results. Additionally most fingerprint matching algorithms are not scale invariant. So if the finger is farther away from the camera on a subsequent "scan", it may not match the original. </p>
<p>The software package I used for the visualizations is the excellent and BSD licensed <a href="https://sourceafis.angeloflogic.com/" rel="noreferrer">SourceAFIS</a>. No corporate "open source version"/ "paid version" shenanigans either although it's currently only ported to C# and Java (limited). </p>
<p><strong>Non Camera Based Solutions:</strong></p>
<p>For the frightening small number of devices that have hardware that support "USB Host Mode" you can <a href="http://developer.android.com/guide/topics/connectivity/usb/host.html" rel="noreferrer">write a custom driver</a> to integrate a fingerprint scanner with Android. I'll be honest, for the two models I've done this for it was a huge pain. I accomplished it by using <a href="http://www.wireshark.org/" rel="noreferrer">wireshark</a> to sniff USB packets between the scanner and a linux box that had a working driver and then writing an Android driver based on the sniffed commands.</p>
<p><strong>Cross Compiling FingerJetFX</strong></p>
<p>Once you have worked out a solution for image acquisition (both potential solutions have their drawbacks) you can start to worry about getting FingerJetFX running on Android. First you'll use their SDK to write a self contained C++ program that takes an image and turns it into a template. After that you really have two options.</p>
<ol>
<li>Compile it to a library and use JNI to interface with it. </li>
<li>Compile it to an executable and let your Android program call it as a subprocess.</li>
</ol>
<p>For either you'll need the <a href="http://developer.android.com/tools/sdk/ndk/index.html" rel="noreferrer">NDK</a>. I've never used JNI so I'll defer to <a href="http://blog.edwards-research.com/2012/04/tutorial-android-jni/" rel="noreferrer">the wisdom</a> of <a href="http://code.google.com/p/awesomeguy/wiki/JNITutorial" rel="noreferrer">others</a> on how best us it. I always tend to choose route #2. For this application I think it's appropriate since you're only really calling the native code to do one thing, template your image. Once you've got your native program running and cross compiled you can <a href="https://stackoverflow.com/questions/4703131/is-it-possible-to-run-a-native-arm-binary-on-a-non-rooted-android-phone/6803287#6803287">use the answer to this question</a> to package it with your android app and call it from your Android code. </p> |
14,299,638 | Existential vs. Universally quantified types in Haskell | <p>What exactly is the difference between these? I think I understand how existential types work, they are like having a base class in OO without a way to down cast. How are universal types different? </p> | 14,299,983 | 2 | 3 | null | 2013-01-13 01:07:04.713 UTC | 31 | 2019-10-03 22:29:26.63 UTC | 2017-07-28 16:41:50.703 UTC | null | 6,936,361 | null | 1,615,960 | null | 1 | 60 | haskell|polymorphism|existential-type | 10,541 | <p>The terms "universal" and "existential" here come from the similarly-named quantifiers in <a href="http://en.wikipedia.org/wiki/Predicate_logic">predicate logic</a>. </p>
<p><a href="http://en.wikipedia.org/wiki/Universal_quantification">Universal quantification</a> is normally written as ∀, which you can read as "for all", and means roughly what it sounds like: in a logical statement resembling "∀x. ..." whatever is in place of the "..." is true for all possible "x" you could choose from whatever set of things is being quantified over.</p>
<p><a href="http://en.wikipedia.org/wiki/Existential_quantification">Existential quantification</a> is normally written as ∃, which you can read as "there exists", and means that in a logical statement resembling "∃x. ..." whatever is in place of the "..." is true for some unspecified "x" taken from the set of things being quantified over.</p>
<p>In Haskell, the things being quantified over are types (ignoring certain language extensions, at least), our logical statements are also types, and instead of being "true" we think about "can be implemented".</p>
<p>So, a universally quantified type like <code>forall a. a -> a</code> means that, for any possible type "a", we can implement a function whose type is <code>a -> a</code>. And indeed we can:</p>
<pre><code>id :: forall a. a -> a
id x = x
</code></pre>
<p>Since <code>a</code> is universally quantified we know nothing about it, and therefore cannot inspect the argument in any way. So <code>id</code> is the only possible function of that type<sup>(1)</sup>.</p>
<p>In Haskell, universal quantification is the "default"--any type variables in a signature are implicitly universally quantified, which is why the type of <code>id</code> is normally written as just <code>a -> a</code>. This is also known as <a href="http://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a>, often just called "polymorphism" in Haskell, and in some other languages (e.g., C#) known as "generics".</p>
<p>An <em>existentially</em> quantified type like <code>exists a. a -> a</code> means that, for <em>some particular</em> type "a", we can implement a function whose type is <code>a -> a</code>. Any function will do, so I'll pick one:</p>
<pre><code>func :: exists a. a -> a
func True = False
func False = True
</code></pre>
<p>...which is of course the "not" function on booleans. But the catch is that we can't <em>use</em> it as such, because all we know about the type "a" is that it exists. Any information about <em>which</em> type it might be has been discarded, which means we can't apply <code>func</code> to any values.</p>
<p>This is not very useful.</p>
<p>So what <em>can</em> we do with <code>func</code>? Well, we know that it's a function with the same type for its input and output, so we could compose it with itself, for example. Essentially, the only things you can do with something that has an existential type are the things you can do based on the non-existential parts of the type. Similarly, given something of type <code>exists a. [a]</code> we can find its length, or concatenate it to itself, or drop some elements, or anything else we can do to any list.</p>
<p>That last bit brings us back around to universal quantifiers, and the reason why Haskell<sup>(2)</sup> doesn't have existential types directly (my <code>exists</code> above is entirely fictitious, alas): since things with existentially quantified types can only be used with operations that have universally quantified types, we can write the type <code>exists a. a</code> as <code>forall r. (forall a. a -> r) -> r</code>--in other words, for all result types <code>r</code>, given a function that for all types <code>a</code> takes an argument of type <code>a</code> and returns a value of type <code>r</code>, we can get a result of type <code>r</code>.</p>
<p>If it's not clear to you why those are nearly equivalent, note that the overall type is not universally quantified for <code>a</code>--rather, it takes an argument that itself is universally quantified for <code>a</code>, which it can then use with whatever specific type it chooses.</p>
<hr>
<p>As an aside, while Haskell doesn't really have a notion of subtyping in the usual sense, we can treat quantifiers as expressing a form of subtyping, with a hierarchy going from universal to concrete to existential. Something of type <code>forall a. a</code> could be converted to any other type, so it could be seen as a subtype of everything; on the other hand, any type could be converted to the type <code>exists a. a</code>, making that a parent type of everything. Of course, the former is impossible (there are no values of type <code>forall a. a</code> except errors) and the latter is useless (you can't do anything with the type <code>exists a. a</code>), but the analogy works on paper at least. :]</p>
<p>Note that the equivalence between an existential type and a universally quantified argument works for the same reason that <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29">variance</a> flips for function inputs.</p>
<hr>
<p>So, the basic idea is roughly that universally quantified types describe things that work the same for any type, while existential types describe things that work with a specific but unknown type.</p>
<hr>
<p><strong>1:</strong> Well, not quite--only if we ignore functions that cause errors, such as <code>notId x = undefined</code>, including functions which never terminate, such as <code>loopForever x = loopForever x</code>.</p>
<p><strong>2:</strong> Well, GHC. Without extensions, Haskell only has the implicit universal quantifiers and no real way of talking about existential types at all.</p> |
14,288,288 | Gitlab repository mirroring | <p>Is it possible to have <a href="http://gitlabhq.com/" rel="nofollow noreferrer">gitlab</a> set up to automatically sync (mirror) a repository hosted at another location?</p>
<p>At the moment, the easiest way I know of doing this involves manually pushing to the two (gitlab and the other) repository, but this is time consuming and error prone.</p>
<p>The greatest problem is that a mirror can resynchronize if two users concurrently push changes to the two different repositories. The best method I can come up with to prevent this issue is to ensure users can only push to one of the repositories.</p> | 14,291,690 | 10 | 1 | null | 2013-01-11 23:24:24.307 UTC | 40 | 2022-01-15 13:01:49.753 UTC | 2021-04-30 15:13:50.363 UTC | null | 3,783,352 | null | 1,595,865 | null | 1 | 66 | git|version-control|mirroring|gitlab | 61,601 | <p>Update Dec 2016: Mirroring is suported with GitLAb EE 8.2+: see "<a href="https://gitlab.com/help/workflow/repository_mirroring.md" rel="noreferrer">Repository mirroring</a>".</p>
<p>As commented by <a href="https://stackoverflow.com/users/4454315/xiaodong-qi">Xiaodong Qi</a>:</p>
<blockquote>
<p>This answer can be simplified without using any command lines (just set it up on Gitlab repo management interface)</p>
</blockquote>
<hr>
<p>Original answer (January 2013)</p>
<p>If your remote mirror repo is a <a href="http://sitaramc.github.com/concepts/bare.html" rel="noreferrer"><em>bare</em> repo</a>, then you can add a post-receive hook to your gitlab-managed repo, and push to your remote repo in it.</p>
<pre><code>#!/bin/bash
git push --mirror [email protected]:/path/to/repo.git
</code></pre>
<p>As Gitolite (used by Gitlab) <a href="http://sitaramc.github.com/gitolite/cust.html#hooks" rel="noreferrer">mentions</a>:</p>
<blockquote>
<p>if you want to install a hook in only a few specific repositories, do it directly on the server.</p>
</blockquote>
<p>which would be in:</p>
<pre><code>~git/repositories/yourRepo.git/hook/post-receive
</code></pre>
<hr>
<p>Caveat (Update Ocotober 2014)</p>
<p><a href="https://stackoverflow.com/users/895245/ciro-santilli">Ciro Santilli</a> points out <a href="https://stackoverflow.com/questions/14288288/gitlab-repository-mirroring/14291690#comment41606464_14291690">in the comments</a>:</p>
<blockquote>
<p><strong>Today (Q4 2014) this will fail</strong> because GitLab automatically symlinks github.com/gitlabhq/gitlab-shell/tree/… into every repository it manages.<br>
So if you make this change, every repository you modify will try to push.<br>
Not to mention possible conflicts when upgrading <code>gitlab-shell</code>, and that the current script is a ruby script, not bash (and you should not remove it!). </p>
<p>You could correct this by reading the current directory name and ensuring bijection between that and the remote, but I recommend people to stay far far away from those things</p>
</blockquote>
<p>See (and vote for) <a href="http://feedback.gitlab.com/forums/176466-general/suggestions/4614663-automatic-push-to-remote-mirror-repo-after-push-to" rel="noreferrer">feeadback "<strong>Automatic push to remote mirror repo after push to GitLab Repo</strong>"</a>.</p>
<hr>
<p>Update July 2016: I see this kind of feature added for GitLab EE (Enterprise Edition): <a href="https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/249/builds" rel="noreferrer">MR 249</a></p>
<ul>
<li>Add ability to enter remote push URL under Mirror Repository settings</li>
<li>Add implementation code to push to remote repository</li>
<li>Add new background worker</li>
<li>Show latest update date and sync errors if they exists.</li>
<li>Sync remote mirror every hour.</li>
</ul>
<p>Note that the recent <code>Remote Mirror Repository</code> (<a href="https://gitlab.com/gitlab-org/gitlab-ce/issues/17940" rel="noreferrer">issues 17940</a>) can be tricky:</p>
<blockquote>
<p>I'm currently trying to shift main development of the Open Source npm modules of my company Lossless GmbH (<a href="https://www.npmjs.com/~lossless" rel="noreferrer">https://www.npmjs.com/~lossless</a>) from GitHub.com to GitLab.com</p>
<p>I'm importing all the repos from GitHub, however when I try to switch off <code>Mirror Repository</code> and switch on <code>Remote Mirror Repository</code> with the original GitHub URL I get an error saying: </p>
</blockquote>
<pre><code>Remote mirrors url is already in use
</code></pre>
<p>Here is one of the repos this fails with: <a href="https://gitlab.com/pushrocks/npmts" rel="noreferrer">https://gitlab.com/pushrocks/npmts</a>
Edited 2 months ago</p>
<blockquote>
<p>turns out, it just requires multiple steps:</p>
<ul>
<li>disable the Mirror Repository</li>
<li>press save</li>
<li>remove the URl</li>
<li>press save</li>
<li>then add the Remote Mirror</li>
</ul>
</blockquote> |
14,284,494 | MySQL Error 1264: out of range value for column | <p>As I <code>SET</code> cust_fax in a table in MySQL like this:</p>
<pre><code>cust_fax integer(10) NOT NULL,
</code></pre>
<p>and then I insert value like this:</p>
<pre><code>INSERT INTO database values ('3172978990');
</code></pre>
<p>but then it say </p>
<blockquote>
<p>`error 1264` out of value for column</p>
</blockquote>
<p>And I want to know where the error is? My set? Or other?</p>
<p>Any answer will be appreciated!</p> | 14,284,564 | 6 | 3 | null | 2013-01-11 18:33:09.523 UTC | 15 | 2022-04-10 05:34:59.387 UTC | 2017-03-31 11:21:35.497 UTC | null | 476,951 | null | 1,906,411 | null | 1 | 106 | mysql|sql|insert|integer | 458,125 | <p>The value 3172978990 is greater than 2147483647 – the maximum value for <code>INT</code> – hence the error. MySQL integer types and their ranges are <a href="https://dev.mysql.com/doc/refman/8.0/en/integer-types.html" rel="noreferrer">listed here</a>.</p>
<p>Also note that the <code>(10)</code> in <code>INT(10)</code> does not define the "size" of an integer. It specifies the <a href="https://dev.mysql.com/doc/refman/8.0/en/numeric-type-attributes.html" rel="noreferrer">display width</a> of the column. This information is advisory only.</p>
<p>To fix the error, change your datatype to <code>VARCHAR</code>. Phone and Fax numbers should be stored as strings. See <a href="https://stackoverflow.com/q/75105/87015">this discussion</a>.</p> |
14,162,648 | SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry | <p>I have a strange scenario in which the auto identity int column in my SQL Server 2012 database is not incrementing properly.</p>
<p>Say I have a table which uses an int auto identity as a primary key it is sporadically skipping increments, for example:</p>
<p>1,
2,
3,
4,
5,
1004,
1005</p>
<p>This is happening on a random number of tables at very random times, can not replicate it to find any trends.</p>
<p>How is this happening?
Is there a way to make it stop?</p> | 14,162,761 | 3 | 5 | null | 2013-01-04 18:19:23.743 UTC | 33 | 2018-02-27 23:48:17.067 UTC | null | null | null | null | 1,384,204 | null | 1 | 129 | sql|sql-server|sql-server-2012|identity | 112,815 | <p>This is all perfectly normal. Microsoft added <code>sequences</code> in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look <a href="http://www.codeproject.com/Tips/668042/SQL-Server-2012-Auto-Identity-Column-Value-Jump-Is" rel="noreferrer">here</a> for some explanation.</p>
<p>If you want to have the old behaviour, you can:</p>
<ol>
<li>use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.</li>
<li>use a sequence generator with the NO CACHE setting (<a href="http://msdn.microsoft.com/en-us/library/ff878091.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ff878091.aspx</a>)</li>
</ol> |
13,916,620 | REST API Login Pattern | <p>I am creating a REST api, closely following apigee suggestions, using nouns not verbs, api version baked into the url, two api paths per collection, GET POST PUT DELETE usage, etc.</p>
<p>I am working on the login system, but unsure of the proper REST way to login users. I am not working on security at this point, just the login pattern or flow. (Later we will be adding 2 step oAuth, with an HMAC, etc)</p>
<p>Possible Options</p>
<ul>
<li>A POST to something like <code>https://api...com/v1/login.json</code> </li>
<li>A PUT to something like <code>https://api...com/v1/users.json</code></li>
<li>Something I have not though of...</li>
</ul>
<p>What is the proper REST style for logging in users?</p> | 14,031,061 | 3 | 10 | null | 2012-12-17 15:05:14.797 UTC | 119 | 2021-03-24 04:48:01.03 UTC | 2021-03-24 04:48:01.03 UTC | null | 9,213,345 | null | 1,649,865 | null | 1 | 199 | design-patterns|rest | 179,351 | <p><a href="http://www.ics.uci.edu/~fielding/pubs/webarch_icse2000.pdf" rel="noreferrer">Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor</a>, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:</p>
<blockquote>
<p>All REST interactions are <em><strong>stateless</strong></em>. That is, each <em><strong>request contains
all of the information necessary for a connector to understand the
request, independent of any requests that may have preceded it</strong></em>. </p>
</blockquote>
<p>This restriction accomplishes four functions, 1st and 3rd are important in this particular case:</p>
<ul>
<li><em>1st</em>: it <strong>removes any need for the connectors to retain application state
between requests</strong>, thus reducing consumption of physical resources
and improving scalability;</li>
<li><em>3rd</em>: it allows an intermediary to view and <strong>understand a request in isolation</strong>,
which may be necessary when services are dynamically rearranged;</li>
</ul>
<p>And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.</p>
<p>One of examples how to archeive this is <a href="http://en.wikipedia.org/wiki/Hash-based_message_authentication_code" rel="noreferrer"><strong>hash-based message authentication code</strong> or <strong>HMAC</strong></a>. In practice this means adding a hash code of current message to every request. Hash code calculated by <em>cryptographic hash function</em> in combination with a <em>secret cryptographic key</em>. <em>Cryptographic hash function</em> is either predefined or part of <em>code-on-demand</em> REST conception (for example JavaScript). <em>Secret cryptographic key</em> should be provided by server to client as resource, and client uses it to calculate hash code for every request.</p>
<p>There are a lot of examples of <strong>HMAC</strong> implementations, but I'd like you to pay attention to the following three:</p>
<ul>
<li><a href="http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html" rel="noreferrer">Authenticating REST Requests for Amazon Simple Storage Service (Amazon S3)</a></li>
<li><a href="https://stackoverflow.com/a/8366526/443366">Answer by Mauriceless on quiestion: "How to implement HMAC Authentication in a RESTful WCF API"</a></li>
<li><a href="http://code.google.com/p/crypto-js/#Progressive_HMAC_Hashing" rel="noreferrer">crypto-js: JavaScript implementations of standard and secure cryptographic algorithms</a></li>
</ul>
<h2>How it works in practice</h2>
<p>If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is <em>no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is</em>, and it possible to adjust this schema with time.</p>
<p>Hope this will helps you to find the proper solution!</p> |
47,460,085 | Error Message "Xcode alone is not sufficient on Sierra" | <p>I'd like to install openCV to vectorize image, but there's a series error message regarding Xcode and Ruby.</p>
<p>First, I use terminal to install openCV, <code>brew install opencv</code>. </p>
<p>Then, I got error message indicating that the system doesn't like my ruby version.</p>
<pre><code>/usr/local/Homebrew/Library/Homebrew/brew.rb:12:in `<main>':
Homebrew must be run under Ruby 2.3! You're running 2.0.0. (RuntimeError)
</code></pre>
<p>So, I want to upgrade my ruby. I followed several update strategy from <a href="https://stackoverflow.com/questions/38194032/how-to-update-ruby-version-2-0-0-to-the-latest-version-in-mac-osx-yosemite">this</a> post. First ruby upgrade trial: <code>brew link --overwrite ruby</code> & <code>brew unlink ruby && brew link ruby</code> and get</p>
<pre><code>Error: No such keg: /usr/local/Cellar/ruby
</code></pre>
<p>Then second ruby upgrade trial: <code>brew upgrade ruby</code> and see the following error message. </p>
<pre><code>Error: Xcode alone is not sufficient on Sierra.
Install the Command Line Tools:
xcode-select --install
</code></pre>
<p>This error message means I need to install Xcode which I already install. So, I check my Xcode status with <code>code-select -p</code> and get <code>/Applications/Xcode.app/Contents/Developer</code> which means I am fine. </p>
<p>I saw a <a href="https://www.pyimagesearch.com/2016/12/19/install-opencv-3-on-macos-with-homebrew-the-easy-way/" rel="noreferrer">comment</a> regarding where you install python could be a big issue. Quote from the source:</p>
<blockquote>
<p>If you see <code>/usr/local/bin/python3</code> then you are correctly using the Homebrew version of Python. If the output is instead <code>/usr/bin/python3</code> then you are incorrectly using the system version of Python.</p>
</blockquote>
<p>I check <code>which python3</code> and get</p>
<pre><code>/Users/******/anaconda3/bin/python3
</code></pre>
<p>Could this be the problem? How can I change system version to local?</p> | 47,475,201 | 5 | 5 | null | 2017-11-23 16:41:36.65 UTC | 7 | 2020-01-18 00:03:40.69 UTC | 2017-11-24 14:22:33.433 UTC | null | 6,765,415 | null | 6,765,415 | null | 1 | 47 | ruby|xcode|python-3.x|homebrew|command-line-tool | 33,665 | <p>Let me explain this myself so people won't make the same mistakes.</p>
<p>When I saw the last line of the error message </p>
<pre><code>Error: Xcode alone is not sufficient on Sierra.
Install the Command Line Tools:
xcode-select --install
</code></pre>
<p>My thought was: I already have Xcode why the system ask me to "reinstall" it. However, thanks for @SamiKuhmonen @ Beartech @patrick kuang suggestion, I search a <a href="https://courses.growthschool.com/courses/path-to-rails-developer/lectures/744354" rel="noreferrer">page</a> (in Mandarin). <code>xcode-select --install</code> does not reinstall the whole Xcode. It means install some missing command line tools which is required by installing Ruby.</p> |
9,132,930 | JavaScript date.format is not a function | <p>I am using this piece of code to get string representing date <code>yyyy-mm-dd</code> from a hidden field and then format it as needed:</p>
<pre><code>var date_string = $('#end-date').val();
var splitDate = date_string.split("-");
var end_date = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
end_date.format("dddd, mmmm dS, yyyy")
</code></pre>
<p>But it throws an error:</p>
<pre><code>end_date.format is not a function
</code></pre>
<p>Why does it happen and how to solve this issue?</p> | 9,132,972 | 2 | 1 | null | 2012-02-03 17:36:13.427 UTC | 2 | 2014-05-24 18:12:26.777 UTC | null | null | null | null | 135,829 | null | 1 | 16 | javascript|html | 73,617 | <p>That is because <code>.format</code> is not a native JavaScript function on <code>Date.prototype</code>.</p>
<p>You need to add a lib like this one: <a href="http://jacwright.com/projects/javascript/date_format/">http://jacwright.com/projects/javascript/date_format/</a></p>
<p>I personally use <a href="http://momentjs.com/">http://momentjs.com/</a> to manage dates in JavaScript</p> |
34,100,048 | Create empty branch on GitHub | <p>I want to create a new GitHub branch, called <code>release</code>.</p>
<p>This branch <strong>needs to be empty</strong>! However, there is an existing branch with x commits and I don't want to have its commit history.</p>
<p>The only method I found is to create a <em>local</em> <code>--orphan</code> branch.</p> | 34,100,189 | 5 | 5 | null | 2015-12-05 01:07:50.997 UTC | 86 | 2021-11-12 07:12:15.183 UTC | 2020-07-14 14:56:16.82 UTC | null | 3,266,847 | null | 5,498,155 | null | 1 | 246 | git|github | 171,821 | <p><strong>November 2021 Update:</strong> As of git version 2.27, you can now use <code>git switch --orphan <new branch></code> to create an empty branch with no history.</p>
<p>Unlike <code>git checkout --orphan <new branch></code>, this branch won't have any files from your current branch (save for those which git doesn't track).</p>
<p>This should be the preferred way to create empty branches with no prior history.</p>
<p>Once you actually have commits on this branch, it can be pushed to github via <code>git push -u origin <branch name></code>:</p>
<pre class="lang-sh prettyprint-override"><code>git switch --orphan <new branch>
git commit --allow-empty -m "Initial commit on orphan branch"
git push -u origin <new branch>
</code></pre>
<p><strong>Original answer:</strong></p>
<p>What's wrong with the <code>--orphan</code> option? If you want a branch that is empty and have no history, this is the way to go...</p>
<pre><code>git checkout --orphan empty-branch
</code></pre>
<p>Then you can remove all the files you'll have in the staging area (so that they don't get committed):</p>
<pre><code>git rm -rf .
</code></pre>
<p>At this point you have an empty branch, on your machine.</p>
<p>Before you can push to GitHub (or any other Git repository), you will need at least one commit, even if it does not have any content on it (i.e. empty commit), as you cannot push an empty branch</p>
<pre><code>git commit --allow-empty -m "root commit"
</code></pre>
<p>Finally, push it to the remote, and crack open a beer</p>
<pre><code>git push origin empty-branch
</code></pre> |
841,696 | Please explain in the simplest, most jargon-free English possible, the "universal property of fold"? | <p>I am working through "Real World Haskell", which led to to a free PDF called <a href="http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.cs.nott.ac.uk%2F~gmh%2Ffold.pdf&ei=G5gESt-OPNKLtgfMrIGbBw&rct=j&q=%22A+tutorial+on+the+universality+and+expressiveness+of+fold%22&usg=AFQjCNG81_xijGu4ipQdCGBIxkR8z1Lj6w" rel="noreferrer">"A tutorial on the universality and expressiveness of fold"</a>. It makes the point that a "fold" is "universal". I am wrestling with his definition of "universal", and would like to hear the from those who have already invested time digesting it: <strong>Please explain in the simplest, most jargon-free English possible, the "universal property of fold"?</strong> What is this "universal property", and why is it important?</p>
<p>Thanks.</p> | 842,484 | 5 | 3 | null | 2009-05-08 20:41:56.41 UTC | 9 | 2013-12-15 14:35:28.03 UTC | 2013-12-15 14:35:28.03 UTC | null | 1,243,762 | null | 80,112 | null | 1 | 15 | functional-programming|fold|haskell | 1,935 | <p>(Jargon mode off :-)</p>
<p>The universal property is just a way of proving that two expressions are equal. (That's what is meant by the jargon "proof principle".)
The universal property says that if you are able to prove these two equations</p>
<pre><code>g [] = v
g (x:xs) = f x (g xs)
</code></pre>
<p>then you may conclude the additional equation</p>
<pre><code>g = fold f v
</code></pre>
<p>The converse is also true, but that's trivial to show just by expanding the definition of <code>fold</code>. The universal property is a much deeper property (which is a jargony way of saying it's less obvious why it is true.)</p>
<p>The reason it's interesting to do this at all is that it lets you avoid proof by induction, which is almost always worth avoiding.</p> |
367,178 | Usage of IoC Containers; specifically Windsor | <p>I think the answer to this question is so obivous that noone has bothered writing about this, but its late and I really can't get my head around this.</p>
<p>I've been reading into IoC containers (Windsor in this case) and I'm missing how you talk to the container from the various parts of your code.</p>
<p>I get DI, I've been doing poor mans DI (empty constructors calling overloaded injection constructors with default parameter implementations) for some time and I can completely see the benefit of the container. However, Im missing one vital piece of info; how are you supposed to reference the container every time you need a service from it?</p>
<p>Do I create a single global insance which I pass around? Surely not!</p>
<p>I know I should call this:</p>
<pre><code>WindsorContainer container = new WindsorContainer(new XmlInterpreter());
</code></pre>
<p>(for example) when I want to load my XML config, but then what do I do with container? Does creating a new container every time thereafter persist the loaded config through some internal static majicks or otherwise, or do I have to reload the config every time (i guess not, or lifecycles couldnt work).</p>
<p>Failing to understand this is preventing me from working out how the lifecycles work, and getting on with using some IoC awsomeness</p>
<p>Thanks,</p>
<p>Andrew</p> | 367,388 | 5 | 0 | null | 2008-12-14 23:52:08.72 UTC | 11 | 2012-08-21 21:32:02.413 UTC | null | null | null | Andrew Bullock | 28,543 | null | 1 | 28 | c#|inversion-of-control|castle-windsor | 8,440 | <p>99% of the cases it's one container instance per app. Normally you initialize it in Application_Start (for a web app), <a href="https://github.com/castleproject/Castle.MonoRail-READONLY/blob/45ac205867396b1b7ad287a872e5b20afd0af837/src/TempWeb/Global.asax.cs" rel="nofollow noreferrer">like this</a>.</p>
<p>After that, it's really up to the consumer of the container. For example, some frameworks, like <a href="http://www.castleproject.org/MonoRail/" rel="nofollow noreferrer">Monorail</a> and <a href="http://www.codeplex.com/aspnet" rel="nofollow noreferrer">ASP.NET MVC</a> allow you to intercept the creation of the instances (the controllers in this case), so you just register the controllers and their dependencies in the container and that's it, whenever you get a request the container takes care of injecting each controller with its dependencies. See for example <a href="http://mvccontrib.codeplex.com/SourceControl/changeset/view/6aa25407de83#src%2fSamples%2fMvcContrib.Samples.WindsorControllerFactory%2fControllers%2fHomeController.cs" rel="nofollow noreferrer">this ASP.NET MVC controller</a>.
In these frameworks, you hardly ever need to call or even reference the container in your classes, which is the recommended usage.</p>
<p>Other frameworks don't let you get in the creation process easily (like Webforms) so you have to resort to hacks like <a href="http://ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx" rel="nofollow noreferrer">this one</a>, or <em>pull</em> the required dependencies (that is, explicitly calling the container). To pull dependencies, use a static gateway to the container like <a href="https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/commons/Rhino.Commons/RhinoContainer/IoC.cs" rel="nofollow noreferrer">this one</a> or the one described by <a href="https://stackoverflow.com/questions/367178/usage-of-ioc-containers-specifically-windsor#367190">maxnk</a>. Note that by doing this, you're actually using the container as a Service Locator, which doesn't decouple things as well as inversion of control. (see difference <a href="http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection" rel="nofollow noreferrer">here</a> and <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" rel="nofollow noreferrer">here</a>)</p>
<p>Hope this clears your doubts.</p> |
742,451 | What is a good regular expression for catching typos in an email address? | <p>When users create an account on my site I want to make server validation for emails to not accept <em>every</em> input.</p>
<p>I will send a confirmation, in a way to do a <a href="https://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard/156441#156441">handshake validation</a>.</p>
<p>I am looking for <strong>something simple, not <em>the best</em></strong>, but not too simple that doesn't validate anything. I don't know where limitation must be, since any regular expression will not do the correct validation because is not possible to do it with regular expressions.</p>
<p>I'm trying to limit the sintax and visual complexity inherent to regular expressions, because in this case any will be correct.</p>
<p>What regexp can I use to do that?</p> | 742,455 | 5 | 4 | null | 2009-04-12 21:19:57.603 UTC | 23 | 2022-02-18 06:48:24.453 UTC | 2022-02-18 06:48:24.453 UTC | null | 96,944 | null | 32,173 | null | 1 | 92 | c#|regex|email-validation | 69,679 | <pre><code>^\S+@\S+$
</code></pre> |
579,262 | What is the purpose of the EBP frame pointer register? | <p>I'm a beginner in assembly language and have noticed that the x86 code emitted by compilers usually keeps the frame pointer around even in release/optimized mode when it could use the <code>EBP</code> register for something else.</p>
<p>I understand why the frame pointer might make code easier to debug, and might be necessary if <code>alloca()</code> is called within a function. However, x86 has very few registers and using two of them to hold the location of the stack frame when one would suffice just doesn't make sense to me. Why is omitting the frame pointer considered a bad idea even in optimized/release builds?</p> | 579,311 | 5 | 10 | null | 2009-02-23 20:45:38.04 UTC | 53 | 2018-06-11 18:45:00.487 UTC | 2018-06-11 18:45:00.487 UTC | dsimcha | 224,132 | dsimcha | 23,903 | null | 1 | 103 | performance|assembly|x86 | 58,369 | <p>Frame pointer is a reference pointer allowing a debugger to know where local variable or an argument is at with a single constant offset. Although ESP's value changes over the course of execution, EBP remains the same making it possible to reach the same variable at the same offset (such as first parameter will always be at EBP+8 while ESP offsets can change significantly since you'll be pushing/popping things)</p>
<p>Why don't compilers throw away frame pointer? Because with frame pointer, the debugger can figure out where local variables and arguments are using the symbol table since they are guaranteed to be at a constant offset to EBP. Otherwise there isn't an easy way to figure where a local variable is at any point in code.</p>
<p>As Greg mentioned, it also helps stack unwinding for a debugger since EBP provides a reverse linked list of stack frames therefore letting the debugger to figure out size of stack frame (local variables + arguments) of the function.</p>
<p>Most compilers provide an option to omit frame pointers although it makes debugging really hard. That option should never be used globally, even in release code. You don't know when you'll need to debug a user's crash.</p> |
125,813 | How to determine the OS path separator in JavaScript? | <p>How can I tell in JavaScript what path separator is used in the OS where the script is running?</p> | 125,825 | 5 | 4 | null | 2008-09-24 07:23:24.95 UTC | 8 | 2021-12-10 09:53:45.953 UTC | 2020-10-21 08:17:43.62 UTC | null | 1,402,846 | Pawel Pojawa | null | null | 1 | 111 | javascript|file|directory | 73,439 | <p>Afair you can always use / as a path separator, even on Windows.</p>
<p>Quote from <a href="http://bytes.com/forum/thread23123.html" rel="noreferrer">http://bytes.com/forum/thread23123.html</a>:</p>
<blockquote>
<p>So, the situation can be summed up
rather simply:</p>
<ul>
<li><p>All DOS services since DOS 2.0 and all Windows APIs accept either forward
slash or backslash. Always have.</p></li>
<li><p>None of the standard command shells (CMD or COMMAND) will accept forward
slashes. Even the "cd ./tmp" example
given in a previous post fails.</p></li>
</ul>
</blockquote> |
748,014 | Do I need to manually close an ifstream? | <p>Do I need to manually call <code>close()</code> when I use a <code>std::ifstream</code>?</p>
<p>For example, in the code:</p>
<pre><code>std::string readContentsOfFile(std::string fileName) {
std::ifstream file(fileName.c_str());
if (file.good()) {
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
return buffer.str();
}
throw std::runtime_exception("file not found");
}
</code></pre>
<p>Do I need to call <code>file.close()</code> manually? Shouldn't <code>ifstream</code> make use of <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> for closing files?</p> | 748,059 | 5 | 0 | null | 2009-04-14 14:59:26.16 UTC | 51 | 2018-10-15 08:49:06.25 UTC | 2014-11-04 21:19:57.04 UTC | null | 1,950,231 | null | 61,915 | null | 1 | 243 | c++|ifstream|raii | 90,161 | <p>NO</p>
<p>This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes.</p>
<p>If you want to close the file before the end of a function you can always use a nested scope.</p>
<p>In the standard (27.8.1.5 Class template basic_ifstream), <code>ifstream</code> is to be implemented with a <code>basic_filebuf</code> member holding the actual file handle. It is held as a member so that when an ifstream object destructs, it also calls the destructor on <code>basic_filebuf</code>. And from the standard (27.8.1.2), that destructor closes the file:</p>
<blockquote>
<p><code>virtual ˜basic_filebuf();</code></p>
<p><strong>Effects:</strong> Destroys an object of class <code>basic_filebuf<charT,traits></code>. Calls <code>close()</code>.</p>
</blockquote> |
1,134,075 | Finding node order in XML document in SQL Server | <p>How can I find the order of nodes in an XML document?</p>
<p>What I have is a document like this:</p>
<pre><code><value code="1">
<value code="11">
<value code="111"/>
</value>
<value code="12">
<value code="121">
<value code="1211"/>
<value code="1212"/>
</value>
</value>
</value>
</code></pre>
<p>and I'm trying to get this thing into a table defined like</p>
<pre><code>CREATE TABLE values(
code int,
parent_code int,
ord int
)
</code></pre>
<p>Preserving the order of the values from the XML document (they can't be ordered by their code). I want to be able to say</p>
<pre><code>SELECT code
FROM values
WHERE parent_code = 121
ORDER BY ord
</code></pre>
<p>and the results should, deterministically, be </p>
<pre><code>code
1211
1212
</code></pre>
<p>I have tried</p>
<pre><code>SELECT
value.value('@code', 'varchar(20)') code,
value.value('../@code', 'varchar(20)') parent,
value.value('position()', 'int')
FROM @xml.nodes('/root//value') n(value)
ORDER BY code desc
</code></pre>
<p>But it doesn't accept the <code>position()</code> function ('<code>position()</code>' can only be used within a predicate or XPath selector).</p>
<p>I guess it's possible some way, but how?</p> | 9,863,151 | 6 | 3 | null | 2009-07-15 21:03:58.237 UTC | 12 | 2020-04-22 08:53:57.207 UTC | 2017-09-04 14:26:50.013 UTC | null | 4,519,059 | null | 47,161 | null | 1 | 19 | sql|sql-server|xml|xquery | 17,730 | <p>You can emulate the <code>position()</code> function by counting the number of sibling nodes preceding each node:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
code = value.value('@code', 'int'),
parent_code = value.value('../@code', 'int'),
ord = value.value('for $i in . return count(../*[. << $i]) + 1', 'int')
FROM @Xml.nodes('//value') AS T(value)
</code></pre>
<p>Here is the result set:</p>
<pre class="lang-sql prettyprint-override"><code>code parent_code ord
---- ----------- ---
1 NULL 1
11 1 1
111 11 1
12 1 2
121 12 1
1211 121 1
1212 121 2
</code></pre>
<p><strong>How it works:</strong></p>
<ul>
<li>The <a href="http://msdn.microsoft.com/en-us/library/ms190945.aspx" rel="noreferrer"><code>for $i in .</code></a> clause defines a variable named <code>$i</code> that contains the current node (<code>.</code>). This is basically a hack to work around XQuery's lack of an XSLT-like <code>current()</code> function.</li>
<li>The <code>../*</code> expression selects all siblings (children of the parent) of the current node.</li>
<li>The <code>[. << $i]</code> predicate filters the list of siblings to those that precede (<a href="http://msdn.microsoft.com/en-us/library/ms190935.aspx" rel="noreferrer"><code><<</code></a>) the current node (<code>$i</code>).</li>
<li>We <code>count()</code> the number of preceding siblings and then add 1 to get the position. That way the first node (which has no preceding siblings) is assigned a position of 1.</li>
</ul> |
42,536,506 | Could not load file or assembly 'Microsoft.CodeAnalysis, version= 1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependenc | <p>An update occurred last night and now I find myself unable to do a ctrl + '.' for code suggestions in VS 2015. An error message comes up saying the following:</p>
<blockquote>
<p>Could not load file or assembly 'Microsoft.CodeAnalysis, version= 1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.</p>
</blockquote>
<p>I can still build and develop but this will be really annoying without this feature. I admit it, I am getting soft!</p>
<p>Anyone have a suggestion for fixing this bug?</p> | 42,596,568 | 19 | 3 | null | 2017-03-01 16:04:26.26 UTC | 9 | 2022-04-14 09:53:40.743 UTC | 2017-05-22 18:56:00.453 UTC | null | 1,959,948 | null | 3,019,291 | null | 1 | 90 | c#|visual-studio-2015 | 96,094 | <p>I had the same problem with Visual Studio 2015 Update 2, to solve the problem globally for all solutions, update to <strong>Visual Studio 2015 Update 3</strong>. Here is a link: <a href="https://www.visualstudio.com/en-us/news/releasenotes/vs2015-update3-vs" rel="noreferrer">Download from here</a> </p> |
21,250,849 | npm install doesn't create node_modules directory | <p>I am trying to do a homework for a mongodb uni course. They gave us some files, instructions are:</p>
<p>run <code>npm install mongodb</code> then <code>node app.js</code></p>
<p>for some reason npm install does not create a node_modules directory but I don't see any build errors:</p>
<pre><code>mongo-uni/hw1-2$ npm install mongodb
npm WARN package.json [email protected] path is also the name of a node core module.
npm http GET https://registry.npmjs.org/mongodb
npm http 304 https://registry.npmjs.org/mongodb
npm http GET https://registry.npmjs.org/bson/0.2.5
npm http GET https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/bson/0.2.5
&gt; [email protected] install /home/jasonshark/node_modules/mongodb/node_modules/kerberos
&gt; (node-gyp rebuild 2&gt; builderror.log) || (exit 0)
make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'
SOLINK_MODULE(target) Release/obj.target/kerberos.node
SOLINK_MODULE(target) Release/obj.target/kerberos.node: Finished
COPY Release/kerberos.node
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/kerberos/build'
&gt; [email protected] install /home/jasonshark/node_modules/mongodb/node_modules/bson
&gt; (node-gyp rebuild 2&gt; builderror.log) || (exit 0)
make: Entering directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
CXX(target) Release/obj.target/bson/ext/bson.o
make: Leaving directory `/home/jasonshark/node_modules/mongodb/node_modules/bson/build'
[email protected] ../../../node_modules/mongodb
├── [email protected]
└── [email protected]
mongo-uni/hw1-2$ node app.js
Failed to load c++ bson extension, using pure JS version
'No document found'
</code></pre> | 30,518,020 | 12 | 4 | null | 2014-01-21 06:33:11.543 UTC | 9 | 2022-06-30 07:58:29.953 UTC | 2014-01-21 06:38:42.5 UTC | null | 1,388,319 | null | 2,031,033 | null | 1 | 77 | node.js|npm|node-modules | 190,637 | <p><code>npm init</code></p>
<p>It is all you need. It will create the package.json file on the fly for you.</p> |
17,917,160 | iOS developer program certificate transfer | <p>I have some problems with my developer certificate and profile. I have certificate of developer program on my office Mac. I want to develop and test the app on my device at home, so I have added my device and generated provision profile from office Mac. Download and install *.cer and provision on my home Mac, but I saw the error:</p>
<pre><code>The identity 'iPhone Developer' doesn't match any valid, non-expired certificate/private key pair in your keychains
</code></pre>
<p>How to transfer keys from office Mac to my home Mac?</p> | 17,917,209 | 3 | 0 | null | 2013-07-29 06:17:04.743 UTC | 10 | 2018-07-01 21:47:05.3 UTC | 2018-07-01 21:47:05.3 UTC | null | 1,506,363 | null | 1,727,703 | null | 1 | 30 | ios|objective-c|swift|xcode|provisioning-profile | 23,118 | <ul>
<li>Open your keychain program at workplace.</li>
<li>Select My certificates section. Select entries listed as iOS Developer certificate, iOS Distribution Certificate etc. For the sake of simplicity select everything that you find related to your membership.</li>
<li>Select Export.</li>
<li>It will ask you enter choice of password. Enter it.</li>
<li>It will export p12 file. Transfer this file to your home mac.</li>
<li>At home mac, import this p12 file into your Keychain Program.</li>
<li>Start XCode and try to build again using the provisioning profile.</li>
<li>If the above does not work, try the entire thing with Keys section of your Keychain program.</li>
</ul> |
1,947,121 | A good NASM/FASM tutorial? | <p>Does anyone know any good <a href="http://www.nasm.us/" rel="noreferrer">NASM</a> or FASM tutorials? I am trying to learn assembler but I can't seem to find any good resources on it.</p> | 1,947,135 | 5 | 2 | null | 2009-12-22 15:33:03.67 UTC | 30 | 2013-10-27 21:37:28.987 UTC | 2013-08-09 13:42:12.71 UTC | user1228 | null | null | 139,766 | null | 1 | 38 | assembly|nasm|fasm | 43,925 | <p>There is e.g. <a href="http://leto.net/writing/nasm.php" rel="noreferrer">Writing A Useful Program With NASM </a> and of course the obvious <a href="http://www.nasm.us/doc/nasmdoc3.html" rel="noreferrer">http://www.nasm.us/doc/nasmdoc3.html</a>.</p>
<p>There are a couple of sample programs at <a href="http://www.csee.umbc.edu/help/nasm/sample.shtml" rel="noreferrer">http://www.csee.umbc.edu/help/nasm/sample.shtml</a></p>
<p>If you are looking for a more general introduction to assembly programming there is <a href="http://homepage.mac.com/randyhyde/webster.cs.ucr.edu/index.html" rel="noreferrer">The Art of Assembly Programming</a> and the wikipedia page on NASM references <a href="https://rads.stackoverflow.com/amzn/click/com/0471375233" rel="noreferrer" rel="nofollow noreferrer">Assembly Language Step by Step</a> by Jeff Duntemann.</p> |
1,962,332 | How to draw vectors (physical 2D/3D vectors) in MATLAB? | <p>I want to know the simplest way to plot vectors in <a href="http://en.wikipedia.org/wiki/MATLAB" rel="noreferrer">MATLAB</a>.
For example:</p>
<pre><code>a = [2 3 5];
b = [1 1 0];
c = a + b;
</code></pre>
<p>I want to visualize this vector addition as head-to-tail/parallelogram method. How do I plot these vectors with an arrow-head?</p> | 1,962,413 | 6 | 0 | null | 2009-12-26 00:43:02.49 UTC | 8 | 2016-02-29 06:18:07.333 UTC | 2009-12-27 16:18:54.86 UTC | null | 63,550 | null | 107,349 | null | 1 | 20 | matlab|vector|plot | 151,818 | <pre><code>a = [2 3 5];
b = [1 1 0];
c = a+b;
starts = zeros(3,3);
ends = [a;b;c];
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal
</code></pre> |
2,008,149 | Is there something like LINQ for Java? | <p>Started to learn LINQ with C#.<br/>
Especially LINQ to Objects and LINQ to XML.<br/>
I really enjoy the power of LINQ.<br/></p>
<p>I learned that there is something called <a href="http://hugoware.net/Projects/jLinq" rel="nofollow noreferrer">JLINQ</a> a JavaScript implementation.<br/>
Also (as Catbert posted) Scala will have <a href="http://permalink.gmane.org/gmane.comp.lang.scala.announce/154" rel="nofollow noreferrer">LINQ</a></p>
<p>Do you know if LINQ or something similar will be a part of Java 7?<br/>
<br/>
Update: Interesting post from 2008 - <a href="https://stackoverflow.com/questions/346721/linq-for-java">LINQ for Java tool</a></p> | 2,008,262 | 8 | 5 | null | 2010-01-05 18:22:10.637 UTC | 11 | 2020-05-14 07:25:08.56 UTC | 2020-05-14 07:25:08.56 UTC | null | 1,409,881 | null | 49,544 | null | 1 | 26 | java|linq|scala|closures|java-7 | 14,286 | <p>Look at <a href="http://www.scala-lang.org/" rel="noreferrer">Scala</a>, which is powerful functional programming language, but is similar to Java and runs on Java platform.</p>
<p>In Scala it is possible to use essentially the same code constructs as in LINQ, albeit without special query comprehensions syntax present in C# or VB.</p>
<p><strong>EDIT :</strong></p>
<p>Here's an example of Scala's querying capabilities :</p>
<pre><code>// Get all StackOverflow users with more than 20,000 reputation points.
val topUsers = for{
u <- users
if u.reputation > 20000
} yield u;
println ("Users with more than 20,000 reputation:")
for (u <- topUsers) {
println u.name
}
</code></pre> |
1,868,333 | How can I determine the type of a generic field in Java? | <p>I have been trying to determine the type of a field in a class. I've seen all the introspection methods but haven't quite figured out how to do it. This is going to be used to generate xml/json from a java class. I've looked at a number of the questions here but haven't found exactly what I need.</p>
<p>Example:</p>
<pre><code>class Person {
public final String name;
public final List<Person> children;
}
</code></pre>
<p>When I marshall this object, I need to know that the <code>chidren</code> field is a list of objects of type <code>Person</code>, so I can marshall it properly.</p>
<p>I had tried</p>
<pre><code>for (Field field : Person.class.getDeclaredFields()) {
System.out.format("Type: %s%n", field.getType());
}
</code></pre>
<p>But this will only tell me that it's a <code>List</code>, not a <code>List</code> of <code>Person</code>s</p>
<p>Thanks</p> | 1,868,375 | 8 | 1 | null | 2009-12-08 17:00:07.543 UTC | 22 | 2021-04-20 14:25:04.687 UTC | 2016-09-01 21:25:07.893 UTC | null | 227,299 | null | 227,299 | null | 1 | 41 | java|generics|reflection|types|introspection | 58,858 | <p>Have a look at <a href="http://java.sun.com/docs/books/tutorial/reflect/member/fieldTypes.html" rel="noreferrer">Obtaining Field Types</a> from the Java Tutorial <a href="http://java.sun.com/docs/books/tutorial/reflect/" rel="noreferrer">Trail: The Reflection API</a>. </p>
<p>Basically, what you need to do is to get all <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html" rel="noreferrer"><code>java.lang.reflect.Field</code></a> of your class <strike>and call <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html#getType%28%29" rel="noreferrer"><code>Field#getType()</code></a> on each of them</strike> (check edit below). To get <strong>all</strong> object fields including public, protected, package and private access fields, simply use <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaredFields%28%29" rel="noreferrer"><code>Class.getDeclaredFields()</code></a>. Something like this:</p>
<pre><code>for (Field field : Person.class.getDeclaredFields()) {
System.out.format("Type: %s%n", field.getType());
System.out.format("GenericType: %s%n", field.getGenericType());
}
</code></pre>
<p><strong>EDIT:</strong> As pointed out by <a href="https://stackoverflow.com/users/49237/wowest">wowest</a> in a comment, you actually need to call <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html#getGenericType%28%29" rel="noreferrer"><code>Field#getGenericType()</code></a>, check if the returned <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Type.html" rel="noreferrer"><code>Type</code></a> is a <code>ParameterizedType</code> and then grab the parameters accordingly. Use <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getRawType%28%29" rel="noreferrer"><code>ParameterizedType#getRawType()</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29" rel="noreferrer"><code>ParameterizedType#getActualTypeArgument()</code></a> to get the raw type and an array of the types argument of a <code>ParameterizedType</code> respectively. The following code demonstrates this:</p>
<pre><code>for (Field field : Person.class.getDeclaredFields()) {
System.out.print("Field: " + field.getName() + " - ");
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)type;
System.out.print("Raw type: " + pType.getRawType() + " - ");
System.out.println("Type args: " + pType.getActualTypeArguments()[0]);
} else {
System.out.println("Type: " + field.getType());
}
}
</code></pre>
<p>And would output:</p>
<pre><code>Field: name - Type: class java.lang.String
Field: children - Raw type: interface java.util.List - Type args: class foo.Person
</code></pre> |
1,641,957 | Is an array name a pointer? | <p>Is an array's name a pointer in C?
If not, what is the difference between an array's name and a pointer variable?</p> | 1,641,963 | 8 | 8 | null | 2009-10-29 06:38:05.2 UTC | 180 | 2020-09-04 15:52:04.277 UTC | 2017-05-22 08:30:33.56 UTC | null | 584,518 | user188276 | null | null | 1 | 251 | c|arrays|pointers | 95,198 | <p>An array is an array and a pointer is a pointer, but in most cases array names are <em>converted</em> to pointers. A term often used is that they <em>decay</em> to pointers.</p>
<p>Here is an array:</p>
<pre><code>int a[7];
</code></pre>
<p><code>a</code> contains space for seven integers, and you can put a value in one of them with an assignment, like this:</p>
<pre><code>a[3] = 9;
</code></pre>
<p>Here is a pointer:</p>
<pre><code>int *p;
</code></pre>
<p><code>p</code> doesn't contain any spaces for integers, but it can point to a space for an integer. We can, for example, set it to point to one of the places in the array <code>a</code>, such as the first one:</p>
<pre><code>p = &a[0];
</code></pre>
<p>What can be confusing is that you can also write this:</p>
<pre><code>p = a;
</code></pre>
<p>This does <em>not</em> copy the contents of the array <code>a</code> into the pointer <code>p</code> (whatever that would mean). Instead, the array name <code>a</code> is converted to a pointer to its first element. So that assignment does the same as the previous one.</p>
<p>Now you can use <code>p</code> in a similar way to an array:</p>
<pre><code>p[3] = 17;
</code></pre>
<p>The reason that this works is that the array dereferencing operator in C, <code>[ ]</code>, is defined in terms of pointers. <code>x[y]</code> means: start with the pointer <code>x</code>, step <code>y</code> elements forward after what the pointer points to, and then take whatever is there. Using pointer arithmetic syntax, <code>x[y]</code> can also be written as <code>*(x+y)</code>.</p>
<p>For this to work with a normal array, such as our <code>a</code>, the name <code>a</code> in <code>a[3]</code> must first be converted to a pointer (to the first element in <code>a</code>). Then we step 3 elements forward, and take whatever is there. In other words: take the element at position 3 in the array. (Which is the fourth element in the array, since the first one is numbered 0.)</p>
<p>So, in summary, array names in a C program are (in most cases) converted to pointers. One exception is when we use the <code>sizeof</code> operator on an array. If <code>a</code> was converted to a pointer in this context, <code>sizeof a</code> would give the size of a pointer and not of the actual array, which would be rather useless, so in that case <code>a</code> means the array itself.</p> |
1,359,680 | C# Training Quizzes | <p>I have been programming 10 years, mostly in vba and vb.net but I know c# well enough to program what I normally do. I yesterday was applying for a Senior c# position and I did so poorly on the induction test its not funny :)</p>
<p>I have always found that for me the best way to learn and recall is via questions and answers (multichoice and short answer). That is, a question is posed and after I answer instant feedback is given as to whether I choose right or wrong and the reasons why.</p>
<p>As such I was wondering if anyone knew of or could recommend a C# quiz website. Something like a daily c# quiz to keep my brain up to date and fresh if I'm not always programming in it. Not something wimpy either. Something that does everything. Paying is not an obstacle, id prefer to pay for a good resource than muck around.</p>
<p>Thank you</p> | 1,359,712 | 9 | 4 | null | 2009-08-31 22:26:33.923 UTC | 18 | 2013-09-09 18:18:05.9 UTC | 2013-09-09 18:18:05.9 UTC | user1228 | null | John Sheppard | null | null | 1 | 15 | c#|c | 26,177 | <p>You might want to take a look at <a href="http://www.microsoft.com/click/areyoucertifiable/" rel="noreferrer">Are You Certifiable</a> from Microsoft.</p>
<p>You have to register with a Windows Live ID to access all the questions. The questions they have cover a range of programming technologies (includes SQL Server and sysadmin). The questions are multiple choice and include a paragraph or two on why each response was correct or incorrect.</p>
<p>The site includes a cheesy point system with awards and badges.</p> |
1,670,463 | Latex - Change margins of only a few pages | <p>I have a Latex document where I need to change the margins of only a few pages (the pages where I'm adding a lot of graphics).</p>
<p>In particular, I'd like to change the top margins (<code>\voffset</code>). I've tried doing:</p>
<pre><code>\addtolength{\voffset}{-4cm}
% Insert images here
\addtolength{\voffset}{4cm}
</code></pre>
<p>but it didn't work. I've seen references to the geometry package, but I haven't found how to use it for a bunch of pages, and not for the whole document.</p>
<p>Any hints?</p> | 1,670,572 | 10 | 0 | null | 2009-11-03 22:10:51.217 UTC | 34 | 2022-06-20 23:57:15.953 UTC | null | null | null | null | 7,277 | null | 1 | 123 | latex | 217,535 | <p>I've used this in <code>beamer</code>, but not for general documents, but it looks like that's what the original hint suggests</p>
<pre><code>\newenvironment{changemargin}[2]{%
\begin{list}{}{%
\setlength{\topsep}{0pt}%
\setlength{\leftmargin}{#1}%
\setlength{\rightmargin}{#2}%
\setlength{\listparindent}{\parindent}%
\setlength{\itemindent}{\parindent}%
\setlength{\parsep}{\parskip}%
}%
\item[]}{\end{list}}
</code></pre>
<p>Then to use it</p>
<pre><code>\begin{changemargin}{-1cm}{-1cm}
</code></pre>
<p>don't forget to </p>
<pre><code>\end{changemargin}
</code></pre>
<p>at the end of the page</p>
<p>I got this from <a href="https://texfaq.org/FAQ-chngmargonfly" rel="noreferrer">Changing margins “on the fly”</a> in the TeX FAQ.</p> |
2,113,069 | C# getting its own class name | <p>If I have a class called <code>MyProgram</code>, is there a way of retrieving "<em>MyProgram</em>" as a string?</p> | 2,113,076 | 11 | 0 | null | 2010-01-21 21:30:26.173 UTC | 66 | 2021-07-12 02:05:58.017 UTC | 2016-12-21 02:19:26.373 UTC | user6269864 | null | null | 144,152 | null | 1 | 624 | c#|reflection | 531,162 | <p>Try this:</p>
<pre><code>this.GetType().Name
</code></pre> |
2,100,829 | When should you branch? | <p>When working with a SCM system, when should you branch?</p> | 2,100,846 | 12 | 0 | null | 2010-01-20 11:06:32.187 UTC | 51 | 2022-07-26 14:06:14.21 UTC | 2010-01-20 11:08:16.273 UTC | null | 20,972 | null | 38,522 | null | 1 | 112 | version-control|branch | 38,280 | <p>There are several uses for branching. One of the most common uses is for separating projects that once had a common code base. This is very useful to experiment with your code, without affecting the main trunk.</p>
<p>In general, you would see two branch types:</p>
<ul>
<li><p>Feature Branch: If a particular feature is disruptive enough that you don't want the entire development team to be affected in its early stages, you can create a branch on which to do this work.</p></li>
<li><p>Fixes Branch: While development continues on the main trunk, a fixes branch can be created to hold the fixes to the latest released version of the software. </p></li>
</ul>
<p>You may be interested in checking out the following article, which explains the principles of branching, and when to use them:</p>
<ul>
<li><a href="http://nedbatchelder.com/text/quicksvnbranch.html" rel="noreferrer">Ned Batchelder - Subversion branching quick start</a></li>
</ul> |
33,567,101 | Using lapply to change column names of a list of data frames | <p>I'm trying to use <strong>lapply</strong> on a list of data frames; but failing at passing the parameters correctly (I think). </p>
<p>List of data frames:</p>
<pre><code>df1 <- data.frame(A = 1:10, B= 11:20)
df2 <- data.frame(A = 21:30, B = 31:40)
listDF <- list(df1, df2,df3) #multiple data frames w. way less columns than the length of vector todos
</code></pre>
<p>Vector with columns names:</p>
<pre><code>todos <-c('col1','col2', ......'colN')
</code></pre>
<p>I'd like to change the column names using lapply:</p>
<pre><code>lapply (listDF, function(x) { colnames(x)[2:length(x)] <-todos[1:length(x)-1] } )
</code></pre>
<p>but this doesn't change the names at all. Am I not passing the data frames themselves, but something else? I just want to change names, not to return the result to a new object.</p>
<p>Thanks in advance, p.</p> | 33,567,207 | 3 | 3 | null | 2015-11-06 12:44:48.303 UTC | 9 | 2019-02-22 17:47:16.113 UTC | 2016-02-16 18:26:55.84 UTC | null | 2,204,410 | null | 3,310,782 | null | 1 | 16 | r|dataframe|lapply | 26,612 | <p>You can also use <code>setNames</code> if you want to replace all columns</p>
<pre><code>df1 <- data.frame(A = 1:10, B= 11:20)
df2 <- data.frame(A = 21:30, B = 31:40)
listDF <- list(df1, df2)
new_col_name <- c("C", "D")
lapply(listDF, setNames, nm = new_col_name)
## [[1]]
## C D
## 1 1 11
## 2 2 12
## 3 3 13
## 4 4 14
## 5 5 15
## 6 6 16
## 7 7 17
## 8 8 18
## 9 9 19
## 10 10 20
## [[2]]
## C D
## 1 21 31
## 2 22 32
## 3 23 33
## 4 24 34
## 5 25 35
## 6 26 36
## 7 27 37
## 8 28 38
## 9 29 39
## 10 30 40
</code></pre>
<p>If you need to replace only a subset of column names, then you can use the solution of @Jogo</p>
<pre><code>lapply(listDF, function(df) {
names(df)[-1] <- new_col_name[-ncol(df)]
df
})
</code></pre>
<p>A last point, in R there is a difference between a:b - 1 and a:(b - 1)</p>
<pre><code>1:10 - 1
## [1] 0 1 2 3 4 5 6 7 8 9
1:(10 - 1)
## [1] 1 2 3 4 5 6 7 8 9
</code></pre>
<p><strong>EDIT</strong></p>
<p>If you want to change the column names of the <code>data.frame</code> in global environment from a list, you can use <code>list2env</code> but I'm not sure it is the best way to achieve want you want. You also need to modify your list and use named list, the name should be the same as name of the <code>data.frame</code> you need to replace.</p>
<pre><code>listDF <- list(df1 = df1, df2 = df2)
new_col_name <- c("C", "D")
listDF <- lapply(listDF, function(df) {
names(df)[-1] <- new_col_name[-ncol(df)]
df
})
list2env(listDF, envir = .GlobalEnv)
str(df1)
## 'data.frame': 10 obs. of 2 variables:
## $ A: int 1 2 3 4 5 6 7 8 9 10
## $ C: int 11 12 13 14 15 16 17 18 19 20
</code></pre> |
8,579,330 | Appending to crontab with a shell script on Ubuntu | <p>I'm trying to add a line to the crontab on Ubuntu.</p>
<p>Right now, I'm doing <code>crontab -e</code> and editing the crontab there.</p>
<p>However, I can't seem to find the real crontab file, since <code>crontab -e</code> seems to give you a temporary working copy.</p>
<p><code>/etc/crontab</code> looks like the system crontab.</p>
<p>What is the path of the crontab that <code>crontab -e</code> saves to?</p>
<p>Thanks!</p> | 8,579,472 | 4 | 2 | null | 2011-12-20 17:19:54.637 UTC | 17 | 2015-02-17 11:03:25.06 UTC | null | null | null | null | 773,862 | null | 1 | 54 | ubuntu|cron|debian|crontab | 46,417 | <p>Use <code>crontab -l > file</code> to list current user's crontab to the <code>file</code>, and <code>crontab file</code>, to install new crontab.</p> |
17,911,918 | Bootstrap Modal popping up but has a "tinted" page and can't interact | <p>I am using bootstrap to set up a modal popup. When a button is clicked, the modal dialog opens, but the entire page is slightly "tinted", and I can't interact with the modal (the page essentially freezes). Do you know why this would be? Here is the code:</p>
<p>button:</p>
<pre><code><a class="add-list-button-no-margin opener" id="id" data-toggle="modal" href="#myModal" style="color: white; font:14px / 14px 'DINMedium','Helvetica Neue',Helvetica,Arial,sans-serif;">Play my city</a>
</code></pre>
<p>modal:</p>
<pre><code><div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Congratulations!</h4>
</div>
<div class="modal-body">
<h4>Text in a modal</h4>
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p>
<h4>Popover in a modal</h4>
<p>This <a href="#" role="button" class="btn btn-default popover-test" title="A Title" data-content="And here's some amazing content. It's very engaging. right?">button</a> should trigger a popover on click.</p>
<h4>Tooltips in a modal</h4>
<p><a href="#" class="tooltip-test" title="Tooltip">This link</a> and <a href="#" class="tooltip-test" title="Tooltip">that link</a> should have tooltips on hover.</p>
<hr>
<h4>Overflowing text to show optional scrollbar</h4>
<p>body</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code></pre>
<p>EDIT:</p>
<p>Here are the included files:</p>
<pre><code><link media="all" type="text/css" rel="stylesheet" href="http://crowdtest.dev:8888/assets/CSS/style.css">
<link media="all" type="text/css" rel="stylesheet" href="http://crowdtest.dev:8888/assets/CSS/jquery-ui-1.10.1.custom.min.css">
<link media="all" type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css">
<link media="all" type="text/css" rel="stylesheet" href="http://crowdtest.dev:8888/assets/CSS/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script src="http://crowdtest.dev:8888/assets/js/script.js"></script>
<script src="http://crowdtest.dev:8888/assets/js/jquery-ui-1.10.1.custom.min.js"></script>
<script src="http://crowdtest.dev:8888/assets/js/bootstrap.js"></script>
</code></pre>
<p>EDIT: Happens in all browsers tried (Chrome, Firefox, Safari)</p> | 17,914,626 | 10 | 5 | null | 2013-07-28 19:19:07.42 UTC | 11 | 2021-09-07 19:32:10.57 UTC | 2013-07-29 00:55:33.793 UTC | null | 1,072,337 | null | 1,072,337 | null | 1 | 31 | twitter-bootstrap|modal-dialog | 43,951 | <p>Ok, so I figured out the issue. </p>
<p>If the modal container has a fixed position or is within an element with fixed position this behavior will occur.</p>
<p>Easiest way is to just move the modal div so it is outside any elements with special positioning. One good place might be just before the closing body tag .</p>
<p>This is what I did, and it worked. </p> |
6,552,141 | How can a stack underflow happen in C++? | <p>What is a simple example in C++ that causes a stack underflow in the case of invoking and returning from method calls?</p>
<p>I am familiar with the calling convention, i.e <code>thiscall</code>, <code>stdcall</code> and the <code>cdecl</code> and way they would clean the stack. Wouldn't a stack underflow automatically be taken care of by the code generated by the compiler?</p>
<p>What are the situations that can get me into trouble with stack underflow? </p> | 6,553,169 | 4 | 10 | null | 2011-07-01 18:56:12.413 UTC | 9 | 2019-03-26 16:59:21.73 UTC | 2019-03-26 16:59:21.73 UTC | null | 1,711,796 | null | 352,341 | null | 1 | 19 | c++|compiler-construction|stackunderflow | 18,576 | <p>The only way I can see this actually happening would be if you declared a function to use the <code>stdcall</code> (or any other calling convention that specifies the callee clean the stack) and then invoke the function through a function pointer that was specified as a <code>cdecl</code> (or any other calling convention where the stack is cleaned by the caller). If you do that, the called function will pop the stack before returning and then the caller would also pop the stack leading to underflow and terrible things.</p>
<p>In the specific case of member functions, the calling convention is usually referred to as <code>thiscall</code> and whether the caller or the callee cleans the stack depends on the compiler.</p>
<p>See <a href="http://en.wikipedia.org/wiki/X86_calling_conventions">here</a> for details of calling conventions.</p> |
6,339,756 | Why UTF-32 exists whereas only 21 bits are necessary to encode every character? | <p>We know that codepoints can be in this interval 0..10FFFF which is less than 2^21. Then why do we need UTF-32 when all codepoints can be represented by 3 bytes? UTF-24 should be enough.</p> | 6,339,781 | 4 | 0 | null | 2011-06-14 06:15:06.733 UTC | 9 | 2021-12-27 09:56:20.853 UTC | null | null | null | null | 585,795 | null | 1 | 34 | unicode|encoding | 6,278 | <p>Computers are generally much better at dealing with data on 4 byte boundaries. The benefits in terms of reduced memory consumption are relatively small compared with the pain of working on 3-byte boundaries.</p>
<p>(I <em>speculate</em> there was also a reluctance to have a limit that was "only what we can currently imagine being useful" when coming up with the original design. After all, that's caused a lot of problems in the past, e.g. with IPv4. While I can't see us ever needing more than 24 bits, if 32 bits is more convenient <em>anyway</em> then it seems reasonable to avoid having a limit which <em>might</em> just be hit one day, via reserved ranges etc.)</p>
<p>I guess this is a bit like asking why we often have 8-bit, 16-bit, 32-bit and 64-bit integer datatypes (byte, int, long, whatever) but not 24-bit ones. I'm sure there are lots of occasions where we know that a number will never go beyond 2<sup>21</sup>, but it's just simpler to use <code>int</code> than to create a 24-bit type.</p> |
36,059,986 | how to $project ObjectId to string value in mongodb aggregate? | <p>Is there an operator I could use in <strong>aggregate</strong> function to get a string instead of ObjectId in response? </p>
<pre><code>db.something.aggregate([
{ "$match": { "property": { "$exists": true } } },
{ "$project": { "stringId": "$_id.???" } }
])
</code></pre> | 51,231,012 | 3 | 3 | null | 2016-03-17 12:00:48.003 UTC | 10 | 2019-12-19 07:07:20.973 UTC | 2019-12-19 07:07:20.973 UTC | null | 7,510,657 | null | 55,514 | null | 1 | 41 | mongodb|mongodb-query|aggregation-framework | 45,662 | <p>Mongodb <strong>4.0</strong> has introduced <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/toString/" rel="noreferrer"><strong><code>$toString</code></strong></a> aggregation operator. So, Now you can easily convert ObjectId to string</p>
<pre><code>db.collection.aggregate([
{
$project: {
_id: {
$toString: "$_id"
}
}
}
])
</code></pre>
<p>OR vice versa using <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/" rel="noreferrer"><strong><code>$toObjectId</code></strong></a> aggregation</p>
<pre><code>db.collection.aggregate([
{
$project: {
_id: {
$toObjectId: "$_id"
}
}
}
])
</code></pre> |
16,033,521 | inline border styles in an HTML Email | <p>I'm working on a responsive HTML email and I'm having a rendering problem in Gmail ONLY in IE (just had to be!) It works fine in the other 27 client variants. we need to support</p>
<p>I've set up a fiddle here: <a href="http://jsfiddle.net/39gzj/" rel="nofollow">http://jsfiddle.net/39gzj/</a></p>
<p>Now if you look at the code, you will see that there is a border that is grey, which then contains another border that is white. For some bizarre reason, Gmail in Explorer, will not show this border at all, save for the border at the bottom of the sign up bottom. I thought it was something to do with the way that I had coded the border (I'm going off someone elses code, I've only made some minor changes to this) as the border has been done as follows:</p>
<pre><code>border-left-style:solid;border-left-width:1px;border-left-color:#fff;
</code></pre>
<p>So I changed the way that the border both grey and white to be declared as follows:</p>
<pre><code>border-left-style: 1px solid #fff;
</code></pre>
<p>But this makes no difference whatsoever. This is driving me insane so please help if you can. I thought it may be something to do with the widths? But having played around with this it just broke the problem in all other clients. Any help would be much appreciated as I may smash my head into my computer screen soon.</p>
<p>Appreciate that this code contains crazy inline styles but this is of course the nature of HTML emails.</p>
<p>UPDATE: Removing the white inner border that is on the <code><td></code> elements renders the grey border. Is this something to do with me setting the widths incorrectly?</p>
<p>UPDATE 2 : It's IE9 that this is being rendered incorrectly in. And ONLY for Gmail. </p> | 16,034,193 | 2 | 7 | null | 2013-04-16 09:35:29.993 UTC | null | 2015-07-07 17:58:29.523 UTC | 2013-04-16 10:17:37.983 UTC | null | 508,248 | null | 508,248 | null | 1 | 5 | html|css|html-email | 41,180 | <p>Your problem is that the border is on the table itself. You tend to find that the email clients don't like that. The way that I got around it was by placing tables within tables a bit like this:</p>
<pre><code><table width="600" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="600" valign="top" align="center" bgcolor="#CCCCCC">
<img src="spacer.gif" width="1px" height="1px" style="border:0px; display:block;">
<table width="598" cellpadding="0" cellspacing="0" border="0" bgcolor="#FFFFFF">
<tr>
<td width="598" align="left">
Text Here
</td>
</tr>
</table>
<img src="spacer.gif" width="1px" height="1px" style="border:0px; display:block;">
</td>
</tr>
</table>
<br/><br/><br/>
<table width="600" cellpadding="0" cellspacing="1" border="0" bgcolor="#CCCCCC">
<tr>
<td width="600" valign="top" align="left" bgcolor="#FFFFFF">
Text Here
</td>
</tr>
</table>
</code></pre>
<p>Here is the code on a: <a href="http://jsfiddle.net/9P8cj/1/" rel="nofollow">jsfiddle</a>
I have created 2 different ways to get a similar effect. You can choose the one that works best for yourself.</p>
<p>I also see that you have used max-width which some email clients dont like so that might be your problem. here is the campaignmonitor guide to css classes and what you should and should not use: <a href="http://www.campaignmonitor.com/css/" rel="nofollow">http://www.campaignmonitor.com/css/</a></p> |
5,198,304 | How to keep form values after post | <p>I am trying to find what the easiest way to keep form values after post. I am really trying to have to keep from learning ajax right this second for the one form, Plus I am not sure how hard it would be to implement ajax into my already existing google map page. So I am trying to find a way to retain the values of two date fields after submit has been pushed</p> | 5,198,784 | 2 | 5 | null | 2011-03-04 19:24:29.433 UTC | 8 | 2020-01-02 04:48:23.217 UTC | 2015-09-09 07:57:16.78 UTC | null | 1,059,828 | null | 271,534 | null | 1 | 31 | php|javascript|html|ajax | 124,905 | <p>If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:</p>
<pre><code><input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />
</code></pre> |
288,850 | How to return JSON from a 2.0 asmx web service | <p>I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!</p>
<p>Here is the call:</p>
<pre><code> $(document).ready(function() {
$.ajax({
type: "POST",
url: "DonationsService.asmx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Hide the fake progress indicator graphic.
$('#RSSContent').removeClass('loading');
// Insert the returned HTML into the <div>.
$('#RSSContent').html(msg.d);
}
});
});
</code></pre>
<p>Here is what the request header looks like in Fiddler:</p>
<pre><code>POST /DonationsService.asmx/GetDate HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://localhost:1238/text.htm
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727)
Host: localhost:1238
Content-Length: 2
Connection: Keep-Alive
Pragma: no-cache
</code></pre>
<p>I have tried setting the contentType to 'text/json' and get the same results.</p>
<p>Here is the web service method:</p>
<pre><code><WebMethod()> _
Public Function GetDate() As String
'just playing around with Newtonsoft.Json
Dim sb As New StringBuilder
Dim sw As New IO.StringWriter(sb)
Dim strOut As String = String.Empty
Using jw As New JsonTextWriter(sw)
With jw
.WriteStartObject()
.WritePropertyName("DateTime")
.WriteValue(DateTime.Now.ToString)
.WriteEndObject()
End With
strOut = sw.ToString
End Using
Return strOut
End Function
</code></pre>
<p>and here is what it returns:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>
</code></pre>
<p>Does anyone know how to force the web service to return Json when I ask for Json?</p>
<p>Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.</p> | 289,332 | 7 | 2 | null | 2008-11-14 00:12:09.347 UTC | 12 | 2014-04-04 08:12:16.34 UTC | 2014-01-17 15:07:10.567 UTC | null | 1,193,596 | camainc | 7,232 | null | 1 | 27 | jquery|.net|asp.net|ajax|web-services | 69,441 | <p>It's no problem to <a href="http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/" rel="noreferrer">return JSON from ASMX services in ASP.NET 2.0</a>. You just need the ASP.NET AJAX Extensions installed.</p>
<p>Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.</p>
<p>Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/" rel="noreferrer">The ".d" is a security feature that came with 3.5</a>.</p> |
1,206,903 | How do I require an inline in the Django Admin? | <p>I have the following admin setup so that I can add/edit a user and their profile at the same time. </p>
<pre><code>class ProfileInline(admin.StackedInline):
"""
Allows profile to be added when creating user
"""
model = Profile
class UserProfileAdmin(admin.ModelAdmin):
"""
Options for the admin interface
"""
inlines = [ProfileInline]
list_display = ['edit_obj', 'name', 'username', 'email', 'is_active',
'last_login', 'delete_obj']
list_display_links = ['username']
list_filter = ['is_active']
fieldsets = (
(None, {
'fields': ('first_name', 'last_name', 'email', 'username',
'is_active', 'is_superuser')}),
)
ordering = ['last_name', 'first_name']
search_fields = ['first_name', 'last_name']
admin.site.register(User, UserProfileAdmin)
</code></pre>
<p>The problem is I need two of the fields in the Profile inline form to be required when adding the user. The inline form doesn't validate unless input is entered. Is there anyway to make the inline required, so that it can't be left blank?</p> | 1,233,644 | 7 | 0 | null | 2009-07-30 14:21:19.99 UTC | 12 | 2022-03-19 14:23:09.6 UTC | 2022-03-19 10:47:28.683 UTC | null | 8,172,439 | null | 147,862 | null | 1 | 29 | python|python-3.x|django|django-admin|inline | 15,102 | <p>I took Carl's advice and made a much better implementation then the hack-ish one I mentioned in my comment to his answer. Here is my solution:</p>
<p>From my forms.py:</p>
<pre><code>from django.forms.models import BaseInlineFormSet
class RequiredInlineFormSet(BaseInlineFormSet):
"""
Generates an inline formset that is required
"""
def _construct_form(self, i, **kwargs):
"""
Override the method to change the form attribute empty_permitted
"""
form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
form.empty_permitted = False
return form
</code></pre>
<p>And the admin.py</p>
<pre><code>class ProfileInline(admin.StackedInline):
"""
Allows profile to be added when creating user
"""
model = Profile
extra = 1
max_num = 1
formset = RequiredInlineFormSet
class UserProfileAdmin(admin.ModelAdmin):
"""
Options for the admin interface
"""
inlines = [ProfileInline]
list_display = ['edit_obj', 'name', 'username', 'email', 'is_active',
'last_login', 'delete_obj']
list_display_links = ['username']
list_filter = ['is_active']
fieldsets = (
(None, {
'fields': ('first_name', 'last_name', 'email', 'username',
'is_active', 'is_superuser')}),
(('Groups'), {'fields': ('groups', )}),
)
ordering = ['last_name', 'first_name']
search_fields = ['first_name', 'last_name']
admin.site.register(User, UserProfileAdmin)
</code></pre>
<p>This does exactly what I want, it makes the Profile inline formset validate. So since there are required fields in the profile form it will validate and fail if the required information isn't entered on the inline form.</p> |
829,007 | Find out what process registered a global hotkey? (Windows API) | <p>As far as I've been able to find out, Windows doesn't offer an API function to tell what application has registered a global hotkey (via RegisterHotkey). I can only find out that a hotkey is registered if RegisterHotkey returns false, but not who "owns" the hotkey.</p>
<p>In the absence of a direct API, could there be a roundabout way? Windows maintains the handle associated with each registred hotkey - it's a little maddening that there should be no way of getting at this information.</p>
<p>Example of something that likely wouldn't work: send (simulate) a registered hotkey, then intercept the hotkey message Windows will send to the process that registered it. First, I don't think intercepting the message would reveal the destination window handle. Second, even if it were possible, it would be a bad thing to do, since sending hotkeys would trigger all sorts of potentially unwanted activity from various programs. </p>
<p>It's nothing critical, but I've seen frequent requests for such functionality, and have myself been a victim of applications that register hotkeys without even disclosing it anywhere in the UI or docs. </p>
<p>(Working in Delphi, and no more than an apprentice at WinAPI, please be kind.)</p> | 887,086 | 7 | 0 | null | 2009-05-06 10:32:49.253 UTC | 61 | 2022-09-21 06:43:19.277 UTC | 2022-02-09 20:20:12.24 UTC | null | 4,294,399 | null | 9,226 | null | 1 | 135 | delphi|winapi|hotkeys|registerhotkey | 37,546 | <p>Your question piqued my interest, so I've done a bit of digging and while, unfortunately I don't have a proper answer for you, I thought I'd share what I have.</p>
<p>I found this <a href="http://groups.google.com/group/borland.public.delphi.winapi/msg/ceb5818acd623a24" rel="noreferrer">example of creating keyboard hook (in Delphi)</a> written in 1998, but is compilable in Delphi 2007 with a couple of tweaks. </p>
<p>It's a DLL with a call to <code>SetWindowsHookEx</code> that passes through a callback function, which can then intercept key strokes: In this case, it's tinkering with them for fun, changing left cursor to right, etc. A simple app then calls the DLL and reports back its results based on a TTimer event. If you're interested I can post the Delphi 2007 based code.</p>
<p>It's well documented and commented and you potentially could use it as a basis of working out where a key press is going. If you could get the handle of the application that sent the key strokes, you could track it back that way. With that handle you'd be able to get the information you need quite easily.</p>
<p>Other apps have tried determining hotkeys by going through their Shortcuts since they can contain a Shortcut key, which is just another term for hotkey. However most applications don't tend to set this property so it might not return much. If you are interested in that route, Delphi has access to <code>IShellLink</code> COM interface which you could use to load a shortcut up from and get its hotkey:</p>
<pre><code>uses ShlObj, ComObj, ShellAPI, ActiveX, CommCtrl;
procedure GetShellLinkHotKey;
var
LinkFile : WideString;
SL: IShellLink;
PF: IPersistFile;
HotKey : Word;
HotKeyMod: Byte;
HotKeyText : string;
begin
LinkFile := 'C:\Temp\Temp.lnk';
OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, SL));
// The IShellLink implementer must also support the IPersistFile
// interface. Get an interface pointer to it.
PF := SL as IPersistFile;
// Load file into IPersistFile object
OleCheck(PF.Load(PWideChar(LinkFile), STGM_READ));
// Resolve the link by calling the Resolve interface function.
OleCheck(SL.Resolve(0, SLR_ANY_MATCH or SLR_NO_UI));
// Get hotkey info
OleCheck(SL.GetHotKey(HotKey));
// Extract the HotKey and Modifier properties.
HotKeyText := '';
HotKeyMod := Hi(HotKey);
if (HotKeyMod and HOTKEYF_ALT) = HOTKEYF_ALT then
HotKeyText := 'ALT+';
if (HotKeyMod and HOTKEYF_CONTROL) = HOTKEYF_CONTROL then
HotKeyText := HotKeyText + 'CTRL+';
if (HotKeyMod and HOTKEYF_SHIFT) = HOTKEYF_SHIFT then
HotKeyText := HotKeyText + 'SHIFT+';
if (HotKeyMod and HOTKEYF_EXT) = HOTKEYF_EXT then
HotKeyText := HotKeyText + 'Extended+';
HotKeyText := HotKeyText + Char(Lo(HotKey));
if (HotKeyText = '') or (HotKeyText = #0) then
HotKeyText := 'None';
ShowMessage('Shortcut Key - ' + HotKeyText);
end;
</code></pre>
<p>If you've got access to <a href="http://my.safaribooksonline.com/" rel="noreferrer">Safari Books Online</a>, there is a <a href="http://my.safaribooksonline.com/0672321157/ch16lev1sec3" rel="noreferrer">good section about working with shortcuts / shell links</a> in the Borland Delphi 6 Developer's Guide by Steve Teixeira and Xavier Pacheco. My example above is a butchered version from there and <a href="http://delphicikk.atw.hu/listaz.php?id=2351&oldal=1" rel="noreferrer">this site</a>.</p>
<p>Hope that helps!</p> |
206,318 | Are there any HTTP/HTTPS interception tools other than Fiddler, Charles, Poster, and Achilles? | <p>I'm in the process of testing my application with respect to security. </p>
<p>Aside from <a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">Fiddler</a>, <a href="http://www.charlesproxy.com/" rel="noreferrer">Charles</a> and <a href="https://addons.mozilla.org/en-us/firefox/addon/poster/" rel="noreferrer">Poster</a> (Firefox plug in). Are there any other free to use https interception (and editing) applications out there? Especially ones which can be installed w/o admin privileges. </p>
<p>Achilles comes to mind, but I don't think it can handle https traffic.</p> | 234,487 | 8 | 4 | null | 2008-10-15 20:31:05.687 UTC | 23 | 2015-12-17 11:35:15.55 UTC | 2012-07-23 08:46:00.56 UTC | oneBelizean | 587,642 | oneBelizean | 17,337 | null | 1 | 30 | security|http|testing|https | 51,713 | <p>Achilles does work on HTTPS traffic, but they note on their site that it is not the best tool any more.</p>
<p>Their suggestions are <a href="http://portswigger.net/burp/" rel="noreferrer">Burp Suite</a> and <a href="http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project" rel="noreferrer">WebScarab</a> both of which I highly recommend.</p> |
724,862 | Converting from hex to string | <p>I need to check for a <code>string</code> located inside a packet that I receive as <code>byte</code> array. If I use <code>BitConverter.ToString()</code>, I get the bytes as <code>string</code> with dashes (f.e.: 00-50-25-40-A5-FF).<br>
I tried most functions I found after a quick googling, but most of them have input parameter type <code>string</code> and if I call them with the <code>string</code> with dashes, It throws an exception.</p>
<p>I need a function that turns hex(as <code>string</code> or as <code>byte</code>) into the <code>string</code> that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is <code>string</code>, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because <code>BitConverter</code> doesn't convert correctly.</p> | 724,905 | 8 | 2 | null | 2009-04-07 09:45:10.9 UTC | 13 | 2022-09-16 06:31:18.43 UTC | 2014-01-15 17:02:21.277 UTC | null | 1,864,167 | null | 81,800 | null | 1 | 43 | c#|string|hex|bitconverter | 186,196 | <p>Like so?</p>
<pre><code>static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
</code></pre> |
502,303 | How do I programmatically get the GUID of an application in C# with .NET? | <p>I need to access the assembly of my project in C#.</p>
<p>I can see the GUID in the 'Assembly Information' dialog in under project properties, and at the moment I have just copied it to a const in the code. The GUID will never change, so this is not that bad of a solution, but it would be nice to access it directly. Is there a way to do this?</p> | 502,327 | 8 | 3 | null | 2009-02-02 05:49:28.067 UTC | 26 | 2022-08-10 23:34:10.043 UTC | 2022-08-10 23:31:42.807 UTC | moocha | 63,550 | Nathan | 6,062 | null | 1 | 117 | c#|.net | 122,421 | <p>Try the following code. The value you are looking for is stored on a <code>GuidAttribute</code> instance attached to the <code>Assembly</code></p>
<pre class="lang-cs prettyprint-override"><code>using System.Runtime.InteropServices;
static void Main(string[] args)
{
var assembly = typeof(Program).Assembly;
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];
var id = attribute.Value;
Console.WriteLine(id);
}
</code></pre> |
350,419 | How do you reconcile common C++ naming conventions with those of the libraries | <p>Most C++ naming conventions dictate the use of <code>camelCaseIdentifiers</code>: names that start with an uppercase letter for classes (<code>Person</code>, <code>Booking</code>) and names that start with a lowercase letter for fields and variables (<code>getPrice()</code>, <code>isValid()</code>, <code>largestValue</code>). These recommendations are completely at odds with the naming conventions of the C++ library, which involve lowercase names for classes (<code>string</code>, <code>set</code>, <code>map</code>, <code>fstream</code>) and <code>names_joined_with_an_underscore</code> for methods and fields (<code>find_first_of</code>, <code>lower_bound</code>, <code>reverse_iterator</code>, <code>first_type</code>). Further complicating the picture are operating system and C library functions, which involve compressed lowercase names in C and Unix and functions starting with an uppercase letter in Windows.</p>
<p>As a result my code is a mess, because some identifiers use the C++ library, C, or operating system naming convention, and others use the prescribed C++ convention. Writing classes or methods that wrap functionality of the library is painful, because one ends with different-style names for similar things.</p>
<p>So, how do you reconcile these disparate naming conventions?</p> | 350,448 | 10 | 0 | null | 2008-12-08 18:36:35.94 UTC | 11 | 2020-05-10 01:16:31.36 UTC | 2017-05-23 17:28:01.427 UTC | null | 396,583 | Diomidis Spinellis | 20,520 | null | 1 | 45 | c++|coding-style|naming-conventions | 10,770 | <p>One way it to adopt the C++ <code>naming_convention</code>, this is what most code examples in the literature do nowadays.</p>
<p>I slowly see these conventions move into production code but it's a battle against MFC naming conventions that still prevail in many places.</p>
<p>Other style differences that fight against old standards are using trailing underscores rather than <code>m_</code> to denote members.</p> |
10,499 | Oracle - What TNS Names file am I using? | <p>Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using.</p>
<p>What's the best way to figure this out? ++happy for various platform solutions. </p> | 29,807 | 11 | 0 | null | 2008-08-13 23:49:15.623 UTC | 21 | 2016-04-10 13:02:16.583 UTC | 2008-08-30 09:07:24.703 UTC | Mark Harrison | 116 | Mark Harrison | 116 | null | 1 | 59 | oracle|connection|tnsnames|tns | 230,693 | <p>Oracle provides a utility called <code>tnsping</code>:</p>
<pre><code>R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
</code></pre>
<p>This should show what file you're using. The utility sits in the Oracle <code>bin</code> directory.</p> |
238,284 | How to copy text programmatically in my Android app? | <p>I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press <code>Menu+A</code> then <code>Menu+C</code> to copy the value, but how would I do this programmatically?</p> | 238,297 | 15 | 2 | null | 2008-10-26 17:13:32.487 UTC | 54 | 2022-07-19 09:39:09.393 UTC | 2018-07-31 10:09:33.84 UTC | Andy Lester | 7,874,047 | Zach | 9,128 | null | 1 | 256 | android|menu|clipboardmanager | 122,961 | <p>Use <a href="https://developer.android.com/reference/android/content/ClipboardManager#setPrimaryClip(android.content.ClipData)" rel="noreferrer"><code>ClipboardManager#setPrimaryClip</code></a> method:</p>
<pre><code>import android.content.ClipboardManager;
// ...
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
</code></pre>
<p><a href="http://developer.android.com/reference/android/content/ClipboardManager.html" rel="noreferrer"><code>ClipboardManager</code> API reference</a></p> |
147,528 | How do I force a DIV block to extend to the bottom of a page even if it has no content? | <p>In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display.</p>
<p>Here is my <strong>DEMO</strong>:</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-css lang-css prettyprint-override"><code>body {
font-family: Trebuchet MS, Verdana, MS Sans Serif;
font-size:0.9em;
margin:0;
padding:0;
}
div#header {
width: 100%;
height: 100px;
}
#header a {
background-position: 100px 30px;
background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px;
height: 80px;
display: block;
}
#header, #menuwrapper {
background-repeat: repeat;
background-image: url(site-style-images/darkblue_background_color.jpg);
}
#menu #menuwrapper {
height:25px;
}
div#menuwrapper {
width:100%
}
#menu, #content {
width:1024px;
margin: 0 auto;
}
div#menu {
height: 25px;
background-color:#50657a;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form1">
<div id="header">
<a title="Home" href="index.html" />
</div>
<div id="menuwrapper">
<div id="menu">
</div>
</div>
<div id="content">
</div>
</form></code></pre>
</div>
</div>
</p> | 579,123 | 18 | 1 | null | 2008-09-29 04:40:24.29 UTC | 51 | 2021-10-03 19:15:39.377 UTC | 2021-04-21 06:52:33.543 UTC | Marcel Tjandraatmadja | 11,044,542 | null | 17,211 | null | 1 | 214 | css|html|border | 420,265 | <p>Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using:</p>
<pre><code>html,body { height:100%; }
</code></pre>
<p>You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit.</p>
<p>This site has some excellent examples:</p>
<p><a href="http://www.brunildo.org/test/html_body_0.html" rel="noreferrer">http://www.brunildo.org/test/html_body_0.html</a><br>
<a href="http://www.brunildo.org/test/html_body_11b.html" rel="noreferrer">http://www.brunildo.org/test/html_body_11b.html</a><br>
<a href="http://www.brunildo.org/test/index.html" rel="noreferrer">http://www.brunildo.org/test/index.html</a><br></p>
<p>I also recommend going to <a href="http://quirksmode.org/" rel="noreferrer">http://quirksmode.org/</a></p> |
606,191 | Convert bytes to a string | <p>I captured the standard output of an external program into a <code>bytes</code> object:</p>
<pre class="lang-none prettyprint-override"><code>>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
</code></pre>
<p>I want to convert that to a normal Python string, so that I can print it like this:</p>
<pre class="lang-none prettyprint-override"><code>>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
</code></pre>
<p>I tried the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp" rel="nofollow noreferrer"><code>binascii.b2a_qp()</code></a> method, but got the same <code>bytes</code> object again:</p>
<pre class="lang-none prettyprint-override"><code>>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
</code></pre>
<p>How do I convert the <code>bytes</code> object to a <code>str</code> with Python 3?</p> | 606,199 | 24 | 5 | null | 2009-03-03 12:23:01.583 UTC | 551 | 2022-09-19 17:00:33.33 UTC | 2022-09-19 17:00:33.33 UTC | J.F. Sebastian | 63,550 | Tomas Sedovic | 2,239 | null | 1 | 3,455 | python|string|python-3.x | 4,317,582 | <p><a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode" rel="noreferrer">Decode the <code>bytes</code> object</a> to produce a string:</p>
<pre><code>>>> b"abcde".decode("utf-8")
'abcde'
</code></pre>
<p>The above example <em>assumes</em> that the <code>bytes</code> object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!</p> |
6,854,996 | MySQL INSERT IF (custom if statements) | <p>First, here's the concise summary of the question:</p>
<p>Is it possible to run an <code>INSERT</code> statement conditionally?
Something akin to this:</p>
<pre><code>IF(expression) INSERT...
</code></pre>
<p>Now, I know I can do this with a stored procedure.
My question is: can I do this in my query?</p>
<hr>
<p>Now, why would I want to do that?</p>
<p>Let's assume we have the following 2 tables:</p>
<pre><code>products: id, qty_on_hand
orders: id, product_id, qty
</code></pre>
<p>Now, let's say an order for 20 Voodoo Dolls (product id 2) comes in.<br />
We first check if there's enough Quantity On Hand:</p>
<pre><code>SELECT IF(
( SELECT SUM(qty) FROM orders WHERE product_id = 2 ) + 20
<=
( SELECT qty_on_hand FROM products WHERE id = 2)
, 'true', 'false');
</code></pre>
<p>Then, if it evaluates to true, we run an <code>INSERT</code> query.<br />
So far so good.</p>
<hr>
<p>However, there's a problem with concurrency.<br />
If 2 orders come in at the <em>exact same time</em>, they might both read the quantity-on-hand before any one of them has entered the order.
They'll then both place the order, thus exceeding the <code>qty_on_hand</code>.</p>
<hr>
<p>So, back to the root of the question:<br />
Is it possible to run an <code>INSERT</code> statement conditionally, so that we can combine both these queries into one?</p>
<p>I searched around a lot, and the only type of conditional <code>INSERT</code> statement that I could find was <code>ON DUPLICATE KEY</code>, which obviously does not apply here.</p> | 6,855,014 | 5 | 0 | null | 2011-07-28 06:44:35.79 UTC | 16 | 2020-05-14 18:41:08.35 UTC | 2011-08-18 04:15:05.16 UTC | null | 825,568 | null | 825,568 | null | 1 | 50 | mysql|concurrency|insert|if-statement|race-condition | 102,926 | <pre><code>INSERT INTO TABLE
SELECT value_for_column1, value_for_column2, ...
FROM wherever
WHERE your_special_condition
</code></pre>
<p>If no rows are returned from the select (because your special condition is false) no insert happens.</p>
<p>Using your schema from question (assuming your <code>id</code> column is <code>auto_increment</code>):</p>
<pre><code>insert into orders (product_id, qty)
select 2, 20
where (SELECT qty_on_hand FROM products WHERE id = 2) > 20;
</code></pre>
<p>This will insert no rows if there's not enough stock on hand, otherwise it will create the order row.</p>
<p>Nice idea btw!</p> |
6,468,349 | How to remove Black background between start new activity during slide_left animation? | <p>When I call new activity by animation the background gets black.<br />
How can I remove remove the black background?</p>
<p>For the animation I'm using:</p>
<pre><code>getWindow().setBackgroundDrawableResource(R.drawable.mainbg_);
overridePendingTransition (R.anim.push_up_in,0);
</code></pre> | 6,468,734 | 6 | 0 | null | 2011-06-24 13:18:12.957 UTC | 10 | 2022-03-11 16:11:19.13 UTC | 2022-03-11 16:11:19.13 UTC | null | 10,749,567 | null | 644,182 | null | 1 | 37 | android|android-activity|android-animation|android-drawable|android-transitions | 27,554 | <p>set the theme of that activity as transluscent in manifest file</p>
<pre><code>android:theme="@android:style/Theme.Translucent"
</code></pre>
<p>so your code will be something like this</p>
<pre><code><activity android:name=".AdActivity"
android:theme="@android:style/Theme.Translucent" />
</code></pre> |
6,992,793 | Is there any benefit in using PHP comments over HTML comments in HTML code? | <p>I heard someone say that there is, so I was wondering.</p>
<p>HTML comment:</p>
<pre><code><!-- Comment goes here. -->
</code></pre>
<p>PHP comment:</p>
<pre><code><?php // Comment goes here. ?>
</code></pre> | 6,992,816 | 6 | 2 | null | 2011-08-09 07:29:46.597 UTC | 0 | 2021-09-29 07:40:45.327 UTC | 2013-01-05 17:42:32.197 UTC | null | 200,145 | null | 200,145 | null | 1 | 44 | php|html|comments | 2,799 | <p>Unlike HTML comments, PHP comments don't show up in the final output. That is often desirable, as comments are usually internal notes that are none of anybody's business.</p> |
6,597,967 | .Net Coding Standards Using a prefix "Is" or "Has" on Method Names | <p>Is it advisable to prefix an "<em>Is</em>" or a "<em>Has</em>" when creating a method that returns a Boolean. My feeling is that this practice is more suited to defining property names. </p>
<p>Say, we have a method like the following has some logic:</p>
<pre><code>bool IsActivePage()
{
// Some logic to determine if the page is active...
}
</code></pre>
<p>Would it be more preferable to rename the method to <em>GetActivePageStatus</em> and then create a boolean property <em>IsActivePage</em> that returns the result of that method.</p>
<p>What is the .NET standard? All opinions will be appreciated?</p> | 6,598,131 | 7 | 3 | null | 2011-07-06 14:22:34.453 UTC | 8 | 2020-01-22 19:57:06.58 UTC | 2011-07-06 14:29:42.603 UTC | null | 96,780 | null | 477,097 | null | 1 | 28 | c#|.net|coding-style | 10,950 | <p>The <a href="http://msdn.microsoft.com/en-us/library/ms229012.aspx" rel="noreferrer">Framework Design Guidelines</a> state that you should "give methods names that are verbs or verb phrases" since "typically methods act on data". <em>Properties</em>, on the other hand, should be named "using a noun, noun phrase, or an adjective" and "you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value".</p>
<p>In this case, you are using a method rather than a property, probably since it is either expensive or has some side effects. I suggest you choose the name that provides the most clarity of what the returned value represents. The important part is that you're being consistent and that you're not confusing other developers with your convention.</p> |
6,585,417 | Stored procedure slow when called from web, fast from Management Studio | <p>I have stored procedure that insanely times out every single time it's called from the web application.</p>
<p>I fired up the Sql Profiler and traced the calls that time out and finally found out these things: </p>
<ol>
<li>When executed the statements from within the MS SQL Management Studio, with same arguments (in fact, I copied the procedure call from sql profile trace and ran it): It finishes in 5~6 seconds avg. </li>
<li>But when called from web application, it takes in excess of 30 seconds (in trace) so my webpage actually times out by then. </li>
</ol>
<p>Apart from the fact that my web application has its own user, every thing is same (same database, connection, server etc)
I also tried running the query directly in the studio with the web application's user and it doesn't take more than 6 sec.</p>
<p>How do I find out what is happening? </p>
<p>I am assuming it has nothing to do with the fact that we use BLL > DAL layers or Table adapters as the trace clearly shows the delay is in the actual procedure. That is all I can think of.</p>
<p><strong>EDIT</strong> I found out in <a href="http://aspadvice.com/blogs/ssmith/archive/2008/02/15/Stored-Procedure-Performance-Varies-Between-ADO.NET-and-Management-Studio.aspx" rel="noreferrer">this link</a> that ADO.NET sets <code>ARITHABORT</code> to true - which is good for most of the time but sometime this happens, and the suggested work-around is to add <code>with recompile</code> option to the stored proc. In my case, it's not working but I suspect it's something very similar to this. Anyone knows what else ADO.NET does or where I can find the spec?</p> | 6,586,281 | 8 | 7 | null | 2011-07-05 15:46:50.66 UTC | 43 | 2021-06-04 11:31:07.337 UTC | 2017-09-19 01:23:19.053 UTC | null | 3,885,376 | null | 363,674 | null | 1 | 109 | asp.net|sql-server-2008|stored-procedures | 78,176 | <p>I've had a similar issue arise in the past, so I'm eager to see a resolution to this question. Aaron Bertrand's comment on the OP led to <a href="https://stackoverflow.com/questions/2248112/sql-server-query-times-out-when-executed-from-web-but-super-fast-when-executed/">Query times out when executed from web, but super-fast when executed from SSMS</a>, and while the question is not a duplicate, the answer may very well apply to your situation.</p>
<p>In essence, it sounds like SQL Server may have a corrupt cached execution plan. You're hitting the bad plan with your web server, but SSMS lands on a different plan since there is a different setting on the ARITHABORT flag (which would otherwise have no impact on your particular query/stored proc).</p>
<p>See <a href="https://stackoverflow.com/questions/834124/ado-net-calling-t-sql-stored-procedure-causes-a-sqltimeoutexception/839055#839055">ADO.NET calling T-SQL Stored Procedure causes a SqlTimeoutException</a> for another example, with a more complete explanation and resolution.</p> |
6,904,825 | Deserialize JSON to anonymous object | <p>In C#, I have successfully serialized an anonymous object into JSON by use of code like this...</p>
<pre><code>var obj = new { Amount = 108, Message = "Hello" };
JavaScriptSerializer serializer = new JavaScriptSerializer();
String output = serializer.Serialize(obj);
</code></pre>
<p>However, what I would like to be able to do later is to deserialize the JSON string back into an anonymous object. Something like this...</p>
<pre><code>var obj2 = serializer.Deserialize(output, object);
</code></pre>
<p>But the serializer.Deserialize() method requires a second parameter that is the type of object it will deserialize to.</p>
<p>I tried this...</p>
<pre><code>var obj2 = serializer.Deserialize(output, obj.GetType());
</code></pre>
<p>But this produces an error:</p>
<blockquote>
<p>No parameterless constructor defined for type of '<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.</p>
</blockquote>
<p>I'm not sure what this error means.</p> | 6,905,037 | 9 | 1 | null | 2011-08-01 21:43:03.727 UTC | 13 | 2022-03-11 14:14:04.037 UTC | 2022-02-24 08:03:46.29 UTC | null | 326,820 | null | 410,167 | null | 1 | 64 | c#|asp.net|json | 93,725 | <p><a href="http://james.newtonking.com/pages/json-net.aspx" rel="noreferrer"><strong>JSON.Net</strong></a> is a powerful library to work with JSON in .Net</p>
<p>There's a method <a href="http://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm" rel="noreferrer">DeserializeAnonymousType</a> you can tap in to.</p>
<p><strong><em>Update</em></strong>: Json.Net is now included with ASP.Net, however my latest favorite that I use is <a href="https://github.com/jsonfx/jsonfx" rel="noreferrer"><strong>JsonFX</strong></a>. It's got great linq support as well, check it out.</p>
<p><strong><em>Update 2</em></strong>: I've moved on from JsonFX, and currently use <a href="https://github.com/ServiceStack/ServiceStack.Text" rel="noreferrer"><strong>ServiceStack.Text</strong></a>, it's fast!</p> |
15,776,365 | HTML Best Practices: Should I use ’ or the special keyboard shortcut? | <p>I know that <code>&rsquo;</code> will produce an apostrophe in an HTML document.</p>
<p>I also know that <code>option shift right bracket</code> on a Mac will simply produce a <code>’</code> character.</p>
<p>Are there best practices for writing code, e.g., should I write</p>
<pre><code><b>The User&rsquo;s Forum</b>
</code></pre>
<p>or</p>
<pre><code><b>The User’s Forum</b>
</code></pre>
<p>(note that by using the keyboard shortcut I've been able to type <code>’</code> instead of <code>'</code> above)</p>
<p>It strikes me that the latter (using the keyboard shortcut) is more robust, as it's not likely to display the raw HTML if, for example, it's not escaped.</p>
<p>On the other hand, the special ’ character may not be readable in some browsers, perhaps(?).</p>
<p>Anyone have any best practices on this?</p> | 15,776,551 | 6 | 5 | null | 2013-04-02 23:38:21.91 UTC | 13 | 2020-11-04 07:42:33.563 UTC | null | null | null | null | 2,238,214 | null | 1 | 54 | html|apostrophe|smart-quotes | 159,916 | <p>I don't think that one is better than the other in general; it depends on how you intend to use it.</p>
<ul>
<li>If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (<code>&rsquo;</code>).</li>
<li>If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.</li>
<li>If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity</li>
<li>If you need to convert the file between various character encodings or formats, you may want to use the entity</li>
<li>If your HTML code may escape entities improperly, you may want to use the character.</li>
</ul>
<p>In general I would lean more towards using the character because as you point out it is easier to read and type.</p> |
15,673,889 | Correct usage of rvalue references as parameters | <p>Let's take the following method as an example:</p>
<pre><code>void Asset::Load( const std::string& path )
{
// complicated method....
}
</code></pre>
<p>General use of this method would be as follows:</p>
<pre><code>Asset exampleAsset;
exampleAsset.Load("image0.png");
</code></pre>
<p>Since we know most of the time the Path is a temporary rvalue, does it make sense to add an Rvalue version of this method? And if so, is this a correct implementation;</p>
<pre><code>void Asset::Load( const std::string& path )
{
// complicated method....
}
void Asset::Load( std::string&& path )
{
Load(path); // call the above method
}
</code></pre>
<p>Is this a correct approach to writing rvalue versions of methods?</p> | 15,674,543 | 6 | 0 | null | 2013-03-28 03:43:08.53 UTC | 27 | 2021-10-20 07:31:27.74 UTC | 2020-05-02 20:51:04.95 UTC | null | 72,178 | null | 965,619 | null | 1 | 69 | c++|c++11|rvalue-reference | 49,816 | <p>For your particular case, the second overload is useless.</p>
<p>With the original code, which has just one overload for <code>Load</code>, this function is called for lvalues and rvalues.</p>
<p>With the new code, the first overload is called for lvalues and the second is called for rvalues. However, the second overload calls the first one. At the end, the effect of calling one or the other implies that the same operation (whatever the first overload does) will be performed.</p>
<p>Therefore, the effects of the original code and the new code are the same but the first code is just simpler.</p>
<p>Deciding whether a function must take an argument by value, lvalue reference or rvalue reference depends very much on what it does. You should provide an overload taking rvalue references when you want to move the passed argument. There are several good <a href="https://stackoverflow.com/questions/3106110/what-are-move-semantics">references</a> on move semantincs out there, so I won't cover it here.</p>
<p><strong>Bonus</strong>:</p>
<p>To help me make my point consider this simple <code>probe</code> class:</p>
<pre><code>struct probe {
probe(const char* ) { std::cout << "ctr " << std::endl; }
probe(const probe& ) { std::cout << "copy" << std::endl; }
probe(probe&& ) { std::cout << "move" << std::endl; }
};
</code></pre>
<p>Now consider this function:</p>
<pre><code>void f(const probe& p) {
probe q(p);
// use q;
}
</code></pre>
<p>Calling <code>f("foo");</code> produces the following output:</p>
<pre><code>ctr
copy
</code></pre>
<p>No surprises here: we create a temporary <code>probe</code> passing the <code>const char*</code> <code>"foo"</code>. Hence the first output line. Then, this temporary is bound to <code>p</code> and a copy <code>q</code> of <code>p</code> is created inside <code>f</code>. Hence the second output line.</p>
<p>Now, consider taking <code>p</code> by value, that is, change <code>f</code> to:</p>
<pre><code>void f(probe p) {
// use p;
}
</code></pre>
<p>The output of <code>f("foo");</code> is now</p>
<pre><code>ctr
</code></pre>
<p>Some will be surprised that in this case: there's no copy! In general, if you take an argument by reference and copy it inside your function, then it's better to take the argument by value. In this case, instead of creating a temporary and copying it, the compiler can construct the argument (<code>p</code> in this case) direct from the input (<code>"foo"</code>). For more information, see <a href="http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">Want Speed? Pass by Value.</a> by Dave Abrahams.</p>
<p>There are two notable exceptions to this guideline: constructors and assignment operators. </p>
<p>Consider this class:</p>
<pre><code>struct foo {
probe p;
foo(const probe& q) : p(q) { }
};
</code></pre>
<p>The constructor takes a <code>probe</code> by const reference and then copy it to <code>p</code>. In this case, following the guideline above doesn't bring any performance improvement and <code>probe</code>'s copy constructor will be called anyway. However, taking <code>q</code> by value might create an overload resolution issue similar to the one with assignment operator that I shall cover now.</p>
<p>Suppose that our class <code>probe</code> has a non-throwing <code>swap</code> method. Then the suggested implementation of its assignment operator (thinking in C++03 terms for the time being) is</p>
<pre><code>probe& operator =(const probe& other) {
probe tmp(other);
swap(tmp);
return *this;
}
</code></pre>
<p>Then, according to the guideline above, it's better to write it like this</p>
<pre><code>probe& operator =(probe tmp) {
swap(tmp);
return *this;
}
</code></pre>
<p>Now enter C++11 with rvalue references and move semantics. You decided to add a move assignment operator:</p>
<pre><code>probe& operator =(probe&&);
</code></pre>
<p>Now calling the assignment operator on a temporary creates an ambiguity because both overloads are viable and none is preferred over the other. To resolve this issue, use the original implementation of the assignment operator (taking the argument by const reference).</p>
<p>Actually, this issue is not particular to constructors and assignment operators and might happen with any function. (It's more likely that you will experience it with constructors and assignment operators though.) For instance, calling <code>g("foo");</code> when <code>g</code> has the following two overloads raises the ambiguity:</p>
<pre><code>void g(probe);
void g(probe&&);
</code></pre> |
15,859,113 | $.focus() not working | <p>The <a href="http://api.jquery.com/focus/" rel="noreferrer">last example of jQuery's <code>focus()</code> documentation</a> states</p>
<pre><code>$('#id').focus()
</code></pre>
<p>should make the input focused (active). I can't seem to get this working.</p>
<p>Even in the console on this site, I'm trying it for the search box</p>
<pre><code>$('input[name="q"]').focus()
</code></pre>
<p>and I'm getting nothing. Any ideas?</p> | 15,859,155 | 20 | 6 | null | 2013-04-07 05:12:39.457 UTC | 27 | 2022-08-16 15:56:23.78 UTC | null | null | null | null | 1,406,664 | null | 1 | 194 | jquery | 234,434 | <p>Actually the example you gave for focusing on this site works just fine, as long as you're not focused in the console. The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box:</p>
<pre><code>setTimeout(function() { $('input[name="q"]').focus() }, 3000);
</code></pre>
<p>As for your other one, the one thing that has given me trouble in the past is order of events. You cannot call focus() on an element that hasn't been attached to the DOM. Has the element you are trying to focus already been attached to the DOM?</p> |
50,549,611 | Slicing a vector in C++ | <p>Is there an equivalent of list slicing <code>[1:]</code> from Python in C++ with vectors? I simply want to get all but the first element from a vector.</p>
<p>Python's list slicing operator:</p>
<pre><code>list1 = [1, 2, 3]
list2 = list1[1:]
print(list2) # [2, 3]
</code></pre>
<p>C++ Desired result:</p>
<pre><code>std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2;
v2 = v1[1:];
std::cout << v2 << std::endl; //{2, 3}
</code></pre> | 50,549,636 | 6 | 6 | null | 2018-05-27 06:30:07.253 UTC | 12 | 2022-03-30 09:31:14.193 UTC | 2021-07-16 03:09:18.29 UTC | null | 5,376,789 | null | 9,620,849 | null | 1 | 70 | python|c++|vector|slice | 67,347 | <p>This can easily be done using <code>std::vector</code>'s copy constructor:</p>
<pre><code>v2 = std::vector<int>(v1.begin() + 1, v1.end());
</code></pre> |
10,275,769 | BigInteger.toString method is deleting leading 0 | <p>I am trying to generate MD5 sum using MessageDigest.
And i am having following code. </p>
<pre><code>byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
output = bigInt.toString(16);
</code></pre>
<p>This returns not 32 character string but a 31 character string <code>8611c0b0832bce5a19ceee626a403a7</code></p>
<p>Expected String is <code>08611c0b0832bce5a19ceee626a403a7</code></p>
<p>Leading 0 is missing in the output.</p>
<p>I tried the other method </p>
<pre><code>byte[] md5sum = digest.digest();
output = new String(Hex.encodeHex(md5sum));
</code></pre>
<p>And the output is as expected.</p>
<p>I checked the doc and Integer.toString does the conversion according to it</p>
<blockquote>
<p>The digit-to-character mapping provided by Character.forDigit is
used, and a minus sign is prepended if appropriate.</p>
</blockquote>
<p>and in Character.forDigit methos</p>
<blockquote>
<p>The digit argument is valid if 0 <=digit < radix.</p>
</blockquote>
<p>Can some one tell me how two methods are different and why leading 0 is deleted?</p> | 10,275,845 | 5 | 5 | null | 2012-04-23 06:24:47.857 UTC | 6 | 2021-10-21 09:58:35.033 UTC | 2012-04-23 06:39:43.193 UTC | null | 818,557 | null | 446,976 | null | 1 | 31 | java|tostring|biginteger | 18,041 | <p>I would personally <em>avoid</em> using <code>BigInteger</code> to convert binary data to text. That's not really what it's there for, even if it <em>can</em> be used for that. There's loads of code available to convert a <code>byte[]</code> to its hex representation - e.g. using <a href="http://commons.apache.org/codec/">Apache Commons Codec</a> or a simple single method:</p>
<pre><code>private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
public static String toHex(byte[] data) {
char[] chars = new char[data.length * 2];
for (int i = 0; i < data.length; i++) {
chars[i * 2] = HEX_DIGITS[(data[i] >> 4) & 0xf];
chars[i * 2 + 1] = HEX_DIGITS[data[i] & 0xf];
}
return new String(chars);
}
</code></pre> |
31,876,372 | What is reification? | <p>I know that Java implements parametric polymorphism (Generics) with erasure. I understand what erasure is.</p>
<p>I know that C# implements parametric polymorphism with reification. I know that can make you write</p>
<pre><code>public void dosomething(List<String> input) {}
public void dosomething(List<Int> input) {}
</code></pre>
<p>or that you can know at runtime what the type parameter of some parameterised type is, but I don't understand what it <em>is</em>.</p>
<ul>
<li>What is a reified type?</li>
<li>What is a reified value?</li>
<li>What happens when a type/value is reified?</li>
</ul> | 31,876,747 | 4 | 4 | null | 2015-08-07 11:13:14.837 UTC | 63 | 2022-09-23 20:18:12.143 UTC | 2015-08-21 18:18:49.13 UTC | null | 1,783,619 | null | 381,801 | null | 1 | 175 | c#|generics|reification | 16,034 | <p>Reification is the process of taking an abstract thing and creating a concrete thing.</p>
<p>The term <em>reification</em> in C# generics refers to the process by which a <a href="https://stackoverflow.com/questions/2564745/what-is-the-difference-between-a-generic-type-and-a-generic-type-definition"><em>generic type definition</em></a> and one or more <em>generic type arguments</em> (the abstract thing) are combined to create a new <em>generic type</em> (the concrete thing).</p>
<p>To phrase it differently, it is the process of taking the definition of <code>List<T></code> and <code>int</code> and producing a concrete <code>List<int></code> type.</p>
<p>To understand it further, compare the following approaches:</p>
<ul>
<li><p>In Java generics, a generic type definition is transformed to essentially one concrete generic type shared across all allowed type argument combinations. Thus, multiple (source code level) types are mapped to one (binary level) type - but as a result, <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer">information about the type arguments of an instance is discarded in that instance (type erasure)</a>.</p>
<ol>
<li>As a side effect of this implementation technique, the only generic type arguments that are natively allowed are those types that can share the binary code of their concrete type; which means those types whose storage locations have interchangeable representations; which means reference types. <a href="https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html" rel="noreferrer">Using value types as generic type arguments requires boxing them</a> (placing them in a simple reference type wrapper).</li>
<li>No code is duplicated in order to implement generics this way.</li>
<li>Type information that could have been available at runtime (using reflection) is lost. This, in turn, means that specialization of a generic type (the ability to use specialized <em>source code</em> for any particular generic argument combination) is very restricted.</li>
<li>This mechanism doesn't require support from the runtime environment.</li>
<li>There are a few <a href="https://softwareengineering.stackexchange.com/questions/280169/if-scala-runs-on-the-jvm-how-can-scala-do-things-that-java-seemingly-cannot/280189#280189">workarounds to retain type information</a> that a Java program or a JVM-based language can use.</li>
</ol></li>
<li><p>In C# generics, the generic type definition is maintained in memory at runtime. Whenever a new concrete type is required, the runtime environment combines the generic type definition and the type arguments and creates the new type (reification). So we get a new type for each combination of the type arguments, <em>at runtime</em>. </p>
<ol>
<li>This implementation technique allows any kind of type argument combination to be instantiated. Using value types as generic type arguments does not cause boxing, since these types get their own implementation. (<a href="https://stackoverflow.com/questions/2111857/why-do-we-need-boxing-and-unboxing-in-c">Boxing still exists in C#</a>, of course - but it happens in other scenarios, not this one.)</li>
<li>Code duplication could be an issue - but in practice it isn't, because sufficiently smart implementations (<a href="http://blogs.msdn.com/b/carlos/archive/2009/11/09/net-generics-and-code-bloat-or-its-lack-thereof.aspx" rel="noreferrer">this includes Microsoft .NET</a> and <a href="http://www.mono-project.com/docs/advanced/runtime/docs/generic-sharing/" rel="noreferrer">Mono</a>) can share code for some instantiations.</li>
<li>Type information is maintained, which allows specialization to an extent, by examining type arguments using reflection. However, the degree of specialization is limited, as a result of the fact that a generic type definition is compiled <em>before</em> any reification happens (this is done by <a href="https://stackoverflow.com/questions/11436802/how-are-c-sharp-generics-implemented">compiling the definition against the constraints on the type parameters</a> - thus, <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx" rel="noreferrer">the compiler has to be able "understand" the definition even in the absence of specific type arguments</a>).</li>
<li>This implementation technique depends heavily on runtime support and JIT-compilation (which is why you often hear that <a href="http://developer.xamarin.com/guides/ios/advanced_topics/limitations/" rel="noreferrer">C# generics have some limitations on platforms like iOS</a>, where dynamic code generation is restricted).</li>
<li>In the context of C# generics, reification is done for you by the runtime environment. However, if you want to more intuitively understand the difference between a generic type definition and a concrete generic type, <a href="https://msdn.microsoft.com/en-us/library/ms131508(v=vs.110).aspx" rel="noreferrer">you can always perform a reification on your own, using the <code>System.Type</code> class</a> (even if the particular generic type argument combination you're instantiating didn't appear in your source code directly).</li>
</ol></li>
<li><p>In C++ templates, the template definition is maintained in memory at compile time. Whenever a new instantiation of a template type is required in the source code, the compiler combines the template definition and the template arguments and creates the new type. So we get a unique type for each combination of the template arguments, <em>at compile time</em>.</p>
<ol>
<li>This implementation technique allows any kind of type argument combination to be instantiated. </li>
<li>This is known to duplicate binary code but a sufficiently smart tool-chain could still detect this and share code for some instantiations.</li>
<li>The template definition itself is not "compiled" - <a href="https://msdn.microsoft.com/en-us/library/c6cyy67b.aspx" rel="noreferrer">only its concrete instantiations are actually compiled</a>. This places fewer constraints on the compiler and allows a greater degree of <a href="http://www.cprogramming.com/tutorial/template_specialization.html" rel="noreferrer">template specialization</a>.</li>
<li>Since template instantiations are performed at compile time, no runtime support is needed here either.</li>
<li>This process is lately referred to as <a href="https://stackoverflow.com/questions/14189604/what-is-monomorphisation-with-context-to-c"><em>monomorphization</em></a>, especially in the Rust community. The word is used in contrast to <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism" rel="noreferrer"><em>parametric polymorphism</em></a>, which is the name of the concept that generics come from.</li>
</ol></li>
</ul> |
53,103,148 | Services and ViewModels in Android MVVM - How do they interact? | <p>I've been using ViewModels from Android Architecture for some time now, and abide by never exposing the ViewModel to Context/Views (Android Framework/UI). However, recently I have run into an interesting problem.</p>
<p>When making a timer app, when a timer is started, a Service is run in the background running the timer. This way, when the application is closed, the timer still runs in the foreground in the notification bar until all timers have ceased. However, this means that all of my Timer objects and state are contained in this Service. My UI needs to be updated on each tick, but the Model doesn't necessarily need updated <strong>How do ViewModels fit in with this scenario?</strong> </p>
<p>Should the Activity receive LocalBroadcasts and notify the ViewModel every time?
Should the UI state be read from Service->Activity->VM? It almost seems like the Service is the ViewModel, but this doesn't seem efficient.</p> | 53,174,404 | 2 | 3 | null | 2018-11-01 14:19:01.627 UTC | 9 | 2020-07-05 03:34:56.847 UTC | 2018-11-01 14:30:06.157 UTC | null | 1,327,957 | null | 1,327,957 | null | 1 | 34 | android|mvvm|android-service|android-architecture-components | 14,193 | <p>After some toying with different structures, the Service has found it's place in MVVM. What was throwing me off in this situation was thinking a Service shouldn't be started from a ViewModel and the fact that two repositories were necessary: Room Database to store Timers and a Service to represent the state of ongoing timers (onTick, play/pause status, etc). A ViewModel should not have any reference to views, but application context is OK. So starting the Service from a ViewModel is doable by extending the <strong>AndroidViewModel</strong> class. Here is the final structure:</p>
<p><strong>Model Layer</strong></p>
<ul>
<li><strong><em>Service</em></strong> - Maintains a list of active timers, emits onTick() EventBus events, maintains active timer play/pause status. Ends itself once there are no active timers.</li>
<li><strong><em>Room Database</em></strong> - Stores timers for future use (name, total time, etc.)</li>
</ul>
<p><strong>ViewModel</strong></p>
<ul>
<li><strong><em>ViewModel</em></strong> - Listens for UI events, performs business logic, and emits EventBus posts. Any change in Model is communicated through the ViewModel</li>
</ul>
<p><strong>UI</strong></p>
<ul>
<li><strong><em>Activity</em></strong> - performs application flow tasks. Listens for relevant ViewModel communications to swap fragments/start new activities, etc.</li>
<li><strong><em>Fragment</em></strong> - handles animations and UI. Also notifies ViewModel of user interaction</li>
</ul> |
13,326,806 | Enable USB debugging through Clockworkmod with adb | <p>So, a few days ago my Nexus 7 got dropped, and now there's a big crack in the screen. The touchscreen is broken. That is, I can still see what happens, but it is unresponsive. <br>
I have found a way to completely control it through adb, and through this I rooted it. <br>
However, rooting it wiped all my data and settings, including USB debugging. The result is that I can't control it anymore at all, other than turning it off and changing volume. <br>
Clockworkmod has adb built in. I can fully control CWM from my pc, and access my tablet's files etc. <br>
<br>
Now my question is, is it possible to enable USB debugging through Clockworkmod with adb or any other method, and if yes, how? <br>
I do have root access to all files and settings, and I am able to get any needed binary file on it, be it a native Android file, a Cyanogenmod file, any native ARM Linux binary, or something else (think sqlite3 for example). <br>
I also have an <code>adb backup -all -system</code> backup on my pc, but I can't restore it through CWM as far as I can see. <br>
I have access to both Linux and Windows.<br>
<br>
Update: I have tried enabling adb in <code>/data/data/com.android.providers.settings/databases/settings.db</code> with sqlite3, but after a reboot the value of <code>adb_enabled</code> was deleted and reinserted at the bottom, with value 0. However some other setting I changed did persist. <br>
I have also tried to modify /init.rc, but this file is also being rewritten on boot it seems.</p> | 13,332,721 | 2 | 3 | null | 2012-11-10 22:47:08.203 UTC | 11 | 2012-11-11 15:46:52.51 UTC | 2012-11-11 02:41:14.353 UTC | null | 1,488,308 | null | 1,488,308 | null | 1 | 19 | android|adb|root|touchscreen|nexus-7 | 97,503 | <p>Well, as far as I know, You can try doing this:</p>
<ul>
<li>Run an ADB shell in ClockworkMod</li>
<li>Remount /system in readwrite mode.</li>
<li>Add this to /system/build.prop: <b>persist.service.adb.enable=1</b></li>
<li>Save the file.</li>
</ul> |
13,469,803 | PHP - Merging two arrays into one array (also Remove Duplicates) | <p>Hi I'm Trying to merge two arrays and also want to remove duplicate values from final Array.</p>
<p>Here is my Array 1:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
</code></pre>
<p>And this is my array 2:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
</code></pre>
<p>I'm using <code>array_merge</code> for merging both arrays into one array. it is giving output like this</p>
<pre><code>Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
[1] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
</code></pre>
<p>I want to remove these duplicate entries or can I remove these before merging...
Pleas help..
Thanks!!!!!!!</p> | 13,469,882 | 8 | 4 | null | 2012-11-20 09:10:01.66 UTC | 23 | 2021-03-01 09:12:23.867 UTC | 2017-12-28 12:09:11.837 UTC | null | 6,868,227 | null | 1,550,566 | null | 1 | 125 | php|arrays|wordpress|multidimensional-array | 133,637 | <pre><code>array_unique(array_merge($array1,$array2), SORT_REGULAR);
</code></pre>
<p><a href="http://se2.php.net/manual/en/function.array-unique.php">http://se2.php.net/manual/en/function.array-unique.php</a></p> |
20,374,083 | Deserialize json array stream one item at a time | <p>I serialize an array of large objects to a json http response stream. Now I want to deserialize these objects from the stream one at a time. Are there any c# libraries that will let me do this? I've looked at json.net but it seems I'd have to deserialize the complete array of objects at once.</p>
<pre><code>[{large json object},{large json object}.....]
</code></pre>
<p>Clarification: I want to read one json object from the stream at a time and deserialize it.</p> | 20,386,292 | 4 | 3 | null | 2013-12-04 11:26:01.337 UTC | 15 | 2019-02-15 23:33:32.893 UTC | 2013-12-04 12:25:41.25 UTC | null | 475,807 | null | 475,807 | null | 1 | 39 | c#|json|serialization|stream|json.net | 27,576 | <p>In order to read the JSON incrementally, you'll need to use a <code>JsonTextReader</code> in combination with a <code>StreamReader</code>. But, you don't necessarily have to read all the JSON manually from the reader. You should be able to leverage the Linq-To-JSON API to load each large object from the reader so that you can work with it more easily.</p>
<p>For a simple example, say I had a JSON file that looked like this:</p>
<pre><code>[
{
"name": "foo",
"id": 1
},
{
"name": "bar",
"id": 2
},
{
"name": "baz",
"id": 3
}
]
</code></pre>
<p>Code to read it incrementally from the file might look something like the following. (In your case you would replace the FileStream with your response stream.)</p>
<pre><code>using (FileStream fs = new FileStream(@"C:\temp\data.json", FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader reader = new JsonTextReader(sr))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
// Load each object from the stream and do something with it
JObject obj = JObject.Load(reader);
Console.WriteLine(obj["id"] + " - " + obj["name"]);
}
}
}
</code></pre>
<p>Output of the above would look like this:</p>
<pre><code>1 - foo
2 - bar
3 - baz
</code></pre> |
24,379,601 | How to make an HTTP request + basic auth in Swift | <p>I have a RESTFull service with basic authentication and I want to invoke it from iOS+swift. How and where I must provide Credential for this request?</p>
<p>My code (sorry, I just start learn iOS/obj-c/swift):</p>
<pre><code>class APIProxy: NSObject {
var data: NSMutableData = NSMutableData()
func connectToWebApi() {
var urlPath = "http://xx.xx.xx.xx/BP3_0_32/ru/hs/testservis/somemethod"
NSLog("connection string \(urlPath)")
var url: NSURL = NSURL(string: urlPath)
var request = NSMutableURLRequest(URL: url)
let username = "hs"
let password = "1"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromMask(0))
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self)
connection.start()
}
//NSURLConnection delegate method
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
println("Failed with error:\(error.localizedDescription)")
}
//NSURLConnection delegate method
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//New request so we need to clear the data object
self.data = NSMutableData()
}
//NSURLConnection delegate method
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
//Append incoming data
self.data.appendData(data)
}
//NSURLConnection delegate method
func connectionDidFinishLoading(connection: NSURLConnection!) {
NSLog("connectionDidFinishLoading");
}
}
</code></pre> | 24,380,884 | 9 | 2 | null | 2014-06-24 06:20:14.433 UTC | 41 | 2022-03-18 06:10:40.84 UTC | 2021-07-28 13:24:08.903 UTC | null | 921,573 | null | 2,618,519 | null | 1 | 115 | ios|swift | 125,667 | <p>You provide credentials in a <code>URLRequest</code> instance, like this in Swift 3:</p>
<pre><code>let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
</code></pre>
<p>Or in an <code>NSMutableURLRequest</code> in Swift 2:</p>
<pre><code>// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
</code></pre> |
16,349,884 | Updating package with Bower | <p>I am trying to update angular 1.0.5 to 1.0.6. I use Yeoman, and when try to update it is installing 1.0.5. I cleared the cache (removed everything from ~/.bower), still get the below log. I checked the <a href="https://github.com/angular/bower-angular/blob/master/angular.js" rel="noreferrer">repo</a>, and it has 1.0.6. Is there a way I can make it update to 1.0.6.</p>
<pre><code>bower update angular
bower cloning git://github.com/angular/bower-angular.git
..
bower installing angular#v1.0.5
bower info angular
angular
Versions:
- v1.0.6
- v1.0.5
- v1.0.4
- v1.0.3
$ bower --version
0.8.5
yo --version
1.0.0-beta.3
</code></pre> | 16,356,149 | 2 | 2 | null | 2013-05-03 00:38:45.263 UTC | 1 | 2016-02-26 05:04:04.09 UTC | 2015-02-25 00:09:49.383 UTC | null | 31,671 | null | 303,477 | null | 1 | 44 | javascript|angularjs|bower | 51,713 | <p>You have to upgrade to latest version of Bower: <code>npm update -g bower</code></p>
<p>bower-angular 1.0.6 switched from component.json to bower.json which is only supported in Bower >=0.9.0</p> |
11,398,397 | Oracle - How to use merge to update a column based on the values from other table and columns | <p>I would like to update the values in closed_date column based on the values comparison from other columns and other table. I used Oracle merge into statement. But it gave me an error:</p>
<p>Error: ORA-00969: missing ON keyword</p>
<p>I am not sure what goes wrong. Do I miss anything? Below is my script:</p>
<pre><code>MERGE INTO PR_DMN dmn
USING (select alg.PR_DMN_ID, alg.PR_ACTIVITY_ID, alg.ACTIVITY_TS from PR_ACTIVITY_LOG) alg
ON dmn.PR_DMN_ID = alg.PR_DMN_ID
-- update
WHEN MATCHED THEN
UPDATE SET dmn.CLOSED_DATE =
(CASE
WHEN alg.PR_ACTIVITY_ID IN ('10009', '10010', '10011', '10013') THEN alg.ACTIVITY_TS
WHEN alg.PR_ACTIVITY_ID = '10005' AND dmn.CONT_RESP_TS <= dmn.CONT_RESP_DUE_TS THEN dmn.CONT_RESP_TS
WHEN alg.PR_ACTIVITY_ID = '10008' AND dmn.CORR_RESP_TS <= dmn.CORR_RESP_DUE_TS THEN dmn.CORR_RESP_TS
ELSE dmn.CLOSED_DATE
END)
</code></pre> | 11,400,052 | 1 | 3 | null | 2012-07-09 15:36:21.403 UTC | null | 2012-07-17 10:00:02.837 UTC | 2012-07-17 10:00:02.837 UTC | null | 966,703 | null | 1,279,486 | null | 1 | 4 | sql|oracle | 38,344 | <p>You have two errors, as you can see with a simple example. Firstly the <code>on</code> clause needs to be wrapped in parenthesis. Secondly, you can't reference the alias of the sub-select in the <code>using</code> clause within that sub-query.</p>
<p>If I set up a simple example using your table names as follows:</p>
<pre><code>create table pr_dmn as
select level as a, sysdate as b
from dual
connect by level <= 10;
Table created.
create table PR_ACTIVITY_LOG as
select level as a, sysdate as b
from dual
connect by level <= 20;
Table created.
</code></pre>
<p>Then execute the correct query it should work:</p>
<pre><code>merge into pr_dmn dmn
using (select a, b from pr_activity_log) alg -- no alg. inside the sub-query
on (dmn.a = alg.a) -- wrapped in parenthesis
when matched then
update set dmn.b = alg.b
;
10 rows merged.
</code></pre>
<p>I always find <a href="http://psoug.org/reference/merge.html" rel="noreferrer">PSOUG</a> a good reference for things like this, though the <a href="http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9016.htm#SQLRF01606" rel="noreferrer">documentation</a> has some good examples as well.</p> |
15,469,284 | JPA, custom query and dates | <p>I'm facing a strange issue. I've search including here in stack overflow and for JPA and Custom query I should specified the parameter. So I have a query string since I have over 14 fields but I'm facing issues with the dates. I'm always getting the IllegalStateException</p>
<pre><code>INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > :startDate AND t.enddate < :endDate ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalStateException: Query argument startDate not found in the list of parameters provided during query execution.
</code></pre>
<p>as for my query:</p>
<pre><code>Query q = em.createQuery(query).setParameter("startDate", startDate, TemporalType.TIMESTAMP).setParameter("endDate", endDate, TemporalType.DATE);
</code></pre>
<p>Although I'm getting that the parameter is not found, I have it in the setParameter and also set in the query as seen in the INFO line.</p>
<p>Any ideas?</p>
<p>Thanks in advance</p>
<p>EDIT:</p>
<pre><code>INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > ?1 AND t.enddate < ?2 ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalStateException: Query argument 1 not found in the list of parameters provided during query execution.
q = em.createQuery(query).setParameter(1, startDate, TemporalType.TIMESTAMP).setParameter(2, endDate, TemporalType.TIMESTAMP);
</code></pre>
<p>Also and as advised, I've checked that the Date I'm using is java.util.Date. and in the entity class I have as Timestamp. But still I cannot have this working and not sure where I am failing.</p>
<p>Just to make sure that all the things are as they should, I forced the query to be string and I got the correct Exception:</p>
<pre><code>INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > :startDate AND t.enddate < :endDate ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalArgumentException: You have attempted to set a value of type class java.lang.String for parameter startDate with expected type of class java.util.Date
</code></pre>
<p>But then again, I change to date and it fails :S
I've checked the reasons for this IllegalStateException:</p>
<p>And from the debug and from the <a href="http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#getResultList%28%29" rel="nofollow">javadoc</a> I get the following:
getResultList</p>
<p><strong>IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement.</strong></p>
<p>I'm not doing a update nor delete :/</p>
<p>EDIT 2: Adding the Entity relevant part:</p>
<pre><code>@Basic(optional = false)
@NotNull
@Column(name = "startdate")
@Temporal(TemporalType.TIMESTAMP)
private Date startdate;
@Column(name = "enddate")
@Temporal(TemporalType.TIMESTAMP)
private Date enddate;
</code></pre>
<p>AS for the database creating script the columns are being created like this:</p>
<pre><code> startdate timestamp with time zone NOT NULL,
endate timestamp with time zone,
</code></pre>
<p>If I do a normal SQL query like:
"select * from tbl_tickets where startdate > '2012-02-01 00:00:00' and enddate < '2013-03-18 23:59:50'"</p>
<p>I get the desired results. I guess I could do with native query but that would be going around the problem and not fixing this issue, right?</p>
<p><strong>EDIT 3:</strong> Although I had everything set up properly, the init of the bean was calling again the query without the args ( sorry and thank you all for your help. It helped me checking what was amiss)</p> | 15,469,590 | 4 | 1 | null | 2013-03-18 03:23:14.697 UTC | 1 | 2013-03-19 01:17:27.023 UTC | 2013-03-19 01:17:27.023 UTC | null | 765,147 | null | 765,147 | null | 1 | 3 | java|datetime|jpa | 78,640 | <p>javadoc for both</p>
<pre><code>setParameter(String name, java.util.Date value, TemporalType temporalType)`
setParameter(String name, java.util.Calendar value, TemporalType temporalType)`
</code></pre>
<p>states:</p>
<blockquote>
<p>Throws: <code>IllegalArgumentException</code> - if the parameter name does not correspond to a parameter of the query or if the value argument is of incorrect type</p>
</blockquote>
<p>Since you didn't provide full code, verify that:</p>
<ul>
<li><p>Java value <code>startDate</code> is of type <code>java.util.Date</code> or <code>java.util.Calendar</code>.</p></li>
<li><p>SQL column <code>startDate</code> has valid SQL date type <code>TIMESTAMP</code>. </p></li>
</ul> |
17,213,293 | How to get R plot window size? | <p>How can I get the size of the plot window in R? I've been using xwininfo, but there must be a function or variable in R to extract the current plot height and width.</p>
<p><em>UPDATE</em></p>
<p>This works as a <code>savePlot()</code> replacement if you don't have Cairo support and you want to export plots to Windows or other 100 dpi devices:</p>
<pre><code>dev.copy(png, "myplot.png", width=dev.size("px")[1], height=dev.size("px")[2],
res=100, bg="transparent")
dev.off()
</code></pre> | 17,213,579 | 3 | 0 | null | 2013-06-20 12:08:14.067 UTC | 10 | 2014-06-11 06:41:56.863 UTC | 2014-06-11 06:41:56.863 UTC | null | 489,704 | null | 382,271 | null | 1 | 16 | r|plot | 17,650 | <p>You can use <code>dev.size</code>. Here is an example:</p>
<pre><code> x11()
plot(1)
dev.size("in")
[1] 6.989583 6.992017
dev.size("cm")
[1] 17.75354 17.75972
</code></pre>
<p>This gets the size of your plotting window in inches and centimeters. </p>
<p>Similar for a <code>png</code> device:</p>
<pre><code> png('kk.png')
dev.size("in")
[1] 6.666667 6.666667
</code></pre>
<p>Does this help you?</p> |
22,015,179 | Fatal error: Call to undefined function sqlsrv_connect() | <p>I have come across quite a few post regarding the same subject question, however I am still unable to resolve it and so I ask. I am trying to connect to sql in my php script. My connection string is:</p>
<pre><code>/* Specify the server and connection string attributes. */
$serverName = "xxx-PC\SQLExpress";
$connectionOptions = array("Database"=>"Salesforce");
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false)
{
die(print_r(sqlsrv_errors(), true));
}
</code></pre>
<p>I have installed and included the following in my <code>php.ini</code> file located under the wamp folder: <code>C:\wamp\bin\php\php5.4.16</code>:</p>
<pre><code>extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
</code></pre>
<p>My <code>wampserver</code> is running fine and so are the <code>wampapache</code> and <code>wampsqld</code> services. I am able to execute php.exe successfully. However I am unable to make the connection to <code>SQL Server 2008 R2</code> where my database is located. Please help!</p>
<p>EDIT 1: The wamp server is running the wampmysql service while I am trying to connect to <code>SQL Server 2008 R2</code>. Could this be the reason? Should I be using <code>MySQL</code> instead of <code>SQL</code>? Any pointers?</p>
<p>EDIT 2: I do not see <code>sqlsrv</code> section at all when I run <code>phpinfo()</code> though I have added <code>extension=php_sqlsrv_54_ts.dll</code> in the <code>php.ini</code> file located in the bin folder of the wamp server. </p>
<p><img src="https://i.stack.imgur.com/WAckT.png" alt="enter image description here"></p> | 22,043,692 | 8 | 2 | null | 2014-02-25 13:06:53.597 UTC | 4 | 2022-07-28 18:52:46.077 UTC | 2014-02-27 05:57:03.83 UTC | null | 1,478,133 | null | 1,478,133 | null | 1 | 36 | php|sql-server|wamp | 227,643 | <p><a href="https://stackoverflow.com/questions/14849010/fatal-error-call-to-undefined-function-pg-connect?rq=1">This</a> helped me get to my answer. There are two <code>php.ini</code> files located, in my case, for wamp. One is under the php folder and the other one is in the <code>C:\wamp\bin\apache\Apachex.x.x\bin</code> folder. When connecting to SQL through <code>sqlsrv_connect</code> function, we are referring to the <code>php.ini</code> file in the <code>apache</code> folder. Add the following (as per your version) to this file:</p>
<pre><code>extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
</code></pre> |
21,987,596 | Get CSS transform property with jQuery | <p>I'm trying to get the <code>-webkit-transform: translateY('')</code> property in a variable.</p>
<p>HTML</p>
<pre><code><form class="form-con" style="-webkit-transform: translateY(-802px);"></form>
</code></pre>
<p>JS</p>
<pre><code>$('.foo').click(function() {
var current_pull = parseInt($('.form-con').css('transform').split(',')[4]);
});
</code></pre>
<p>This is returning '0', instead of the correct value.</p> | 21,987,646 | 4 | 3 | null | 2014-02-24 12:20:09.053 UTC | 7 | 2017-03-06 08:49:33.68 UTC | null | null | null | null | 560,291 | null | 1 | 23 | javascript|jquery | 64,063 | <pre><code>$('.foo').click(function() {
var current_pull = parseInt($('.form-con').css('transform').split(',')[5]);
});
</code></pre> |
21,856,097 | How can I check JavaScript code for syntax errors ONLY from the command line? | <p>JavaScript programs can be checked for errors in IDEs or using <a href="https://stackoverflow.com/questions/5279226/how-to-check-client-side-javascript-code-for-errors">online web apps</a> but I'm looking for a way to detect syntax errors <em>alone</em>.</p>
<p>I've tried JSLint and JSHint and looked at their options but I haven't been able to find a combination that would exclude warnings and <a href="https://github.com/jshint/jshint/issues/1533" rel="noreferrer">just shows the syntax errors</a>.</p>
<p>How do I check JavaScript code <em>for syntax errors only</em> from the command line? </p> | 22,824,099 | 6 | 8 | null | 2014-02-18 14:00:40.293 UTC | 8 | 2021-10-05 13:23:31.847 UTC | 2017-05-23 12:17:38.603 UTC | null | -1 | null | 1,269,037 | null | 1 | 47 | javascript|syntax-error|jslint|jshint | 34,784 | <p>The solution is to enable jshint's <code>--verbose</code> option, which shows the error or warning code (e.g. <code>E020</code> for <code>Expected '}' to match '{'</code> or <code>W110</code> for <code>Mixed double and single quotes</code>), then grep for errors only:</p>
<pre><code>jshint --verbose test.js | grep -E E[0-9]+.$
</code></pre> |
26,824,225 | Loop through folder, renaming files that meet specific criteria using VBA? | <p>I am new to VBA (and have only a bit of training in java), but assembled this bit of code with the help of other posts here and have hit a wall.</p>
<p>I am trying to write code that will cycle through each file in a folder, testing if each file meets certain criteria. If criteria are met, the file names should be edited, overwriting (or deleting prior) any existing files with the same name. Copies of these newly renamed files should then be copied to a different folder. I believe I'm very close, but my code refuses to cycle through all files and/or crashes Excel when it is run. Help please? :-)</p>
<pre><code>Sub RenameImages()
Const FILEPATH As String = _
"C:\\CurrentPath"
Const NEWPATH As String = _
"C:\\AditionalPath"
Dim strfile As String
Dim freplace As String
Dim fprefix As String
Dim fsuffix As String
Dim propfname As String
Dim FileExistsbol As Boolean
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
strfile = Dir(FILEPATH)
Do While (strfile <> "")
Debug.Print strfile
If Mid$(strfile, 4, 1) = "_" Then
fprefix = Left$(strfile, 3)
fsuffix = Right$(strfile, 5)
freplace = "Page"
propfname = FILEPATH & fprefix & freplace & fsuffix
FileExistsbol = FileExists(propfname)
If FileExistsbol Then
Kill propfname
End If
Name FILEPATH & strfile As propfname
'fso.CopyFile(FILEPATH & propfname, NEWPATH & propfname, True)
End If
strfile = Dir(FILEPATH)
Loop
End Sub
</code></pre>
<p>If it's helpful, the file names start as ABC_mm_dd_hh_Page_#.jpg and the goal is to cut them down to ABCPage#.jpg</p>
<p>Thanks SO much!</p> | 26,924,038 | 3 | 2 | null | 2014-11-09 02:09:07.41 UTC | 2 | 2018-06-08 22:46:12.257 UTC | null | null | null | null | 4,231,532 | null | 1 | 5 | vba|excel|excel-2013 | 39,746 | <p>I think it's a good idea to first collect all of the filenames in an array or collection before starting to process them, particularly if you're going to be renaming them. If you don't there's no guarantee you won't confuse Dir(), leading it to skip files or process the "same" file twice. Also in VBA there's no need to escape backslashes in strings.</p>
<p>Here's an example using a collection:</p>
<pre><code>Sub Tester()
Dim fls, f
Set fls = GetFiles("D:\Analysis\", "*.xls*")
For Each f In fls
Debug.Print f
Next f
End Sub
Function GetFiles(path As String, Optional pattern As String = "") As Collection
Dim rv As New Collection, f
If Right(path, 1) <> "\" Then path = path & "\"
f = Dir(path & pattern)
Do While Len(f) > 0
rv.Add path & f
f = Dir() 'no parameter
Loop
Set GetFiles = rv
End Function
</code></pre> |
26,745,462 | How do I use basic HTTP authentication with the python Requests library? | <p>I'm trying to use basic HTTP authentication in python. I am using the <a href="https://docs.python-requests.org/" rel="noreferrer">Requests library</a>:</p>
<pre><code>auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')
</code></pre>
<p>Response form <b>auth</b> variable:<br></p>
<pre><code><<class 'requests.cookies.RequestsCookieJar'>[<Cookie JSESSIONID=cb10906c6219c07f887dff5312fb for appdynamics/controller>]>
200
CaseInsensitiveDict({'content-encoding': 'gzip', 'x-powered-by': 'JSP/2.2', 'transfer-encoding': 'chunked', 'set-cookie': 'JSESSIONID=cb10906c6219c07f887dff5312fb; Path=/controller; HttpOnly', 'expires': 'Wed, 05 Nov 2014 19:03:37 GMT', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'no-cache', 'cache-control': 'max-age=78000', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html;charset=ISO-8859-1'})
</code></pre>
<p>But when I try to get data from different location, - I'm got 401 error</p>
<pre><code><<class 'requests.cookies.RequestsCookieJar'>[]>
401
CaseInsensitiveDict({'content-length': '1073', 'x-powered-by': 'Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)', 'expires': 'Thu, 01 Jan 1970 00:00:00 UTC', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'No-cache', 'cache-control': 'no-cache', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html', 'www-authenticate': 'Basic realm="controller_realm"'})
</code></pre>
<p>As far as I understand - in second request are not substituted session parameters.</p> | 26,746,603 | 6 | 3 | null | 2014-11-04 21:34:36.773 UTC | 19 | 2022-09-01 11:08:03.993 UTC | 2021-06-22 11:15:20.37 UTC | null | 362,951 | null | 2,991,712 | null | 1 | 104 | python|api|python-requests|appdynamics | 193,686 | <p>You need to use a <a href="https://requests.readthedocs.io/en/latest/user/advanced/#session-objects" rel="noreferrer">session object</a> and send the authentication <em>each request</em>. The session will also track cookies for you:</p>
<pre><code>session = requests.Session()
session.auth = (user, password)
auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')
</code></pre> |
39,659,127 | Restrict variadic template arguments | <p>Can we restrict variadic template arguments to a certain type? I.e., achieve something like this (not real C++ of course):</p>
<pre><code>struct X {};
auto foo(X... args)
</code></pre>
<p>Here my intention is to have a function which accepts a variable number of <code>X</code> parameters.</p>
<p>The closest we have is this:</p>
<pre><code>template <class... Args>
auto foo(Args... args)
</code></pre>
<p>but this accepts any type of parameter.</p> | 39,659,128 | 6 | 7 | null | 2016-09-23 11:00:11.38 UTC | 22 | 2022-08-07 07:42:49.437 UTC | 2016-09-23 11:17:02.45 UTC | null | 1,774,667 | null | 2,805,305 | null | 1 | 52 | c++|templates|variadic-templates|c++17|c++-faq | 7,147 | <p>Yes it is possible. First of all you need to decide if you want to accept only the type, or if you want to accept a implicitly convertible type. I use <code>std::is_convertible</code> in the examples because it better mimics the behavior of non-templated parameters, e.g. a <code>long long</code> parameter will accept an <code>int</code> argument. If for whatever reason you need just that type to be accepted, replace <code>std::is_convertible</code> with <code>std:is_same</code> (you might need to add <code>std::remove_reference</code> and <code>std::remove_cv</code>).</p>
<p>Unfortunately, in <code>C++</code> narrowing conversion e.g. (<code>long long</code> to <code>int</code> and even <code>double</code> to <code>int</code>) are implicit conversions. And while in a classical setup you can get warnings when those occur, you don't get that with <code>std::is_convertible</code>. At least not at the call. You might get the warnings in the body of the function if you make such an assignment. But with a little trick we can get the error at the call site with templates too.</p>
<p>So without further ado here it goes:</p>
<hr />
<p>The testing rig:</p>
<pre><code>struct X {};
struct Derived : X {};
struct Y { operator X() { return {}; }};
struct Z {};
foo_x : function that accepts X arguments
int main ()
{
int i{};
X x{};
Derived d{};
Y y{};
Z z{};
foo_x(x, x, y, d); // should work
foo_y(x, x, y, d, z); // should not work due to unrelated z
};
</code></pre>
<hr />
<h1>C++20 Concepts</h1>
<p><del>Not here yet, but soon.</del> Available in gcc trunk (March 2020). This is the most simple, clear, elegant and safe solution:</p>
<pre><code>#include <concepts>
auto foo(std::convertible_to<X> auto ... args) {}
foo(x, x, y, d); // OK
foo(x, x, y, d, z); // error:
</code></pre>
<p>We get a very nice error. Especially the</p>
<blockquote>
<p>constraints not satisfied</p>
</blockquote>
<p>is sweet.</p>
<h3>Dealing with narrowing:</h3>
<p>I didn't find a concept in the library so we need to create one:</p>
<pre><code>template <class From, class To>
concept ConvertibleNoNarrowing = std::convertible_to<From, To>
&& requires(void (*foo)(To), From f) {
foo({f});
};
auto foo_ni(ConvertibleNoNarrowing<int> auto ... args) {}
foo_ni(24, 12); // OK
foo_ni(24, (short)12); // OK
foo_ni(24, (long)12); // error
foo_ni(24, 12, 15.2); // error
</code></pre>
<h1>C++17</h1>
<p>We make use of the very nice <a href="http://en.cppreference.com/w/cpp/language/fold" rel="noreferrer">fold expression</a>:</p>
<pre><code>template <class... Args,
class Enable = std::enable_if_t<(... && std::is_convertible_v<Args, X>)>>
auto foo_x(Args... args) {}
foo_x(x, x, y, d, z); // OK
foo_x(x, x, y, d, z, d); // error
</code></pre>
<p>Unfortunately we get a less clear error:</p>
<blockquote>
<p>template argument deduction/substitution failed: [...]</p>
</blockquote>
<h3>Narrowing</h3>
<p>We can avoid narrowing, but we have to cook a trait <code>is_convertible_no_narrowing</code> (maybe name it differently):</p>
<pre><code>template <class From, class To>
struct is_convertible_no_narrowing_impl {
template <class F, class T,
class Enable = decltype(std::declval<T &>() = {std::declval<F>()})>
static auto test(F f, T t) -> std::true_type;
static auto test(...) -> std::false_type;
static constexpr bool value =
decltype(test(std::declval<From>(), std::declval<To>()))::value;
};
template <class From, class To>
struct is_convertible_no_narrowing
: std::integral_constant<
bool, is_convertible_no_narrowing_impl<From, To>::value> {};
</code></pre>
<h1>C++14</h1>
<p>We create a conjunction helper:<br/>
<sub>please note that in <code>C++17</code> there will be a <code>std::conjunction</code>, but it will take <code>std::integral_constant</code> arguments</sub></p>
<pre><code>template <bool... B>
struct conjunction {};
template <bool Head, bool... Tail>
struct conjunction<Head, Tail...>
: std::integral_constant<bool, Head && conjunction<Tail...>::value>{};
template <bool B>
struct conjunction<B> : std::integral_constant<bool, B> {};
</code></pre>
<p>and now we can have our function:</p>
<pre><code>template <class... Args,
class Enable = std::enable_if_t<
conjunction<std::is_convertible<Args, X>::value...>::value>>
auto foo_x(Args... args) {}
foo_x(x, x, y, d); // OK
foo_x(x, x, y, d, z); // Error
</code></pre>
<h1>C++11</h1>
<p>just minor tweaks to the C++14 version:</p>
<pre><code>template <bool... B>
struct conjunction {};
template <bool Head, bool... Tail>
struct conjunction<Head, Tail...>
: std::integral_constant<bool, Head && conjunction<Tail...>::value>{};
template <bool B>
struct conjunction<B> : std::integral_constant<bool, B> {};
template <class... Args,
class Enable = typename std::enable_if<
conjunction<std::is_convertible<Args, X>::value...>::value>::type>
auto foo_x(Args... args) -> void {}
foo_x(x, x, y, d); // OK
foo_x(x, x, y, d, z); // Error
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.