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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,177,399 |
How to display image from database in CodeIgniter?
|
<p>I am using CodeIgniter 2.1.0 and MySQL database. I have uploaded an image through a form and successfully stored it in a uploads directory and I have also successfully stored the full path of the image in my database. but i am having problem with showing the image by calling the full path from my database.</p>
<p>Here is my code for the upload:</p>
<pre><code>$image_path = realpath(APPPATH . '../uploads');
$config = array(
'allowed_types' => 'jpeg|png|gif|jpg',
'upload_path' => $image_path,
'max_size' => 2097152,
'overwrite' => TRUE,
'file_name' => '_' . $i . '_'
);
$this -> load -> library('upload', $config);
</code></pre>
<p>When I am storing the full path of the image in my database, it looks something like this</p>
<pre><code>C:/wamp/www/my_project/uploads/_1_.jpg
</code></pre>
<p>If i try</p>
<pre><code><img src="<?php echo $data['screenshot'];?>" />
//($data['screenshot'] refers to the image location retrieved from database)
</code></pre>
<p>this in my view file, no image is displayed. What am I doing wrong? Please someone tell me. What is the standard procedure?</p>
| 9,177,839 | 3 | 2 | null |
2012-02-07 13:49:38.67 UTC
| 3 |
2012-09-07 09:31:26.093 UTC
|
2012-02-07 14:01:01.773 UTC
| null | 1,156,026 | null | 1,156,026 | null | 1 | 7 |
mysql|image-processing|imageview|codeigniter-2|image-uploading
| 38,393 |
<p>In your database, if i have understood correctly, you're storing the image as <code>C:/wamp/www/my_project/uploads/_1_.jpg</code></p>
<p>So when you're echoing out the image path the <code>img src</code> attribute, you will have</p>
<p></p>
<p>which won't work as this as local path on your machine. I won't have that image on my file system. The image needs to be accessible on the webserver. (like your index.php file)</p>
<p>So you need the store the image as either this:</p>
<p><code>uploads/_1_.jpg</code></p>
<p>and then do <code><img src="<?php echo $data['screenshot'];?>" /></code></p>
<p>Or store the image as:</p>
<p><code>_1_.jpg</code> and
and then do </p>
<p><code><img src="<?php echo sprintf("uploads/%s", $data['screenshot']);?>" /></code></p>
<p>EDIT: To be clear: Where you're storing it is correct. But, you don't need the full path in the DB, you just need the web server path. </p>
|
9,186,150 |
Decoding and understanding assembly code
|
<p>So a little background. I am a beginner with c and assembly code, we have an "bomb" assignment (written in c)which calls methods that require certain passwords, but the code is not visible and I need to determine the correct password by looking at the assembly code.</p>
<p>The code indicates the password for this method is 6 numbers, which is passed as "input" to method phase 2 (I am trying to avoid triggering ). </p>
<p>The part I am getting confused on is is jumping from +64 to +42. It seems to be a loop but I am unsure how the stack is affected with each pass. It looks like the loop exits if the last two numbers are the same, and it has something to do with adding and subtracting 4 but I am unsure how the addresses are traversed.
If anyone can translate what exactly is going on, or if i need to look in any particular registers/locations it would help greatly. There are 4 more phases which are each supposed to be more complex so I want to get a good understanding in how to approach reading these.</p>
<p>Also if anyone has a good resource (like a printable table) with assembly code keywords that would be helpful too, and also if there are any differences between 32-bit and 64-bit registers i need to worry about other than the register names..</p>
<pre><code> 82 phase_2(input);
(gdb) disas phase_2
Dump of assembler code for function phase_2:
0x000000000040106b <phase_2+0>: push %rbp
0x000000000040106c <phase_2+1>: push %rbx
0x000000000040106d <phase_2+2>: sub $0x28,%rsp
0x0000000000401071 <phase_2+6>: mov %rsp,%rsi
0x0000000000401074 <phase_2+9>: callq 0x401457 <read_six_numbers>
0x0000000000401079 <phase_2+14>: cmpl $0x0,(%rsp)
0x000000000040107d <phase_2+18>: jne 0x401086 <phase_2+27>
0x000000000040107f <phase_2+20>: cmpl $0x1,0x4(%rsp)
0x0000000000401084 <phase_2+25>: je 0x40108b <phase_2+32>
0x0000000000401086 <phase_2+27>: callq 0x401421 <explode_bomb>
0x000000000040108b <phase_2+32>: lea 0x8(%rsp),%rbx
0x0000000000401090 <phase_2+37>: lea 0x18(%rsp),%rbp
0x0000000000401095 <phase_2+42>: mov -0x8(%rbx),%eax
0x0000000000401098 <phase_2+45>: add -0x4(%rbx),%eax
0x000000000040109b <phase_2+48>: cmp %eax,(%rbx)
0x000000000040109d <phase_2+50>: je 0x4010a4 <phase_2+57>
0x000000000040109f <phase_2+52>: callq 0x401421 <explode_bomb>
0x00000000004010a4 <phase_2+57>: add $0x4,%rbx
0x00000000004010a8 <phase_2+61>: cmp %rbp,%rbx
0x00000000004010ab <phase_2+64>: jne 0x401095 <phase_2+42>
0x00000000004010ad <phase_2+66>: add $0x28,%rsp
0x00000000004010b1 <phase_2+70>: pop %rbx
0x00000000004010b2 <phase_2+71>: pop %rbp
0x00000000004010b3 <phase_2+72>: retq
</code></pre>
| 9,188,023 | 1 | 2 | null |
2012-02-08 00:22:08.06 UTC
| 17 |
2012-09-20 12:56:05.18 UTC
|
2012-09-20 12:56:05.18 UTC
| null | 1,288 | null | 1,186,511 | null | 1 | 21 |
c|gdb|assemblies
| 26,986 |
<p>Here is a C equivalent of phase2:</p>
<pre><code>int t[6];
read_six_numbers (t);
if ((t[0] != 0) || (t[1] != 1)) {
explode_bomb();
}
for (int i = 2; i < 6; i++) {
if (t[i] != t[i - 2] + t[i - 1]) {
explode_bomb();
}
}
</code></pre>
<p>So the password is 0, 1, 1, 2, 3, 5.</p>
<p>How did I do this ? By gradually replacing the assembly with C.</p>
<p>You'll note that the stack pointer (rsp) never changes. You can see the stack as an array t of 32 bits numbers. That is each time you move by 4 bytes you move to the next element. i.e. 0(%rsp), 4(%rsp), ... are equivalent to t[0], t[1], ...</p>
<p>I'll show you a possible gradual transformation of the bit you have trouble with:</p>
<pre><code> lea 0x8(%rsp),%rbx
lea 0x18(%rsp),%rbp
<phase_2+42>: mov -0x8(%rbx),%eax
add -0x4(%rbx),%eax
cmp %eax,(%rbx)
je <phase_2+57>
callq explode_bomb
<phase_2+57>: add $0x4,%rbx
cmp %rbp,%rbx
jne phase_2+42
------------------------------------------------------
rbx = rsp + 8;
rbp = rsp + 24;
<phase_2+42>: eax = [rbx - 8];
eax += [rbx - 4];
if (eax == [rbx]) goto <phase_2+57>;
explode_bomb();
<phase_2+57>: rbx += 4;
if (rbx != rbp) goto phase_2+42;
------------------------------------------------------
rbx = rsp + 8;
rbp = rsp + 24;
do {
eax = [rbx - 8] + [rbx - 4];
if (eax != [rbx]) {
explode_bomb();
}
rbx += 4;
} while (rbx != rbp);
------------------------------------------------------
rbx = 8;
do {
eax = [rsp + rbx - 8] + [rsp + rbx - 4];
if (eax != [rsp + rbx]) {
explode_bomb();
}
rbx += 4;
} while (rbx < 24);
------------------------------------------------------
i = 2;
do {
eax = t[i - 2] + t[i - 1];
if (eax != t[i]) {
explode_bomb();
}
i += 1;
} while (i < 6);
------------------------------------------------------
for (int i = 2; i < 6; i++) {
if (t[i] != t[i - 2] + t[i - 1]) {
explode_bomb();
}
}
</code></pre>
<p>If you take the time to understand these transformations you'll be able to transform and understand any piece of assembly.</p>
|
29,530,199 |
Why can't I use protected constructors outside the package?
|
<p>Why can't I use protected constructors outside the package for this piece of code:</p>
<pre><code>package code;
public class Example{
protected Example(){}
...
}
</code></pre>
<p>Check.java</p>
<pre><code>package test;
public class Check extends Example {
void m1() {
Example ex=new Example(); //compilation error
}
}
</code></pre>
<ol>
<li>Why do i get the error even though i have extended the class?
Please explain</li>
</ol>
<p><strong>EDIT:</strong></p>
<p>Compilation error:</p>
<blockquote>
<p>The constructor Example() is not visible</p>
</blockquote>
| 29,530,299 | 3 | 4 | null |
2015-04-09 05:07:11.42 UTC
| 7 |
2018-06-14 12:20:19.917 UTC
|
2018-06-14 12:20:19.917 UTC
| null | 1,033,581 | null | 4,029,693 | null | 1 | 39 |
java|protected|access-modifiers
| 12,774 |
<p>protected modifier is used only with in the package and in sub-classes outside the package. When you create a object using <code>Example ex=new Example();</code> it will call parent class constructor by default. </p>
<p>As parent class constructor being protected you are getting a compile time error. You need to call the protected constructor according to JSL 6.6.2.2 as shown below in example 2.</p>
<pre><code>package Super;
public class SuperConstructorCall {
protected SuperConstructorCall() {
}
}
package Child;
import Super.SuperConstructorCall;
public class ChildCall extends SuperConstructorCall
{
public static void main(String[] args) {
SuperConstructorCall s = new SuperConstructorCall(); // Compile time error saying SuperConstructorCall() has protected access in SuperConstructorCall
}
}
</code></pre>
<p>Example 2 conforming to <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2.2" rel="noreferrer">JLS 6.6.2.2</a>:</p>
<pre><code>package Super;
public class SuperConstructorCall {
protected SuperConstructorCall() {
}
}
package Child;
import Super.SuperConstructorCall;
public class ChildCall extends SuperConstructorCall
{
public static void main(String[] args) {
SuperConstructorCall s = new SuperConstructorCall(){}; // This will work as the access is by an anonymous class instance creation expression
}
}
</code></pre>
|
16,261,119 |
Typescript objects serialization?
|
<p>Are there any means for JSON serialization/deserialization of Typescript objects so that they don't lose type information? Simple <code>JSON.parse(JSON.stringify)</code> has too many caveats.</p>
<p>Or I should use adhoc solutions?</p>
| 16,261,168 | 6 | 0 | null |
2013-04-28 08:38:34.387 UTC
| 8 |
2022-05-02 11:35:23.13 UTC
|
2022-05-02 11:35:23.13 UTC
| null | 83,938 | null | 83,938 | null | 1 | 55 |
javascript|json|serialization|typescript
| 77,151 |
<p>Use Interfaces to get strong types:</p>
<pre><code>// Creating
var foo:any = {};
foo.x = 3;
foo.y='123';
var jsonString = JSON.stringify(foo);
alert(jsonString);
// Reading
interface Bar{
x:number;
y?:string;
}
var baz:Bar = JSON.parse(jsonString);
alert(baz.y);
</code></pre>
<p>And use type assertion "<>" if you need to. </p>
|
16,143,684 |
Can Java 8 code be compiled to run on Java 7 JVM?
|
<p>Java 8 introduces important new language features such as lambda expressions.</p>
<p>Are these changes in the language accompanied by such significant changes in the compiled bytecode that would prevent it from being run on a Java 7 virtual machine without using some retrotranslator?</p>
| 22,492,421 | 5 | 1 | null |
2013-04-22 09:29:24.503 UTC
| 31 |
2017-09-12 07:06:52.183 UTC
|
2017-09-12 07:06:52.183 UTC
| null | 320,911 | null | 574,351 | null | 1 | 168 |
java|jvm|compatibility|java-7|java-8
| 72,275 |
<p>No, using 1.8 features in your source code requires you to target a 1.8 VM. I just tried the new Java 8 release and tried compiling with <code>-target 1.7 -source 1.8</code>, and the compiler refuses:</p>
<pre><code>$ javac Test -source 1.8 -target 1.7
javac: source release 1.8 requires target release 1.8
</code></pre>
|
42,117,911 |
Lambda functions vs bind, memory! (and performance)
|
<p>I would like to determine which is the best practice between equivalent solutions. The use case is an instance of a class that listen to an event. Dr. Axel Rauschmayer <a href="http://www.2ality.com/2016/02/arrow-functions-vs-bind.html" rel="noreferrer">prefers the lambda</a> for readability. I agree with him. But in term of performance and memory consumption, which is the best?</p>
<h1>With a lambda function</h1>
<pre><code>class Abc {
constructor() {
let el = document.getElementById("my-btn")
if (el)
el.addEventListener("click", evt => this.onClick(evt))
}
onClick(evt) {
console.log("Clicked!", evt.target)
}
}
</code></pre>
<p>Can someone to confirm or infirm if the local variables (here <code>el</code>) can't be cleared by the garbage collector? Or, are modern browsers capable to detect they are unused in the closure?</p>
<h1>With <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind" rel="noreferrer"><code>Function.prototype.bind</code></a>:</h1>
<pre><code>class Abc {
constructor() {
let el = document.getElementById("my-btn")
if (el)
el.addEventListener("click", this.onClick.bind(this))
}
onClick(evt) {
console.log("Clicked!", evt.target)
}
}
</code></pre>
<p>There is no memory issue, but all benchmarks suggest that <code>bind</code> is far slower than a closure (an example <a href="https://jsperf.com/bind-vs-closure-setup/32" rel="noreferrer">here</a>).</p>
<p><em>EDIT: I don't agree with the comments that ignore the performance issue of <code>bind</code>. I suggest to read <a href="https://stackoverflow.com/a/17638540/3786294">this answer</a> with the code of the implementation in Chrome. It cannot be efficient. And I insist: <strong>all</strong> the benchmarks I saw, show similar results on <strong>all</strong> browsers.</em></p>
<p>Is there a way to have a low memory usage and a good performance at the same time?</p>
| 42,395,668 | 1 | 21 | null |
2017-02-08 16:00:47.21 UTC
| 8 |
2017-02-22 15:32:24.41 UTC
|
2017-05-23 11:47:35.397 UTC
| null | -1 | null | 3,786,294 | null | 1 | 30 |
javascript|lambda|bind
| 12,543 |
<h1>Closures (or <em>arrow functions</em>, aka <em>lambdas</em>) don't cause memory leaks</h1>
<blockquote>
<p>Can someone to confirm or infirm if the local variables (here <code>el</code>) can't be cleared by the garbage collector? Or, are modern browsers capable to detect they are unused in the closure?</p>
</blockquote>
<p><strong>Yes</strong>, modern JavaScript engines are able to detect variables from parent scopes that are visible from a closure but unused. I found a way to prove that.</p>
<h3>Step 1: the closure uses a variable of 10 MB</h3>
<p>I used this code in Chromium:</p>
<pre><code>class Abc {
constructor() {
let arr = new Uint8Array(1024*1024*10) // 10 MB
let el = document.getElementById("my-btn")
if (el)
el.addEventListener("click", ev => this.onClick(ev, arr))
}
onClick(ev) {
console.log("Clicked!", ev.target)
}
}
new Abc()
</code></pre>
<p>Notice the variable <code>arr</code> of type <code>Uint8Array</code>. It is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays" rel="noreferrer">typed array</a> with a size of 10 megabytes. In this first version, the variable <code>arr</code> is used in the closure.</p>
<p>Then, in the developer tools of Chromium, tab "Profiles", I take a <em>Heap Snapshot</em>:</p>
<p><a href="https://i.stack.imgur.com/zYT3P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zYT3P.png" alt="Snapshot 1: the variable <code>arr</code> is used in the closure"></a></p>
<p>After ordering by decreasing size, the first row is: <em>"system / JSArrayBufferData"</em> with a size of 10 MB. It is our variable <code>arr</code>.</p>
<h3>Step 2: the variable of 10 MB is visible but unused in the closure</h3>
<p>Now I just remove the <code>arr</code> parameter in this line of code:</p>
<pre><code> el.addEventListener("click", ev => this.onClick(ev))
</code></pre>
<p>Then, a second snapshot:</p>
<p><a href="https://i.stack.imgur.com/2iL8E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2iL8E.png" alt="Snapshot 2: the variable <code>arr</code> is not used in the closure"></a></p>
<p>The first row has vanished.</p>
<p><strong>This experience confirms that the garbage collector is capable to clean variables from parent scopes that are visible but unused in active closures.</strong></p>
<h1>About <code>Function.prototype.bind</code></h1>
<p>I quote the <a href="https://google.github.io/styleguide/jsguide.html#features-functions-arrow-functions" rel="noreferrer">Google JavaScript Style Guide</a>, section on arrow functions:</p>
<blockquote>
<p>Never call <code>f.bind(this)</code> or <code>goog.bind(f, this)</code> (and avoid writing <code>const self = this</code>). All of these can be expressed more clearly and less error-prone with an arrow function. This is particularly useful for callbacks, which sometimes pass unexpected additional arguments.</p>
</blockquote>
<p>Google clearly recommends to use lambdas rather than <code>Function.prototype.bind</code>.</p>
<p>Related:</p>
<ul>
<li><em><a href="https://stackoverflow.com/a/17638540/3786294">Why is bind slower than a closure?</a></em></li>
<li><a href="https://jsperf.com/bind-vs-closure-setup/32" rel="noreferrer">A benchmark</a></li>
<li><em><a href="http://www.2ality.com/2016/02/arrow-functions-vs-bind.html" rel="noreferrer">Arrow functions vs. bind()</a></em> from Dr. Axel Rauschmayer</li>
</ul>
<hr>
|
57,751,607 |
Package '@angular/cli' is not a dependency
|
<p>I am getting the following error when I try to run the command</p>
<p><code>ng update @angular/cli @angular/core --allow-dirty</code></p>
<pre><code>Repository is not clean. Update changes will be mixed with pre-existing changes.
Using package manager: 'npm'
Collecting installed dependencies...
Found 28 dependencies.
Package '@angular/cli' is not a dependency.
</code></pre>
| 57,752,631 | 6 | 1 | null |
2019-09-02 04:58:29.427 UTC
| 8 |
2022-09-21 06:58:44.72 UTC
|
2019-10-30 03:50:02.003 UTC
| null | 410,937 | null | 9,526,337 | null | 1 | 111 |
angular|angular-cli
| 95,445 |
<p>First commit all your changes to the repo and then try following commands. </p>
<pre><code>npm i -g @angular/cli@8.0.0
</code></pre>
<p>and </p>
<pre><code>ng update --all --force
</code></pre>
<p>Please read <a href="https://github.com/angular/angular-cli/issues/14561" rel="noreferrer">this</a> issue on github</p>
|
17,444,248 |
Reason: (noSuchName) There is no such variable name in this MIB
|
<p>I am using centos Operating System.<br>
i am trying to get the memory statistics of localhost through <code>snmpget</code> command, i am getting this error. </p>
<pre><code>snmpget -v 1 -c public localhost .1.3.6.1.4.1.2021.4.6
Error in packet
Reason: (noSuchName) There is no such variable name in this MIB.
Failed object: UCD-SNMP-MIB::memAvailReal
</code></pre>
<p>But, if i fire this one .. i am getting the output..</p>
<pre><code>snmpget -v 1 -c public localhost .1.3.6.1.2.1.1.3.0
DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (58756) 0:09:47.56
</code></pre>
<p>I am not getting what I am doing wrong. I exported the path of <code>/usr/share/snmp/mibs/</code> to <code>$PATH</code> variable.<br>
can any one help me out.</p>
| 17,463,065 | 1 | 0 | null |
2013-07-03 09:21:51.773 UTC
| 2 |
2013-07-04 06:13:50.23 UTC
|
2013-07-03 09:40:49.407 UTC
| null | 1,061,636 | null | 2,545,616 | null | 1 | 9 |
centos|snmp
| 39,997 |
<p>You'd better read the FAQ page of net-snmp,</p>
<p><a href="http://www.net-snmp.org/wiki/index.php/FAQ:Applications_09">http://www.net-snmp.org/wiki/index.php/FAQ:Applications_09</a></p>
<p>You should use </p>
<p><code>snmpget -v 1 -c public localhost .1.3.6.1.4.1.2021.4.6.0</code>.</p>
|
21,982,187 |
Bash: Loop until command exit status equals 0
|
<p>I have a netcat installed on my local machine and a service running on port 25565. Using the command:</p>
<pre><code>nc 127.0.0.1 25565 < /dev/null; echo $?
</code></pre>
<p>Netcat checks if the port is open and returns a 0 if it open, and a 1 if it closed.</p>
<p>I am trying to write a bash script to loop endlessly and execute the above command every second until the output from the command equals 0 (the port opens).</p>
<p>My current script just keeps endlessly looping "...", even after the port opens (the 1 becomes a 0).</p>
<pre><code>until [ "nc 127.0.0.1 25565 < /dev/null; echo $?" = "0" ]; do
echo "..."
sleep 1
done
echo "The command output changed!"
</code></pre>
<p>What am I doing wrong here?</p>
| 21,982,743 | 2 | 2 | null |
2014-02-24 08:11:10.02 UTC
| 4 |
2020-10-28 22:17:12.54 UTC
|
2015-10-09 05:56:12.64 UTC
| null | 667,820 | null | 2,274,960 | null | 1 | 27 |
linux|bash|loops|netcat
| 41,022 |
<p><strong>Keep it Simple</strong></p>
<pre><code>until nc -z 127.0.0.1 25565
do
echo ...
sleep 1
done
</code></pre>
<p><em>Just let the shell deal with the exit status implicitly</em></p>
<p>The shell can deal with the exit status (recorded in <code>$?</code>) in two ways, explicit, and implicit.</p>
<p>Explicit: <code>status=$?</code>, which allows for further processing.</p>
<p>Implicit:</p>
<p>For every statement, <em>in your mind</em>, add the word "succeeds" to the command, and then add
<code>if</code>, <code>until</code> or <code>while</code> constructs around them, until the phrase makes sense.</p>
<p><code>until nc </code><em>succeeds</em><code>; do ...; done</code></p>
<hr />
<p>The <code>-z</code> option will stop <code>nc</code> from reading stdin, so there's no need for the <code>< /dev/null</code> redirect.</p>
|
19,601,921 |
Center Crop an Android VideoView
|
<p>I am looking for something like the CENTER_CROP in <a href="http://developer.android.com/reference/android/widget/ImageView.ScaleType.html">ImageView.ScaleType</a></p>
<blockquote>
<p>Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view. From XML, use this syntax: android:scaleType="centerCrop"</p>
</blockquote>
<p>but for a VideoView. Does anything like this exist?</p>
| 23,011,598 | 5 | 4 | null |
2013-10-26 01:45:53.203 UTC
| 6 |
2022-04-13 21:29:24.043 UTC
| null | null | null | null | 1,359,431 | null | 1 | 29 |
android|scale|center|crop|android-videoview
| 20,217 |
<p>You can only achieve this with a TextureView. (surfaceView won't work either). Here's a lib for playing video in a textureView with center crop function. TextureView can only be used in api level 14 and up unfortunately. </p>
<p><a href="https://github.com/dmytrodanylyk/android-video-crop" rel="noreferrer">https://github.com/dmytrodanylyk/android-video-crop</a></p>
<p>Another possibility is to zoom in the videoview just right, but I haven't tried that yet.</p>
|
17,601,615 |
The Chrome extension popup is not working, click events are not handled
|
<p>I have created a JavaScript variable and when I click on the button it should increment by 1, but its not happening.</p>
<p>Here's <code>manifest.json</code>.</p>
<pre><code>{
"name":"Facebook",
"version":"1.0",
"description":"My Facebook Profile",
"manifest_version":2,
"browser_action":{
"default_icon":"google-plus-red-128.png",
"default_popup":"hello.html"
}
}
</code></pre>
<p>Here is the code for the html page </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script>
var a=0;
function count()
{
a++;
document.getElementById("demo").innerHTML=a;
return a;
}
</script>
</head>
<body>
<p id="demo">=a</p>
<button type="button" onclick="count()">Count</button>
</body>
</html>
</code></pre>
<p>I want the extension to show me the value of a and increment it by one each time I click on the extension or the button</p>
<p><img src="https://i.stack.imgur.com/G0dMA.png" alt="picture of the extension"></p>
| 17,612,988 | 2 | 7 | null |
2013-07-11 19:18:38.283 UTC
| 13 |
2013-07-13 21:13:14.647 UTC
|
2013-07-13 21:13:14.647 UTC
| null | 938,089 | null | 2,293,974 | null | 1 | 36 |
javascript|google-chrome|button|google-chrome-extension|content-security-policy
| 49,468 |
<p>Your code is not working because it violates the default <a href="https://developer.chrome.com/extensions/contentSecurityPolicy.html" rel="noreferrer">Content Security Policy</a>. I've created a screencast of one minute to show what's wrong:</p>
<p><a href="https://i.stack.imgur.com/s8Wxd.gif" rel="noreferrer" title="1 minute screencast to show what's wrong"><img src="https://i.stack.imgur.com/s8Wxd.gif" alt="screencast" title="1 minute screencast to show what's wrong" /></a></p>
<p>First, I've shown how to debug the problem. Right-click on your popup button, and click on <a href="https://developer.chrome.com/extensions/tut_debugging.html#inspect-popup" rel="noreferrer">"Inspect popup"</a>. After doing that, you will see the following error message:</p>
<blockquote>
<p>Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".</p>
</blockquote>
<p>This explains that your code is not working, because it violates the default CSP: <a href="https://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution" rel="noreferrer">Inline JavaScript will not be executed</a>. To solve the problem, you have to remove all inline JavaScript from your HTML file, and put it in a separate JS file.</p>
<p>The result is shown below:</p>
<h3><code>hello.html</code> (popup page)</h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo">=a</p>
<button type="button" <b>id="do-count"</b>>Count</button>
<b><script src="popup.js"></script></b>
</body>
</html>
</code></pre>
<h3><code>popup.js</code></h3>
<pre class="lang-js prettyprint-override"><code>var a=0;
function <b>count</b>() {
a++;
document.getElementById('demo').<b>textContent</b> = a;
}
<b>document.getElementById('do-count').onclick = count;</b></code></pre>
<p>Note that I've replaced <code>innerHTML</code> with <code>textContent</code>. Learn to use <code>textContent</code> instead of <code>innerHTML</code> when you intend to change the text. In this simple example it does not matter, but in more complex applications, it might become a security issue in the form of XSS.</p>
|
18,709,834 |
HTTP Status 424 or 500 for error on external dependency
|
<p>I am trying to create a service that has 2 dependencies. One of the dependencies is internally managed while the 2nd requires an external http outbound call to a third party API. The sequence requires the updating the resource and then executing the http outbound call. </p>
<p>So my question is, on the event of a failure on the 2nd step, what is the correct http status code to return?</p>
<p>Should the response be 424 or 500 with a message body explaining the encountered error?</p>
<ul>
<li>424: Method Failure - Indicates the method was not executed on a particular resource within its scope because some part of the method's execution failed causing the entire method to be aborted.</li>
<li>500: Internal Server Error. </li>
</ul>
| 18,711,343 | 3 | 0 | null |
2013-09-10 02:27:27.73 UTC
| 8 |
2017-10-25 16:11:44.543 UTC
|
2017-10-25 16:11:44.543 UTC
| null | 317,522 | null | 887,040 | null | 1 | 92 |
rest|http-status-codes
| 69,181 |
<p>The failure you're asking about is one that has occurred within the internals of the service itself, so a 5xx status code range is the correct choice. 503 Service Unavailable looks perfect for the situation you've described.</p>
<p>5xx codes are for telling the client that even though the request was fine, the server has had some kind of problem fulfilling the request. On the other hand, 4xx codes are used to tell the client it has done something wrong (and that the server is just fine, thanks). <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10" rel="noreferrer">Sections 10.4 and 10.5 of the HTTP 1.1 spec</a> explain the different purposes of 4xx and 5xx codes.</p>
<p>Status code 424 is defined in the <a href="https://www.rfc-editor.org/rfc/rfc4918" rel="noreferrer">WebDAV standard</a> and is for a case where the client needs to change what it is doing - the server isn't experiencing any problem here.</p>
|
18,713,415 |
User Activity Tracking using javascript library
|
<p>Is it possible to track every action of a user on a webpage and creating log of it? The idea is to transfer log of user actions to server via AJAX and saving it. On each event for each element I can write code/logic to write some log in console, but I was wondering if there is any library/shortcut available which can log all actions on webpage at client side including events and actions such as copy, paste, click, double click, selection etc. with their element reference.</p>
| 26,142,412 | 4 | 4 | null |
2013-09-10 07:53:59.78 UTC
| 25 |
2021-01-07 12:30:16.44 UTC
|
2021-01-07 12:30:16.44 UTC
| null | 6,887,084 | null | 1,356,109 | null | 1 | 17 |
javascript|jquery|html|dom|logging
| 41,848 |
<p>You can use ready-made solutions:</p>
<ul>
<li><a href="http://www.google.com/analytics/">http://www.google.com/analytics/</a></li>
<li><a href="http://www.clicktale.com/">http://www.clicktale.com/</a></li>
<li><a href="https://segment.io/">https://segment.io/</a></li>
<li><a href="http://www.extrawatch.com/">http://www.extrawatch.com/</a></li>
<li><a href="http://mouseflow.com/">http://mouseflow.com/</a></li>
<li><a href="https://www.seevolution.com/">https://www.seevolution.com/</a></li>
<li><a href="http://clicky.com/">http://clicky.com/</a></li>
</ul>
<p>You can do amazing stuff with Google Analytics and its Event Tracker:</p>
<ul>
<li><a href="https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide">https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide</a></li>
<li><a href="http://searchenginewatch.com/article/2287906/10-Google-Analytics-Custom-Events-That-Track-the-Untrackable">http://searchenginewatch.com/article/2287906/10-Google-Analytics-Custom-Events-That-Track-the-Untrackable</a></li>
</ul>
<p>If you're looking for a custom-made solution, you can try the following one with PHP and JavaScript:</p>
<ul>
<li><a href="http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/">http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/</a></li>
</ul>
<p>Keep in mind that using third-party solutions is better performance-wise. Writing the coordinates of the mouse movements in a database in real time, needs a lot of resources.</p>
|
5,048,695 |
jQuery Mobile for mobile and desktop?
|
<p>I'm developing a web app. MySql/PHP back-end, and HTML/jQuery front-end.</p>
<p>I wanted to use jQuery UI framework. </p>
<p>Now is see that jQuery Mobile is out, and I want to make the app accessible to mobile devices as much as possible.</p>
<p>I Googled, but didn't find a quality answer. </p>
<p>Can I make it all to work form the same code if I use jQuery Mobile? </p>
<p>I'd like it to show mobile widgets if accessed form mobile browser.<br>
But use jQuery UI widgets is accessed from desktop browser.</p>
<p>Is that possible just by using jQuery Mobile and its markup, or I have to write the front-end for mobile (jQuery Mobile) and desktop (jQuery UI) separately? </p>
<p>That is, can jQuery Mobile, automatically "fall-back" to jQuery UI if accessed from desktop browser.</p>
| 5,048,725 | 3 | 0 | null |
2011-02-19 03:38:42.037 UTC
| 17 |
2016-05-09 05:40:19.177 UTC
|
2016-05-09 05:40:19.177 UTC
| null | 13,302 | null | 329,200 | null | 1 | 44 |
jquery|jquery-ui|mobile|jquery-mobile
| 26,078 |
<p>I think it largely depends on what you want to do and functionality you're trying to capture. If you want a webpage to behave a certain way on mobile and the same desktop, then with some careful coding/testing, you'll be alright with jquery.mobile. </p>
<p>If you check out the CSS for jquery.mobile (uncompressed version), you can actually edit the code directly to show the HTML elements the way you want to for particular screen sizes. Just select the one for desktop / large screen sizes to scale appropriately. </p>
<p>Depending on what you're trying to accomplish in terms of your mobile version, I'd also check out <a href="http://jqtjs.com/">jQTouch</a> - which allows for mobile-specific functionality, such as "tap" (in place of "click"), as an example - but also has a desktopCompatability option, so it reverts for desktop browsers. </p>
<p>One note, with either of these libraries, you'll still need the root jquery library.</p>
<p>Hope this helps.</p>
|
9,476,131 |
Is there a way to remove the authorization prompt from command-line instances of Instruments (Xcode)?
|
<p>I am currently using Instruments via a bash script to initiate the command-line interface to start up runs of the Automation plug-in. </p>
<p>With 4.2, this worked well enough, however with the upgrade to Xcode 4.3, I am now being prompted for an authorized user to 'analyze other processes'. No user is ever actually authenticated, even if the correct credentials are granted. I get the following error:</p>
<pre><code>Failed to authorize rights (0x20) with status: -60007.
2012-02-27 19:30:37.232 instruments[54151:1c03] Failed to connect to local pid watcher service: (os/kern) failure
</code></pre>
<p>Even with the authentication failure, the Automation plug-in executes, however this requires my script to have a physical babysitter enter credentials, which in many ways defeats the purpose of these command-line runs. Is it possible to add the user details as arguments? Or is there some other way to skip over this prompt without requiring a person at the keys?</p>
<p><strong>-- EDIT --</strong></p>
<p>This authorization dialog appears when you try to run UIAutomation tests from the GUI for the first time.</p>
<p><img src="https://i.stack.imgur.com/Es3Gr.png" alt="enter image description here"></p>
<p>Filed a <a href="https://openradar.appspot.com/radar?id=1544403" rel="nofollow noreferrer">radar rdar://10945962</a>.</p>
<p><strong>-- EDIT --</strong></p>
<p>Once the authorization dialog has been answered in the GUI, the prompts stop appearing on the command-line. This kind of work-around doesn't seem valid as an 'answer' though.</p>
| 9,678,612 | 11 | 4 | null |
2012-02-28 03:53:00.857 UTC
| 24 |
2022-05-09 23:31:01.307 UTC
|
2022-05-09 23:31:01.307 UTC
| null | 5,175,709 | null | 392,410 | null | 1 | 30 |
ios|keychain|instruments|ios-ui-automation
| 20,252 |
<p>Here's a wonderful command that may work for you:</p>
<pre><code>security unlock-keychain -p [password] "${HOME}/Library/Keychains/login.keychain"
</code></pre>
<p>It's the command-line way to gain access to a keychain on the Mac. I haven't tested it with Automation, but it's how I've integrated my iOS builds with Jenkins.</p>
<p>(<em>Replace [password] with the password</em>)</p>
|
15,233,290 |
ToString("X") produces single digit hex numbers
|
<p>We wrote a crude data scope.</p>
<p>(The freeware terminal programs we found were unable to keep up with Bluetooth speeds)</p>
<p>The results are okay, and we are writing them to a Comma separated file for use with a spreadsheet. It would be better to see the hex values line up in nice columns in the RichTextBox instead of the way it looks now (Screen cap appended).</p>
<p>This is the routine that adds the digits (e.g., numbers from <code>0</code> to <code>FF</code>) to the text in the RichTextBox.</p>
<pre><code> public void Write(byte[] b)
{
if (writting)
{
for (int i = 0; i < b.Length; i++)
{
storage[sPlace++] = b[i];
pass += b[i].ToString("X") + " "; //// <<<--- Here is the problem
if (sPlace % numericUpDown1.Value == 0)
{
pass += "\r\n";
}
}
}
}
</code></pre>
<p>I would like a way for the instruction <code>pass += b[i].ToString("X") + " ";</code> to produce a leading zero on values from <code>00h</code> to <code>0Fh</code></p>
<p>Or, some other way to turn the value in byte <code>b</code> into two alphabetic characters from <code>00</code> to <code>FF</code></p>
<p><img src="https://i.stack.imgur.com/iSvi6.png" alt="enter image description here"></p>
<p>Digits on left, <code>FF 40 0 5</code> Line up nice and neatly, because they are identical. As soon as we encounter any difference in data, the columns vanish and the data become extremely difficult to read with human observation.</p>
| 15,233,319 | 1 | 2 | null |
2013-03-05 20:18:47.323 UTC
| 5 |
2018-10-15 11:57:24.747 UTC
|
2014-01-14 13:21:40.203 UTC
| null | 1,901,636 | null | 1,901,636 | null | 1 | 28 |
c#|hex
| 96,164 |
<p>Use a <a href="http://msdn.microsoft.com/en-us/library/txafckwd.aspx" rel="noreferrer">composite</a> format string:</p>
<pre><code>pass += b[i].ToString("X2") + " ";
</code></pre>
<p>The documentation on MSDN, <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="noreferrer">Standard Numeric Format Strings</a> has examples.</p>
|
15,164,886 |
Hadoop speculative task execution
|
<p>In Google's MapReduce paper, they have a backup task, I think it's the same thing with speculative task in Hadoop. How is the speculative task implemented? When I start a speculative task, does the task start from the very begining as the older and slowly one, or just start from where the older task has reached(if so, does it have to copy all the intermediate status and data?)</p>
| 15,165,199 | 1 | 1 | null |
2013-03-01 18:56:31.31 UTC
| 16 |
2016-03-24 17:11:35.98 UTC
| null | null | null | null | 495,798 | null | 1 | 31 |
hadoop|mapreduce
| 38,296 |
<p>One problem with the Hadoop system is that by dividing the tasks across many nodes, it is possible for a few slow nodes to rate-limit the rest of the program.</p>
<p>Tasks may be slow for various reasons, including hardware degradation, or software mis-configuration, but the causes may be hard to detect since the tasks still complete successfully, albeit after a longer time than expected. Hadoop doesn’t try to diagnose and fix slow-running tasks; instead, it tries to detect when a task is running slower than expected and launches another, equivalent, task as a backup. This is termed speculative execution of tasks.</p>
<p>For example if one node has a slow disk controller, then it may be reading its input at only 10% the speed of all the other nodes. So when 99 map tasks are already complete, the system is still waiting for the final map task to check in, which takes much longer than all the other nodes.</p>
<p>By forcing tasks to run in isolation from one another, individual tasks do not know where their inputs come from. Tasks trust the Hadoop platform to just deliver the appropriate input. Therefore, the same input can be processed multiple times in parallel, to exploit differences in machine capabilities. As most of the tasks in a job are coming to a close, the Hadoop platform will schedule redundant copies of the remaining tasks across several nodes which do not have other work to perform. This process is known as speculative execution. When tasks complete, they announce this fact to the JobTracker. Whichever copy of a task finishes first becomes the definitive copy. If other copies were executing speculatively, Hadoop tells the TaskTrackers to abandon the tasks and discard their outputs. The Reducers then receive their inputs from whichever Mapper completed successfully, first.</p>
<p>Speculative execution is enabled by default. You can disable speculative execution for the mappers and reducers by setting the <code>mapred.map.tasks.speculative.execution</code> and <code>mapred.reduce.tasks.speculative.execution</code> JobConf options to false, respectively using old API, while with newer API you may consider changing <code>mapreduce.map.speculative</code> and <code>mapreduce.reduce.speculative</code>.</p>
<p>So to answer your question it does start afresh and has nothing to do with how much the other task has done/completed.</p>
<p>Reference: <a href="http://developer.yahoo.com/hadoop/tutorial/module4.html">http://developer.yahoo.com/hadoop/tutorial/module4.html</a></p>
|
28,002,261 |
Parse 'Date & Time' string in Javascript which are of custom format
|
<p>I have to parse a date and time string of format "2015-01-16 22:15:00". I want to parse this into JavaScript Date Object. Any help on this?</p>
<p>I tried some jquery plugins, moment.js, date.js, xdate.js. Still no luck.</p>
| 28,002,368 | 6 | 2 | null |
2015-01-17 17:38:07.13 UTC
| 5 |
2021-12-06 13:08:04.853 UTC
| null | null | null | null | 2,323,097 | null | 1 | 21 |
javascript|jquery|momentjs|datejs|datetime-parsing
| 80,603 |
<p>With moment.js you can create a moment object using the <a href="http://momentjs.com/docs/#/parsing/string-format/">String+Format constructor</a>:</p>
<pre><code>var momentDate = moment('2015-01-16 22:15:00', 'YYYY-MM-DD HH:mm:ss');
</code></pre>
<p>Then, you can convert it to JavaScript Date Object using <a href="http://momentjs.com/docs/#/displaying/as-javascript-date/">toDate() method</a>:</p>
<pre><code>var jsDate = momentDate.toDate();
</code></pre>
|
8,023,829 |
NSDictionary setValue:forKey: -- getting "this class is not key value coding-compliant for the key"
|
<p>I have this simple loop in my program:</p>
<pre><code>for (Element *e in items)
{
NSDictionary *article = [[NSDictionary alloc] init];
NSLog([[e selectElement: @"title"] contentsText]);
[article setValue: [[e selectElement: @"title"] contentsText] forKey: @"Title"];
[self.articles insertObject: article atIndex: [self.articles count]];
[article release];
}
</code></pre>
<p>It is using the ElementParser library to make a dictionary of values from an RSS feed (there are other values besides "title" which I have omitted). <code>self.articles</code> is an NSMutableArray which is storing all of the dictionaries in the RSS document.</p>
<p>In the end, this should produce an array of dictionaries, with each dictionary containing the information I need about the item at any array index. When I try to use <code>setValue:forKey:</code> it gives me the </p>
<p><code>this class is not key value coding-compliant for the key "Title"</code></p>
<p>error. This has nothing to do with Interface Builder, it is all code-only. Why am I getting this error?</p>
| 8,023,875 | 2 | 2 | null |
2011-11-05 22:43:04.407 UTC
| 4 |
2011-11-05 22:50:09.457 UTC
| null | null | null | null | 29,595 | null | 1 | 26 |
objective-c|data-structures|nsdictionary
| 40,586 |
<p>First off, you're using <code>-setValue:forKey:</code> on a dictionary when you should be using <code>-setObject:forKey:</code>. Secondly, you're trying to mutate an <code>NSDictionary</code>, which is an immutable object, instead of an <code>NSMutableDictionary</code>, which would work. If you switch to using <code>-setObject:forKey:</code> you'll probably get an exception telling you that the dictionary is immutable. Switch your <code>article</code> initialization over to</p>
<pre><code>NSMutableDictionary *article = [[NSMutableDictionary alloc] init];
</code></pre>
<p>and it should work.</p>
|
8,706,017 |
maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e
|
<p>I have a fairly simple Maven project:</p>
<pre class="lang-xml prettyprint-override"><code><project>
<dependencies>
...
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>However, I get the following error in m2eclipse:</p>
<pre><code>Description Resource Path Location Type
maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e. pom.xml /jasperreports-test line 60 Maven Project Build Lifecycle Mapping Problem
</code></pre>
<p>Why do I care if m2eclipse doesn't "support" this task? Maven does, and that's all I really care about. How can I get this error in my project to go away? </p>
| 8,752,807 | 8 | 3 | null |
2012-01-02 22:34:48.863 UTC
| 49 |
2015-03-06 11:14:27.313 UTC
|
2014-05-20 03:54:30.53 UTC
| null | 1,521,627 | null | 128,967 | null | 1 | 156 |
eclipse|maven|m2eclipse
| 133,657 |
<p>It seems to be a known issue. You can instruct m2e to ignore this. </p>
<p><strong>Option 1: pom.xml</strong></p>
<p>Add the following inside your <code><build/></code> tag:</p>
<pre><code><pluginManagement>
<plugins>
<!-- Ignore/Execute plugin execution -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<!-- copy-dependency plugin -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins></pluginManagement>
</code></pre>
<p>You will need to do Maven... -> Update Project Configuration on your project after this.</p>
<p>Read more: <a href="http://wiki.eclipse.org/M2E_plugin_execution_not_covered#m2e_maven_plugin_coverage_status">http://wiki.eclipse.org/M2E_plugin_execution_not_covered#m2e_maven_plugin_coverage_status</a></p>
<p><strong>Option 2: Global Eclipse Override</strong></p>
<p>To avoid changing your POM files, the ignore override can be applied to the whole workspace via Eclipse settings.</p>
<p>Save this file somewhere on the disk: <a href="https://gist.github.com/maksimov/8906462">https://gist.github.com/maksimov/8906462</a></p>
<p>In <code>Eclipse/Preferences/Maven/Lifecycle Mappings</code> browse to this file and click OK:</p>
<p><img src="https://i.stack.imgur.com/o7cfG.png" alt="Eclipse Settings"></p>
|
5,227,607 |
Posting an embedded video link using the Facebook Graph API
|
<p>When manually attaching a video link (from YouTube, Vimeo, etc) to a post using the Facebook web interface, Facebook automatically recognizes the link as a video, and allows the resulting status message to play the video inline. The video is displayed as an embedded player in the Wall or News feed.</p>
<hr>
<p>Here's an example of what an embedded video looks like after posting manually.</p>
<p><img src="https://img.skitch.com/20110308-mxwqs11yj94igprkm98xewqs5d.png" alt="Embedded Video"></p>
<hr>
<p>When posting a link using the Graph API, the video is not embedded. </p>
<pre><code>curl -F 'access_token=...' \
-F 'message=Link to YouTube' \
-F 'link=http://www.youtube.com/watch?v=3aICB2mUu2k' \
https://graph.facebook.com/me/feed
</code></pre>
<p><img src="https://img.skitch.com/20110308-qhim3wcyfu9u9gnt4qh1bujy3q.png" alt="Not-Embedded Video"></p>
<hr>
<p>I suspect the answer is related to the <code>source</code> argument, but I'm not sure what the URL should be there. Specifying the same URL just leads to a post with no thumbnail image whatsoever.</p>
<blockquote>
<p><a href="http://developers.facebook.com/docs/reference/api/post/" rel="noreferrer">source</a>: A URL to a Flash movie or video file
to be embedded within the post.
read_stream. </p>
</blockquote>
<p><strong>How can the same embedded behavior be accomplished by using the Graph API alone?</strong></p>
| 5,316,090 | 7 | 2 | null |
2011-03-08 02:20:49.543 UTC
| 27 |
2015-07-31 08:28:43.737 UTC
| null | null | null | null | 8,985 | null | 1 | 41 |
facebook|youtube|facebook-graph-api|embed|vimeo
| 53,808 |
<p>It appears that you have to extract the URLs of the actual swf in the page and the thumbnail image yourself. For example, this seems to work:</p>
<pre><code>curl -F 'access_token=...' \
-F 'message=Link to YouTube' \
-F 'link=http://www.youtube.com/watch?v=3aICB2mUu2k' \
-F 'source=http://www.youtube.com/v/3aICB2mUu2k' \
-F 'picture=http://img.youtube.com/vi/3aICB2mUu2k/0.jpg' \
https://graph.facebook.com/me/feed
</code></pre>
<p>It appears that you can generate a valid source and picture from the page URL. The URL looks like <code>http://www.youtube.com/watch?v=<code></code>; take the code (3aICB2mUu2k here) and insert it into the URLs <code>http://www.youtube.com/e/<code></code> for the source and and <code>http://img.youtube.com/vi/<code>/0.jpg</code> for the picture.</p>
|
5,376,559 |
Is Perl a compiled or an interpreted programming language?
|
<p>Is Perl compiled or interpreted?</p>
| 5,376,580 | 9 | 0 | null |
2011-03-21 10:46:50.58 UTC
| 11 |
2021-01-26 20:06:21.77 UTC
|
2013-04-08 17:26:38.683 UTC
| null | 1,350,209 | null | 134,246 | null | 1 | 28 |
perl|interpreted-language|compiled-language
| 28,540 |
<p>Well, that depends on what you mean by a compiled language. Maybe this is why googling did not bring forth a clear answer to your question.</p>
<p>One viewpoint is that compilation means compiling from a source code description to another, i.e. <a href="http://en.wikipedia.org/wiki/Code_generation_%28compiler%29" rel="noreferrer">code generation</a>.</p>
<p>If we accept these premises, then Perl 6 can be compiled and Perl 5 and older are interpreted languages.</p>
<p>Perl 6 is specifically compiled to <a href="http://www.parrot.org/" rel="noreferrer">Parrot bytecode</a>. Perl 6 is therefore a properly compiled language, in the same way say, <a href="http://en.wikipedia.org/wiki/Java_compiler" rel="noreferrer">Java is</a>.</p>
<p>Perl 5 and older parses the Perl source code to an internal list or tree, but I don't think it should be called a proper compiler, except maybe in a theoretical sense. It does not output any bytecode, assembly or real machine code usually associated with compilers. The parsing stage of Perl to check Perl syntax used to be called "compiling" the source. It is used to check the syntactical validity of a Perl source file without running it.</p>
<p>It is invoked as:</p>
<pre><code>perl -c myprog.pl
</code></pre>
<p>But if you look at the help for Perl options, -c actually stands for "check".</p>
<pre><code>-c check syntax only (runs BEGIN and CHECK blocks)
</code></pre>
<p><sup>(To further complicate things, Perl 5 had support for writing out internal bytecode but it was <a href="http://www.perlmonks.org/index.pl?node_id=722382" rel="noreferrer">removed in version 5.10</a>. Presumably because it was buggy, I don't know.)</sup></p>
<p><strong>On the other hand</strong>, if you argue that compilation is the act of parsing a source tree into any other kind of representation, well, that parsing makes Perl a compiled language. Perl must completely parse a source file before it can start executing it. By this definition, any language which can start executing a source file immediately before parsing would be an interpreted language.</p>
<p><strong>A third way</strong> to look at this is from how these words, "interpreted" and "compiled" are most often used by professionals in the field. I would bet good money that if a random subset of programmers were asked to choose "compiled" or "interpreted" when thinking of Perl, most would choose "interpreted". Not because of some theoretical argument over the nature of Perl, but because "compiled" usually invokes thoughts of "compiling", "linking", "object code" etc, while "interpreted" is taken to mean "write the code, try it". Right or wrong, that may be good to know when trying to determine if Perl is, <em>truly</em>, interpreted or in fact, compiled. You are going to run into many arguments on your quest.</p>
|
16,773,189 |
"Hacking" a way to a remote shell in 5 characters
|
<p>This weekend, there was a CTF wargame happening, Secuinside CTF 2013 ( <a href="http://war.secuinside.com/" rel="nofollow">http://war.secuinside.com/</a> )</p>
<p>Being a computer security enthousiast, I took a look at the challenges, and at their solutions after the CTF was over.</p>
<p>One of the challenges was about <strong>getting a remote shell on a server</strong>, given that a daemon called "givemeshell" is running on this server. What the daemon does is keeping a socket open on a chosen port, let's say port 12345.</p>
<p>When the socket receives something, the daemon takes the <strong>first 5 chars</strong> and launch them in a shell.</p>
<p>For example, if I send <code>cat file</code>, the daemon will launch the command <code>cat f</code> in a shell. <strong>No response is sent</strong>, so I can't know the result of the command.</p>
<p><strong>The objective is to read a file</strong> containing the flag.</p>
<p>Now, someone gave me this solution :</p>
<pre><code>$ nc 1.2.3.4 12345
4<>a
$ nc 1.2.3.4 12345
sh<&4
sh>&4
cat flag
The flag is _FLAG_
</code></pre>
<p>I tested this solution and it works. But after spending several hours trying to understand it, I still can't figure out what it does and why it works. I understand this is about redirecting something...</p>
<p>Can someone explain it to me? Thanks!</p>
| 16,775,110 | 1 | 2 | null |
2013-05-27 12:25:43.863 UTC
| 8 |
2013-11-07 14:28:32.417 UTC
|
2013-11-07 14:28:32.417 UTC
|
user1228
| null | null | 1,532,392 | null | 1 | 11 |
bash|security|shell
| 1,782 |
<p>4 is your connection's file descriptor.</p>
<p>0 is the program stdin, 1 is the program stdout, 2 is the program stderr, when you created a socket to listen for connections it was then assigned to 3, and when it accepted your connection, a new file descriptor of number 4 was created to handle this connection.</p>
<p>4 is the ID of the file descriptor of your connection to the backdoor, assuming you are the first one to connect.</p>
<p>You then type <code>sh<&4</code>. It opens <code>sh</code> and tell it should get all input directly from your connection.</p>
<p>Right now you are already in full control of the shell, because <code>sh</code> took over and every command you send is interpreted directly by it. But you still cannot see any output!</p>
<p>Then you type <code>sh>&4</code> to open a new level of <code>sh</code> inside the other saying it should push all output to your file descriptor. The trick is done! Two-way communication.</p>
|
29,543,780 |
Why do linked lists use pointers instead of storing nodes inside of nodes
|
<p>I've worked with linked lists before extensively in Java, but I'm very new to C++. I was using this node class that was given to me in a project just fine</p>
<pre><code>class Node
{
public:
Node(int data);
int m_data;
Node *m_next;
};
</code></pre>
<p>but I had one question that wasn't answered very well. Why is it necessary to use</p>
<pre><code>Node *m_next;
</code></pre>
<p>to point to the next node in the list instead of</p>
<pre><code>Node m_next;
</code></pre>
<p>I understand that it is better to use the pointer version; I'm not going to argue facts, but I don't know why it's better. I got a not so clear answer about how the pointer is better for memory allocation, and I was wondering if anyone here could help me understand that better.</p>
| 29,543,917 | 11 | 22 | null |
2015-04-09 16:17:12.857 UTC
| 24 |
2020-07-10 00:48:30.857 UTC
|
2016-03-27 20:33:36.647 UTC
| null | 3,772,221 | null | 3,772,221 | null | 1 | 125 |
c++|pointers|linked-list
| 16,190 |
<p>It's not just better, it's the only possible way.</p>
<p>If you stored a <code>Node</code> <em>object</em> inside itself, what would <code>sizeof(Node)</code> be? It would be <code>sizeof(int) + sizeof(Node)</code>, which would be equal to <code>sizeof(int) + (sizeof(int) + sizeof(Node))</code>, which would be equal to <code>sizeof(int) + (sizeof(int) + (sizeof(int) + sizeof(Node)))</code>, etc. to infinity.</p>
<p>An object like that can't exist. It's <em>impossible</em>.</p>
|
65,303,304 |
Xcode 12.3: Building for iOS Simulator, but the linked and embedded framework was built for iOS + iOS Simulator
|
<p>I have an app using a linked and embedded custom framework. The app built properly for iOS devices and simulators until Xcode 12.2. Starting from Xcode 12.3 however, I'm getting the following error:</p>
<blockquote>
<p>Building for iOS Simulator, but the linked and embedded framework 'My.framework' was built for iOS + iOS Simulator.</p>
</blockquote>
<p>The framework is built for both devices and simulators (as the error actually says) and merged using <code>lipo</code>, so it should be able to run everywhere without issues.</p>
<p>Am I missing something here? Is there a relevant change in Xcode 12.3?</p>
| 65,315,026 | 4 | 9 | null |
2020-12-15 09:39:08.4 UTC
| 40 |
2022-08-19 23:24:42.19 UTC
|
2022-08-19 22:49:41.62 UTC
| null | 63,550 | null | 1,707,129 | null | 1 | 187 |
ios|xcode12|lipo
| 104,189 |
<p>I'm afraid that this is actually the correct error and the framework shouldn't contain iOS and iOS Simulator code at the same time. Apple tries to force us to use <code>XCFramework</code>s for this purpose. They started it in Xcode 11 and just tightened up the restrictions.</p>
<p>The only correct way to resolve this is to rebuild the framework as an <a href="https://developer.apple.com/videos/play/wwdc2019/416/" rel="nofollow noreferrer">XCFramework</a>. Which is easy to do:</p>
<pre class="lang-none prettyprint-override"><code>xcrun xcodebuild -create-xcframework \
-framework /path/to/ios.framework \
-framework /path/to/sim.framework \
-output combined.xcframework
</code></pre>
<p>You can start with a combined <code>.framework</code>. Make two copies of the framework, and use <code>lipo</code> to remove the slices from the binary that are associated with a different SDK.</p>
<p>It is based on the original answer from Apple <a href="https://developer.apple.com/forums/thread/669411?answerId=652663022#652663022" rel="nofollow noreferrer">here</a>.</p>
<p>My particular case is that I'm getting this error using <a href="https://github.com/tmspzz/Rome" rel="nofollow noreferrer">Rome</a>, which produces these frameworks (a possible solution is <a href="https://github.com/CocoaPods/Rome/pull/90" rel="nofollow noreferrer">here</a>). Also, a lot of struggling is going on on the <a href="https://github.com/Carthage/Carthage/issues/3019" rel="nofollow noreferrer">Carthage side</a>.</p>
|
12,445,010 |
What is The use of moveToFirst () in SQLite Cursors
|
<p>I am a programming newbie
and I found this piece of code in the internet and it works fine</p>
<pre><code>Cursor c=db.query(DataBase.TB_NAME, new String[] {DataBase.KEY_ROWID,DataBase.KEY_RATE}, DataBase.KEY_ROWID+"= 1", null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
</code></pre>
<p>but I am not able to understand the use of the</p>
<pre><code>if(c!=null)
{
c.moveToFirst();
}
</code></pre>
<p>part. What does it do exactly , and if I remove the</p>
<pre><code>if(c!=null) { c.moveToFirst(); }
</code></pre>
<p>part, the code doesn't work.</p>
| 12,445,030 | 5 | 0 | null |
2012-09-16 06:58:24.233 UTC
| 7 |
2021-12-23 04:08:58.933 UTC
|
2021-12-23 04:08:58.933 UTC
| null | 4,294,399 | null | 1,675,286 | null | 1 | 23 |
android|sqlite|database-cursor
| 49,595 |
<p>The docs for <a href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query%28java.lang.String,%20java.lang.String%5B%5D,%20java.lang.String,%20java.lang.String%5B%5D,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String%29">SQLiteDatabase.query()</a> say that the query methods return:</p>
<p>"A Cursor object, which is positioned before the first entry."</p>
<p>Calling <code>moveToFirst()</code> does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Note that to guard against an empty return set, the code you posted should be testing the return value (which it is not doing).</p>
<p>Unlike the call to <code>moveToFirst()</code>, the test for <code>if(c!=null)</code> is useless; <code>query()</code> will either return a <code>Cursor</code> object or it will throw an exception. It will never return <code>null</code>.</p>
|
12,639,407 |
SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error
|
<p>I have the following SQL query:</p>
<pre><code>IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1')
UPDATE component_psar
SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1',
col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1'
WHERE tbl_id = '2' AND row_nr = '1'
ELSE
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4,
col_5, col_6, unit, add_info, fsar_lock)
VALUES ('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
</code></pre>
<p>Ignore the fact that I'm trying to set every column to '1'. It's just example data. :)</p>
<p>Anyways, executing this query returns a syntax error:</p>
<pre><code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM
component_psar WHERE tbl_id = '2' AND row_nr = '1') UP' at line 1
</code></pre>
<p>I've been staring at it and searching the internet for a good half an hour and just can't find this supposed syntax error. It's probably going to end up being something really dumb that I'm missing but I could use you guys' help on this one.</p>
| 12,639,529 | 6 | 4 | null |
2012-09-28 11:46:57.247 UTC
| 10 |
2017-05-05 15:23:59.037 UTC
|
2012-09-28 12:27:09.747 UTC
| null | 1,297,603 | null | 1,540,332 | null | 1 | 33 |
mysql|sql
| 132,866 |
<pre><code>INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
ON DUPLICATE KEY UPDATE col_1 = VALUES(col_1), col_2 = VALUES(col_2), col_3 = VALUES(col_3), col_4 = VALUES(col_4), col_5 = VALUES(col_5), col_6 = VALUES(col_6), unit = VALUES(unit), add_info = VALUES(add_info), fsar_lock = VALUES(fsar_lock)
</code></pre>
<p>Would work with <code>tbl_id</code> and <code>row_nr</code> having <code>UNIQUE</code> key.</p>
<p>This is the method DocJonas linked to with an example.</p>
|
12,419,619 |
What's the difference between ng-model and ng-bind
|
<p>I'm currently learning AngularJS and am having difficulty understanding the difference between <code>ng-bind</code> and <code>ng-model</code>.</p>
<p>Can anyone tell me how they differ and when one should be used over the other?</p>
| 12,420,157 | 8 | 0 | null |
2012-09-14 07:02:10.507 UTC
| 160 |
2018-11-16 13:09:20.28 UTC
|
2016-11-16 09:45:03.2 UTC
| null | 133,203 | null | 448,337 | null | 1 | 560 |
angularjs|angular-ngmodel|ng-bind
| 252,043 |
<p><strong>ng-bind</strong> has one-way data binding ($scope --> view). It has a shortcut <code>{{ val }}</code>
which displays the scope value <code>$scope.val</code> inserted into html where <code>val</code> is a variable name.</p>
<p><strong>ng-model</strong> is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <code><input ng-model="val"/></code>.</p>
|
12,370,495 |
Share a cookie between two websites
|
<p>I have built a website (A) which logs in to and retrieves customer data from a separate web service.</p>
<p>The organisation that owns (A) also has a website (B) which has a web form. They want a logged in customer on (A) to be able to click across to (B) and see a pre-populated form with their details.</p>
<p>This means (A) must write their customer ID to a cookie, which (B) can read, and then (B) can request the data from the web service, and pre-populate the form.</p>
<p>This raises two questions:</p>
<ol>
<li><p>Can website (B) read the cookie for website (A)?</p></li>
<li><p>If so, to prevent someone from editing a cookie and seeing other people's data in the form, I would need to do something like encrypt the cookie on (A) and then have that decrypted in (B) - any suggestions along this line?</p></li>
</ol>
<p>I can't change the existing login to OAuth or something, as the web service is consumed by several other sites, so this cannot change.</p>
| 12,370,586 | 7 | 1 | null |
2012-09-11 13:10:10.163 UTC
| 17 |
2019-04-19 02:37:45.067 UTC
| null | null | null | null | 214,980 | null | 1 | 51 |
http|cookies
| 75,677 |
<p>No. Website B can't read a cookie from website A. </p>
<p>The easiest work-around is to pass login/credential information from website A to website B and have website B set a seperate cookie. For example, after logging into website A you could have them quickly redirected to website B with an encrypted querystring. Website B could then read the information, set its own cookie, and redirect the user back to site A.</p>
<p>It's messy but possible.</p>
|
12,450,321 |
why is javascript node.js not on google app engine
|
<p>Google created the V8 JavaScript engine: V8 compiles JavaScript source code directly into machine code when it is first executed.</p>
<p>Node.js is built on V8 - why is Google not offering any Node.js servers like Microsoft Azure?</p>
<p>Google App Engine would be a natural place to put Node.js.</p>
<p>Do you know why Google is not doing just that?</p>
| 24,427,331 | 12 | 3 | null |
2012-09-16 20:08:34.76 UTC
| 29 |
2021-07-04 18:36:29.987 UTC
|
2019-07-25 14:42:16.053 UTC
| null | 1,082,449 | null | 699,215 | null | 1 | 72 |
google-app-engine|node.js
| 34,821 |
<p>As of June 2014, Google had a limited preview for custom languages on <a href="https://stackoverflow.com/questions/22697049/what-is-the-difference-between-google-app-engine-and-google-compute-engine">Google App Engine (which is different from Google Compute Engine)</a>.</p>
<p>Watch <a href="https://www.youtube.com/watch?v=Q8jZHc0NS6A" rel="nofollow noreferrer">Building Node.js applications with App Engine and Custom Runtimes</a> and check out <a href="https://cloud.google.com/appengine/docs/managed-vms/" rel="nofollow noreferrer">https://cloud.google.com/appengine/docs/managed-vms/</a>:</p>
<blockquote>
<p>App Engine now offers a second hosting option: Managed VMs. The Managed VM hosting environment lets you run App Engine applications on configurable Compute Engine Virtual Machines (VMs).
You can also use Managed VMs to deploy user-configurable <a href="https://cloud.google.com/appengine/docs/managed-vms/custom-runtimes" rel="nofollow noreferrer">custom runtimes</a>, such as for <a href="https://cloud.google.com/solutions/nodejs/" rel="nofollow noreferrer">Node.js</a> and other runtimes.</p>
</blockquote>
<p>The procedure to get into the beta is:</p>
<h1>Sign up and create a Managed VM project</h1>
<p>Managed VMs are in Limited Preview, you must sign up for access to this feature, create a billing-enabled project, and tell us about your project so we can whitelist it to run in a Managed VM. Follow these steps:</p>
<ol>
<li>Sign up for access to Managed VMs.</li>
<li>Join the app-engine-managed-vms Google Group to participate in discussions about Managed VMs.</li>
<li>Projects (or apps - they are the same thing) must be in a U.S. data center. If you're planning to use an existing project, skip to the next step. Otherwise, create a new app in a U.S. data center. Navigate to <a href="https://preview.appengine.google.com" rel="nofollow noreferrer">https://preview.appengine.google.com</a> and create a new app.</li>
<li>Enable billing for the project. Visit the page <a href="https://cloud.google.com/console/project/apps~" rel="nofollow noreferrer">https://cloud.google.com/console/project/apps~</a>, where is the ID of your project. Click on Settings in the left menu and then enable billing. If your app is billed under a Premier account, email us at app-engine-managed-vm-tt-id@google.com to have your new Cloud project billed under the same account.</li>
<li>Send an email to app-engine-managed-vm-tt-id@google.com with the application ID in the subject line.</li>
</ol>
<p>When we receive your email, we’ll configure some resources behind the scenes and notify you via email when your project is ready to go. The email includes final instructions for setup. If you encounter an error while following these instructions, contact us at app-engine-managed-vm-tt-id@google.com.</p>
|
19,158,559 |
How to fix a header on scroll
|
<p>I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.</p>
<p>Can I do this using just css and html or do i need jquery too?</p>
<p>I have created a demo so you can understand. Any help would be great!</p>
<p><a href="http://jsfiddle.net/gxRC9/4/" rel="nofollow noreferrer">http://jsfiddle.net/gxRC9/4/</a></p>
<pre><code>body{
margin:0px;
padding:0px;
}
.clear{
clear:both;
}
.container{
height:2000px;
}
.cover-photo-container{
width:700px;
height: 348px;
margin-bottom: 20px;
background-color:red;
}
.small-box{
width:163px;
height:100px;
border:1px solid blue;
float:left;
}
.sticky-header{
width:700px;
height:50px;
background:orange;
postion:fixed;
}
</code></pre>
| 19,158,690 | 16 | 4 | null |
2013-10-03 11:54:34.11 UTC
| 30 |
2022-08-23 09:01:33.4 UTC
|
2021-10-30 11:53:34.377 UTC
| null | 3,343,230 | null | 2,798,492 | null | 1 | 58 |
jquery|css|header|fixed
| 342,458 |
<p>You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="sticky"></div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.fixed {
position: fixed;
top:0; left:0;
width: 100%; }
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();
if (scroll >= 100) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
</code></pre>
<p>Example fiddle: <a href="http://jsfiddle.net/gxRC9/501/" rel="noreferrer">http://jsfiddle.net/gxRC9/501/</a></p>
<hr>
<p><strong>EDIT: Extended example</strong></p>
<p>If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, <code>offset().top</code> can be used.</p>
<pre><code>var stickyOffset = $('.sticky').offset().top;
$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();
if (scroll >= stickyOffset) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
</code></pre>
<p>Extended example fiddle: <a href="http://jsfiddle.net/gxRC9/502/" rel="noreferrer">http://jsfiddle.net/gxRC9/502/</a></p>
|
19,066,066 |
iOS 7 UIWebView not rendering
|
<p>I'm porting my app to iOS 7 and I have a problem with UIWebView in iOS 7.
I load local html string in it with this code:</p>
<pre><code>NSURL *baseURL = [NSURL fileURLWithPath: DOCUMENTS_DIRECTORY];
[self.descWebView loadHTMLString:html baseURL:baseURL];
</code></pre>
<p>It works perfectly on iOS 6 and prior but on iOS 7 it doesn't rendering and the UIWebView is still white. And this message appears in console:</p>
<pre><code>void SendDelegateMessage(NSInvocation *): delegate
(webView:decidePolicyForNavigationAction:request:frame:decisionListener:)
failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
</code></pre>
<p>Thanks for your replies.</p>
| 19,328,839 | 10 | 6 | null |
2013-09-28 10:46:14.357 UTC
| 5 |
2015-11-30 04:30:16.853 UTC
| null | null | null | null | 2,826,077 | null | 1 | 28 |
ios|uiwebview|ios7
| 11,492 |
<p>As mentioned by @zaplitny, I had to update Crittercism to the latest version (4.1.0) for this problem to go away. </p>
|
24,430,220 |
E11000 duplicate key error index in mongodb mongoose
|
<p>Following is my <code>user</code> schema in <code>user.js</code> model -</p>
<pre><code>var userSchema = new mongoose.Schema({
local: {
name: { type: String },
email : { type: String, require: true, unique: true },
password: { type: String, require:true },
},
facebook: {
id : { type: String },
token : { type: String },
email : { type: String },
name : { type: String }
}
});
var User = mongoose.model('User',userSchema);
module.exports = User;
</code></pre>
<p>This is how I am using it in my controller - </p>
<pre><code>var user = require('./../models/user.js');
</code></pre>
<p>This is how I am saving it in the db -</p>
<pre><code>user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
if(err)
res.send(err);
else {
console.log(result);
req.session.user = result;
res.send({"code":200,"message":"Record inserted successfully"});
}
});
</code></pre>
<p><strong>Error</strong> -</p>
<pre><code>{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1 dup key: { : null }"}
</code></pre>
<p>I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ?</p>
<p>FYI - <code>req.body.email</code> and <code>req.body.password</code> are fetching values.</p>
<p>I also checked this post but no help <a href="https://stackoverflow.com/questions/21119928/getting-err-e11000-duplicate-key-error-when-inserting-into-mongo-using-the">STACK LINK</a></p>
<p>If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the local.email</p>
| 24,430,345 | 22 | 4 | null |
2014-06-26 12:12:30.777 UTC
| 71 |
2022-08-24 09:34:38.477 UTC
|
2018-08-09 05:14:35.473 UTC
| null | 6,792,646 | null | 1,594,368 | null | 1 | 332 |
node.js|mongodb|mongoose
| 476,396 |
<p>The error message is saying that there's already a record with <code>null</code> as the email. In other words, you already have a user without an email address.</p>
<p>The relevant documentation for this:</p>
<blockquote>
<p>If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.</p>
<p>You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.</p>
</blockquote>
<p><a href="http://docs.mongodb.org/manual/core/index-unique/#unique-index-and-missing-field" rel="noreferrer">unique indexes</a></p>
<blockquote>
<p>Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.</p>
</blockquote>
<p>In other words, a sparse index is ok with multiple documents all having <code>null</code> values.</p>
<p><a href="http://docs.mongodb.org/manual/core/index-sparse/" rel="noreferrer">sparse indexes</a></p>
<hr />
<p>From comments:</p>
<p>Your error says that the key is named <code>mydb.users.$email_1</code> which makes me suspect that you have an index on both <code>users.email</code> and <code>users.local.email</code> (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with <code>mydb.users.getIndexes()</code> if this is the case and manually remove the unwanted index with <code>mydb.users.dropIndex(<name>)</code>.</p>
|
24,340,061 |
iOS 8 Custom Keyboard
|
<p>I am trying to build a custom keyboard, it's like a emoji keyboard, but the keyboard's data is from a json file. After parse this json file and get the data, how to make the custom keyboard use it and show in the keyboard view, like the emoji keyboard that built in? Right now, I follow App Extension Keyboard: Custom Keyboard guide, and there only small bits of information here. Is there any tutorial or guide about how to create a custom emoji keyboard online? The current codes I am trying are below:</p>
<pre><code>class KeyboardViewController: UIInputViewController {
override func viewDidLoad() {
super.viewDidLoad()
var error: NSError?
let yanFile = NSBundle.mainBundle().pathForResource("yan", ofType: "json")
let yanData = NSData(contentsOfFile: yanFile) as NSData
let yanDict = NSJSONSerialization.JSONObjectWithData(yanData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
println("dict: \(yanDict)") //print nothing in console
// Perform custom UI setup here
self.nextKeyboardButton = UIButton.buttonWithType(.System) as UIButton
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), forState: .Normal)
}
}
</code></pre>
<p>The json like below:</p>
<pre><code>{
"list":
[
{
"tag": "laugh",
"yan":
[
"o(*≧▽≦)ツ┏━┓",
"(/≥▽≤/)",
"ヾ(o◕∀◕)ノ"
]
},
{
"tag": "wanna",
"yan":
[
"✪ω✪",
"╰(*°▽°*)╯",
"≖‿≖✧",
">ㅂ<",
"ˋ▽ˊ",
"✪ε✪",
"✪υ✪",
"ヾ (o ° ω ° O ) ノ゙",
"(。◕ˇ∀ˇ◕)",
"(¯﹃¯)"
]
}
]
}
</code></pre>
| 24,480,540 | 2 | 5 | null |
2014-06-21 09:03:34.34 UTC
| 11 |
2016-02-01 04:15:41.67 UTC
|
2016-02-01 04:15:41.67 UTC
| null | 189,804 | null | 1,037,295 | null | 1 | 12 |
ios|keyboard|swift|ios8|ios-app-extension
| 11,440 |
<p>You can build a xib file by clicking new file -> view</p>
<p>1) inside the xib file create a uiview 320x216 and you can drag'n'drop whatever controls you want into it</p>
<p>2) then you can load the nib like this into your keyboard's inputView:</p>
<pre><code>// Perform custom UI setup here
UIView *layout = [[[NSBundle mainBundle] loadNibNamed:@"keyboardXib" owner:self options:nil] objectAtIndex:0];
[self.inputView addSubview:layout];
</code></pre>
<p>3) i think it's amazing if you build a JSON to keyboard api
you send a JSON of the keyboard map to your app
and the app knows how to arrange the keys on the inputView accordingly</p>
<p>let us know if you build this project!</p>
<p>EDIT:</p>
<p>4) Most of what you need to do is parse the JSON and display the content you want from the JSON uibuttons, and also decide what text they are inserting into the text field</p>
<p>check out this question: <a href="https://stackoverflow.com/questions/24013410/how-to-parse-a-json-file-in-swift">How to parse a JSON file in swift?</a></p>
<p>Good luck!</p>
|
24,297,257 |
Save HTML of some website in a txt file with python
|
<p>I need save the HTML code of any website in a txt file, is a very easy exercise but I have doubts with this because a have a function that do this:</p>
<pre><code>import urllib.request
def get_html(url):
f=open('htmlcode.txt','w')
page=urllib.request.urlopen(url)
pagetext=page.read() ## Save the html and later save in the file
f.write(pagetext)
f.close()
</code></pre>
<p>But this doesn't work.</p>
| 24,297,356 | 2 | 9 | null |
2014-06-19 01:05:17.247 UTC
| 6 |
2019-09-26 06:47:45.047 UTC
|
2014-10-28 19:03:24.353 UTC
| null | 3,001,761 | null | 2,036,128 | null | 1 | 14 |
python|html|parsing|python-3.x|urllib
| 46,412 |
<p>Easiest way would be to use <a href="https://docs.python.org/2/library/urllib.html#urllib.urlretrieve" rel="noreferrer">urlretrieve</a>:</p>
<pre><code>import urllib
urllib.urlretrieve("http://www.example.com/test.html", "test.txt")
</code></pre>
<p>For Python 3.x the code is as follows:</p>
<pre><code>import urllib.request
urllib.request.urlretrieve("http://www.example.com/test.html", "test.txt")
</code></pre>
|
22,669,528 |
Securely storing environment variables in GAE with app.yaml
|
<p>I need to store API keys and other sensitive information in <code>app.yaml</code> as environment variables for deployment on GAE. The issue with this is that if I push <code>app.yaml</code> to GitHub, this information becomes public (not good). I don't want to store the info in a datastore as it does not suit the project. Rather, I'd like to swap out the values from a file that is listed in <code>.gitignore</code> on each deployment of the app.</p>
<p>Here is my app.yaml file:</p>
<pre><code>application: myapp
version: 3
runtime: python27
api_version: 1
threadsafe: true
libraries:
- name: webapp2
version: latest
- name: jinja2
version: latest
handlers:
- url: /static
static_dir: static
- url: /.*
script: main.application
login: required
secure: always
# auth_fail_action: unauthorized
env_variables:
CLIENT_ID: ${CLIENT_ID}
CLIENT_SECRET: ${CLIENT_SECRET}
ORG: ${ORG}
ACCESS_TOKEN: ${ACCESS_TOKEN}
SESSION_SECRET: ${SESSION_SECRET}
</code></pre>
<p>Any ideas?</p>
| 35,261,091 | 15 | 7 | null |
2014-03-26 18:08:23.807 UTC
| 41 |
2022-02-18 08:19:13.54 UTC
| null | null | null | null | 1,676,476 | null | 1 | 116 |
python|google-app-engine|python-2.7|environment-variables
| 53,106 |
<p>If it's sensitive data, you should not store it in source code as it will be checked into source control. The wrong people (inside or outside your organization) may find it there. Also, your development environment probably uses different config values from your production environment. If these values are stored in code, you will have to run different code in development and production, which is messy and bad practice.</p>
<p>In my projects, I put config data in the datastore using this class:</p>
<pre><code>from google.appengine.ext import ndb
class Settings(ndb.Model):
name = ndb.StringProperty()
value = ndb.StringProperty()
@staticmethod
def get(name):
NOT_SET_VALUE = "NOT SET"
retval = Settings.query(Settings.name == name).get()
if not retval:
retval = Settings()
retval.name = name
retval.value = NOT_SET_VALUE
retval.put()
if retval.value == NOT_SET_VALUE:
raise Exception(('Setting %s not found in the database. A placeholder ' +
'record has been created. Go to the Developers Console for your app ' +
'in App Engine, look up the Settings record with name=%s and enter ' +
'its value in that record\'s value field.') % (name, name))
return retval.value
</code></pre>
<p>Your application would do this to get a value:</p>
<pre><code>API_KEY = Settings.get('API_KEY')
</code></pre>
<p>If there is a value for that key in the datastore, you will get it. If there isn't, a placeholder record will be created and an exception will be thrown. The exception will remind you to go to the Developers Console and update the placeholder record.</p>
<p>I find this takes the guessing out of setting config values. If you are unsure of what config values to set, just run the code and it will tell you!</p>
<p>The code above uses the ndb library which uses memcache and the datastore under the hood, so it's fast.</p>
<hr>
<p><strong>Update:</strong></p>
<p><em>jelder</em> asked for how to find the Datastore values in the App Engine console and set them. Here is how:</p>
<ol>
<li><p>Go to <a href="https://console.cloud.google.com/datastore/" rel="noreferrer">https://console.cloud.google.com/datastore/</a></p></li>
<li><p>Select your project at the top of the page if it's not already selected.</p></li>
<li><p>In the <em>Kind</em> dropdown box, select <em>Settings</em>.</p></li>
<li><p>If you ran the code above, your keys will show up. They will all have the value <em>NOT SET</em>. Click each one and set its value.</p></li>
</ol>
<p>Hope this helps!</p>
<p><a href="https://i.stack.imgur.com/cs0bV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cs0bV.png" alt="Your settings, created by the Settings class"></a></p>
<p><a href="https://i.stack.imgur.com/Xx4C4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xx4C4.png" alt="Click to edit"></a></p>
<p><a href="https://i.stack.imgur.com/OrKxR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OrKxR.png" alt="Enter the real value and save"></a></p>
|
8,419,332 |
Proper session hijacking prevention in PHP
|
<p>I know this topic has been discussed <em>a lot</em>, but I have a few specific questions still not answered. For example:</p>
<pre><code>// **PREVENTING SESSION HIJACKING**
// Prevents javascript XSS attacks aimed to steal the session ID
ini_set('session.cookie_httponly', 1);
// Adds entropy into the randomization of the session ID, as PHP's random number
// generator has some known flaws
ini_set('session.entropy_file', '/dev/urandom');
// Uses a strong hash
ini_set('session.hash_function', 'whirlpool');
</code></pre>
<hr>
<pre><code>// **PREVENTING SESSION FIXATION**
// Session ID cannot be passed through URLs
ini_set('session.use_only_cookies', 1);
// Uses a secure connection (HTTPS) if possible
ini_set('session.cookie_secure', 1);
</code></pre>
<hr>
<pre><code>session_start();
// If the user is already logged
if (isset($_SESSION['uid'])) {
// If the IP or the navigator doesn't match with the one stored in the session
// there's probably a session hijacking going on
if ($_SESSION['ip'] !== getIp() || $_SESSION['user_agent_id'] !== getUserAgentId()) {
// Then it destroys the session
session_unset();
session_destroy();
// Creates a new one
session_regenerate_id(true); // Prevent's session fixation
session_id(sha1(uniqid(microtime())); // Sets a random ID for the session
}
} else {
session_regenerate_id(true); // Prevent's session fixation
session_id(sha1(uniqid(microtime())); // Sets a random ID for the session
// Set the default values for the session
setSessionDefaults();
$_SESSION['ip'] = getIp(); // Saves the user's IP
$_SESSION['user_agent_id'] = getUserAgentId(); // Saves the user's navigator
}
</code></pre>
<p>So, my questions are</p>
<ul>
<li>do the <code>ini_set</code>'s provide enough security?</li>
<li>is it okay to save the user's IP and navigator and then check it
every time the page is loaded to detect a session hijack? Could this be problematic in any way?</li>
<li>is the use of <code>session_regenerate_id()</code> correct?</li>
<li>is the use of <code>session_id()</code> correct?</li>
</ul>
| 8,419,884 | 1 | 6 | null |
2011-12-07 17:02:34.637 UTC
| 20 |
2016-03-02 01:54:23.927 UTC
| null | null | null | null | 2,612,112 | null | 1 | 23 |
php|security|session|sessionid|session-hijacking
| 10,503 |
<p>Your configuration is awesome. You definitely read up on how to lock down php sessions. However this line of code negates a lot of the protection provided by your php configuration:
<code>session_id(sha1(uniqid(microtime()));</code></p>
<p>This is a <strong>particularly awful</strong> method of generating a session id. Based on your configurations you are generating the session id from <code>/dev/urandom</code> which is a awesome entropy pool. This is going to be a lot more random than uniqid() which is already mostly a timestamp, adding another timestamp to this mix doesn't help at all. Remove this line of code, asap. </p>
<p>Checking the IP address is problematic, ip addresses change for legitimate reasons, such as if the user is behind a load balancer or TOR. The user agent check is pointless, it is like having a GET variable like <code>?is_hacker=False</code>, if the attacker has the session id they probably have the user agent, and if they don't this value is really easy to brute force. </p>
|
8,656,089 |
Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP
|
<p>I have made a function that finds all the URLs within an html file and repeats the same process for each html content linked to the discovered URLs. The function is recursive and can go on endlessly. However, I have put a limit on the recursion by setting a global variable which causes the recursion to stop after 100 recursions.</p>
<p>However, php returns this error:</p>
<blockquote>
<p>Fatal error: Maximum function nesting level of '100' reached,
aborting! in
D:\wamp\www\crawler1\simplehtmldom_1_5\simple_html_dom.php on line
1355</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/J6cIy.png" alt="ERROR" /></p>
<p>I found a solution here: <a href="https://stackoverflow.com/questions/4293775/increasing-nesting-functions-calls-limit">Increasing nesting function calls limit</a> but this is not working in my case.</p>
<p><em>I am quoting one of the answers from the link mentioned above. Please do consider it.</em></p>
<blockquote>
<p>"Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.</p>
<p>I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let >you go past the 100 iterations, but you will eventually hit the memory limits."</p>
</blockquote>
<p>Is there a way to increase the maximum function nesting level in PHP</p>
| 8,667,421 | 23 | 6 | null |
2011-12-28 12:46:23.873 UTC
| 28 |
2020-12-31 18:09:07.29 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 569,085 | null | 1 | 146 |
recursion|xdebug|php
| 313,801 |
<p>A simple solution solved my problem. I just commented this line:</p>
<pre><code>zend_extension = "d:/wamp/bin/php/php5.3.8/zend_ext/php_xdebug-2.1.2-5.3-vc9.dll
</code></pre>
<p>in my <code>php.ini</code> file. This extension was limiting the stack to <code>100</code> so I disabled it. The recursive function is now working as anticipated.</p>
|
10,949,937 |
How to call a controller method from Javascript
|
<p>I am displaying a bunch of movies in a table, I am eventually deleting each movie through Javascript which hides the div. </p>
<p>I now want to delete the movie from the database as well, so what is the best way to call the controller method from the Javascript?</p>
| 10,950,172 | 4 | 3 | null |
2012-06-08 13:37:27.83 UTC
| null |
2022-08-18 16:46:31.967 UTC
|
2014-09-30 14:47:27.723 UTC
| null | 2,460,971 | null | 781,238 | null | 1 | 7 |
asp.net|.net|asp.net-mvc-3
| 73,295 |
<p>Have an <strong>HTTPPost</strong> action method to delete in your <code>movie</code> controller</p>
<pre><code>[HttpPost]
public ActionResult Delete(int id)
{
try
{
repo.DeleteMovie(id);
return "deleted"
}
catch(Exception ex)
{
//Log errror
}
return "failed";
}
</code></pre>
<p>And in your View,</p>
<pre><code><a href="#" data-movieId="34" class="movie">Delete Avengers</a>
<a href="#" data-movieId="35" class="movie">Delete Iron Man</a>
<script type="text/javascript">
$(function(){
$(".movie").click(function(e){
e.preventDefault();
$.post("@Url.Action("Delete","Movie")", { id : $(this).data("movieId")} ,function(data){
alert(data);
});
});
});
</script>
</code></pre>
|
11,029,538 |
SQLite query from multiple tables using SQLiteDatabase
|
<p>I have 2 tables in my database, for example: <code>Table1: id (PK), data1</code> and <code>Table2: id (PK), id_table1 (FK), data2</code>. How can I make a query like that: </p>
<pre><code>SELECT * FROM Table1, Table2 WHERE Table1.id = Table2.id_table1
GROUP BY Table1.data1
</code></pre>
<p>I'm using <code>SQLiteDatabase</code> and its <code>query()</code> method.</p>
<pre><code>Cursor mCursor = db.query(true, new String[] {"Table1","Table2"},
new String[] {"Table1.id","data1", "Table2.id", "id_table1", "data2"},
"Table1.id=Table2.id_table1", null, "Table1.data1", null,null,null);
</code></pre>
<p>But there's a problem with the second arg - it's only possible to use String, not String[] (like <code>new String[] {"Table1","Table2}</code>). What should I do to make a query from multiple tables in that way?</p>
| 11,029,587 | 2 | 0 | null |
2012-06-14 08:40:28.797 UTC
| 12 |
2012-06-14 08:53:14.56 UTC
|
2012-06-14 08:41:59.793 UTC
| null | 385,478 | null | 1,049,280 | null | 1 | 13 |
android|sqlite
| 54,265 |
<p>Try this:</p>
<pre><code>Cursor mCursor = db.rawQuery("SELECT * FROM Table1, Table2 " +
"WHERE Table1.id = Table2.id_table1 " +
"GROUP BY Table1.data1", null);
</code></pre>
|
11,337,420 |
Can I use an existing user as Django admin when enabling admin for the first time?
|
<p>I have built a Django site for a while, but I never enabled Django admin. </p>
<p>User accounts are registered on both LDAP and Django, but the master record is based on LDAP. So I must use the account in LDAP as super user.</p>
<p>When I enable Django Admin, I am prompted to create a super user. Can I use an existing account (registered on both LDAP and Django db) as super user?</p>
<p>How?</p>
| 11,337,600 | 2 | 0 | null |
2012-07-05 03:06:40.383 UTC
| 11 |
2020-03-04 17:12:18.853 UTC
|
2012-07-05 03:12:43.703 UTC
| null | 15,168 | null | 1,253,487 | null | 1 | 30 |
django|django-admin
| 13,999 |
<p>Yes, but you'll do it through the Django shell:</p>
<pre><code>python manage.py shell
</code></pre>
<p>Then fetch your user from the database:</p>
<pre><code>from django.contrib.auth.models import User
user = User.objects.get(username="myname")
user.is_staff = True
user.is_admin = True
user.save()
</code></pre>
<p>Exit the shell, and that user will now be an admin user.</p>
<p>You can also add the line</p>
<pre><code>user.is_superuser = True
</code></pre>
<p>before calling <code>user.save()</code> if you want or need this user to be a superuser and have all the available permissions.</p>
|
10,930,624 |
Creating JSON objects directly from model classes in Java
|
<p>I have some model classes like <code>Customer</code>, <code>Product</code>, etc. in my project which have several fields and their setter-getter methods, I need to <strong>exchange objects of these classes as a JSONObject via Sockets</strong> to and from client and server.</p>
<p>Is there any way I can create <code>JSONObject</code> directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.</p>
<p>Example:</p>
<pre><code>Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....
</code></pre>
<p>And I create JSON Object as:</p>
<pre><code>JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.
</code></pre>
<p>Which gets me something like:</p>
<pre><code>{"name":"Foo Bar","city":"Atlantis"...}
</code></pre>
<p>Please note that, in some of my model classes, certain properties are itself <strong>an object of other model class</strong>. Such as:</p>
<pre><code>Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
</code></pre>
<p>In a case like above, as I'd expect, the yielded JSON object would be:</p>
<pre><code>{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}
</code></pre>
<p>I know I could create something like <code>toJSONString()</code> in each model class and have the JSON-friendly string created and manipulate it then, but in my previous experiences of creating RESTful service in Java (which is totally out of context for this question), I could return JSON string from the service method by using <code>@Produces(MediaType.APPLICATION_JSON)</code> and have the method returning object of model class. So it produced JSON string, which I could consume at the client end.</p>
<p>I was wondering if it's possible to get similar behavior in current scenario.</p>
| 10,930,794 | 5 | 0 | null |
2012-06-07 11:10:05.547 UTC
| 2 |
2019-12-20 09:11:26.01 UTC
|
2019-09-18 16:34:32.23 UTC
| null | 2,306,173 | null | 414,749 | null | 1 | 32 |
java|json|sockets
| 102,749 |
<p><a href="http://code.google.com/p/google-gson/">Google GSON</a> does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.</p>
<pre><code>Gson g = ...;
String jsonString = g.toJson(new Customer());
</code></pre>
|
11,039,658 |
How to check whether a select box is empty using JQuery/Javascript
|
<p>I have a select box that is being populated dynamically from a database. As of right now the population of this check box is working flawlessly.</p>
<p>I have added functionality that consists of a button which on click calls <code>isSelextBoxEmpty</code>. The job of this function is to know whether this particular check box has been populated or not; if it has not then it will simply do nothing.</p>
<p><strong>My problem</strong> is in determining whether this select box is empty or not.</p>
<p>Here is a very simplified example of what I am dealing with:</p>
<pre><code><li>
<label for="fruit_name">Fruit</label>
<select name="some_fruit" id="fruit_name" onclick="populate_box('fruit', this);">
</select>
</li>
</code></pre>
<p>My function, which is called from a separate button, looks like this:</p>
<pre><code>function isSelextBoxEmpty(selectBoxId) {
var selected_value = $('#fruit_name');
/* More options... still testing the proper way:
var selected_value = $('#fruit_name').text;
var selected_value = $('#fruit_name').value;
var selected_value = $('#fruit_name').length;
var selected_value = $('#fruit_name option:selected', this);
var selected_value = document.getElementById('fruit_name');
var selected_value = document.getElementById('fruit_name').length;
var selected_value = document.getElementById('fruit_name').value;
var selected_value = document.getElementById('fruit_name').innerHTML;
*/
if (selected_value) {
alert("NOT null, value: " + selected_value);
// do something
}
}
</code></pre>
<p>Don't worry about what this does and how it does it. Right now what matters to me is that I can't check whether or not the checkbox is empty, I am just not sure how to go about it. I have read a lot through forums and documentation but there are many implications in doing this since it depends on the implementation itself. </p>
<p>For instance using <code>document.getElementById(...)...</code> will not necessarily return false and it depends on how you use it. Also using <code>$("#someID")...</code> in jQuery may or may not produce the desired results. I have already tried many different times as you can see in the <em>commented lines</em>, all of which can be evaluated in the <code>if(...)</code> statement.</p>
<p>Do you have any suggestions or ideas on how to go about achieving this? Thanks in advance!</p>
| 11,039,741 | 4 | 0 | null |
2012-06-14 19:01:13.68 UTC
| 9 |
2021-04-13 09:22:49.487 UTC
|
2020-03-23 15:27:21.53 UTC
| null | 1,046,690 | null | 1,046,690 | null | 1 | 40 |
javascript|jquery|html|jquery-mobile|jquery-selectbox
| 145,132 |
<p>To check whether select box has any values:</p>
<pre><code>if( $('#fruit_name').has('option').length > 0 ) {
</code></pre>
<p>To check whether selected value is empty:</p>
<pre><code>if( !$('#fruit_name').val() ) {
</code></pre>
|
10,877,494 |
Including header files in C/C++ more than once
|
<p>Is it ever useful to include a header file more than once in C or C++?</p>
<p>If the mechanism is never used, why would the compiler ever worry about including a file twice; if it really were useless, wouldn't it be more convenient if newer compilers made sure every header is included only once?</p>
<p>Edit:</p>
<p>I understand that there are standard ways of doing things like <a href="http://en.wikipedia.org/wiki/Include_guard" rel="noreferrer">include guards</a> and <a href="http://en.wikipedia.org/wiki/Pragma_once" rel="noreferrer">pragma once</a>, but why should you have to specify even that? Shouldn't it be the default behavior of the compiler to include files only once?</p>
| 10,877,554 | 6 | 3 | null |
2012-06-04 07:03:19.29 UTC
| 8 |
2014-10-23 15:56:12.957 UTC
|
2014-10-23 15:56:12.957 UTC
| null | -1 | null | 956,134 | null | 1 | 49 |
c++|c|header-files
| 6,535 |
<p>Yes, it's useful when generating code with the preprocessor, or doing tricks like Boost.PP does.</p>
<p>For an example, see X Macros. The basic idea is that the file contains the body of the macro and you <code>#define</code> the arguments and then <code>#include</code> it. Here's a contrived example:</p>
<p>macro.xpp</p>
<pre><code>std::cout << MESSAGE;
#undef MESSAGE
</code></pre>
<p>file.cpp:</p>
<pre><code>int main() {
# define MESSAGE "hello world"
# include "macro.xpp"
}
</code></pre>
<p>This also allows you to use <code>#if</code> and friends on the arguments, something that normal macros can't do.</p>
|
11,082,278 |
How to properly assemble a valid xlsx file from its internal sub-components?
|
<p>I'm trying to create an xlsx file programmatically on iOS. Since the internal data of xlsx files is basically stored in separate xml files, I tried to recreate xlsx structure with all its files and subdirectories, compress them into a zip file and set its extension to xlsx. I use GDataXML parser/writer for creating all the necessary xml files. However, the file I get can't be opened as xlsx file. Even if I rip all the data from a valid xlsx file, create all the xml files manually by copying data from the original xml files and compress them manually, I can't recreate a valid xlsx file.</p>
<p>The questions are: </p>
<ul>
<li>is xlsx really just an archive containing xml files?</li>
<li>how do I create a valid xlsx file programmatically if I can't just compress xml files into zip file and set its extension to xlsx?</li>
</ul>
| 11,116,875 | 4 | 0 | null |
2012-06-18 11:54:51.083 UTC
| 22 |
2022-03-10 12:26:00.633 UTC
|
2012-06-18 12:51:03.07 UTC
| null | 293,317 | null | 293,317 | null | 1 | 53 |
xml|zip|xlsx
| 44,555 |
<p>In answer to your questions:</p>
<ol>
<li>XLSX is just a collection of XML files in a zip container. There is no other magic.</li>
<li>If you decompress/unzip a valid XLSX files and then recompress/zip it and you can't read the resulting output then the problem is generally with the files being rezipped or, less likely, the zipping software. The main thing to check is that the directory structure was maintained in the zip file.</li>
</ol>
<p>Example of the contents of an xlsx file:</p>
<pre><code>unzip -l example.xlsx
Archive: example.xlsx
Length Date Time Name
-------- ---- ---- ----
769 10-15-14 09:23 xl/worksheets/sheet1.xml
550 10-15-14 09:22 xl/workbook.xml
201 10-15-14 09:22 xl/sharedStrings.xml
...
</code></pre>
<p>I regularly unzip XLSX files, make minor changes for testing and re-zip them without any issue.</p>
<p>Update: The important thing is to avoid zipping the parent directory. Here is an example using the <code>zip</code> system utility on Linux or the OS X:</p>
<pre class="lang-sh prettyprint-override"><code># Unzip an xlsx file into a directory.
unzip example.xlsx -d newdir
# Make some valid changes to the files.
cd newdir/
vi xl/worksheets/sheet1.xml
# Rezip the files *FROM* the unzipped directory.
# Note: you could also re-zip to the original file if required.
find . -type f | xargs zip ../newfile.xlsx
# Check the file looks okay.
cd ..
unzip -l newfile.xlsx
xdg-open newfile.xlsx
</code></pre>
|
10,894,122 |
Java regex for support Unicode?
|
<p>To match A to Z, we will use regex:</p>
<blockquote>
<p>[A-Za-z]</p>
</blockquote>
<p>How to allow regex to match utf8 characters entered by user? For example Chinese words like 环保部</p>
| 10,894,689 | 4 | 1 | null |
2012-06-05 08:42:49.423 UTC
| 27 |
2020-03-09 08:30:32.923 UTC
|
2012-06-05 09:50:09.97 UTC
| null | 1,136,195 | null | 108,869 | null | 1 | 89 |
java|regex|unicode|cjk
| 83,731 |
<p>What you are looking for are Unicode properties.</p>
<p>e.g. <code>\p{L}</code> is any kind of letter from any language</p>
<p>So a regex to match such a Chinese word could be something like</p>
<pre><code>\p{L}+
</code></pre>
<p>There are many such properties, for more details see <a href="http://www.regular-expressions.info/unicode.html#prop" rel="noreferrer">regular-expressions.info</a></p>
<p>Another option is to use the modifier</p>
<p><code>Pattern.UNICODE_CHARACTER_CLASS</code></p>
<p>In Java 7 there is a new property <code>Pattern.UNICODE_CHARACTER_CLASS</code> that enables the Unicode version of the predefined character classes <a href="https://stackoverflow.com/a/9500409/626273">see my answer here for some more details and links</a></p>
<p>You could do something like this</p>
<pre><code>Pattern p = Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS);
</code></pre>
<p>and <code>\w</code> would match all letters and all digits from any languages (and of course some word combining characters like <code>_</code>).</p>
|
11,170,827 |
How do I tell a Python script to use a particular version
|
<p>How do I, in the main.py module (presumably), tell Python which interpreter to use? What I mean is: if I want a particular script to use version 3 of Python to interpret the entire program, how do I do that?</p>
<p>Bonus: How would this affect a virtualenv? Am I right in thinking that if I create a virtualenv for my program and then tell it to use a different version of Python, then I may encounter some conflicts?</p>
| 11,171,390 | 8 | 0 | null |
2012-06-23 15:46:23.33 UTC
| 17 |
2022-03-31 08:29:40.007 UTC
|
2017-01-20 17:26:38.007 UTC
| null | 63,550 | null | 508,385 | null | 1 | 99 |
python|version|virtualenv
| 235,798 |
<p>You can add a shebang line the to the top of the script:</p>
<pre class="lang-sh prettyprint-override"><code>#!/usr/bin/env python2.7
</code></pre>
<p>But that will only work when executing as <code>./my_program.py</code>.</p>
<p>If you execute as <code>python my_program.py</code>, then the whatever Python version that <code>which python</code> returns will be used.</p>
<p>In re: to virtualenv use: <code>virtualenv -p /usr/bin/python3.2</code> or whatever to set it up to use that Python executable.</p>
|
12,762,272 |
android CountDownTimer - additional milliseconds delay between ticks
|
<p>From my observation the android CountDownTimer countDownInterval between ticks happens to be not accurate, the countDownInterval is regularly a few milliseconds longer than specified. The countDownInterval in my specific app is 1000ms, just counting down a certain amount of time with one second steps. </p>
<p>Due to this prolonged ticks I end up having less ticks then wanted when the the countdowntimer runs long enough which screws up the displayed countdown of the time (a 2 second step happens on the UI level when enough additional ms have summed up)</p>
<p>Looking into the source of CountDownTimer it seems possible to twist it so it corrects this unwanted inaccuracy yet I was wondering if there is already a better CountDownTimer available in the java/android world.</p>
<p>Thanks buddies for any pointer ...</p>
| 12,762,416 | 6 | 0 | null |
2012-10-06 17:47:13.037 UTC
| 12 |
2019-08-18 14:07:14.353 UTC
| null | null | null | null | 1,621,859 | null | 1 | 9 |
android
| 14,398 |
<p><strong>Rewrite</strong></p>
<p>As you said, you also noticed that the next time in <code>onTick()</code> is calculated from the time the previous <code>onTick()</code> ran, which introduces a tiny error on <em>every</em> tick. I changed the CountDownTimer source code to call each <code>onTick()</code> at the specified intervals from the start time.</p>
<p>I build this upon the CountDownTimer framework, so cut & paste <a href="http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/os/CountDownTimer.java/?v=source">the source code</a> into your project and give the class a unique name. (I called mine MoreAccurateTimer.) Now make a few changes:</p>
<ol>
<li><p>Add a new class variable:</p>
<pre><code>private long mNextTime;
</code></pre></li>
<li><p>Change <code>start()</code>:</p>
<pre><code>public synchronized final MoreAccurateTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mNextTime = SystemClock.uptimeMillis();
mStopTimeInFuture = mNextTime + mMillisInFuture;
mNextTime += mCountdownInterval;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG), mNextTime);
return this;
}
</code></pre></li>
<li><p>Change the Handler's <code>handlerMessage()</code>:</p>
<pre><code>@Override
public void handleMessage(Message msg) {
synchronized (MoreAccurateTimer.this) {
final long millisLeft = mStopTimeInFuture - SystemClock.uptimeMillis();
if (millisLeft <= 0) {
onFinish();
} else {
onTick(millisLeft);
// Calculate next tick by adding the countdown interval from the original start time
// If user's onTick() took too long, skip the intervals that were already missed
long currentTime = SystemClock.uptimeMillis();
do {
mNextTime += mCountdownInterval;
} while (currentTime > mNextTime);
// Make sure this interval doesn't exceed the stop time
if(mNextTime < mStopTimeInFuture)
sendMessageAtTime(obtainMessage(MSG), mNextTime);
else
sendMessageAtTime(obtainMessage(MSG), mStopTimeInFuture);
}
}
}
</code></pre></li>
</ol>
|
12,809,971 |
Quick Print HTML5 Canvas
|
<p>I want to send/print the canvas image directly to the default printer. That means a quick printing. </p>
<p>Anyone can give a hint.</p>
<p>Javascript or jQuery. </p>
| 17,061,022 | 5 | 2 | null |
2012-10-09 23:41:35.247 UTC
| 5 |
2022-03-30 18:03:50.68 UTC
| null | null | null | null | 855,185 | null | 1 | 11 |
javascript|jquery|html|canvas
| 44,503 |
<p>I have searched alot and found a solution which works perfectly :)
Used <strong>onclick</strong> event</p>
<pre><code>function printCanvas()
{
var dataUrl = document.getElementById('anycanvas').toDataURL(); //attempt to save base64 string to server using this var
var windowContent = '<!DOCTYPE html>';
windowContent += '<html>'
windowContent += '<head><title>Print canvas</title></head>';
windowContent += '<body>'
windowContent += '<img src="' + dataUrl + '">';
windowContent += '</body>';
windowContent += '</html>';
var printWin = window.open('','','width=340,height=260');
printWin.document.open();
printWin.document.write(windowContent);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
</code></pre>
|
12,997,635 |
Object passed as parameter to another class, by value or reference?
|
<p>In C#, I know that by default, any parameters passed into a function would be by copy, that's, within the function, there is a local copy of the parameter. But, what about when an object is passed as parameter to another class? </p>
<p>Would a scenario like the following one be passed by reference or by value:</p>
<pre><code>class MyClass {
private Object localObj;
public void SetObject(Object obj) {
localObj = obj;
}
}
void Main() {
Object someTestObj = new Object();
someTestObj.name = "My Name";
MyClass cls = New MyClass();
cls.SetObject(someTesetObj);
}
</code></pre>
<p>In this case, would the class variable <code>localObj</code> be having the same copy as the <code>someTestObj</code> created in the <code>Main</code> driver class? Or would the two variables be pointing to a different object instance?</p>
| 12,997,745 | 7 | 1 | null |
2012-10-21 12:04:49.293 UTC
| 3 |
2021-05-06 16:57:30.073 UTC
| null | null | null | null | 750,511 | null | 1 | 24 |
c#|pass-by-reference
| 148,486 |
<p>Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Employee
{
public string Name { get; set; }
}
public class MyClass
{
public Employee EmpObj;
public void SetObject(Employee obj)
{
EmpObj = obj;
}
}
public class Program
{
static void Main(string[] args)
{
Employee someTestObj = new Employee();
someTestObj.Name = "ABC";
MyClass cls = new MyClass();
cls.SetObject(someTestObj);
Console.WriteLine("Changing Emp Name To xyz");
someTestObj.Name = "xyz";
Console.WriteLine("Accessing Assigned Emp Name");
Console.WriteLine(cls.EmpObj.Name);
Console.ReadLine();
}
}
}
</code></pre>
|
12,997,645 |
What operator is <> in VBA
|
<p>I was studying some <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged 'vba'" rel="tag">vba</a> code and came across this: </p>
<pre><code>If DblBalance <> 0 Then
</code></pre>
<p>I can't figure out what operator this is, any help would be appreciated.</p>
| 12,997,654 | 7 | 0 | null |
2012-10-21 12:05:22.537 UTC
| 6 |
2018-04-02 18:17:42.497 UTC
|
2018-04-02 18:17:42.497 UTC
| null | 8,112,776 | null | 823,528 | null | 1 | 25 |
vba|operators
| 206,119 |
<p>It is the "not equal" operator, i.e. the equivalent of <code>!=</code> in pretty much every other language.</p>
|
12,837,682 |
non-breaking utf-8 0xc2a0 space and preg_replace strange behaviour
|
<p>In my string I have utf-8 non-breaking space (0xc2a0) and I want to replace it with something else.</p>
<p>When I use</p>
<pre><code>$str=preg_replace('~\xc2\xa0~', 'X', $str);
</code></pre>
<p>it works OK.</p>
<p>But when I use</p>
<pre><code>$str=preg_replace('~\x{C2A0}~siu', 'W', $str);
</code></pre>
<p>non-breaking space is not found (and replaced).</p>
<p>Why? What is wrong with second regexp?</p>
<p>The format <code>\x{C2A0}</code> is correct, also I used <code>u</code> flag.</p>
| 12,838,189 | 5 | 1 | null |
2012-10-11 10:38:07.46 UTC
| 14 |
2018-09-10 11:48:19.917 UTC
|
2012-10-11 11:00:54.377 UTC
| null | 626,273 | null | 1,137,546 | null | 1 | 36 |
php|regex
| 28,748 |
<p>Actually the documentation about escape sequences in PHP is wrong. When you use <code>\xc2\xa0</code> syntax, it searches for UTF-8 character. But with <code>\x{c2a0}</code> syntax, it tries to convert the Unicode sequence to UTF-8 encoded character.</p>
<p>A non breaking space is <code>U+00A0</code> (Unicode) but encoded as <code>C2A0</code> in UTF-8. So if you try with the pattern <code>~\x{00a0}~siu</code>, it will work as expected.</p>
|
12,857,604 |
Python - How to check if Redis server is available
|
<p>I'm developing a Python Service(Class) for accessing Redis Server. I want to know how to check if Redis Server is running or not. And also if somehow I'm not able to connect to it.</p>
<p>Here is a part of my code</p>
<pre><code>import redis
rs = redis.Redis("localhost")
print rs
</code></pre>
<p>It prints the following</p>
<pre><code><redis.client.Redis object at 0x120ba50>
</code></pre>
<p>even if my Redis Server is not running. </p>
<p>As I found that my Python Code connects to the Server only when I do a <strong>set()</strong> or <strong>get()</strong> with my redis instance.</p>
<p>So I dont want other services using my class to get an Exception saying</p>
<pre><code>redis.exceptions.ConnectionError: Error 111 connecting localhost:6379. Connection refused.
</code></pre>
<p>I want to return proper message/Error code. How can I do that??</p>
| 12,968,704 | 7 | 2 | null |
2012-10-12 10:59:52.303 UTC
| 9 |
2021-07-21 17:00:18.8 UTC
| null | null | null | null | 1,655,450 | null | 1 | 44 |
python|redis
| 82,042 |
<p>The official way to check if redis server availability is ping ( <a href="http://redis.io/topics/quickstart" rel="noreferrer">http://redis.io/topics/quickstart</a> ).</p>
<p>One solution is to subclass redis and do 2 things:</p>
<ol>
<li>check for a connection at instantiation</li>
<li>write an exception handler in the case of no connectivity when making requests</li>
</ol>
|
13,052,857 |
Comparing two lists using the greater than or less than operator
|
<p>I noticed a piece of code recently directly comparing two lists of integers like so:</p>
<pre><code>a = [10,3,5, ...]
b = [5,4,3, ...,]
if a > b:
...
</code></pre>
<p>which seemed a bit peculiar, but I imagined it would return <code>True</code> if all of <code>list_a</code>'s elements are larger then <code>list_b</code>'s and False if each element is equal or <code>list_b</code>'s elements are larger then <code>list_a</code>'s. So I tested it: </p>
<pre><code>>>> a=[3,3,3,3]
>>> b=[4,4,4,4]
>>> a>b
False
>>> b>a
True
</code></pre>
<p>Ok that works. As does: </p>
<pre><code>>>> b = [1,1,1,1]
>>> a = [1,1,1,1]
>>> a>b
False
>>> b>a
False
</code></pre>
<p>but when it gets more fuzzy:</p>
<pre><code>>>> a=[1,1,3,1]
>>> b=[1,3,1,1]
>>> a>b
False
>>> b>a
True
</code></pre>
<p>or: </p>
<pre><code>>>> a=[1,3,1,1]
>>> b=[1,1,3,3]
>>> a>b
True
>>> b>a
False
</code></pre>
<p>the results are a bit stranger. What is python actually doing? It seems that it's returning the result in favour of the first list in which the left most element is greater then the corresponding? </p>
| 13,052,908 | 3 | 0 | null |
2012-10-24 15:51:55.657 UTC
| 13 |
2021-09-25 00:47:59.43 UTC
| null | null | null | null | 396,300 | null | 1 | 52 |
python|list
| 40,006 |
<p>From <a href="http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types" rel="noreferrer">Comparing Sequences and Other Types</a> in the Python tutorial:</p>
<blockquote>
<p>The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. </p>
</blockquote>
<p>See also the Wikipedia article about <a href="http://en.wikipedia.org/wiki/Lexicographical_order" rel="noreferrer">lexicographical order</a>.</p>
|
16,712,413 |
An error when creating new project in android studio
|
<p><strong>Every time I create new project i get this error:</strong></p>
<pre><code>Failed to import new Gradle project: Could not fetch model of type 'IdeaProject' using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at http://gradle.org/docs/1.6/userguide/gradle_daemon.html
Please read below process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Consult IDE log for more details (Help | Show Log)
</code></pre>
<p><strong>Any Idea?</strong></p>
| 19,469,594 | 12 | 2 | null |
2013-05-23 11:10:41.537 UTC
| 9 |
2016-09-22 23:21:10 UTC
|
2013-07-22 21:34:17.573 UTC
| null | 1,373,278 | null | 2,281,822 | null | 1 | 22 |
android|gradle|android-studio
| 43,997 |
<p>Start Android Studio, close any open project.</p>
<p>On the right side, click on Configure -> Settings.</p>
<p>On the left side, in Compiler->Gradle set VM Options to "-Xmx512m" (without quotes)</p>
<p>Press OK, then create a project. Worked for me.</p>
|
16,721,051 |
Multi-tenant Django applications: altering database connection per request?
|
<p>I'm looking for working code and ideas from others who have tried to build a multi-tenant Django application using database-level isolation.</p>
<p><strong>Update/Solution:</strong> I ended solving this in a new opensource project: see <a href="https://github.com/mik3y/django-db-multitenant">django-db-multitenant</a></p>
<h3>Goal</h3>
<p>My goal is to multiplex requests as they come in to a single app server (WSGI frontend like gunicorn), based on the request hostname or request path (for instance, <code>foo.example.com/</code> sets the Django connection to use database <code>foo</code>, and <code>bar.example.com/</code> uses database <code>bar</code>).</p>
<h3>Precedent</h3>
<p>I'm aware of a few existing solutions for multi tenancy in Django:</p>
<ol>
<li><a href="https://github.com/bcarneiro/django-tenant-schemas">django-tenant-schemas</a>: This is very close to what I want: you install its middleware at highest precedence, and it sends a <code>SET search_path</code> command to the db. Unfortunately, it is Postgres specific and I am stuck with MySQL.</li>
<li><a href="https://github.com/pombredanne/django-simple-multitenant">django-simple-multitenant</a>: The strategy here is to add a "tenant" foreign key to all models, and adjust all application business logic to key off of that. Basically each row is becomes indexed by <code>(id, tenant_id)</code> rather than <code>(id)</code>. I've tried, and don't like, this approach for a number of reasons: it makes the application more complex, it can lead to hard-to-find bugs, and it provides no database-level isolation.</li>
<li>One {app server, django settings file with appropriate db} per tenant. Aka poor man's multi tenancy (actually rich man's, given the resources it involves). I do not want to spin up a new app server per tenant, and for scalability I want any app server to be able to dispatch requests for any client.</li>
</ol>
<h3>Ideas</h3>
<p>My best idea so far is to do something like <code>django-tenant-schemas</code>: in the first middleware, grab <code>django.db.connection</code> and fiddle with the database selection rather than the schema. I haven't quite thought through what this means in terms of pooled/persistent connections</p>
<p>Another dead end I pursued was tenant-specific table prefixes: Setting aside that I'd need them to be dynamic, even a global table prefix is not easily achieved in Django (see <a href="https://code.djangoproject.com/ticket/5000">rejected ticket 5000</a>, among others).</p>
<p>Finally, Django <a href="https://code.djangoproject.com/ticket/5000">multiple database support</a> lets you define multiple named databases, and mux among them based on the instance type and read/write mode. Not helpful since there is no facility to select the db on a per-request basis.</p>
<h3>Question</h3>
<p>Has anyone managed something similar? If so, how did you implement it?</p>
| 17,600,266 | 3 | 6 | null |
2013-05-23 18:13:24.08 UTC
| 21 |
2019-02-27 00:32:44.493 UTC
|
2013-12-02 07:13:00.67 UTC
| null | 642,485 | null | 642,485 | null | 1 | 33 |
mysql|django|multi-tenant
| 7,892 |
<p>For the record, I chose to implement a variation of my first idea: issue a <code>USE <dbname></code> in an early request middleware. I also set the CACHE prefix the same way.</p>
<p>I'm using it on a small production site, looking up the tenant name from a Redis database based on the request host. So far, I'm quite happy with the results.</p>
<p>I've turned it into a (hopefully resuable) github project here: <a href="https://github.com/mik3y/django-db-multitenant" rel="nofollow">https://github.com/mik3y/django-db-multitenant</a></p>
|
16,678,927 |
Is MemoryCache scope session or application wide?
|
<p>I'm using <code>MemoryCache</code> in ASP.NET and it is working well. I have an object that is cached for an hour to prevent fresh pulls of data from the repository.</p>
<p>I can see the caching working in debug, but also once deployed to the server, after the 1st call is made and the object is cached subsequent calls are about 1/5 of the time. </p>
<p>However I'm noticing that each <em>new</em> client call (still inside that 1 hour window - in fact just a minute or 2 later) seems to have the 1st call to my service (that is doing the caching) taking almost as long as the original call before the data was cached.</p>
<p>This made me start to wonder - is <code>MemoryCache</code> session specific, and each new client making the call is storing it's own cache, or is something else going on to cause the 1st call to take so long even <em>after</em> I know the data has been cached?</p>
| 16,689,455 | 2 | 1 | null |
2013-05-21 20:28:01.66 UTC
| 20 |
2018-08-24 00:00:40.163 UTC
|
2013-05-21 21:02:36.803 UTC
| null | 76,337 | null | 410,937 | null | 1 | 55 |
asp.net|caching|memorycache
| 37,679 |
<p>From <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx">MSDN</a>:</p>
<blockquote>
<p>The main differences between the Cache and MemoryCache classes are
that the MemoryCache class has been changed to make it usable by .NET
Framework applications that are not ASP.NET applications. For example,
the MemoryCache class has no dependencies on the System.Web assembly.
Another difference is that you can create multiple instances of the
MemoryCache class for use in the same application and in the same
AppDomain instance.</p>
</blockquote>
<p>Reading that and doing some investigation in reflected code it is obvious that <code>MemoryCache</code> is just a simple class. You can use <code>MemoryCache.Default</code> property to (re)use same instance or you can construct as many instances as you want (though recommended is as few as possible).</p>
<p>So basically the answer lies in your code.<br>
If you use <code>MemoryCache.Default</code> then your cache lives as long as your application pool lives. (Just to remind you that default application pool idle time-out is 20 minutes which is less than 1 hour.)</p>
<p>If you create it using <code>new MemoryCache(string, NameValueCollection)</code> then the above mentioned considerations apply plus the context you create your instance in, that is if you create your instance inside controller (which I hope is not the case) then your cache lives for one request</p>
<p>It's a pity I can't find any references, but ... <code>MemoryCache</code> does not guarantee to hold data according to a cache policy you specify. In particular if machine you're running your app on gets stressed on memory your cache might be discarded.</p>
<p>If you still have no luck figuring out what's the reason for early cache item invalidation you could take advantage of <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.removedcallback.aspx"><code>RemoveCallback</code></a> and investigate what is the reason of item invalidation.</p>
|
16,958,448 |
What is http multipart request?
|
<p>I have been writing iPhone applications for some time now, sending data to server, receiving data (via HTTP protocol), without thinking too much about it. Mostly I am theoretically familiar with process, but the part I am not so familiar is HTTP multipart request. I know its basic structure, but the core of it eludes me.</p>
<p>It seems that whenever I am sending something different than plain text (like photos, music), I have to use a multipart request. Can someone briefly explain to me why it is used and what are its advantages?</p>
<p>If I use it, why is it better way to send photos that way?</p>
| 19,712,083 | 3 | 1 | null |
2013-06-06 09:28:21.703 UTC
| 138 |
2022-03-02 16:27:26.45 UTC
|
2016-02-04 14:07:19.533 UTC
| null | 1,788,160 | null | 744,270 | null | 1 | 419 |
http-headers|multipart
| 402,441 |
<p>An HTTP multipart request is an HTTP request that HTTP clients construct to send files and data over to an HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/913626/what-should-a-multipart-http-request-with-multiple-files-look-like">What it looks like</a></li>
<li><a href="http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html" rel="noreferrer">See Multipart Content-Type</a></li>
<li><a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2" rel="noreferrer">See multipart/form-data </a></li>
</ul>
|
4,480,485 |
ASP.net MVC Controller - Constructor usage
|
<p>I'm working on an ASP.net MVC application and I have a question about using constructors for my controllers. </p>
<p>I'm using Entity Framework and linq to Entities for all of my data transactions. I need to access my Entity model for nearly all of my controller actions. When I first started writing the app I was creating an entity object at the beginning of each Action method, performing whatever work I needed to and then returning my result. </p>
<p>I realized that I was creating the same object over and over for each action method so I created a private member variable for the Entity object and started instantiating it in the constructor for each controller. Now each method only references that private member variable to do its work. </p>
<p>I'm still questioning myself on which way is right. I'm wondering A.) which method is most appropriate? B.) in the constructor method, how long are those objects living? C.) are there performance/integrity issues with the constructor method?</p>
| 4,480,604 | 2 | 2 | null |
2010-12-18 22:25:15.11 UTC
| 23 |
2019-10-04 09:57:41.763 UTC
|
2019-10-04 09:57:25.41 UTC
| null | 133 | null | 468,302 | null | 1 | 37 |
asp.net-mvc|asp.net-mvc-2|c#-4.0|constructor
| 46,820 |
<p>You are asking the right questions.</p>
<p>A. It is definitely not appropriate to create this dependencies inside each action method. One of the main features of MVC is the ability to separate concerns. By loading up your controller with these dependencies, you are making the controller for thick. These should be injected into the controller. There are various options for dependency injection (DI). Generally these types of objects can be either injected into the constructor or into a property. My preference is constructor injection.</p>
<p>B. The lifetime of these objects will be determined by the garbage collector. GC is not deterministic. So if you have objects that have connections to resource constrained services (database connections) then you may need to be sure you close those connections your self (instead of relying on dispose). Many times the 'lifetime' concerns are separated out into an inversion of control (IOC) container. There are many out there. My preference is Ninject.</p>
<p>C. The instantiation costs are probably minimal. The database transactions cost are where you probably want to focus your attention. There is a concept called 'unit of work' you may want to look into. Essentially, a database can handle transactions larger than just one save/update operation. Increasing the transaction size can lead to better db performance.</p>
<p>Hope that gets you started.</p>
|
70,344,098 |
Data path "" must NOT have additional properties(extractCss) in Angular 13 while upgrading project
|
<p>I am facing an issue while upgrading my project from angular 8.2.1 to angular 13 version.</p>
<p>After a successful upgrade while preparing a build it is giving me the following error.</p>
<pre><code>Data path "" must NOT have additional properties(extractCss).
</code></pre>
<p>I already renamed <code>styleext</code> with <code>style</code> in the angular.json file, but still not able to find the root cause for this error.</p>
<p><strong>angular.json file is as follows.</strong></p>
<pre><code> {
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"qiwkCollaborator": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
/* "configurations": {
"fr": {
"aot": true,
"outputPath": "dist/qwikCollaborator/fr/",
"i18nFile": "src/translate/messages.fr.xlf",
"i18nFormat": "xlf",
"i18nLocale": "fr",
"i18nMissingTranslation": "error"
},
"en": {
"aot": true,
"outputPath": "dist/qwikCollaborator/en/",
"i18nFile": "src/translate/messages.en.xlf",
"i18nFormat": "xlf",
"i18nLocale": "en",
"i18nMissingTranslation": "error"
}
},*/
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/qiwkCollaborator",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss",
"src/assets/css/custom-mobile.css",
"src/assets/css/custom.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/assets/js/qwikCollaborator.js"
]
},
"configurations": {
"es5": {
"tsConfig": "./tsconfig.es5.json"
},
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
/* "configurations": {
"fr": {
"browserTarget": "qwikCollaborator:build:fr"
},
"en": {
"browserTarget": "qwikCollaborator:build:en"
} ,
},*/
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "qiwkCollaborator:build"
},
"configurations": {
"es5": {
"browserTarget": "qiwkCollaborator:build:es5"
},
"production": {
"browserTarget": "qiwkCollaborator:build:es5"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "qiwkCollaborator:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": ["../node_modules/jspdf/dist/jspdf.min.js"]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "qiwkCollaborator:serve"
},
"configurations": {
"production": {
"devServerTarget": "qiwkCollaborator:serve:production"
}
}
}
}
}},
"defaultProject": "qiwkCollaborator"
}
</code></pre>
<p>How to get rid of this additional property?</p>
<p>can anyone help me with this?</p>
<p>thanks in advance!</p>
| 70,349,043 | 1 | 4 | null |
2021-12-14 05:15:32.3 UTC
| 2 |
2022-01-27 14:41:47.027 UTC
|
2022-01-27 14:41:47.027 UTC
| null | 4,786,273 | null | 8,805,085 | null | 1 | 33 |
angular|angular-upgrade|angular13
| 13,420 |
<p>Just remove the <code>"extractCss": true</code> from your production environment, it will resolve the problem.</p>
<p>The reason about it is extractCss is deprecated, and it's value is true by default.
See more here: <a href="https://stackoverflow.com/questions/67209871/extracting-css-into-js-with-angular-11-deprecated-extractcss">Extracting CSS into JS with Angular 11 (deprecated extractCss)</a></p>
|
9,881,227 |
spring multipart file upload form validation
|
<p>I'm new to spring, and i'm currently struggling with the many pieces required to get a multipart form submit/validation scenario with error beeing displayed in the view.</p>
<p>Here are the files i currently have :</p>
<p>resourceupload.jsp : a view that displays a form to upload the file.</p>
<pre><code><form:form method="post" action="resource/upload" enctype="mutlipart/form-data">
<input name="name" type="text"/>
<input name="file" type="file" />
<input type="submit"/>
<form:errors path="file" cssClass="errors"/>
</form>
</code></pre>
<p>resourceuploadcontroller.java : the controller that handles the form submit, and (unsuccessfuly) tries to post file validation errors back to the view : </p>
<pre><code>@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @RequestParam("file") MultipartFile file , @RequestParam("name") String name,Object command, Errors validationErrors){
..perform some stuff with the file content, checking things in the database, etc...
.. calling validationErrors.reject("file","the error") everytime something goes wrong...
return "redirect:upload"; // redirect to the form, that should display the error messages
</code></pre>
<p>Now, obviously there's something wrong with this approach:</p>
<p>1/ I had to add a dummy "command" object before the validationErrors parameter, otherwise spring would throw me an error. That doesn't seem really right.</p>
<p>2/ After I added that parameter, the redirect doesn't pass the errors to the view. I tried using @SessionAttribute("file") at the start of the controller, without any luck.</p>
<p>If anyone could help... I've had a look at @ResponseBody annotation, but that doesn't seem to be made to be used with views..</p>
| 9,889,452 | 4 | 0 | null |
2012-03-26 23:11:31.78 UTC
| 2 |
2017-01-20 16:51:46.047 UTC
|
2012-05-17 13:40:13.487 UTC
| null | 21,234 | null | 194,470 | null | 1 | 5 |
validation|spring-mvc|multipartform-data
| 40,157 |
<p>Seems like I found the solution on my own.</p>
<p>First, the link that helped me a lot : <a href="http://www.ioncannon.net/programming/975/spring-3-file-upload-example/" rel="nofollow noreferrer">http://www.ioncannon.net/programming/975/spring-3-file-upload-example/</a>
and
<a href="https://stackoverflow.com/questions/2860756/spring-3-mvc-formerrors-not-showing-the-errors">Spring 3 MVC - form:errors not showing the errors</a>
which showed a good trick to display all errors, using </p>
<pre><code><form:errors path="*"/>.
</code></pre>
<p>Now, a list of all the things i changed to make that thing work : </p>
<p>1/ use "rejectValue" instead of "reject".</p>
<p>2/ return the view directly instead of a redirect.</p>
<p>3/ create a "UploadItem" model with a CommonsMultipartFile property</p>
<p>So, all in all, my controller method became</p>
<pre><code>@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @ModelAttribute("uploadItem") UploadItem uploadItem, BindingResult errors){
... use errors.rejectValue ... in case of errors (moving everything i could in a UploadItemValidator.validate function)
return "uploadform"
</code></pre>
<p>Hope that helped.</p>
|
9,721,161 |
Microsoft Interop: Excel Column Names
|
<p>I am using Microsoft Interop to read the data.</p>
<p>In excel-sheet the column-names are like A,B,C,D,....,AA,AB,.... and so on. Is there any way to read this column-names?</p>
<p>If you need any other info please let me know.</p>
<p>Regards,
Priyank</p>
| 9,721,691 | 2 | 6 | null |
2012-03-15 13:53:57.613 UTC
| null |
2013-08-14 11:49:00.797 UTC
| null | null | null | null | 1,060,026 | null | 1 | 10 |
c#|office-interop|excel-interop
| 40,602 |
<pre><code> Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("workbookname");
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
int columnCount = xlWorksheet.UsedRange.Columns.Count;
List<string> columnNames = new List<string>();
for (int c = 1; c < columnCount; c++)
{
if (xlWorksheet.Cells[1, c].Value2 != null)
{
string columnName = xlWorksheet.Columns[c].Address;
Regex reg = new Regex(@"(\$)(\w*):");
if (reg.IsMatch(columnName))
{
Match match = reg.Match(columnName);
columnNames.Add(match.Groups[2].Value);
}
}
}
</code></pre>
<p>This will put each column name in a <code>List<string></code> which you can then bind to a drop down box.</p>
|
9,921,548 |
SSLSocketFactory in java
|
<p>What role does <code>SSLSocketFactory</code> class in java play when using <code>HttpsURLConnection</code>? The java docs is not of much help. </p>
<p>Are there any ways to bind the keystore and the truststore to with the sslsocketfactory object, to make it point to the keystore and the truststore?</p>
<p>Otherwise how will the connection know the location of the keystore and the truststore(I don't want to use java <code>System Properties</code>)? </p>
| 9,921,818 | 1 | 0 | null |
2012-03-29 08:16:48.747 UTC
| 7 |
2016-08-06 00:10:05.683 UTC
|
2016-08-06 00:10:05.683 UTC
| null | 2,913,306 | null | 1,139,023 | null | 1 | 13 |
java|ssl|https
| 43,863 |
<p>It is done through SSLContext. You init one and then use it's socket factory to create HttpsConnection instances.</p>
<p>Here is rough example of how I manage this in my application:</p>
<pre><code>SSLContext sc = SSLContext.getInstance("SSL");
sc.init(myKeyManagerFactory.getKeyManagers(), myTrustManagerArray, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
</code></pre>
<p>after that your openConnection() calls for https sites will use the sslsocketfactory you initialized here.</p>
<p>Here code for TrustManager to use in your ssl context wich will trust all certificates:</p>
<pre><code>TrustManager[] myTrustManagerArray = new TrustManager[]{new TrustEveryoneManager()};
class TrustEveryoneManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] arg0, String arg1){}
public void checkServerTrusted(X509Certificate[] arg0, String arg1){}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
</code></pre>
<p>Upd from Bruno: beware, trusting any certificate, however convenient it is, makes the connection vulnerable to MITM attacks</p>
|
9,729,691 |
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module
|
<p>I am developing a c# application and I get the following error at debug runtime:</p>
<blockquote>
<p>An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in Unknown Module.</p>
<p>Additional information: Could not load file or assembly
'Autodesk.Navisworks.Timeliner.dll' or one of its dependencies. The
specified module could not be found.</p>
</blockquote>
<p>Autodesk.Navisworks.Timeliner.dll is in the debug folder of the application. I have repaired the .net framework (version 4) but it did not resolve it. Any ideas on how to resolve this issue? Thanks. </p>
| 9,729,835 | 6 | 0 | null |
2012-03-15 23:23:19.093 UTC
| 4 |
2021-08-29 02:49:55.713 UTC
| null | null | null | null | 1,261,829 | null | 1 | 14 |
c#|exception|runtime
| 141,679 |
<p>First check - is the working directory the directory that the application is running in:</p>
<ul>
<li>Right-click on your project and select Properties.</li>
<li>Click the Debug tab.</li>
<li>Confirm that the Working directory is either empty or equal to the bin\debug directory.</li>
</ul>
<p>If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there.
If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility <code>DUMPBIN</code>.</p>
<pre><code>dumpbin /imports Autodesk.Navisworks.Timeliner.dll
</code></pre>
<p>If it is a .NET assembly, there are a number of tools that can check dependencies.</p>
<p><code>Reflector</code> has already been mentioned, and I use <code>JustDecompile</code> from Telerik.
<hr />
Also see <a href="https://stackoverflow.com/questions/227886/how-do-i-determine-the-dependencies-of-a-net-application">this question</a></p>
|
10,066,364 |
array_walk an anonymous function
|
<p>Is there a way I can get this array walk with my anonymous function to set the values?</p>
<pre><code>$url = array('dog', 'cat', 'fish');
array_walk($url, function(&$value, &$key) {
$url[$key] = str_replace('dog', '', $value);
});
echo '<pre>';
print_r($url);
echo '</pre>';
</code></pre>
| 10,066,381 | 1 | 0 | null |
2012-04-08 20:47:02.357 UTC
| 3 |
2012-04-08 20:48:46.16 UTC
| null | null | null | null | 216,909 | null | 1 | 32 |
php
| 24,876 |
<p>You are already <a href="http://php.net/manual/en/language.references.pass.php">passing the value by reference</a>, so just do the following:</p>
<pre><code>array_walk($url, function(&$value, &$key) {
$value = str_replace('dog', '', $value);
});
</code></pre>
|
9,736,202 |
Read tab-separated file line into array
|
<p>I would like to read a file into a script, line by line. Each line in the file is multiple values separated by a tab, I'd like to read each line into an array. </p>
<p>Typical bash "read file by line" example;</p>
<pre><code>while read line
do
echo $line;
done < "myfile"
</code></pre>
<p>For me though, myfile looks like this (tab separated values);</p>
<pre><code>value1 value2 value3
value4 value5 value6
</code></pre>
<p>On each iteration of the loop, I'd like each line to go into an array so I can</p>
<pre><code>while read line into myArray
do
echo myArray[0]
echo myArray[1]
echo myArray[2]
done < "myfile"
</code></pre>
<p>This would print the following on the first loop iteration;</p>
<pre><code>value1
value2
value3
</code></pre>
<p>Then on the second iteration it would print</p>
<pre><code>value4
value5
value6
</code></pre>
<p>Is this possible? The only way I can see is to write a small function to break out the values manually, is there built in support in bash for this?</p>
| 9,736,732 | 3 | 0 | null |
2012-03-16 11:10:12.493 UTC
| 34 |
2018-11-12 23:18:31.347 UTC
|
2018-11-12 23:18:31.347 UTC
| null | 6,862,601 | null | 560,065 | null | 1 | 81 |
arrays|bash
| 131,933 |
<p>You're very close:</p>
<pre><code>while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile
</code></pre>
<p>(The <code>-r</code> tells <code>read</code> that <code>\</code> isn't special in the input data; the <code>-a myArray</code> tells it to split the input-line into words and store the results in <code>myArray</code>; and the <code>IFS=$'\t'</code> tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one <em>or more</em> tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)</p>
|
8,328,908 |
javascript surprising array comparison
|
<p>I'm trying to compare two arrays in javascript.</p>
<p>What I'd like is: </p>
<blockquote>
<p>a < b ⇔ ∃ i ≥ 0 s.t. a[i] < b[i] and ∀ 0 ≤ j < i, a[j] = b[j]</p>
</blockquote>
<p>So arrays of non-negative numbers work as desired:</p>
<pre><code>firebug> [0,1,2,3,4] < [1,0,0]
true
</code></pre>
<p>And comparing negative numbers with zero works as expected:</p>
<pre><code>firebug> [-1, 1] < [0, 0]
true
</code></pre>
<p>But comparing negative numbers with negative numbers is... suprising:</p>
<pre><code>firebug> [-2] < [-1]
false
firebug> -2 < -1
true
</code></pre>
<p>What's going on here, so I can correct my intuition for what array comparison <strong>means</strong> in javascript?</p>
| 8,329,014 | 3 | 2 | null |
2011-11-30 15:58:12.39 UTC
| 5 |
2015-06-23 14:47:05.95 UTC
| null | null | null | null | 9,859 | null | 1 | 29 |
javascript|arrays|comparison
| 6,016 |
<p>The array is converted to a string, which comes down to <code>.join()</code>, which in turn joins the elements with a comma (<code>,</code>) as delimiter.</p>
<pre><code>"-1,1" < "0,0" === true
</code></pre>
<p>because the <em>character code</em> of <code>-</code> (45) is smaller than the <em>character code</em> of <code>0</code> (48).</p>
<p>On the other hand,</p>
<pre><code>"-2" < "-1" === false
</code></pre>
<p>because the second character codes are compared (the first are both <code>-</code>, so that doesn't give a result yet), and the character code for <code>2</code> (50) is <em>bigger</em> than the character code of <code>1</code> (49), so this yields <code>false</code>.</p>
<p>It comes down to a lexographical sorting (i.e. by character codes) and not a numerical one, even if the elements are numbers (because of the string coercion).</p>
<p>Basically comparing arrays is not recommended. It is implicitly defined as string comparison, but this can yield surprising results.</p>
|
11,959,841 |
How to place an imageview on top of another imageview in android
|
<p>This is my layout which i tried so far without any success</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white">
<LinearLayout
android:id="@+id/lltest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerHorizontal="true">
<ImageView
android:id="@+id/inside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:src="@drawable/frame"/>
</LinearLayout>
<ImageView
android:id="@+id/outside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/inside_imageview"
android:scaleType="fitXY"/>
</RelativeLayout>
</code></pre>
<p>What i exactly want is to have my outside_imageview on top of inside_imageview with the exact height and width... How to do it through layout?</p>
| 11,959,915 | 7 | 2 | null |
2012-08-14 19:59:45.867 UTC
| 4 |
2019-10-25 14:26:37.817 UTC
| null | null | null | null | 609,387 | null | 1 | 23 |
android|android-layout|imageview
| 63,922 |
<pre><code> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white" >
<ImageView
android:id="@+id/inside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginTop="5dip"
android:src="@drawable/frame" />
<ImageView
android:id="@+id/outside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/inside_imageview"
android:layout_alignBottom="@id/inside_imageview"
android:layout_alignLeft="@id/inside_imageview"
android:layout_alignRight="@id/inside_imageview"
android:scaleType="fitXY" />
</RelativeLayout>
</code></pre>
<p>The <code>layout_align[Top|Bottom|Left|Right]</code> attribute in <code>RelativeLayout</code> is used to align views based on their respective x and y values within the margin. The second <code>ImageView</code> will now be aligned to the top, bottom, left, and right of the first <code>ImageView</code> based on the margins. Padding is ignored in the alignment.</p>
|
11,867,538 |
How can I use Python to transform MongoDB's bsondump into JSON?
|
<p>So I have an enormous quantity of .bson from a MongoDB dump. I am using <a href="http://docs.mongodb.org/manual/reference/bsondump/">bsondump</a> on the command line, piping the output as stdin to python. This successfully converts from BSON to 'JSON' but it is in fact a string, and seemingly not legal JSON.</p>
<p>For example an incoming line looks like this:</p>
<pre><code>{ "_id" : ObjectId( "4d9b642b832a4c4fb2000000" ),
"acted_at" : Date( 1302014955933 ),
"created_at" : Date( 1302014955933 ),
"updated_at" : Date( 1302014955933 ),
"_platform_id" : 3,
"guid" : 72106535190265857 }
</code></pre>
<p>Which I belive is <a href="http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON">Mongo Extended JSON</a>. </p>
<p>When I read in such a line and do:</p>
<pre><code>json_line = json.dumps(line)
</code></pre>
<p>I get:</p>
<pre><code>"{ \"_id\" : ObjectId( \"4d9b642b832a4c4fb2000000\" ),
\"acted_at\" : Date( 1302014955933 ),
\"created_at\" : Date( 1302014955933 ),
\"updated_at\" : Date( 1302014955933 ),
\"_platform_id\" : 3,
\"guid\" : 72106535190265857 }\n"
</code></pre>
<p>Which is still <code><type 'str'></code>.</p>
<p>I have also tried</p>
<pre><code>json_line = json.dumps(line, default=json_util.default)
</code></pre>
<p>(see pymongo json_util - spam detection prevents a third link )
Which seems to output the same as dumps above. loads gives an error:</p>
<pre><code>json_line = json.loads(line, object_hook=json_util.object_hook)
ValueError: No JSON object could be decoded
</code></pre>
<p>So, how can I transform the string of TenGen JSON into parseable JSON?
(the end goal is to stream tab separated data to another database)</p>
| 11,886,476 | 4 | 6 | null |
2012-08-08 15:07:37.717 UTC
| 12 |
2019-07-04 14:11:51.457 UTC
|
2012-08-08 17:59:29.97 UTC
| null | 1,283,745 | null | 1,283,745 | null | 1 | 25 |
python|json|mongodb|bson
| 23,320 |
<p>What you have is a dump in Mongo Extended JSON in TenGen mode (see <a href="http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON">here</a>). Some possible ways to go:</p>
<ol>
<li><p>If you can dump again, use Strict output mode through the MongoDB REST API. That should give you real JSON instead of what you have now.</p></li>
<li><p>Use <code>bson</code> from <a href="http://pypi.python.org/pypi/bson/">http://pypi.python.org/pypi/bson/</a> to read the BSON you already have into Python data structures and then do whatever processing you need on those (possibly outputting JSON).</p></li>
<li><p>Use the MongoDB Python bindings to connect to the database to get the data into Python, and then do whatever processing you need. (If needed, you could set up a local MongoDB instance and import your dumped files into that.)</p></li>
<li><p>Convert the Mongo Extended JSON from TenGen mode to Strict mode. You could develop a separate filter to do it (read from stdin, replace TenGen structures with Strict structures, and output the result on stdout) or you could do it as you process the input.</p></li>
</ol>
<p>Here's an example using Python and regular expressions:</p>
<pre><code>import json, re
from bson import json_util
with open("data.tengenjson", "rb") as f:
# read the entire input; in a real application,
# you would want to read a chunk at a time
bsondata = f.read()
# convert the TenGen JSON to Strict JSON
# here, I just convert the ObjectId and Date structures,
# but it's easy to extend to cover all structures listed at
# http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
jsondata = re.sub(r'ObjectId\s*\(\s*\"(\S+)\"\s*\)',
r'{"$oid": "\1"}',
bsondata)
jsondata = re.sub(r'Date\s*\(\s*(\S+)\s*\)',
r'{"$date": \1}',
jsondata)
# now we can parse this as JSON, and use MongoDB's object_hook
# function to get rich Python data structures inside a dictionary
data = json.loads(jsondata, object_hook=json_util.object_hook)
# just print the output for demonstration, along with the type
print(data)
print(type(data))
# serialise to JSON and print
print(json_util.dumps(data))
</code></pre>
<p>Depending on your goal, one of these should be a reasonable starting point.</p>
|
11,608,238 |
Is it possible to add a where clause with list comprehension?
|
<p>Consider the following list comprehension</p>
<pre><code>[ (x,f(x)) for x in iterable if f(x) ]
</code></pre>
<p>This filters the iterable based a condition <code>f</code> and returns the pairs of <code>x,f(x)</code>. The problem with this approach is <code>f(x)</code> is calculated twice.
It would be great if we could write like</p>
<pre><code>[ (x,fx) for x in iterable if fx where fx = f(x) ]
or
[ (x,fx) for x in iterable if fx with f(x) as fx ]
</code></pre>
<p>But in python we have to write using nested comprehensions to avoid duplicate call to f(x) and it makes the comprehension look less clear</p>
<pre><code>[ (x,fx) for x,fx in ( (y,f(y) for y in iterable ) if fx ]
</code></pre>
<p>Is there any other way to make it more pythonic and readable?</p>
<hr>
<p><strong>Update</strong></p>
<p>Coming soon in python 3.8! <a href="https://www.python.org/dev/peps/pep-0572/#syntax-and-semantics" rel="noreferrer">PEP</a></p>
<pre><code># Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
</code></pre>
| 11,608,419 | 4 | 8 | null |
2012-07-23 07:40:21.643 UTC
| 3 |
2018-12-13 20:02:58.86 UTC
|
2018-12-13 20:02:58.86 UTC
| null | 463,758 | null | 463,758 | null | 1 | 28 |
python|python-3.x|list-comprehension|python-assignment-expression|python-3.8
| 21,328 |
<p>You seek to have <code>let</code>-statement semantics in python list comprehensions, whose scope is available to both the <code>___ for..in</code>(map) and the <code>if ___</code>(filter) part of the comprehension, and whose scope depends on the <code>..for ___ in...</code>.</p>
<hr>
<p><strong>Your solution, modified:</strong>
Your (as you admit unreadable) solution of <code>[ (x,fx) for x,fx in ( (y,f(y) for y in iterable ) if fx ]</code> is the most straightforward way to write the optimization.</p>
<p>Main idea: lift x into the tuple (x,f(x)).</p>
<p>Some would argue the most "pythonic" way to do things would be the original <code>[(x,f(x)) for x in iterable if f(x)]</code> and accept the inefficiencies.</p>
<p>You can however factor out the <code>((y,fy) for y in iterable)</code> into a function, if you plan to do this a lot. This is bad because if you ever wish to have access to more variables than <code>x,fx</code> (e.g. <code>x,fx,ffx</code>), then you will need to rewrite all your list comprehensions. Therefore this isn't a great solution unless you know for sure you only need <code>x,fx</code> and plan to reuse this pattern.</p>
<hr>
<p><strong>Generator expression:</strong></p>
<p>Main idea: use a more complicated alternative to generator expressions: one where python will let you write multiple lines.</p>
<p>You could just use a generator expression, which python plays nicely with:</p>
<pre><code>def xfx(iterable):
for x in iterable:
fx = f(x)
if fx:
yield (x,fx)
xfx(exampleIterable)
</code></pre>
<p>This is how I would personally do it.</p>
<hr>
<p><strong>Memoization/caching:</strong></p>
<p>Main idea: You could also use(abuse?) side-effects and make <code>f</code> have a global memoization cache, so you don't repeat operations.</p>
<p>This can have a bit of overhead, and requires a policy of how large the cache should be and when it should be garbage-collected. Thus this should only be used if you'd have other uses for memoizing f, or if f is very expensive. But it would let you write...</p>
<pre><code>[ (x,f(x)) for x in iterable if f(x) ]
</code></pre>
<p>...like you originally wanted without the performance hit of doing the expensive operations in <code>f</code> twice, even if you technically call it twice. You can add a <code>@memoized</code> decorator to <code>f</code>: <a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize" rel="nofollow noreferrer">example</a> (without maximum cache size). This will work as long as x is hashable (e.g. a number, a tuple, a frozenset, etc.).</p>
<hr>
<p><strong>Dummy values:</strong></p>
<p>Main idea: capture fx=f(x) in a closure and modify the behavior of the list comprehension.</p>
<pre><code>filterTrue(
(lambda fx=f(x): (x,fx) if fx else None)() for x in iterable
)
</code></pre>
<p>where filterTrue(iterable) is filter(None, iterable). You would have to modify this if your list type (a 2-tuple) was actually capable of being <code>None</code>.</p>
|
11,691,775 |
Why my App is not showing up on tablets in Google Play?
|
<p>I just released my app for phones and tablets but it is not showing up in Google Play for tablets.</p>
<p>Checked on Nexus 7 and Asus eeeePad</p>
<p>This is what I have in my manifest file</p>
<pre><code><compatible-screens>
<!--no small size screens -->
<!--Only hdpi and xhdpi for normal size screens -->
<screen android:screenSize="normal" android:screenDensity="mdpi" />
<screen android:screenSize="normal" android:screenDensity="hdpi" />
<screen android:screenSize="normal" android:screenDensity="xhdpi" />
<!-- all large size screens -->
<screen android:screenSize="large" android:screenDensity="ldpi" />
<screen android:screenSize="large" android:screenDensity="mdpi" />
<screen android:screenSize="large" android:screenDensity="hdpi" />
<screen android:screenSize="large" android:screenDensity="xhdpi" />
<!-- all xlarge size screens -->
<screen android:screenSize="xlarge" android:screenDensity="ldpi" />
<screen android:screenSize="xlarge" android:screenDensity="mdpi" />
<screen android:screenSize="xlarge" android:screenDensity="hdpi" />
<screen android:screenSize="xlarge" android:screenDensity="xhdpi" />
</compatible-screens>
</code></pre>
<p>uses-sdk tag</p>
<pre><code><uses-sdk android:minSdkVersion="8" android:targetSdkVersion="11" />
</code></pre>
<p>permissions</p>
<pre><code><uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<permission android:name="com.myapp.something.permission.C2D_MESSAGE" android:protectionLevel="signature" />
</code></pre>
<p>After explicitly adding uses-feature tag to false it started appearing for Asus eeeePad tablet but still not appearing for nexus 7. Here is what I see in developer console</p>
<p>This application is only available to devices with these features, as defined in your application manifest.
Screen densities: <code>LARGE,MDPI LARGE,HDPI LARGE,LDPI LARGE,XHDPI XLARGE,MDPI XLARGE,HDPI XLARGE,LDPI XLARGE,XHDPI NORMAL,MDPI NORMAL,HDPI NORMAL,XHDPI</code>
Required device features</p>
<pre><code>android.hardware.screen.portrait
android.hardware.touchscreen
</code></pre>
| 11,745,425 | 7 | 5 | null |
2012-07-27 16:19:37.793 UTC
| 17 |
2016-09-02 05:32:15.193 UTC
|
2014-09-29 11:01:21.033 UTC
| null | 1,649,309 | null | 1,522,067 | null | 1 | 39 |
android|tablet|google-play
| 39,363 |
<p>At last adding a special case for Nexus 7 with in <code><compatible-screens></code> tag worked for me. As Nexus 7 has tvdpi density</p>
<pre><code><compatible-screens>
<!--no small size screens -->
<!--all normal size screens -->
<screen android:screenSize="normal" android:screenDensity="ldpi" />
<screen android:screenSize="normal" android:screenDensity="mdpi" />
<screen android:screenSize="normal" android:screenDensity="hdpi" />
<screen android:screenSize="normal" android:screenDensity="xhdpi" />
<!-- all large size screens -->
<screen android:screenSize="large" android:screenDensity="ldpi" />
<screen android:screenSize="large" android:screenDensity="mdpi" />
<screen android:screenSize="large" android:screenDensity="hdpi" />
<screen android:screenSize="large" android:screenDensity="xhdpi" />
<!-- all xlarge size screens -->
<screen android:screenSize="xlarge" android:screenDensity="ldpi" />
<screen android:screenSize="xlarge" android:screenDensity="mdpi" />
<screen android:screenSize="xlarge" android:screenDensity="hdpi" />
<screen android:screenSize="xlarge" android:screenDensity="xhdpi" />
<!-- Special case for Nexus 7 -->
<screen android:screenSize="large" android:screenDensity="213" />
</compatible-screens>
</code></pre>
<p>UPDATE:</p>
<p>For xxhdpi devices you can use 480 as an int value</p>
<pre><code> <screen android:screenSize="normal" android:screenDensity="480" />
<screen android:screenSize="large" android:screenDensity="480" />
<screen android:screenSize="xlarge" android:screenDensity="480" />`
</code></pre>
|
11,965,524 |
How to make a regex match case insensitive?
|
<p>I have following regular expression for <a href="http://en.wikipedia.org/wiki/Postal_codes_in_Canada" rel="noreferrer">postal code of Canada</a>. </p>
<pre><code>^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
</code></pre>
<p>It is working fine but accepts only Capital letters. I want it work for both capital and small letters.</p>
| 11,965,836 | 1 | 7 | null |
2012-08-15 07:27:52.657 UTC
| 5 |
2017-04-26 14:16:16.057 UTC
|
2012-08-15 08:00:43.367 UTC
| null | 626,273 | null | 1,512,393 | null | 1 | 53 |
c#|.net|regex
| 67,893 |
<p>Just use the option <code>IgnoreCase</code>, see <a href="http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx">.NET regular Expression Options</a></p>
<p>So your regex creation could look like this</p>
<pre><code>Regex r = new Regex(@"^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$", RegexOptions.IgnoreCase);
</code></pre>
<p>I removed also all your <code>{1}</code> because it is superfluous. Every item is per default matched once, no need to state this explicitly.</p>
<p>The other possibility would be to use inline modifiers, when you are not able to set it on the object.</p>
<pre><code>^(?i)[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$
</code></pre>
|
11,883,534 |
How to dismiss notification after action has been clicked
|
<p>Since API level 16 (Jelly Bean), there is the possibility to add actions to a notification with</p>
<pre><code>builder.addAction(iconId, title, intent);
</code></pre>
<p>But when I add an action to a notification and the action is pressed, the notification is not going to be dismissed.
When the notification itself is being clicked, it can be dismissed with</p>
<pre><code>notification.flags = Notification.FLAG_AUTO_CANCEL;
</code></pre>
<p>or</p>
<pre><code>builder.setAutoCancel(true);
</code></pre>
<p>But obviously, this has nothing to with the actions associated to the notification.</p>
<p>Any hints? Or is this not part of the API yet? I did not find anything.</p>
| 11,884,313 | 10 | 0 | null |
2012-08-09 12:32:08.467 UTC
| 32 |
2022-04-08 10:45:54.163 UTC
|
2016-09-19 14:32:23.77 UTC
| null | 1,276,636 | null | 760,668 | null | 1 | 173 |
android|action|android-notifications
| 128,742 |
<p>When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:</p>
<pre><code>notify(int id, Notification notification)
</code></pre>
<p>To cancel, you would call:</p>
<pre><code>cancel(int id)
</code></pre>
<p>with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?</p>
|
3,936,088 |
MySQL: Split comma separated list into multiple rows
|
<p>I have an unnormalized table with a column containing a comma separated list that is a foreign key to another table:</p>
<pre><code>+----------+-------------+ +--------------+-------+
| part_id | material | | material_id | name |
+----------+-------------+ +--------------+-------+
| 339 | 1.2mm;1.6mm | | 1 | 1.2mm |
| 970 | 1.6mm | | 2 | 1.6mm |
+----------+-------------+ +--------------+-------+
</code></pre>
<p>I want to read this data into a search engine that offers no procedural language.</p>
<p>So is there a way to <strong>either</strong> make a join on this column <strong>or</strong> run a query on this data that inserts appropriate entries into a new table?
The resulting data should look like this:</p>
<pre><code>+---------+-------------+
| part_id | material_id |
+---------+-------------+
| 339 | 1 |
| 339 | 2 |
| 970 | 2 |
+---------+-------------+
</code></pre>
<p>I could think of a solution if the DBMS supported functions returning a table but MySQL apparently doesn't.</p>
| 22,375,303 | 4 | 1 | null |
2010-10-14 17:58:39.43 UTC
| 5 |
2019-06-08 00:16:42.58 UTC
|
2019-06-08 00:16:42.58 UTC
| null | 42,223 | null | 476,074 | null | 1 | 19 |
mysql|sql|delimiter|csv
| 56,633 |
<p>In MySQL this can be achieved as below </p>
<pre><code>SELECT id, length FROM vehicles WHERE id IN ( 117, 148, 126)
+---------------+
| id | length |
+---------------+
| 117 | 25 |
| 126 | 8 |
| 148 | 10 |
+---------------+
SELECT id,vehicle_ids FROM load_plan_configs WHERE load_plan_configs.id =42
+---------------------+
| id | vehicle_ids |
+---------------------+
| 42 | 117, 148, 126 |
+---------------------+
</code></pre>
<p>Now to get the length of comma separated vehicle_ids use below query</p>
<pre><code>Output
SELECT length
FROM vehicles, load_plan_configs
WHERE load_plan_configs.id = 42 AND FIND_IN_SET(
vehicles.id, load_plan_configs.vehicle_ids
)
+---------+
| length |
+---------+
| 25 |
| 8 |
| 10 |
+---------+
</code></pre>
<p><a href="http://amitbrothers.blogspot.in/2014/03/mysql-split-comma-separated-list-into.html" rel="noreferrer">For more info visit http://amitbrothers.blogspot.in/2014/03/mysql-split-comma-separated-list-into.html</a></p>
|
3,340,342 |
Writing to the real STDOUT after System.setOut
|
<p>I'm trying to intercept System.out and System.err, but maintain the ability to write to the original streams directly when necessary.</p>
<pre><code>PrintStream ps = System.out;
System.setOut(new MyMagicPrintStream());
ps.println("foo");
</code></pre>
<p>Unfortunately, the details of the System class' implementation means that in my example, "foo" gets sent to <code>MyMagicPrintStream</code> instead of the real <code>stdout</code>. </p>
<p>Does anyone know how to get references to the real/original <code>OutputStreams</code>?</p>
<p>Thanks.</p>
<p><em>PS: This will otherwise result in a StackOverflowError <-- for SEO.</em></p>
| 3,340,416 | 4 | 0 | null |
2010-07-27 02:18:29.197 UTC
| 10 |
2019-12-27 21:21:06.867 UTC
|
2019-12-27 21:21:06.867 UTC
| null | 1,429,432 | null | 293,358 | null | 1 | 27 |
java
| 21,512 |
<p>try this:</p>
<pre><code>PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out))
</code></pre>
|
3,468,102 |
Regex word boundary expressions
|
<p>Say for example I have the following string <code>"one two(three) (three) four five"</code> and I want to replace <code>"(three)"</code> with <code>"(four)"</code> but not within words. How would I do it?</p>
<p>Basically I want to do a regex replace and end up with the following string:</p>
<pre><code>"one two(three) (four) four five"
</code></pre>
<p>I have tried the following regex but it doesn't work:</p>
<pre><code>@"\b\(three\)\b"
</code></pre>
<p>Basically I am writing some search and replace code and am giving the user the usual options to match case, match whole word etc. In this instance the user has chosen to match whole words but I don't know what the text being searched for will be.</p>
| 3,468,269 | 4 | 1 | null |
2010-08-12 13:25:35.967 UTC
| 6 |
2014-02-05 21:39:44.81 UTC
|
2010-08-12 13:32:44.767 UTC
| null | 418,455 | null | 418,455 | null | 1 | 32 |
c#|regex
| 39,179 |
<p>Your problem stems from a misunderstanding of what <code>\b</code> actually means. Admittedly, it is not obvious.</p>
<p>The reason <code>\b\(three\)\b</code> doesn’t match the threes in your input string is the following:</p>
<ul>
<li><code>\b</code> means: the boundary between a <em>word character</em> and a <em>non-word character</em>.</li>
<li>Letters (e.g. a-z) are considered <em>word characters</em>.</li>
<li>Punctuation marks such as <code>(</code> are considered <em>non-word characters</em>.</li>
</ul>
<p>Here is your input string again, stretched out a bit, and I’ve marked the places where <code>\b</code> matches:</p>
<pre><code> o n e t w o ( t h r e e ) ( t h r e e ) f o u r f i v e
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
</code></pre>
<p>As you can see here, there is a <code>\b</code> between “two” and “(three)”, but not before the second “(three)”.</p>
<p>The moral of the story? “Whole-word search” doesn’t really make much sense if what you’re searching for is not just a word (a string of letters). Since you have punctuation characters (parentheses) in your search string, it is not as such a “word”. If you searched for a word consisting only of <em>word characters</em>, then <code>\b</code> would do what you expect.</p>
<p>You can, of course, use a different Regex to match the string only if it surrounded by spaces or occurs at the beginning or end of the string:</p>
<pre><code>(^|\s)\(three\)(\s|$)
</code></pre>
<p>However, the problem with this is, of course, that if you search for “three” (without the parentheses), it won’t find the one in “(three)” because it doesn’t have spaces around it, even though it is actually a whole word.</p>
<p>I think most text editors (including Visual Studio) will use <code>\b</code> only if your search string actually starts and/or ends with a word character:</p>
<pre><code>var pattern = Regex.Escape(searchString);
if (Regex.IsMatch(searchString, @"^\w"))
pattern = @"\b" + pattern;
if (Regex.IsMatch(searchString, @"\w$"))
pattern = pattern + @"\b";
</code></pre>
<p>That way they will find “(three)” even if you select “whole words only”.</p>
|
3,342,319 |
How do I use T-SQL's Case/When?
|
<p>I have a huge query which uses <em>case/when</em> often. Now I have this SQL here, which does not work.</p>
<pre><code> (select case when xyz.something = 1
then
'SOMETEXT'
else
(select case when xyz.somethingelse = 1)
then
'SOMEOTHERTEXT'
end)
(select case when xyz.somethingelseagain = 2)
then
'SOMEOTHERTEXTGOESHERE'
end)
end) [ColumnName],
</code></pre>
<p>Whats causing trouble is <code>xyz.somethingelseagain = 2</code>, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.</p>
| 3,342,349 | 4 | 0 | null |
2010-07-27 09:40:59.427 UTC
| 9 |
2019-01-28 09:44:36.297 UTC
|
2013-03-06 17:43:55.51 UTC
| null | 5,640 | null | 304,357 | null | 1 | 51 |
tsql|case-when
| 130,543 |
<pre><code>SELECT
CASE
WHEN xyz.something = 1 THEN 'SOMETEXT'
WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
ELSE 'SOMETHING UNKNOWN'
END AS ColumnName;
</code></pre>
|
3,720,222 |
Using Statement with Generics: using ISet<> = System.Collections.Generic.ISet<>
|
<p>Since I am using two different generic collection namespaces (<code>System.Collections.Generic</code> and <code>Iesi.Collections.Generic</code>), I have conflicts. In other parts of the project, I am using both the nunit and mstest framework, but qualify that when I call <code>Assert</code> I want to use the nunit version by </p>
<pre><code>using Assert = NUnit.Framework.Assert;
</code></pre>
<p>Which works great, but I want to do the same thing with generic types. However, the following lines do not work</p>
<pre><code>using ISet = System.Collections.Generic.ISet;
using ISet<> = System.Collections.Generic.ISet<>;
</code></pre>
<p>Does anyone know how to tell .net how to use the using statement with generics?</p>
| 3,720,263 | 6 | 5 | null |
2010-09-15 17:40:56.077 UTC
| 4 |
2020-04-09 10:02:28.473 UTC
|
2013-03-16 14:43:59.123 UTC
| null | 445,517 | null | 128,968 | null | 1 | 48 |
c#|generics|syntax|alias|using
| 8,234 |
<p>I think you're better off aliasing the namespaces themselves as opposed to the generic types (which I don't think is possible).</p>
<p>So for instance:</p>
<pre><code>using S = System.Collections.Generic;
using I = Iesi.Collections.Generic;
</code></pre>
<p>Then for a BCL <code>ISet<int></code>, for example:</p>
<pre><code>S.ISet<int> integers = new S.HashSet<int>();
</code></pre>
|
3,389,620 |
How to fix Subversion «!» status
|
<p>The Subversion manual states:</p>
<blockquote>
<p>'!'</p>
<p>Item is missing (e.g. you moved or
deleted it without using svn). This
also indicates that a directory is
incomplete (a checkout or update was
interrupted).</p>
</blockquote>
<p>But as so often with Subversion, there is no indication on how to fix the problem.</p>
<p>Normally, I would use my trusted <a href="https://web.archive.org/web/20140221005130/http://my.opera.com/krischik/blog/2010/08/02/repair-subversion" rel="noreferrer">Fix_Subversion.command</a> but this time it is trunk and it will take forever.</p>
<p>So is there any faster option?</p>
| 3,389,731 | 6 | 2 | null |
2010-08-02 16:16:24.157 UTC
| 12 |
2020-06-29 11:05:05.773 UTC
|
2020-06-29 11:05:05.773 UTC
| null | 9,802 | null | 341,091 | null | 1 | 65 |
svn
| 60,431 |
<pre><code>svn revert /path/to/file
svn rm /path/to/file # if you want to delete it from svn itself
</code></pre>
<p>Golden rule is: once something is under svn-control, any moving, deleting, renaming, should be done with svn commands (svn mv, svn rm, etc.), not using normal filesystem/file-explorer functions.</p>
|
3,601,273 |
HTML5 and frameborder
|
<p>I have an iframe on an HTML5 document. when I validate I am getting an error telling me that the attribute on the <code>iframe frameBorder</code> is obsolete and to use CSS instead.</p>
<p>I have this attribute <strong><code>frameBorder="0"</code></strong> here because it was the only way I could figure out how to get rid of the border in IE, I tried <code>border:none;</code> in CSS with no luck. Is there a compliant way to fix this?</p>
<p>Thanks.</p>
| 3,601,946 | 6 | 0 | null |
2010-08-30 14:30:02.56 UTC
| 8 |
2019-12-11 08:05:28.307 UTC
|
2015-03-01 03:40:18.897 UTC
| null | 1,696,030 | null | 46,011 | null | 1 | 92 |
css|internet-explorer|html
| 126,354 |
<blockquote>
<p><s>HTML 5 doesn't support attributes such as frameborder, scrolling, marginwidth, and marginheight (which were supported in HTML 4.01). Instead, the HTML 5 specification has introduced the seamless attribute. The seamless attribute allows the inline frame to appear as though it is being rendered as part of the containing document. For example, borders and scrollbars will not appear.</s></p>
</blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#Deprecated_attributes" rel="noreferrer">According to MDN</a></p>
<blockquote>
<p><code>frameborder</code> <strong>Obsolete since HTML5</strong></p>
<p>The value <code>1</code> (the default) draws a border around this frame. The value <code>0</code> removes the border around this frame, but you should instead use the CSS property border to control borders.</p>
</blockquote>
<p>Like the quote above says, you <strong>should</strong> remove the border with CSS;<br>either inline (<code>style="border: none;"</code>) or in your stylesheet (<code>iframe { border: none; }</code>).</p>
<p>That being said, there doesn't seem to be a single iframe provider that doesn't use <code>frameborder="0"</code>. Even YouTube still uses the attribute and doesn't even provide a style attribute to make iframes backwards compatible for when frameborder isn't supported anymore. It's safe to say that the attribute isn't going anywhere soon. This leaves you with 3 options:</p>
<ol>
<li>Keep using <code>frameborder</code>, just to be sure it works (for now)</li>
<li>Use CSS, to do the "right" thing</li>
<li>Use both. Although this doesn't resolve the incompatibility problem (just like option 1), it does and will work in every browser that has been and will be</li>
</ol>
<br>
<p>As for the previous state of this decade-old answer:</p>
<p>The <code>seamless</code> attribute has been supported for such a short time (or not at all by some browsers), that MDN doesn't even list it as a deprecated feature. Don't use it and don't get confused by the comments below.</p>
|
3,925,183 |
Method to Find GridView Column Index by Name
|
<p>I'm trying to write a small method to loop through and find a <code>GridView</code> Column by its Index, since it can change position based on what might be visible.</p>
<p>Here is what I have so far: </p>
<pre><code>private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataColumn col in grid.Columns)
{
if (col.ColumnName.ToLower().Trim() == name.ToLower().Trim()) return col.Ordinal;
}
return -1;
}
</code></pre>
<p>In this case, DataColumn doesn't appear to be the right type to use, but I'm kind of lost as to what I should be doing here.</p>
<p>I can only use .NET 2.0 / 3.5. I can't use 4.0. </p>
| 3,925,334 | 7 | 0 | null |
2010-10-13 15:13:32.7 UTC
| 6 |
2018-12-16 16:27:46.497 UTC
|
2016-03-29 11:23:20.147 UTC
| null | 1,735,406 | null | 398,222 | null | 1 | 21 |
c#|asp.net
| 71,679 |
<p>I figured it out, I needed to be using <code>DataControlField</code> and slightly different syntax.</p>
<p>The working version:</p>
<pre><code>private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return grid.Columns.IndexOf(col);
}
}
return -1;
}
</code></pre>
|
3,964,681 |
Find all files in a directory with extension .txt in Python
|
<p>How can I find all the files in a directory having the extension <code>.txt</code> in python?</p>
| 3,964,691 | 25 | 0 | null |
2010-10-19 01:09:13.617 UTC
| 587 |
2021-11-11 13:54:18.347 UTC
|
2017-04-12 15:56:53.207 UTC
| null | 5,097,722 | null | 201,140 | null | 1 | 1,041 |
python|file-io
| 2,519,920 |
<p>You can use <a href="https://docs.python.org/2/library/glob.html" rel="noreferrer"><code>glob</code></a>:</p>
<pre><code>import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
</code></pre>
<p>or simply <a href="https://docs.python.org/2/library/os.html#os.listdir" rel="noreferrer"><code>os.listdir</code></a>:</p>
<pre><code>import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))
</code></pre>
<p>or if you want to traverse directory, use <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a>:</p>
<pre><code>import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
</code></pre>
|
8,268,154 |
Run ruby script in elevated mode
|
<p>I need to run a ruby script in elevated mode (Admin priviledges) under Windows. Is it possible?</p>
| 8,336,031 | 4 | 2 | null |
2011-11-25 11:04:06.777 UTC
| 8 |
2021-01-10 02:57:22.04 UTC
| null | null | null | null | 19,224 | null | 1 | 8 |
ruby|windows
| 4,881 |
<p>Here's how to do it. The easiest way is to restart your executable with elevaded (Admin) privileges using <code>ShellExecute</code>.</p>
<p>With Ruby you do it like this:</p>
<pre><code>require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute('path_to_ruby_program', nil, nil, 'runas')
</code></pre>
<p>If you have Windows UAC enabled this will give you the familiar Windows pop up dialog that requests Admin privileges. Once you click Yes, your process will run with Admin rights.</p>
<p>The secret trick here is using the the undocumented <code>ShellExecute</code> operation parameter <code>runas</code>, which will elevate the requested operation.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx</a></p>
<p>Also related discussion on how to manually create an elevated command prompt shortcut (which might be a good enough solution in some cases):</p>
<p><a href="http://www.sevenforums.com/tutorials/3718-elevated-command-prompt-shortcut.html" rel="nofollow noreferrer">http://www.sevenforums.com/tutorials/3718-elevated-command-prompt-shortcut.html</a></p>
|
7,839,642 |
int to String in Android
|
<p>I get the id of resource like so:</p>
<pre><code>int test = (context.getResourceId("raw.testc3"));
</code></pre>
<p>I want to get it's id and put it into a string. How can I do this? .toString does not work.</p>
| 7,839,678 | 4 | 0 | null |
2011-10-20 17:16:13.007 UTC
| 6 |
2020-01-31 11:22:48.777 UTC
|
2015-12-05 13:20:33.537 UTC
| null | 196,919 | null | 956,868 | null | 1 | 58 |
android|string
| 88,520 |
<pre><code>String testString = Integer.toString(test);
</code></pre>
|
8,014,500 |
MacOSX: autostart mysql on boot
|
<p>I just installed mysql in terminal through homebrew.</p>
<p>Now when I try to connect to mysql it fails, but after I run <code>mysqld</code> it works.. </p>
<p>So what I need to do now is run mysqld when I boot my Mac.</p>
<p>I've searched Google for <code>mysqld autoload at startup</code> etc. but couldn't find the right answer.</p>
<p>Hope someone can point me in the right direction.. Thanks!</p>
| 8,085,693 | 7 | 0 | null |
2011-11-04 19:05:57.59 UTC
| 11 |
2018-05-10 20:17:57.913 UTC
|
2016-10-27 12:09:40.147 UTC
| null | 147,562 | null | 540,447 | null | 1 | 45 |
macos|terminal|homebrew|mysql
| 36,147 |
<p><code>brew info mysql</code> gives you the instructions for loading MySQL at startup, but here's all you need to do:</p>
<pre><code>mkdir -p ~/Library/LaunchAgents
cp `brew --prefix mysql`/*mysql*.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/*mysql*.plist
</code></pre>
|
8,273,823 |
How can I discard modified files?
|
<p>This is a Linux 2.6 kernel repository. I git clone it to my local host.</p>
<p>After that. I didn't make any change. But when I "git status". I found 13 modified files. I want to discard them, but I can't.</p>
<pre><code>> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git
> status
> # On branch master
> # Changes not staged for commit:
> # (use "git add <file>..." to update what will be committed)
> # (use "git checkout -- <file>..." to discard changes in working directory)
> #
> # modified: include/linux/netfilter/xt_connmark.h
> # modified: include/linux/netfilter/xt_dscp.h
> # modified: include/linux/netfilter/xt_mark.h
> # modified: include/linux/netfilter/xt_rateest.h
> # modified: include/linux/netfilter/xt_tcpmss.h
> # modified: include/linux/netfilter_ipv4/ipt_ecn.h
> # modified: include/linux/netfilter_ipv4/ipt_ttl.h
> # modified: include/linux/netfilter_ipv6/ip6t_hl.h
> # modified: net/ipv4/netfilter/ipt_ecn.c
> # modified: net/netfilter/xt_dscp.c
> # modified: net/netfilter/xt_hl.c
> # modified: net/netfilter/xt_rateest.c
> # modified: net/netfilter/xt_tcpmss.c
> #
> # Untracked files:
> # (use "git add <file>..." to include in what will be committed)
> #
> # samples/hidraw/ no changes added to commit (use "git add" and/or "git commit -a")
> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git
> checkout -- include/linux/netfilter/xt_connmark. h
> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git
> status
> # On branch master
> # Changes not staged for commit:
> # (use "git add <file>..." to update what will be committed)
> # (use "git checkout -- <file>..." to discard changes in working directory)
> #
> # modified: include/linux/netfilter/xt_CONNMARK.h
> # modified: include/linux/netfilter/xt_dscp.h
> # modified: include/linux/netfilter/xt_mark.h
> # modified: include/linux/netfilter/xt_rateest.h
> # modified: include/linux/netfilter/xt_tcpmss.h
> # modified: include/linux/netfilter_ipv4/ipt_ecn.h
> # modified: include/linux/netfilter_ipv4/ipt_ttl.h
> # modified: include/linux/netfilter_ipv6/ip6t_hl.h
> # modified: net/ipv4/netfilter/ipt_ecn.c
> # modified: net/netfilter/xt_dscp.c
> # modified: net/netfilter/xt_hl.c
> # modified: net/netfilter/xt_rateest.c
> # modified: net/netfilter/xt_tcpmss.c
> #
> # Untracked files:
> # (use "git add <file>..." to include in what will be committed)
> #
> # samples/hidraw/ no changes added to commit (use "git add" and/or "git commit -a")
> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git
> checkout -- include/linux/netfilter/xt_dscp.h
> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git
> status
> # On branch master
> # Changes not staged for commit:
> # (use "git add <file>..." to update what will be committed)
> # (use "git checkout -- <file>..." to discard changes in working directory)
> #
> # modified: include/linux/netfilter/xt_CONNMARK.h
> # modified: include/linux/netfilter/xt_DSCP.h
> # modified: include/linux/netfilter/xt_mark.h
> # modified: include/linux/netfilter/xt_rateest.h
> # modified: include/linux/netfilter/xt_tcpmss.h
> # modified: include/linux/netfilter_ipv4/ipt_ecn.h
> # modified: include/linux/netfilter_ipv4/ipt_ttl.h
> # modified: include/linux/netfilter_ipv6/ip6t_hl.h
> # modified: net/ipv4/netfilter/ipt_ecn.c
> # modified: net/netfilter/xt_dscp.c
> # modified: net/netfilter/xt_hl.c
> # modified: net/netfilter/xt_rateest.c
> # modified: net/netfilter/xt_tcpmss.c
> #
> # Untracked files:
> # (use "git add <file>..." to include in what will be committed)
> #
> # samples/hidraw/ no changes added to commit (use "git add" and/or "git commit -a")
> luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$
>
</code></pre>
<p>edited:</p>
<pre><code>luke@Macbook-Pro~/Documents/workspace/linuxkernel/linux-2.6$ git config -l
user.name=99999
user.email=99999
alias.co=checkout
core.editor=mate -w
core.edit=mate -w
core.excludesfile=/Users/luke/.gitignore_global
difftool.sourcetree.cmd=opendiff "$LOCAL" "$REMOTE"
difftool.sourcetree.path=
mergetool.sourcetree.cmd=/Applications/SourceTree.app/Contents/Resources/opendiff-w.sh "$LOCAL" "$REMOTE" -ancestor "$BASE" -merge "$MERGED"
mergetool.sourcetree.trustexitcode=true
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
</code></pre>
<p>edited: this is my diff file:</p>
<pre><code>diff --git a/include/linux/netfilter/xt_CONNMARK.h b/include/linux/netfilter/xt_CONNMARK.h
index 2f2e48e..efc17a8 100644
--- a/include/linux/netfilter/xt_CONNMARK.h
+++ b/include/linux/netfilter/xt_CONNMARK.h
@@ -1,6 +1,31 @@
-#ifndef _XT_CONNMARK_H_target
-#define _XT_CONNMARK_H_target
+#ifndef _XT_CONNMARK_H
+#define _XT_CONNMARK_H
-#include <linux/netfilter/xt_connmark.h>
+#include <linux/types.h>
-#endif /*_XT_CONNMARK_H_target*/
+/* Copyright (C) 2002,2004 MARA Systems AB <http://www.marasystems.com>
+ * by Henrik Nordstrom <hno@marasystems.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ */
+
+enum {
+ XT_CONNMARK_SET = 0,
+ XT_CONNMARK_SAVE,
+ XT_CONNMARK_RESTORE
+};
+
+struct xt_connmark_tginfo1 {
+ __u32 ctmark, ctmask, nfmask;
+ __u8 mode;
+};
+
+struct xt_connmark_mtinfo1 {
+ __u32 mark, mask;
+ __u8 invert;
+};
+
+#endif /*_XT_CONNMARK_H*/
diff --git a/include/linux/netfilter/xt_DSCP.h b/include/linux/netfilter/xt_DSCP.h
index 648e0b3..15f8932 100644
--- a/include/linux/netfilter/xt_DSCP.h
+++ b/include/linux/netfilter/xt_DSCP.h
@@ -1,26 +1,31 @@
-/* x_tables module for setting the IPv4/IPv6 DSCP field
+/* x_tables module for matching the IPv4/IPv6 DSCP field
*
* (C) 2002 Harald Welte <laforge@gnumonks.org>
- * based on ipt_FTOS.c (C) 2000 by Matthew G. Marsh <mgm@paktronix.com>
* This software is distributed under GNU GPL v2, 1991
*
* See RFC2474 for a description of the DSCP field within the IP Header.
*
- * xt_DSCP.h,v 1.7 2002/03/14 12:03:13 laforge Exp
+ * xt_dscp.h,v 1.3 2002/08/05 19:00:21 laforge Exp
*/
-#ifndef _XT_DSCP_TARGET_H
-#define _XT_DSCP_TARGET_H
-#include <linux/netfilter/xt_dscp.h>
+#ifndef _XT_DSCP_H
+#define _XT_DSCP_H
+
#include <linux/types.h>
-/* target info */
-struct xt_DSCP_info {
+#define XT_DSCP_MASK 0xfc /* 11111100 */
+#define XT_DSCP_SHIFT 2
+#define XT_DSCP_MAX 0x3f /* 00111111 */
+
+/* match info */
+struct xt_dscp_info {
__u8 dscp;
+ __u8 invert;
};
-struct xt_tos_target_info {
- __u8 tos_value;
+struct xt_tos_match_info {
__u8 tos_mask;
+ __u8 tos_value;
+ __u8 invert;
};
-#endif /* _XT_DSCP_TARGET_H */
+#endif /* _XT_DSCP_H */
diff --git a/include/linux/netfilter/xt_mark.h b/include/linux/netfilter/xt_mark.h
index ecadc40..41c456d 100644
--- a/include/linux/netfilter/xt_mark.h
+++ b/include/linux/netfilter/xt_mark.h
@@ -1,15 +1,6 @@
-#ifndef _XT_MARK_H
-#define _XT_MARK_H
+#ifndef _XT_MARK_H_target
+#define _XT_MARK_H_target
-#include <linux/types.h>
+#include <linux/netfilter/xt_mark.h>
-struct xt_mark_tginfo2 {
- __u32 mark, mask;
-};
-
-struct xt_mark_mtinfo1 {
- __u32 mark, mask;
- __u8 invert;
-};
-
-#endif /*_XT_MARK_H*/
+#endif /*_XT_MARK_H_target */
diff --git a/include/linux/netfilter/xt_rateest.h b/include/linux/netfilter/xt_rateest.h
index d40a619..6605e20 100644
--- a/include/linux/netfilter/xt_rateest.h
+++ b/include/linux/netfilter/xt_rateest.h
@@ -1,37 +1,15 @@
-#ifndef _XT_RATEEST_MATCH_H
-#define _XT_RATEEST_MATCH_H
+#ifndef _XT_RATEEST_TARGET_H
+#define _XT_RATEEST_TARGET_H
</code></pre>
<p>Due to Stack Overflow length limit. Only part of diff file can be copied here.</p>
<p>still need help</p>
| 8,273,847 | 10 | 4 | null |
2011-11-25 20:16:54.84 UTC
| 11 |
2020-06-09 02:20:33.523 UTC
|
2012-06-01 17:17:42.743 UTC
| null | 229,044 | null | 845,081 | null | 1 | 49 |
git
| 108,655 |
<p>A <code>git reset --hard HEAD</code> should solve the problem.</p>
|
7,771,586 |
How to check what user php is running as?
|
<p>I need to detect if php is running as nobody. How do I do this? </p>
<p>Are there any other names for "nobody"? "apache"? Any others?</p>
| 7,771,662 | 16 | 6 | null |
2011-10-14 17:56:31.37 UTC
| 29 |
2022-05-09 14:24:02.877 UTC
|
2012-07-26 05:06:29.543 UTC
| null | 168,868 |
user429620
| null | null | 1 | 137 |
php|apache
| 199,425 |
<p>If available you can probe the current user account with <a href="http://php.net/posix_geteuid" rel="noreferrer"><code>posix_geteuid</code></a> and then get the user name with <a href="http://php.net/posix_getpwuid" rel="noreferrer"><code>posix_getpwuid</code></a>.</p>
<pre><code>$username = posix_getpwuid(posix_geteuid())['name'];
</code></pre>
<p>If you are running in safe mode however (which is often the case when exec is disabled), then it's unlikely that your PHP process is running under anything but the default <code>www-data</code> or <code>apache</code> account.</p>
|
4,071,811 |
How to transform vertical data into horizontal data with SQL?
|
<p>I have a table "Item" with a number of related items, like so:</p>
<pre><code>ID Rel_ID Name RelRank
--- ------ ---- -------
1 1 foo 1
2 1 bar 2
3 1 zam 3
4 2 foo2 1
</code></pre>
<p>I'm trying to get a query so items with the same Rel_ID would appear in the same row, like so:</p>
<pre><code>Rel_ID Name1 Name2 Name3
------ ----- ----- -----
1 foo bar zam
2 foo2
</code></pre>
<p>I've tried selecting the table multiple times:</p>
<pre><code>SELECT k.Rel_ID, k.name 'Name1', k2.name 'Name2'
FROM item k, item k2
WHERE k.Rel_ID = k2.Rel_ID
</code></pre>
<p>But this fails. Surely there's a transformation or query that could drastically simplify the process, and I'm just missing it because I haven't used SQL in this way before. What am I missing?</p>
<p>[Edit: added RelRank column, which does appear in my data]</p>
| 4,071,845 | 3 | 5 | null |
2010-11-01 18:19:05.02 UTC
| 3 |
2016-09-07 13:44:47.43 UTC
|
2010-11-01 18:34:10.65 UTC
| null | 89,244 | null | 89,244 | null | 1 | 18 |
sql|mysql|pivot
| 74,971 |
<p>Regardless of the database you are using, the concept of what you are trying to achieve is called "Pivot Table".</p>
<p>Here's an example for mysql:
<a href="http://en.wikibooks.org/wiki/MySQL/Pivot_table" rel="noreferrer">http://en.wikibooks.org/wiki/MySQL/Pivot_table</a></p>
<p>Some databases have builtin features for that, see the links below.</p>
<p>SQLServer:
<a href="http://msdn.microsoft.com/de-de/library/ms177410.aspx" rel="noreferrer">http://msdn.microsoft.com/de-de/library/ms177410.aspx</a></p>
<p>Oracle:
<a href="http://www.dba-oracle.com/t_pivot_examples.htm" rel="noreferrer">http://www.dba-oracle.com/t_pivot_examples.htm</a></p>
<p>You can always create a pivot by hand. Just select all the aggregations in a result set and then select from that result set. Note, in your case, you can put all the names into one column using concat (i think that's group_concat in mysql), since you cannot know how many names are related to a a rel_id.</p>
<p>pseudo-select for your case (i don't know mysql):</p>
<pre><code>select rel_id, group_concat(name) from item group by rel_id
</code></pre>
|
4,575,326 |
In Python, can I specify a function argument's default in terms of other arguments?
|
<p>Suppose I have a python function that takes two arguments, but I want the second arg to be optional, with the default being whatever was passed as the first argument. So, I want to do something like this:</p>
<pre><code>def myfunc(arg1, arg2=arg1):
print (arg1, arg2)
</code></pre>
<p>Except that doesn't work. The only workaround I can think of is this:</p>
<pre><code>def myfunc(arg1, arg2=None):
if arg2 is None:
arg2 = arg1
print (arg1, arg2)
</code></pre>
<p>Is there a better way to do this?</p>
| 4,575,371 | 3 | 2 | null |
2011-01-01 19:16:10.93 UTC
| 5 |
2011-01-01 20:38:58.897 UTC
| null | null | null | null | 125,921 | null | 1 | 39 |
python|function|default-value|arguments
| 12,339 |
<p>As @Ignacio says, you can't do this. In your latter example, you might have a situation where <code>None</code> is a valid value for <code>arg2</code>. If this is the case, you can use a sentinel value:</p>
<pre><code>sentinel = object()
def myfunc(arg1, arg2=sentinel):
if arg2 is sentinel:
arg2 = arg1
print (arg1, arg2)
myfunc("foo") # Prints 'foo foo'
myfunc("foo", None) # Prints 'foo None'
</code></pre>
|
4,810,268 |
Eclipse and Facets
|
<p>In the courses java, everyone (or at least most people) seemed to have a working eclipse. They always seemed to have a working faces-config (a visual one), and autocomplete in xhtml files (for facelets). Though for autocomplete, we added *.xhtml files on JSP's.</p>
<p>It seems that this was a part I don't know well about eclipse, and it's fairly annoying since I don't know why. When I import a project (either Maven or existing), it always has no facets but java (and that in 1.5 not even 1.6), while it is supposed to be a webproject and have facelets & dynamic web project.</p>
<p>Can I change those facets? It seems to just work when I put java to 1.6, but trying to edit the dynamic web module version from 2.4 to 2.5 (it is standard on 2.4) without running into some troubles. Even after I just made a fresh maven project (with an archtype in commandline), I'm not able to change much about these facets.</p>
<p>What am I doing wrong? </p>
| 4,810,543 | 4 | 0 | null |
2011-01-26 21:31:53.633 UTC
| 4 |
2016-11-20 18:24:06.023 UTC
| null | null | null | null | 336,547 | null | 1 | 8 |
eclipse|facet
| 42,663 |
<p>Eclipse functionality is driven by project metadata. If you don't have the right metadata, the projects aren't going to behave correctly. </p>
<p>If you are starting from scratch and creating projects in Eclipse, make sure to place all of the metadata files in your source control system (including everything under [project]/.settings directory). </p>
<p>If you are using Maven to generate your Eclipse project metadata, make sure that you find the Maven plugin that knows about WTP. I don't have a reference, but I know it exists. This will ensure that when Maven generates metadata, it will have the correct metadata for web projects.</p>
<blockquote>
<p>Can I change those facets? It seems to
just work when I put java to 1.6, but
trying to edit the dynamic web module
version from 2.4 to 2.5 (it is
standard on 2.4) without running into
some troubles. </p>
</blockquote>
<p>The way facet works is that the facet author can choose not to implement version change logic. Unfortunately the Java EE module facets (such as the dynamic web module) do not have version change implemented. Other facets like Java do support this. So your experience will vary from facet to facet.</p>
<p>If all else fails, you can edit .settings/org.eclipse.wst.common.project.facet.core.xml file by hand. Make sure to do that from Eclipse or you will need to refresh the project afterwards. Just keep in mind that if you are forcing the change like that, you might need to do some manual fixes to your project content. For instance, if you change web spec level, you may need to update the deployment descriptors. </p>
|
4,233,354 |
How to iterate json data in jquery
|
<p>How to iterate the json data in jquery.</p>
<pre><code>[{"id":"856","name":"India"},
{"id":"1035","name":"Chennai"},
{"id":"1048","name":"Delhi"},
{"id":"1113","name":"Lucknow"},
{"id":"1114","name":"Bangalore"},
{"id":"1115","name":"Ahmedabad"},
{"id":"1116","name":"Cochin"},
{"id":"1117","name":"London"},
{"id":"1118","name":"New York"},
{"id":"1119","name":"California"}
]
</code></pre>
| 4,233,367 | 4 | 0 | null |
2010-11-20 15:07:18.723 UTC
| 4 |
2017-10-25 13:26:15.293 UTC
| null | null | null | null | 433,904 | null | 1 | 23 |
jquery|json
| 57,063 |
<p>You can use <a href="http://api.jquery.com/jQuery.each/" rel="noreferrer"><code>$.each()</code></a> like this:</p>
<pre><code>$.each(data, function(i, obj) {
//use obj.id and obj.name here, for example:
alert(obj.name);
});
</code></pre>
|
4,435,853 |
echo outputs -e parameter in bash scripts. How can I prevent this?
|
<p>I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command</p>
<pre><code>$ echo -e 'foo\nbar'
</code></pre>
<p>into an interactive bash shell, I get the expected output:</p>
<pre><code>foo
bar
</code></pre>
<p>But when I use this same command (i've tried this command character for character as a test case) I get the following output:</p>
<pre><code>-e foo
bar
</code></pre>
<p>It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?</p>
| 4,436,025 | 4 | 3 | null |
2010-12-14 04:26:24.533 UTC
| 5 |
2017-03-21 01:22:26.743 UTC
| null | null | null | null | 434,731 | null | 1 | 29 |
bash|echo
| 24,048 |
<p>You need to use <code>#!/bin/bash</code> as the first line in your script. If you don't, or if you use <code>#!/bin/sh</code>, the script will be run by the Bourne shell and its <code>echo</code> doesn't recognize the <code>-e</code> option. In general, it is recommended that all new scripts use <code>printf</code> instead of <code>echo</code> if portability is important.</p>
<p>In Ubuntu, <code>sh</code> is provided by a symlink to <code>/bin/dash</code>.</p>
|
4,115,953 |
Where do tabindex="0" HTML elements end up in the tabbing order?
|
<p>In what order are elements with a <code>tabindex</code> value of 0 focused when the web page is tabbed?</p>
| 4,115,989 | 4 | 2 | null |
2010-11-07 00:39:19.093 UTC
| 11 |
2018-12-26 07:16:52.523 UTC
|
2010-11-07 00:58:16.487 UTC
| null | 20,578 | null | 697,684 | null | 1 | 52 |
html|tabindex
| 66,421 |
<p>The <a href="http://www.w3.org/TR/html401/interact/forms.html#tabbing-navigation" rel="noreferrer">HTML specification</a> states:</p>
<blockquote>
<p>Elements that have identical tabindex
values should be navigated in the
order they appear in the character
stream.</p>
</blockquote>
|
4,230,375 |
What's the easiest way to remove <fieldset> border lines?
|
<p>What's the easiest way to remove the <strong>border</strong> lines of a <code><fieldset></code>?</p>
<p>I mean a cross-browser solution... is that possible ?</p>
| 4,230,381 | 4 | 2 | null |
2010-11-19 23:45:11.617 UTC
| 3 |
2018-12-28 07:05:47 UTC
|
2010-11-20 04:02:55.143 UTC
| null | 333,255 | null | 257,022 | null | 1 | 68 |
html|css
| 86,820 |
<pre><code>fieldset {
border: 0;
}
</code></pre>
|
4,215,472 |
Python: take max N elements from some list
|
<p>Is there some function which would return me the N highest elements from some list?</p>
<p>I.e. if <code>max(l)</code> returns the single highest element, sth. like <code>max(l, count=10)</code> would return me a list of the 10 highest numbers (or less if <code>l</code> is smaller).</p>
<p>Or what would be an efficient easy way to get these? (Except the obvious canonical implementation; also, no such things which involve sorting the whole list first because that would be inefficient compared to the canonical solution.)</p>
| 4,215,776 | 5 | 3 | null |
2010-11-18 13:54:56.453 UTC
| 6 |
2021-10-20 08:04:53.753 UTC
| null | null | null | null | 133,374 | null | 1 | 38 |
python|max
| 39,163 |
<p><a href="http://docs.python.org/library/heapq.html#heapq.nlargest"><code>heapq.nlargest</code></a>:</p>
<pre><code>>>> import heapq, random
>>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100)))
[1.9730767232998481, 1.9326532289091407, 1.7762926716966254]
</code></pre>
|
4,189,365 |
Use jQuery to convert JSON array to HTML bulleted list
|
<p>How can you convert an array of strings represented in JSON format and convert this to an HTML bulleted list using jQuery?</p>
| 4,189,444 | 6 | 4 | null |
2010-11-15 22:13:31.33 UTC
| 2 |
2019-05-25 23:47:56.24 UTC
|
2019-05-25 23:47:56.24 UTC
| null | 819,651 | null | 47,281 | null | 1 | 17 |
jquery|json
| 61,636 |
<pre><code>var ul = $('<ul>').appendTo('body');
var json = { items: ['item 1', 'item 2', 'item 3'] };
$(json.items).each(function(index, item) {
ul.append(
$(document.createElement('li')).text(item)
);
});
</code></pre>
<p>As far as fetching the JSON from your server using AJAX is concerned you could use the <a href="http://api.jquery.com/jQuery.getJSON/"><code>$.getJSON()</code></a> function.</p>
<p><a href="http://jsfiddle.net/kAT8a/">Live demo</a>.</p>
|
4,216,123 |
How to scale a BufferedImage
|
<p>Following the javadocs, I have tried to scale a <code>BufferedImage</code> without success here is my code:</p>
<pre><code>BufferedImage image = MatrixToImageWriter.getBufferedImage(encoded);
Graphics2D grph = image.createGraphics();
grph.scale(2.0, 2.0);
grph.dispose();
</code></pre>
<p>I can't understand why it is not working, any help?</p>
| 4,216,635 | 7 | 3 | null |
2010-11-18 14:59:59.243 UTC
| 29 |
2022-07-05 04:40:32.823 UTC
|
2018-04-04 05:46:36.917 UTC
| null | 4,283,581 | null | 52,924 | null | 1 | 56 |
java|image|image-processing|bufferedimage|image-scaling
| 121,216 |
<p><a href="http://docs.oracle.com/javase/8/docs/api/java/awt/image/AffineTransformOp.html" rel="noreferrer"><code>AffineTransformOp</code></a> offers the additional flexibility of choosing the interpolation type.</p>
<pre><code>BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);
</code></pre>
<p>The fragment shown illustrates <a href="https://en.wikipedia.org/wiki/Image_scaling" rel="noreferrer"><em>resampling</em></a>, not <a href="https://en.wikipedia.org/wiki/Cropping_(image)" rel="noreferrer"><em>cropping</em></a>; this related <a href="https://stackoverflow.com/a/46211880/230513">answer</a> addresses the <a href="https://stackoverflow.com/questions/4216123/how-to-scale-a-bufferedimage/46211880#comment79385871_4216635">issue</a>; some related examples are examined <a href="https://stackoverflow.com/search?tab=votes&q=AffineTransformOp">here</a>.</p>
|
4,398,951 |
Force SSL/https using .htaccess and mod_rewrite
|
<p>How can I force to SSL/https using .htaccess and mod_rewrite page specific in PHP.</p>
| 4,399,158 | 9 | 0 | null |
2010-12-09 13:56:28.533 UTC
| 97 |
2019-07-02 10:27:10.707 UTC
|
2016-05-17 15:18:12.607 UTC
| null | 646,551 | null | 235,007 | null | 1 | 250 |
php|.htaccess|mod-rewrite|ssl|https
| 305,811 |
<p>For Apache, you can use <a href="http://httpd.apache.org/docs/2.2/mod/mod_ssl.html" rel="noreferrer"><code>mod_ssl</code></a> to force SSL with the <a href="http://httpd.apache.org/docs/2.2/mod/mod_ssl.html#sslrequiressl" rel="noreferrer"><code>SSLRequireSSL Directive</code></a>:</p>
<blockquote>
<p>This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.</p>
</blockquote>
<p>This will not do a redirect to https though. To redirect, try the following with <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="noreferrer"><code>mod_rewrite</code></a> in your .htaccess file</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code></pre>
<p>or any of the various approaches given at</p>
<ul>
<li><a href="http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html" rel="noreferrer">http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html</a></li>
</ul>
<p>You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)</p>
<pre><code>if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}
</code></pre>
|
4,749,963 |
What is the best way to stop a Unicorn Server process from running?
|
<p>What is the best way to stop a Unicorn Server process from running? Whenever I try to stop it using <code>kill -p 90234</code> it does not work. It is most likely something I am doing wrong. </p>
<p>Thanks.</p>
| 4,749,994 | 10 | 3 | null |
2011-01-20 16:45:34.663 UTC
| 16 |
2016-09-18 16:21:14.787 UTC
|
2013-10-02 23:41:25.02 UTC
| null | 128,421 | null | 577,180 | null | 1 | 34 |
ruby-on-rails
| 37,078 |
<p>Simple Things There - In Terminal type "ps" and have a look for the Master Unicorn Process. Copy the PID of it and then type "kill −9 90234" (where 90234 is PID of master unicorn process). After that worker process should disappear itself.</p>
|
4,190,429 |
How to clear the Android Stack of activities?
|
<p>I have an application with several Activities in Android and I want the user to be able to log-out by pressing a menu button. The problem I have is that</p>
<p>A) Android doesn't let you terminate the application and<br>
B) even when I send the user to the <code>LoginActivity</code> again they can always press <em>back</em> and get right back to the previous activity they were in.</p>
<p>I already tried to launch the Activity with the two following flags: </p>
<pre><code>Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
</code></pre>
<p>I also tried with each one of them by themselves.</p>
<p>I also tried calling <code>finish()</code> after <code>startActivity(intent)</code> as I read in another StackOverflow
question.</p>
| 4,190,906 | 10 | 2 | null |
2010-11-16 01:29:56.033 UTC
| 11 |
2020-11-12 07:14:57.973 UTC
|
2013-10-08 14:20:37.577 UTC
| null | 356,895 | null | 505,162 | null | 1 | 54 |
android|android-activity|stack|back-stack
| 57,827 |
<p>In your login activity, override the back button, so it hides your app instead of finishing the activity:</p>
<pre><code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
</code></pre>
<p>Also be sure to set android:alwaysRetainTaskState="true" on the root activity, so Android doesn't clear your stack (including the login activity) after 30min of inactivity from user.</p>
<p>Then just call finish() when there is a successful login.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.