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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,324,067 | How do I get str.translate to work with Unicode strings? | <p>I have the following code:</p>
<pre><code>import string
def translate_non_alphanumerics(to_translate, translate_to='_'):
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
translate_table = string.maketrans(not_letters_or_digits,
translate_to
*len(not_letters_or_digits))
return to_translate.translate(translate_table)
</code></pre>
<p>Which works great for non-unicode strings:</p>
<pre><code>>>> translate_non_alphanumerics('<foo>!')
'_foo__'
</code></pre>
<p>But fails for unicode strings:</p>
<pre><code>>>> translate_non_alphanumerics(u'<foo>!')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in translate_non_alphanumerics
TypeError: character mapping must return integer, None or unicode
</code></pre>
<p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods" rel="noreferrer">Python 2.6.2 docs</a> for the str.translate() method.</p>
<p>How do I make this work for Unicode strings?</p> | 1,324,114 | 7 | 2 | null | 2009-08-24 18:52:52.833 UTC | 18 | 2019-12-12 22:30:47.99 UTC | null | null | null | null | 4,766 | null | 1 | 56 | python|unicode|string | 34,909 | <p>The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with <a href="https://docs.python.org/2/library/functions.html#ord" rel="noreferrer"><code>ord</code></a>) to Unicode ordinals. If you want to delete characters, you map to <code>None</code>.</p>
<p>I changed your function to build a dict mapping the ordinal of every character to the ordinal of what you want to translate to:</p>
<pre><code>def translate_non_alphanumerics(to_translate, translate_to=u'_'):
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits)
return to_translate.translate(translate_table)
>>> translate_non_alphanumerics(u'<foo>!')
u'_foo__'
</code></pre>
<p><em>edit:</em> It turns out that the translation mapping must map from the Unicode ordinal (via <code>ord</code>) to either another Unicode ordinal, a Unicode string, or None (to delete). I have thus changed the default value for <code>translate_to</code> to be a Unicode literal. For example:</p>
<pre><code>>>> translate_non_alphanumerics(u'<foo>!', u'bad')
u'badfoobadbad'
</code></pre> |
394,767 | Pointer Arithmetic | <p>Does anyone have any good articles or explanations (blogs, examples) for pointer arithmetic? Figure the audience is a bunch of Java programmers learning C and C++.</p> | 394,774 | 7 | 1 | null | 2008-12-27 07:10:39.027 UTC | 38 | 2012-11-04 23:01:48.467 UTC | 2009-02-17 20:26:14.873 UTC | starblue | 49,246 | ak | 4,653 | null | 1 | 60 | c|pointers|pointer-arithmetic | 104,178 | <p>First, the <a href="http://cslibrary.stanford.edu/104/" rel="noreferrer">binky</a> video may help. It's a nice video about pointers. For arithmetic, here is an example:</p>
<pre><code>int * pa = NULL;
int * pb = NULL;
pa += 1; // pa++. behind the scenes, add sizeof(int) bytes
assert((pa - pb) == 1);
print_out(pa); // possibly outputs 0x4
print_out(pb); // possibly outputs 0x0 (if NULL is actually bit-wise 0x0)
</code></pre>
<p><sub>(Note that incrementing a pointer that contains a null pointer value strictly is undefined behavior. We used NULL because we were only interested in the value of the pointer. Normally, only use increment/decrement when pointing to elements of an array).</sub></p>
<p>The following shows two important concepts</p>
<ul>
<li>addition/subtraction of a integer to a pointer means move the pointer forward / backward by N elements. So if an int is 4 bytes big, pa could contain 0x4 on our platform after having incremented by 1.</li>
<li>subtraction of a pointer by another pointer means getting their distance, measured by elements. So subtracting pb from pa will yield 1, since they have one element distance. </li>
</ul>
<p>On a practical example. Suppose you write a function and people provide you with an start and end pointer (very common thing in C++):</p>
<pre><code>void mutate_them(int *begin, int *end) {
// get the amount of elements
ptrdiff_t n = end - begin;
// allocate space for n elements to do something...
// then iterate. increment begin until it hits end
while(begin != end) {
// do something
begin++;
}
}
</code></pre>
<p><code>ptrdiff_t</code> is what is the type of (end - begin). It may be a synonym for "int" for some compiler, but may be another type for another one. One cannot know, so one chooses the generic typedef <code>ptrdiff_t</code>. </p> |
346,721 | LINQ for Java tool | <p>Would a LINQ for java be a useful tool? I have been working on a tool that will allow a Java object to map to a row in a database. </p>
<ol>
<li>Would this be useful for Java
programmers? </li>
<li>What features would be
useful?</li>
</ol> | 346,735 | 8 | 2 | null | 2008-12-06 20:23:58.08 UTC | 13 | 2019-08-19 20:19:17.093 UTC | 2010-05-31 09:33:46.96 UTC | Milhous | 63,550 | Milhous | 17,712 | null | 1 | 40 | java|sql|mysql|linq | 21,191 | <p>LINQ for Java would be lovely, but the problem is the language integration.</p>
<p>Java doesn't have anything as concise as lambda expressions, and they're one of the bedrocks of LINQ. I suppose they <em>could</em> layer the query expression support on top of normal Java without lambda expressions, by making the expansion create anonymous inner classes - but it would be pretty hideous. You'd also need expression trees if you wanted to do anything like LINQ to SQL.</p>
<p>Checked exceptions <em>might</em> get in the way, but we'd have to see. The equivalent of IQueryable would need to have some sort of general checked exception - or possibly it could be generic in both the element type and the exception type...</p>
<p>Anyway, this is all pie-in-the-sky - given the troubles the Java community is having with closures, I think it would be folly to expect anything like LINQ in Java itself earlier than about 2012. Of course, that's not to say it wouldn't be possible in a "Java-like" language. Groovy has certain useful aspects already, for instance.</p>
<p>For the library side, Hibernate already provides a "non-integrated" version of a lot of the features of LINQ to SQL. For LINQ to Objects, you should look at the <a href="http://code.google.com/p/google-collections/" rel="noreferrer">Google Java Collections API</a> - it's a lot of the same kind of thing (filtering, projecting etc). Without lambdas it's a lot fiddlier to use, of course - but it's still really, really handy. (I use the Google Collections code all the time at work, and I'd hate to go back to the "vanilla" Java collections.)</p> |
630,306 | iPhone REST client | <p>Does anybody know is there any good library for iPhone SDK to call REST web service. I want to have something simple like <a href="http://github.com/adamwiggins/rest-client/tree/master" rel="noreferrer">Heroku rest client</a></p>
<hr>
<p>Thx everybody for help.</p>
<p>My server side is on Rails so looks like ObjectiveResource feet best of my needs.</p> | 633,570 | 9 | 0 | null | 2009-03-10 14:00:22.54 UTC | 22 | 2012-07-17 12:04:22.777 UTC | 2012-07-17 12:04:22.777 UTC | null | 50,776 | Aler | 76,146 | null | 1 | 22 | iphone|web-services|rest | 45,679 | <p>In case your REST service is implemented in Ruby on Rails, the open source ObjectiveResource project is looking very promising. It has been working great for me in a relatively complex project of mine, and I've even contributed some code back to them.</p>
<p><a href="http://iphoneonrails.com/" rel="nofollow noreferrer">ObjectiveResource</a></p> |
287,097 | Inventory database design | <p>This is a question not really about "programming" (is not specific to any language or database), but more of design and architecture. It's also a question of the type "What the best way to do X". I hope does no cause to much "religious" controversy.</p>
<p>In the past I have developed systems that in one way or another, keep some form of inventory of items (not relevant what items). Some using languages/DB's that do not support transactions. In those cases I opted not to save item <em>quantity on hand</em> in a field in the item record. Instead the <em>quantity on hand</em> is calculated totaling inventory received - total of inventory sold. This has resulted in almost no discrepancies in inventory because of software. The tables are properly indexed and the performance is good. There is a archiving process in case the amount of record start to affect performance.</p>
<p>Now, few years ago I started working in this company, and I inherited a system that tracks inventory. But the quantity is saved in a field. When an entry is registered, the quantity received is added to the quantity field for the item. When an item is sold, the quantity is subtracted. This has resulted in discrepancies. In my opinion this is not the right approach, but the previous programmers here swear by it.</p>
<p>I would like to know if there is a consensus on what's the right way is to design such system. Also what resources are available, printed or online, to seek guidance on this.</p>
<p>Thanks</p> | 287,119 | 12 | 1 | null | 2008-11-13 14:38:52.14 UTC | 55 | 2016-07-01 05:58:24.667 UTC | 2013-05-30 06:37:43.777 UTC | Rob | 474,597 | nmarmol | 20,448 | null | 1 | 79 | database|inventory | 50,168 | <p>I have seen both approaches at my current company and would definitely lean towards the first (calculating totals based on stock transactions).</p>
<p>If you are only storing a total quantity in a field somewhere, you have no idea how you arrived at that number. There is no transactional history and you can end up with problems.</p>
<p>The last system I wrote tracks stock by storing each transaction as a record with a positive or negative quantity. I have found it works very well.</p> |
575,196 | Why can a function modify some arguments as perceived by the caller, but not others? | <p>I'm trying to understand Python's approach to variable scope. In this example, why is <code>f()</code> able to alter the value of <code>x</code>, as perceived within <code>main()</code>, but not the value of <code>n</code>?</p>
<pre><code>def f(n, x):
n = 2
x.append(4)
print('In f():', n, x)
def main():
n = 1
x = [0,1,2,3]
print('Before:', n, x)
f(n, x)
print('After: ', n, x)
main()
</code></pre>
<p>Output:</p>
<pre><code>Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3, 4]
</code></pre> | 575,337 | 13 | 2 | null | 2009-02-22 16:42:51.457 UTC | 119 | 2022-09-14 15:09:28.65 UTC | 2018-09-25 17:17:06.713 UTC | J.F. Sebastian | 1,222,951 | Monty Hindman | 55,857 | null | 1 | 242 | python | 213,294 | <p>Some answers contain the word "copy" in the context of a function call. I find it confusing.</p>
<p><strong>Python doesn't copy <em>objects</em> you pass during a function call <em>ever</em>.</strong></p>
<p>Function parameters are <em>names</em>. When you call a function, Python binds these parameters to whatever objects you pass (via names in a caller scope).</p>
<p>Objects can be mutable (like lists) or immutable (like integers and strings in Python). A mutable object you can change. You can't change a name, you just can bind it to another object.</p>
<p>Your example is not about <a href="https://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces" rel="nofollow noreferrer">scopes or namespaces</a>, it is about <a href="http://docs.python.org/reference/executionmodel.html#naming-and-binding" rel="nofollow noreferrer">naming and binding</a> and <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types" rel="nofollow noreferrer">mutability of an object</a> in Python.</p>
<pre><code>def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
n = 2 # put `n` label on `2` balloon
x.append(4) # call `append` method of whatever object `x` is referring to.
print('In f():', n, x)
x = [] # put `x` label on `[]` ballon
# x = [] has no effect on the original list that is passed into the function
</code></pre>
<p>Here are nice pictures on <a href="https://web.archive.org/web/20180121150727/http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables" rel="nofollow noreferrer">the difference between variables in other languages and names in Python</a>.</p> |
420,791 | What is a good use case for static import of methods? | <p>Just got a review comment that my static import of the method was not a good idea. The static import was of a method from a DA class, which has mostly static methods. So in middle of the business logic I had a da activity that apparently seemed to belong to the current class:</p>
<pre><code>import static some.package.DA.*;
class BusinessObject {
void someMethod() {
....
save(this);
}
}
</code></pre>
<p>The reviewer was not keen that I change the code and I didn't but I do kind of agree with him. One reason given for not static-importing was it was confusing where the method was defined, it wasn't in the current class and not in any superclass so it too some time to identify its definition (the web based review system does not have clickable links like IDE :-) I don't really think this matters, static-imports are still quite new and soon we will all get used to locating them.</p>
<p>But the other reason, the one I agree with, is that an unqualified method call seems to belong to current object and should not jump contexts. But if it really did belong, it would make sense to extend that super class.</p>
<p>So, when <em>does</em> it make sense to static import methods? When have you done it? Did/do you like the way the unqualified calls look?</p>
<p>EDIT: The popular opinion seems to be that static-import methods if nobody is going to confuse them as methods of the current class. For example methods from java.lang.Math and java.awt.Color. But if abs and getAlpha are not ambiguous I don't see why readEmployee is. As in lot of programming choices, I think this too is a personal preference thing.</p> | 421,127 | 16 | 2 | null | 2009-01-07 15:46:02.387 UTC | 50 | 2021-07-29 07:21:00.49 UTC | 2021-07-29 07:21:00.49 UTC | Hemal Pandya | 2,049,986 | Hemal Pandya | 18,573 | null | 1 | 154 | java|static-import | 106,226 | <p>This is from Sun's guide when they released the feature (emphasis in original):</p>
<blockquote>
<p>So when should you use static import? <strong>Very sparingly!</strong> Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). ... If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually.</p>
</blockquote>
<p>(<a href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html</a>)</p>
<p>There are two parts I want to call out specifically:</p>
<ul>
<li>Use static imports <strong>only</strong> when you were tempted to "abuse inheritance". In this case, would you have been tempted to have BusinessObject <code>extend some.package.DA</code>? If so, static imports may be a cleaner way of handling this. If you never would have dreamed of extending <code>some.package.DA</code>, then this is probably a poor use of static imports. Don't use it just to save a few characters when typing.</li>
<li><strong>Import individual members.</strong> Say <code>import static some.package.DA.save</code> instead of <code>DA.*</code>. That will make it much easier to find where this imported method is coming from. </li>
</ul>
<p>Personally, I have used this language feature <em>very</em> rarely, and almost always only with constants or enums, never with methods. The trade-off, for me, is almost never worth it.</p> |
991,489 | file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true | <p>I'm trying to delete a file, after writing something in it, with <code>FileOutputStream</code>. This is the code I use for writing:</p>
<pre><code>private void writeContent(File file, String fileContent) {
FileOutputStream to;
try {
to = new FileOutputStream(file);
to.write(fileContent.getBytes());
to.flush();
to.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
</code></pre>
<p>As it is seen, I flush and close the stream, but when I try to delete, <code>file.delete()</code> returns false.</p>
<p>I checked before deletion to see if the file exists, and: <code>file.exists()</code>, <code>file.canRead()</code>, <code>file.canWrite()</code>, <code>file.canExecute()</code> all return true. Just after calling these methods I try <code>file.delete()</code> and returns false.</p>
<p>Is there anything I've done wrong?</p> | 991,573 | 17 | 11 | null | 2009-06-13 20:51:15.397 UTC | 34 | 2019-02-20 02:15:01.68 UTC | 2017-07-14 09:44:00.163 UTC | null | 360,899 | null | 118,485 | null | 1 | 91 | java|file|fileoutputstream | 182,930 | <p>It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used <code>BufferedReader</code>. After reading, I closed the buffer.</p>
<p>Meanwhile I switched and now I'm reading the content using <code>FileInputStream</code>. Also after finishing reading I close the stream. And now it's working.</p>
<p>The problem is I don't have the explanation for this. </p>
<p>I don't know <code>BufferedReader</code> and <code>FileOutputStream</code> to be incompatible.</p> |
388,490 | How to use unicode characters in Windows command line? | <p>We have a project in Team Foundation Server (TFS) that has a non-English character (š) in it. When trying to script a few build-related things we've stumbled upon a problem - we can't pass the <strong>š</strong> letter to the command-line tools. The command prompt or what not else messes it up, and the <strong>tf.exe</strong> utility can't find the specified project.</p>
<p>I've tried different formats for the .bat file (ANSI, UTF-8 with and without <a href="http://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">BOM</a>) as well as scripting it in JavaScript (which is Unicode inherently) - but no luck. How do I execute a program and pass it a <strong>Unicode</strong> command line?</p> | 47,843,552 | 19 | 5 | null | 2008-12-23 09:30:59.323 UTC | 183 | 2022-06-06 07:35:22.97 UTC | 2017-12-22 09:06:01.853 UTC | null | 960,875 | Vilx- | 41,360 | null | 1 | 346 | unicode|command-line|input|windows-console | 520,436 | <p>My background: I use Unicode input/output in a console for years (and do it a lot daily. Moreover, I develop support tools for exactly this task). There are very few problems, as far as you understand the following facts/limitations:</p>
<ul>
<li><code>CMD</code> and “console” are unrelated factors. <code>CMD.exe</code> is a just one of programs which are ready to “work inside” a console (“console applications”).</li>
<li>AFAIK, <code>CMD</code> has perfect support for Unicode; you can enter/output all Unicode chars when <em>any</em> codepage is active. </li>
<li>Windows’ console has A LOT of support for Unicode — but it is not perfect (just “good enough”; see below).</li>
<li><code>chcp 65001</code> is very dangerous. Unless a program was specially designed to work around defects in the Windows’ API (or uses a C runtime library which has these workarounds), it would not work reliably. <a href="https://stackoverflow.com/a/39745938/9106292">Win8 fixes ½ of these problems with <code>cp65001</code>, but the rest is still applicable to Win10</a>.</li>
<li>I work in <code>cp1252</code>. As I already said: <strong>To input/output Unicode in a console, one does not need to set the codepage</strong>.</li>
</ul>
<h1>The details</h1>
<ul>
<li>To read/write Unicode to a console, an application (or its C runtime library) should be smart enough to use not <code>File-I/O</code> API, but <code>Console-I/O</code> API. (For an example, see <a href="https://www.python.org/dev/peps/pep-0528/" rel="noreferrer">how Python does it</a>.)</li>
<li>Likewise, to read Unicode command-line arguments, an application (or its C runtime library) should be smart enough to use the corresponding API.</li>
<li>Console font rendering supports only Unicode characters in BMP (in other words: below <code>U+10000</code>). Only simple text rendering is supported (so European — and some East Asian — languages should work fine — as far as one uses precomposed forms). [There is a <a href="https://stackoverflow.com/a/47852866/9106292">minor fine print</a> here for East Asian and for characters U+0000, U+0001, U+30FB.]</li>
</ul>
<h1>Practical considerations</h1>
<ul>
<li><p>The <strong>defaults</strong> on Window are not very helpful. For best experience, one should tune up 3 pieces of configuration:</p>
<ul>
<li>For output: a comprehensive console font. For best results, I recommend <a href="http://ilyaz.org/software/fonts/" rel="noreferrer">my builds</a>. (The installation instructions are present there — and also listed in other answers on this page.)</li>
<li>For input: a capable keyboard layout. For best results, I recommend <a href="http://k.ilyaz.org/" rel="noreferrer">my layouts</a>.</li>
<li>For input: <a href="https://www.google.com/search?num=100&hl=en&pws=0&q=enable-hex-unicode-entry+windows+registry" rel="noreferrer">allow HEX input of Unicode</a>.</li>
</ul></li>
<li><p>One more gotcha with “Pasting” into a console application (very technical):</p>
<ul>
<li>HEX input delivers a character on <code>KeyUp</code> of <code>Alt</code>; <em>all</em> the other ways to deliver a character happen on <code>KeyDown</code>; so many applications are not ready to see a character on <code>KeyUp</code>. (Only applicable to applications using <code>Console-I/O</code> API.)</li>
<li>Conclusion: many application would not react on HEX input events.</li>
<li>Moreover, what happens with a “Pasted” character depends on the current keyboard layout: if the character can be typed without using prefix keys (but with arbitrary complicated combination of modifiers, as in <code>Ctrl-Alt-AltGr-Kana-Shift-Gray*</code>) then it is delivered on an emulated keypress. This is what any application expects — so pasting anything which contains only such characters is fine.</li>
<li>However, the “other” characters are delivered by <strong>emulating HEX input</strong>.</li>
</ul>
<p><strong><em>Conclusion</em></strong>: unless your keyboard layout supports input of A LOT of characters without prefix keys, <em>some buggy applications</em> may skip characters when you <code>Paste</code> via Console’s UI: <code>Alt-Space E P</code>. (<strong>This</strong> is why I recommend using my keyboard layouts!)</p></li>
</ul>
<p>One should also keep in mind that the “alternative, ‘more capable’ consoles” for Windows <strong>are not consoles at all</strong>. They do not support <code>Console-I/O</code> APIs, so the programs which rely on these APIs to work would not function. (The programs which use only “File-I/O APIs to the console filehandles” would work fine, though.) </p>
<p>One example of such non-console is a part of MicroSoft’s <code>Powershell</code>. I do not use it; to experiment, press and release <code>WinKey</code>, then type <code>powershell</code>.</p>
<hr>
<p>(On the other hand, there are programs such as <a href="https://en.wikipedia.org/wiki/ConEmu" rel="noreferrer"><code>ConEmu</code></a> or <a href="http://adoxa.altervista.org/ansicon/" rel="noreferrer"><code>ANSICON</code></a> which try to do more: they “attempt” to intercept <code>Console-I/O</code> APIs to make “true console applications” work too. This definitely works for toy example programs; in real life, this may or may not solve your particular problems. Experiment.)</p>
<h1>Summary</h1>
<ul>
<li><p>set font, keyboard layout (and optionally, allow HEX input).</p></li>
<li><p>use only programs which go through <code>Console-I/O</code> APIs, and accept Unicode command-line arguments. For example, any <code>cygwin</code>-compiled program should be fine. As I already said, <code>CMD</code> is fine too.</p></li>
</ul>
<p><strong>UPD:</strong> Initially, for a bug in <code>cp65001</code>, I was mixing up Kernel and CRTL layers (<strong>UPD²:</strong> and Windows user-mode API!). <em>Also:</em> Win8 fixes one half of this bug; I clarified the section about “better console” application, and added a reference to how Python does it.</p> |
36,901 | What does ** (double star/asterisk) and * (star/asterisk) do for parameters? | <p>What do <code>*args</code> and <code>**kwargs</code> mean?</p>
<pre><code>def foo(x, y, *args):
def bar(x, y, **kwargs):
</code></pre> | 36,908 | 24 | 6 | null | 2008-08-31 15:04:35.35 UTC | 1,264 | 2022-07-30 19:05:07.813 UTC | 2022-04-01 01:47:59.543 UTC | null | 365,102 | Todd Tingen | 2,572 | null | 1 | 3,111 | python|syntax|parameter-passing|variadic-functions|argument-unpacking | 1,140,986 | <p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href="http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions" rel="noreferrer">more on defining functions</a> in the Python documentation.</p>
<p>The <code>*args</code> will give you all function parameters <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="noreferrer">as a tuple</a>:</p>
<pre><code>def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
</code></pre>
<p>The <code>**kwargs</code> will give you all
<strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p>
<pre><code>def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
</code></pre>
<p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p>
<pre><code>def foo(kind, *args, **kwargs):
pass
</code></pre>
<p>It is also possible to use this the other way around:</p>
<pre><code>def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
</code></pre>
<p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p>
<pre><code>def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
</code></pre>
<p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href="http://www.python.org/dev/peps/pep-3132/" rel="noreferrer">Extended Iterable Unpacking</a>), though it gives a list instead of a tuple in this context:</p>
<pre><code>first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
</code></pre>
<p>Also Python 3 adds new semantic (refer <a href="https://www.python.org/dev/peps/pep-3102/" rel="noreferrer">PEP 3102</a>):</p>
<pre><code>def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
</code></pre>
<p>For example the following works in python 3 but not python 2:</p>
<pre><code>>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}
</code></pre>
<p>Such function accepts only 3 positional arguments, and everything after <code>*</code> can only be passed as keyword arguments.</p>
<h3>Note:</h3>
<ul>
<li>A Python <code>dict</code>, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.</li>
<li>"The order of elements in <code>**kwargs</code> now corresponds to the order in which keyword arguments were passed to the function." - <a href="https://docs.python.org/3/whatsnew/3.6.html" rel="noreferrer">What’s New In Python 3.6</a></li>
<li>In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.</li>
</ul> |
373,449 | What Simple Changes Made the Biggest Improvements to Your Delphi Programs | <p>I have a Delphi 2009 program that handles a lot of data and needs to be as fast as possible and not use too much memory.</p>
<p>What <strong>small simple</strong> changes have you made to your Delphi code that had the biggest impact on the performance of your program by noticeably reducing execution time or memory use?</p>
<hr>
<p>Thanks everyone for all your answers. Many great tips.</p>
<p>For completeness, I'll post a few important articles on Delphi optimization that I found.</p>
<p><a href="http://delphi.about.com/od/objectpascalide/a/beforeoptimize.htm" rel="noreferrer">Before you start optimizing Delphi code</a> at About.com</p>
<p><a href="http://delphi.about.com/od/objectpascalide/a/speedsize.htm" rel="noreferrer">Speed and Size: Top 10 Tricks</a> also at About.com</p>
<p><a href="http://effovex.com/OptimalCode/basics.htm" rel="noreferrer">Code Optimization Fundamentals</a> and <a href="http://effovex.com/OptimalCode/opguide.htm" rel="noreferrer">Delphi Optimization Guidelines</a> at High Performance Delphi, relating to Delphi 7 but still very pertinent.</p> | 1,198,694 | 35 | 6 | 2009-04-21 16:10:07.32 UTC | 2008-12-17 02:00:47.867 UTC | 32 | 2015-11-29 17:46:29.19 UTC | 2013-09-05 01:28:57.157 UTC | lkessler | 30,176 | lkessler | 30,176 | null | 1 | 28 | performance|delphi|memory | 8,722 | <p>The biggest improvement came when I started using AsyncCalls to convert single-threaded applications that used to freeze up the UI, into (sort of) multi-threaded apps.</p>
<p>Although AsyncCalls can do a lot more, I've found it useful for this very simple purpose. Let's say you have a subroutine blocked like this: Disable Button, Do Work, Enable Button.
You move the 'Do Work' part to a local function (call it AsyncDoWork), and add four lines of code: </p>
<pre><code>var a: IAsyncCall;
a := LocalAsyncCall(@AsyncDoWork);
while (NOT a.Finished) do
application.ProcessMessages;
a.Sync;
</code></pre>
<p>What this does for you is run AsyncDoWork in a separate thread, while your main thread remains available to respond to the UI (like dragging the window or clicking Abort.) When AsyncDoWork is finished the code continues. Because I moved it to a local function, all local vars are available, an the code does not need to be changed.</p>
<p>This is a very limited type of 'multi-threading'. Specifically, it's dual threading. You must ensure that your Async function and the UI do not both access the same VCL components or data structures. (I disable all controls except the stop button.)</p>
<p>I don't use this to write new programs. It's just a really quick & easy way to make old programs more responsive. </p> |
6,589,814 | What is the difference between dict and collections.defaultdict? | <p>I was checking out Peter Norvig's <a href="http://norvig.com/spell-correct.html">code</a> on how to write simple spell checkers. At the beginning, he uses this code to insert words into a dictionary.</p>
<pre><code>def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
</code></pre>
<p>What is the difference between a Python dict and the one that was used here? In addition, what is the <code>lambda</code> for? I checked the API documentation <a href="http://docs.python.org/library/collections.html#collections.defaultdict">here</a> and it says that defaultdict is actually derived from dict but how does one decide which one to use?</p> | 6,589,839 | 4 | 4 | null | 2011-07-05 23:02:10.503 UTC | 12 | 2021-12-30 18:49:31.81 UTC | null | null | null | null | 184,046 | null | 1 | 55 | python|dictionary | 34,440 | <p>The difference is that a <code>defaultdict</code> will "default" a value if that key has not been set yet. If you didn't use a <code>defaultdict</code> you'd have to check to see if that key exists, and if it doesn't, set it to what you want.</p>
<p>The lambda is defining a factory for the default value. That function gets called whenever it needs a default value. You could hypothetically have a more complicated default function.</p>
<pre><code>Help on class defaultdict in module collections:
class defaultdict(__builtin__.dict)
| defaultdict(default_factory) --> dict with default factory
|
| The default factory is called without arguments to produce
| a new value when a key is not present, in __getitem__ only.
| A defaultdict compares equal to a dict with the same items.
|
</code></pre>
<p>(from <code>help(type(collections.defaultdict()))</code>)</p>
<p><code>{}.setdefault</code> is similar in nature, but takes in a value instead of a factory function. It's used to set the value if it doesn't already exist... which is a bit different, though.</p> |
6,501,234 | GAE: best practices for storing secret keys? | <p>Are there any non-terrible ways of storing secret keys for Google App Engine? Or, at least, less terrible than checking them into source control?</p> | 6,513,473 | 6 | 1 | null | 2011-06-28 03:26:56.36 UTC | 10 | 2020-05-02 15:30:34.44 UTC | 2011-06-28 05:20:29.993 UTC | null | 71,522 | null | 71,522 | null | 1 | 39 | security|google-app-engine | 12,548 | <p>Not exactly an answer:</p>
<ul>
<li>If you keep keys in the model, anyone who can deploy can read the keys from the model, and deploy again to cover their tracks. While Google lets you download code (unless you disable this feature), I think it only keeps the latest copy of each numbered version.</li>
<li>If you keep keys in a not-checked-in config file and disable code downloads, then only people with the keys can successfully deploy, but nobody can read the keys without sneaking a backdoor into the deployment (potentially not that difficult).</li>
</ul>
<p>At the end of the day, anyone who can deploy can get at the keys, so the question is whether you think the risk is minimized by storing keys in the datastore (which you might make backups of, for example) or on deployer's machines.</p>
<p>A viable alternative might be to combine the two: Store encrypted API keys in the datastore and put the master key in a config file. This has some potentially nice features:</p>
<ul>
<li>Attackers need both access to a copy of the datastore and a copy of the config file (and presumably developers don't make backups of the datastore on a laptop and lose it on the train).</li>
<li>By specifying two keys in the config file, you can do key-rollover (so attackers need a datastore/config of similar age).</li>
<li>With asymmetric crypto, you can make it possible for developers to add an API key to the datastore without needing to read the others.</li>
</ul>
<p>Of course, then you're uploading crypto to Google's servers, which may or may not count as "exporting" crypto with the usual legal issues (e.g. what if Google sets up an Asia-Pacific data centre?).</p> |
6,431,026 | Generating JPA2 Metamodel from a Gradle build script | <p>I'm trying to set up a Gradle build script for a new project. That project will use JPA 2 along with <a href="http://www.querydsl.com/" rel="noreferrer">Querydsl</a>.</p>
<p>On the <a href="http://source.mysema.com/static/querydsl/2.1.2/reference/html/ch02s02.html" rel="noreferrer">following page of Querydsl's reference documentation</a>, they explain how to set up their JPAAnnotationProcessor (apt) for Maven and Ant.</p>
<p>I would like to do the same with Gradle, but I don't know how and my beloved friend did not help me much on this one. I need to find a way to invoke Javac (preferably without any additional dependencies) with arguments to be able to specify the processor that apt should use (?)</p> | 6,447,481 | 7 | 0 | null | 2011-06-21 19:39:08.043 UTC | 12 | 2016-04-20 15:11:20.97 UTC | null | null | null | null | 226,630 | null | 1 | 21 | gradle|apt|querydsl | 14,766 | <p>I did not test it but this should work:</p>
<pre><code>repositories {
mavenCentral()
}
apply plugin: 'java'
dependencies {
compile(group: 'com.mysema.querydsl', name: 'querydsl-apt', version: '1.8.4')
compile(group: 'com.mysema.querydsl', name: 'querydsl-jpa', version: '1.8.4')
compile(group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.6.1')
}
compileJava {
doFirst {
Map otherArgs = [
includeAntRuntime: false,
destdir: destinationDir,
classpath: configurations.compile.asPath,
sourcepath: '',
target: targetCompatibility,
source: sourceCompatibility
]
options.compilerArgs = [
'-processor', 'com.mysema.query.apt.jpa.JPAAnnotationProcessor',
'-s', "${destinationDir.absolutePath}".toString()
]
Map antOptions = otherArgs + options.optionMap()
ant.javac(antOptions) {
source.addToAntBuilder(ant, 'src', FileCollection.AntType.MatchingTask)
options.compilerArgs.each {value ->
compilerarg(value: value)
}
}
}
}
</code></pre>
<p>Hope it helps.</p> |
6,921,105 | Given a filesystem path, is there a shorter way to extract the filename without its extension? | <p>I program in WPF C#. I have e.g. the following path:</p>
<pre><code>C:\Program Files\hello.txt
</code></pre>
<p>and I want to extract <strong><code>hello</code></strong> from it. </p>
<p>The path is a <code>string</code> retrieved from a database. Currently I'm using the following code to split the path by <code>'\'</code> and then split again by <code>'.'</code>:</p>
<pre class="lang-cs prettyprint-override"><code>string path = "C:\\Program Files\\hello.txt";
string[] pathArr = path.Split('\\');
string[] fileArr = pathArr.Last().Split('.');
string fileName = fileArr.Last().ToString();
</code></pre>
<p>It works, but I believe there should be shorter and smarter solution to that. Any idea?</p> | 6,921,127 | 10 | 1 | null | 2011-08-03 02:45:05.387 UTC | 41 | 2021-03-15 13:12:02.823 UTC | 2020-02-04 20:12:58.597 UTC | null | 150,605 | null | 529,310 | null | 1 | 293 | c#|path|filenames|file-extension|path-manipulation | 443,733 | <p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename" rel="noreferrer"><code>Path.GetFileName</code></a></p>
<blockquote>
<p>Returns the file name and extension of a file path that is represented
by a read-only character span.</p>
</blockquote>
<hr />
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension" rel="noreferrer"><code>Path.GetFileNameWithoutExtension</code></a></p>
<blockquote>
<p>Returns the file name without the extension of a file path that is
represented by a read-only character span.</p>
</blockquote>
<hr />
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path" rel="noreferrer"><code>Path</code></a> class is wonderful.</p> |
6,565,471 | How can I exclude directories from grep -R? | <p>I want to traverse all subdirectories, except the "node_modules" directory.</p> | 6,565,519 | 14 | 3 | null | 2011-07-03 20:48:43.077 UTC | 156 | 2021-07-02 17:11:22.107 UTC | null | null | null | null | 179,736 | null | 1 | 980 | linux|unix|grep | 612,114 | <p><strong>SOLUTION 1 (combine <code>find</code> and <code>grep</code>)</strong></p>
<p>The purpose of this solution is not to deal with <code>grep</code> performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.</p>
<p>Use <strong><code>find</code></strong>, for excluding directories foo and bar :</p>
<pre><code>find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
</code></pre>
<p>Then combine <strong><code>find</code></strong> and the non-recursive use of <strong><code>grep</code></strong>, as a portable solution :</p>
<pre><code>find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
</code></pre>
<p><strong>SOLUTION 2 (using the <code>--exclude-dir</code> option of <code>grep</code>):</strong></p>
<p>You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.</p>
<pre><code>grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
</code></pre>
<p>To exclude multiple directories, use <code>--exclude-dir</code> as:</p>
<p><code>--exclude-dir={node_modules,dir1,dir2,dir3}</code></p>
<p><strong>SOLUTION 3 (Ag)</strong></p>
<p>If you frequently search through code, <a href="https://github.com/ggreer/the_silver_searcher" rel="noreferrer">Ag (The Silver Searcher)</a> is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in <code>.gitignore</code>, so you don't have to keep passing the same cumbersome exclude options to <code>grep</code> or <code>find</code>.</p> |
38,113,994 | Why does indexing numpy arrays with brackets and commas differ in behavior? | <p>I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,</p>
<pre><code>>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[1][1]
4 # expected behavior
>>> x[1,1]
4 # expected behavior
>>> x[:][1]
array([3, 4]) # huh?
>>> x[:,1]
array([2, 4, 6]) # expected behavior
</code></pre> | 38,114,048 | 3 | 2 | null | 2016-06-30 04:27:53.54 UTC | 18 | 2019-11-22 06:42:32.563 UTC | null | null | null | null | 3,765,905 | null | 1 | 31 | python|numpy|indexing|slice | 9,314 | <p>This:</p>
<pre><code>x[:, 1]
</code></pre>
<p>means "take all indices of <code>x</code> along the first axis, but only index 1 along the second".</p>
<p>This:</p>
<pre><code>x[:][1]
</code></pre>
<p>means "take all indices of <code>x</code> along the first axis (so all of <code>x</code>), then take index 1 along the <strong>first</strong> axis of the result". You're applying the <code>1</code> to the wrong axis.</p>
<p><code>x[1][2]</code> and <code>x[1, 2]</code> are only equivalent because indexing an array with an integer shifts all remaining axes towards the front of the shape, so the first axis of <code>x[1]</code> is the second axis of <code>x</code>. This doesn't generalize at all; you should almost always use commas instead of multiple indexing steps.</p> |
45,670,823 | How to deal with PyCharm's "Expected type X, got Y instead" | <p>When using PyCharm, Pycharm's code style inspection gives me the warning <code>Expected type 'Union[ndarray, Iterable]', got 'float' instead</code> in the editor if I write <code>np.array(0.0)</code>. When I write <code>np.array([0.0])</code> I get no warning.</p>
<p>When coding</p>
<pre><code>from scipy.special import expit
expit(0.0)
</code></pre>
<p>I get <code>Expected type 'ndarray', got 'float' instead</code>, while </p>
<pre><code>expit(np.array([0.0]))
</code></pre>
<p>solves that.</p>
<p>What I think Pycharm's code style inspection wants to tell me is there's a possibility of a type error, but I am not sure how I should react to that in the sense of good programming. Is PyCharm right to scold me and should I use the long versions or should I keep my short versions for readability and speed of coding?</p>
<p>If I should not change my code to the long versions - can I get rid of the Pycharm's code style inspection warning, or is that a bad idea, because they may be correct in other cases, and I am not able to tune the warnings that specifically?</p> | 45,671,046 | 4 | 3 | null | 2017-08-14 08:55:46.41 UTC | 0 | 2022-06-29 22:45:08.34 UTC | 2019-12-04 11:41:37.803 UTC | null | 12,479,481 | null | 4,533,188 | null | 1 | 23 | python|numpy|pycharm | 51,030 | <p>PyCharm determines from the type-hints of the source code that the arguments you pass are incorrect.</p>
<hr />
<h3>How to disable</h3>
<p>Your question simplifies to one of figuring out how to disable this type checking. However, please be warned,</p>
<blockquote>
<p>Switching off the inspection completely is not a good solution. Most
of the time PyCharm gets it right and this provides useful feedback.
If it's getting it wrong, it's best to raise a ticket with them to see
if it can be fixed.</p>
</blockquote>
<p>You can do that like this:</p>
<ol>
<li><p>Go to <code>Settings/Preferences</code></p>
</li>
<li><p>On the sidebar, click <code>Inspections</code> (under the Editor category)</p>
</li>
<li><p>Expand the <code>Python</code> tab</p>
</li>
<li><p>Scroll down to <code>Type Checker</code> and uncheck it</p>
</li>
</ol>
<p>PyCharm should now stop issuing warnings about incorrect function arguments.</p> |
15,938,866 | Alternative to Breeze.js? | <p>Is there an alternative to Breezejs that does not require .Net or Enterprise Framework Connector or database, and works with plain REST services that accept and return only JSON (no metadata)? </p> | 15,939,442 | 4 | 0 | null | 2013-04-11 00:30:30.263 UTC | 9 | 2015-06-30 05:56:39.267 UTC | 2015-06-09 02:23:40.127 UTC | null | 1,200,803 | null | 433,433 | null | 1 | 32 | breeze | 24,094 | <p>We actually designed Breeze to be independent of .NET, but none of our samples show this yet. In the next week or two we will show how to connect Breeze to a generic HTTP service that returns JSON. We'd love to have your feedback on this when it comes out, as we know it will be a big part of the market.</p>
<p><strong>Edit:</strong> Breeze 1.3.0 is now available and contains the <a href="http://www.breezejs.com/samples/edmunds" rel="noreferrer">Edmunds sample</a>, which is a pure JavaScript client that connects to an HTTP service with <strong>no</strong> dependencies on ASP.NET, Web API, or the Entity Framework. Please take a look and provide us with feedback!</p>
<p><strong>Edit 2:</strong> We will also be releasing a sample soon that shows Breeze working with MongoDB, Express, and Node.js with no Microsoft technologies involved. A Ruby sample is also in the works. Stay tuned!</p>
<p><strong>Edit 3:</strong> <a href="http://www.breezejs.com/documentation/mongodb" rel="noreferrer">MongoDB and node.js support</a> is now available which shows Breeze working with the MEAN stack (MongoDB, Express, AngularJS, Node.js).</p>
<p><strong>Edit 4:</strong> A <a href="http://www.breezejs.com/samples/intro-spa-ruby" rel="noreferrer">Ruby sample</a> is now up. This is John Papa's famous Code Camper JumpStart with a Ruby back-end.</p>
<p><strong>Edit 5:</strong> <a href="http://www.breezejs.com/documentation/nhibernate-support" rel="noreferrer">NHibernate support</a> as well as an accompanying sample are now available.</p>
<p><strong>Edit 6:</strong> <a href="http://www.getbreezenow.com/sequelize-mysqlpostgressql-lite" rel="noreferrer">Node/MySQL/Postgres support</a> as well as an accompanying sample are now available.</p>
<p><strong>Edit 7:</strong> <a href="https://github.com/Breeze/breeze.server.java" rel="noreferrer">Java/Hibernate support</a> as well as an accompanying sample are now available.</p> |
15,684,605 | Python For loop get index | <p>I am writing a simple Python for loop to prnt the current character in a string. However, I could not get the index of the character. Here is what I have, does anyone know a good way to get the current index of the character in the loop?</p>
<pre><code> loopme = 'THIS IS A VERY LONG STRING WITH MANY MANY WORDS!'
for w in loopme:
print "CURRENT WORD IS " + w + " AT CHARACTER "
</code></pre> | 15,684,617 | 2 | 1 | null | 2013-03-28 14:34:45.467 UTC | 12 | 2013-03-28 15:14:43.707 UTC | null | null | null | null | 1,817,081 | null | 1 | 60 | python|loops|for-loop|indexing | 122,961 | <p>Use the <a href="http://docs.python.org/2/library/functions.html#enumerate" rel="noreferrer"><code>enumerate()</code> function</a> to generate the index along with the elements of the sequence you are looping over:</p>
<pre><code>for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
</code></pre> |
15,899,615 | What's the difference between CSS3's :root pseudo class and html? | <p>I can't seem to find much information about this.</p>
<p><a href="http://coding.smashingmagazine.com/2011/03/30/how-to-use-css3-pseudo-classes/" rel="noreferrer">Smashing Magazine</a> seems to be saying that <code>html</code> and <code>:root</code> are the same thing but surely there must be a tiny difference?</p> | 15,899,650 | 4 | 0 | null | 2013-04-09 10:34:53.543 UTC | 10 | 2022-05-15 14:45:50.233 UTC | 2019-05-22 19:51:18.953 UTC | null | 9,591,441 | null | 914,543 | null | 1 | 80 | css|css-selectors|pseudo-class | 20,050 | <p>From the <a href="http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:root" rel="noreferrer">W3C wiki</a>:</p>
<blockquote>
<p>The <code>:root</code> pseudo-class represents an element that is the root of the document. In HTML, this is always the HTML element. </p>
</blockquote>
<p>CSS is a general purpose styling language. It can be used with other document types, not only with HTML, it can be used with SVG for example.</p>
<p>From the <a href="http://www.w3.org/TR/CSS21/" rel="noreferrer">specification</a> (emphasis mine):</p>
<blockquote>
<p>This specification defines Cascading Style Sheets, level 2 revision 1 (CSS 2.1). CSS 2.1 is a style sheet language that allows authors and users to attach style (e.g., fonts and spacing) to <strong>structured documents (e.g., HTML documents and XML applications)</strong>.</p>
</blockquote> |
10,488,112 | How do I put graphics on a JPanel? | <p>I am having a problem adding graphics to a JPanel. If I change the line from panel.add(new graphics()); to frame.add(new graphics()); and do not add the JPanel to the JFrame, the black rectangle appears on the JFrame. I just cannot get the black rectangle to appear on the JPannel and was wondering if someone could help me with this.</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Catch{
public class graphics extends JComponent{
public void paintComponent(Graphics g){
super.paintComponents(g);
g.fillRect(200, 62, 30, 10);
}
}
public void createGUI(){
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(500,500);
frame.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint().getX());
System.out.println(e.getPoint().getY());
}
});
panel.add(new graphics());
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args){
Catch GUI= new Catch();
GUI.createGUI();
}
}
</code></pre> | 10,488,592 | 2 | 4 | null | 2012-05-07 19:44:28.567 UTC | 1 | 2014-04-25 04:02:22.06 UTC | 2012-05-07 21:56:37.803 UTC | null | 418,556 | null | 1,344,742 | null | 1 | 6 | java|swing|graphics|jframe|jpanel | 41,435 | <p>The custom component was 0x0 px.</p>
<pre><code>import java.awt.*;
import javax.swing.*;
public class Catch {
public class MyGraphics extends JComponent {
private static final long serialVersionUID = 1L;
MyGraphics() {
setPreferredSize(new Dimension(500, 100));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(200, 62, 30, 10);
}
}
public void createGUI() {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(new MyGraphics());
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Catch GUI = new Catch();
GUI.createGUI();
}
});
}
}
</code></pre> |
10,294,284 | Remove all special characters from a string in R? | <p>How to remove all special characters from string in R and replace them with spaces ?</p>
<p>Some special characters to remove are : <code>~!@#$%^&*(){}_+:"<>?,./;'[]-=</code></p>
<p>I've tried <code>regex</code> with <code>[:punct:]</code> pattern but it removes only punctuation marks.</p>
<p>Question 2 : And how to remove characters from foreign languages like : <code>â í ü Â á ą ę ś ć</code> ?</p>
<p>Answer : Use <code>[^[:alnum:]]</code> to remove<code>~!@#$%^&*(){}_+:"<>?,./;'[]-=</code> and use <code>[^a-zA-Z0-9]</code> to remove also <code>â í ü Â á ą ę ś ć</code> in <code>regex</code> or <code>regexpr</code> functions.</p>
<p><strong>Solution in base R :</strong></p>
<pre><code>x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-="
gsub("[[:punct:]]", "", x) # no libraries needed
</code></pre> | 10,294,818 | 3 | 4 | null | 2012-04-24 08:24:48.693 UTC | 56 | 2021-02-17 08:23:46.707 UTC | 2021-02-17 08:23:46.707 UTC | null | 783,421 | null | 783,421 | null | 1 | 158 | regex|string|r|character | 295,497 | <p>You need to use <a href="http://www.regular-expressions.info/quickstart.html">regular expressions</a> to identify the unwanted characters. For the most easily readable code, you want the <a href="https://www.rdocumentation.org/packages/stringr/topics/str_replace_all"><code>str_replace_all</code></a> from the <a href="https://cran.r-project.org/web/packages/stringr/index.html"><code>stringr</code></a> package, though <a href="https://www.rdocumentation.org/packages/base/topics/grep"><code>gsub</code></a> from base R works just as well.</p>
<p>The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.</p>
<pre><code>x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
</code></pre>
<p>(The base R equivalent is <code>gsub("[[:punct:]]", " ", x)</code>.)</p>
<p>An alternative is to swap out all non-alphanumeric characters.</p>
<pre><code>str_replace_all(x, "[^[:alnum:]]", " ")
</code></pre>
<p>Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.</p> |
10,567,709 | JavaScript get child element | <p>Why this does not work in firefox i try to select the category and then make subcategory visible.</p>
<pre><code><script type="text/javascript">
function show_sub(cat) {
var cat = document.getElementById("cat");
var sub = cat.getElementsByName("sub");
sub[0].style.display='inline';
}
</script>
</code></pre>
<p>-</p>
<pre><code><ul>
<li id="cat" onclick="show_sub(this)">
Top 1
<ul style="display:none" name="sub">
<li>Sub 1</li>
<li>Sub 2</li>
<li>Sub 3</li>
</ul>
</li>
<li>Top 2</li>
<li>Top 3</li>
<li>Top 4</li>
</ul>
</code></pre>
<p>EDIT Answer is: </p>
<pre><code><script type="text/javascript">
function show_sub(cat) {
cat.getElementsByTagName("ul")[0].style.display = (cat.getElementsByTagName("ul")[0].style.display == "none") ? "inline" : "none";
}
</script>
</code></pre> | 10,568,010 | 3 | 6 | null | 2012-05-12 22:00:49.84 UTC | 11 | 2012-05-13 01:26:31.423 UTC | 2012-05-13 01:26:31.423 UTC | null | 1,085,162 | null | 1,085,162 | null | 1 | 37 | javascript|html | 169,058 | <p>ULs don't have a name attribute, but you can reference the ul by tag name.</p>
<p>Try replacing line 3 in your script with this:</p>
<pre><code>var sub = cat.getElementsByTagName("UL");
</code></pre> |
32,079,364 | How can you make the Docker container use the host machine's '/etc/hosts' file? | <p>I want to make it so that the Docker container I spin up use the same <code>/etc/hosts</code> settings as on the host machine I run from. Is there a way to do this?</p>
<p>I know there is an <a href="https://docs.docker.com/reference/run/#managing-etc-hosts" rel="noreferrer"><code>--add-host</code></a> option with <code>docker run</code>, but that's not exactly what I want because the host machine's <code>/etc/hosts</code> file may be different on different machines, so it's not great for me to hardcode exact IP addresses/hosts with <code>--add-host</code>.</p> | 32,491,150 | 11 | 2 | null | 2015-08-18 17:51:27.91 UTC | 17 | 2022-03-11 12:28:07.48 UTC | 2020-09-03 17:26:03.91 UTC | null | 63,550 | null | 3,006,145 | null | 1 | 84 | docker | 115,957 | <p>Use <code>--network=host</code> in the <code>docker run</code> command. This tells Docker to make the container use the host's network stack. You can learn more <a href="https://docs.docker.com/engine/userguide/networking/" rel="noreferrer">here</a>.</p> |
31,949,355 | What "Clustered Index Scan (Clustered)" means on SQL Server execution plan? | <p>I have a query that fails to execute with "Could not allocate a new page for database 'TEMPDB' because of insufficient disk space in filegroup 'DEFAULT'". </p>
<p>On the way of trouble shooting I am examining the execution plan. There are two costly steps labeled "Clustered Index Scan (Clustered)". I have a hard time find out what this means? </p>
<p>I would appreciate any explanations to "Clustered Index Scan (Clustered)" or suggestions on where to find the related document?</p> | 31,961,357 | 5 | 3 | null | 2015-08-11 18:28:37.327 UTC | 9 | 2020-06-30 04:01:59.96 UTC | 2015-08-11 18:42:12.45 UTC | null | 3,089,523 | null | 3,089,523 | null | 1 | 40 | sql|sql-server|sql-execution-plan | 47,260 | <blockquote>
<p>I would appreciate any explanations to "Clustered Index Scan
(Clustered)"</p>
</blockquote>
<p>I will try to put in the easiest manner, for better understanding you need to understand both index seek and scan.</p>
<p>SO lets build the table </p>
<pre><code>use tempdb GO
create table scanseek (id int , name varchar(50) default ('some random names') )
create clustered index IX_ID_scanseek on scanseek(ID)
declare @i int
SET @i = 0
while (@i <5000)
begin
insert into scanseek
select @i, 'Name' + convert( varchar(5) ,@i)
set @i =@i+1
END
</code></pre>
<p>An index seek is where SQL server uses the <a href="https://en.wikipedia.org/wiki/B-tree" rel="noreferrer">b-tree</a> structure of the index to seek directly to matching records</p>
<p><a href="https://i.stack.imgur.com/FZSny.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FZSny.jpg" alt="enter image description here"></a></p>
<p>you can check your table root and leaf nodes using the DMV below</p>
<pre><code>-- check index level
SELECT
index_level
,record_count
,page_count
,avg_record_size_in_bytes
FROM sys.dm_db_index_physical_stats(DB_ID('tempdb'),OBJECT_ID('scanseek'),NULL,NULL,'DETAILED')
GO
</code></pre>
<p>Now here we have clustered index on column "ID"</p>
<p>lets look for some direct matching records </p>
<pre><code>select * from scanseek where id =340
</code></pre>
<p>and look at the Execution plan</p>
<p><a href="https://i.stack.imgur.com/nqJ5o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nqJ5o.png" alt="enter image description here"></a></p>
<p>you've requested rows directly in the query that's why you got a clustered index SEEK .</p>
<p><strong>Clustered index scan:</strong> When Sql server reads through for the Row(s) from top to bottom in the clustered index.
for example searching data in non key column. In our table NAME is non key column so if we will search some data in the name column we will see <code>clustered index scan</code> because all the rows are in clustered index leaf level.</p>
<p>Example </p>
<pre><code>select * from scanseek where name = 'Name340'
</code></pre>
<p><a href="https://i.stack.imgur.com/pnH7x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pnH7x.png" alt="enter image description here"></a></p>
<p>please note: I made this answer short for better understanding only, if you have any question or suggestion please comment below.</p> |
40,123,319 | Easy way to Encrypt/Decrypt string in Android | <p>My question is how to encrypt a <strong>String</strong>:</p>
<pre><code>String AndroidId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_movie_activity);
cancel = (Button)findViewById(R.id.img_cancle);
linear= (LinearLayout)findViewById(R.id.progress);
linear.setVisibility(View.GONE);
String encrypted = "MzIyNTE2" + "OTQNzM4NTQ=";
Log.e("Encrypt", encrypted);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
AndroidId = wInfo.getMacAddress();
AndroidId=encrypted;
</code></pre>
<p>How do i encrypt my AndroidId in which I storing a MAC address.</p> | 40,175,319 | 5 | 7 | null | 2016-10-19 05:57:46.137 UTC | 25 | 2021-10-09 13:50:09.417 UTC | 2019-06-04 11:09:42.117 UTC | null | 6,879,903 | null | 6,879,903 | null | 1 | 30 | android|encryption | 103,259 | <p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html" rel="noreferrer"><code>Cipher</code></a> for this.</p>
<p>This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.</p>
<p><strong>Sample of encryption and decryption:</strong></p>
<pre><code>public static SecretKey generateKey()
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return secret = new SecretKeySpec(password.getBytes(), "AES");
}
public static byte[] encryptMsg(String message, SecretKey secret)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Encrypt the message. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
return cipherText;
}
public static String decryptMsg(byte[] cipherText, SecretKey secret)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
{
/* Decrypt the message, given derived encContentValues and initialization vector. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
return decryptString;
}
</code></pre>
<p><strong>To encrypt:</strong></p>
<pre><code>SecretKey secret = generateKey();
EncUtil.encryptMsg(String toEncrypt, secret))
</code></pre>
<p><strong>To decrypt:</strong></p>
<pre><code>EncUtil.decryptMsg(byte[] toDecrypt, secret))
</code></pre> |
13,268,698 | Concatenate numerical values in a string | <p>I would like to store this output in a string:</p>
<pre><code>> x=1:5
> cat("hi",x)
hi 1 2 3 4 5
</code></pre>
<p>So I use <code>paste</code>, but I obtain this different result:</p>
<pre><code>> paste("hi",x)
[1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5"
</code></pre>
<p>Any idea how to obtain the string:</p>
<pre><code>"hi 1 2 3 4 5"
</code></pre>
<p>Thank you very much!</p> | 13,268,755 | 3 | 0 | null | 2012-11-07 11:20:26.193 UTC | 4 | 2016-11-09 11:12:20.437 UTC | null | null | null | null | 1,263,739 | null | 1 | 39 | string|r|concatenation|paste|cat | 96,630 | <p>You can force coercion to character for <code>x</code> by concatenating the string <code>"hi"</code> on to <code>x</code>. Then just use <code>paste()</code> with the <code>collapse</code> argument. As in</p>
<pre><code>x <- 1:5
paste(c("hi", x), collapse = " ")
> paste(c("hi", x), collapse = " ")
[1] "hi 1 2 3 4 5"
</code></pre> |
13,399,836 | Can there exist two main methods in a Java program? | <p>Can two main methods exist in a Java program?</p>
<p>Only by the difference in their arguments like:</p>
<pre><code>public static void main(String[] args)
</code></pre>
<p>and second can be</p>
<pre><code>public static void main(StringSecond[] args)
</code></pre>
<p>If it is possible, which Method will be used as the entry point? How to identify this?</p> | 13,399,868 | 16 | 1 | null | 2012-11-15 14:43:40 UTC | 15 | 2021-04-18 01:37:03.34 UTC | 2021-03-09 12:46:49.2 UTC | null | 11,270,766 | null | 1,820,722 | null | 1 | 39 | java|methods|arguments|program-entry-point | 133,363 | <p>As long as method parameters (number (or) type) are different, yes they can. It is called <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html">overloading</a>.</p>
<blockquote>
<p>Overloaded methods are differentiated by the number and the type of the arguments passed into the method</p>
</blockquote>
<pre><code>public static void main(String[] args)
</code></pre>
<p>only main method with single <code>String[]</code> (or) <code>String...</code> as param will be considered as entry point for the program.</p> |
13,756,178 | Writings functions (procedures) for data.table objects | <p>In the book <em>Software for Data Analysis: Programming with R</em>, John Chambers emphasizes that functions should generally not be written for their side effect; rather, that a function should return a value without modifying any variables in its calling environment. Conversely, writing good script using data.table objects should specifically avoid the use of object assignment with <code><-</code>, typically used to store the result of a function.</p>
<p>First, is a technical question. Imagine an R function called <code>proc1</code> that accepts a <code>data.table</code> object <code>x</code> as its argument (in addition to, maybe, other parameters). <code>proc1</code> returns NULL but modifies <code>x</code> using <code>:=</code>. From what I understand, <code>proc1</code> calling <code>proc1(x=x1)</code> makes a copy of <code>x1</code> just because of the way that promises work. However, as demonstrated below, the original object <code>x1</code> is still modified by <code>proc1</code>. Why/how is this? </p>
<pre><code>> require(data.table)
> x1 <- CJ(1:2, 2:3)
> x1
V1 V2
1: 1 2
2: 1 3
3: 2 2
4: 2 3
> proc1 <- function(x){
+ x[,y:= V1*V2]
+ NULL
+ }
> proc1(x1)
NULL
> x1
V1 V2 y
1: 1 2 2
2: 1 3 3
3: 2 2 4
4: 2 3 6
>
</code></pre>
<p>Furthermore, it seems that using <code>proc1(x=x1)</code> isn't any slower than doing the procedure directly on x, indicating that my vague understanding of promises are wrong and that they work in a pass-by-reference sort of way:</p>
<pre><code>> x1 <- CJ(1:2000, 1:500)
> x1[, paste0("V",3:300) := rnorm(1:nrow(x1))]
> proc1 <- function(x){
+ x[,y:= V1*V2]
+ NULL
+ }
> system.time(proc1(x1))
user system elapsed
0.00 0.02 0.02
> x1 <- CJ(1:2000, 1:500)
> system.time(x1[,y:= V1*V2])
user system elapsed
0.03 0.00 0.03
</code></pre>
<p>So, given that passing a data.table argument to a function doesn't add time, that makes it possible to write procedures for data.table objects, incorporating both the speed of data.table and the generalizability of a function. However, given what John Chambers said, that functions should not have side-effects, is it really "ok" to write this type of procedural programming in R? Why was he arguing that side effects are "bad"? If I'm going to ignore his advice, what sort of pitfalls should I be aware of? What can I do to write "good" data.table procedures?</p> | 13,756,636 | 2 | 6 | null | 2012-12-07 02:43:11.617 UTC | 19 | 2012-12-07 14:18:06.937 UTC | 2012-12-07 11:33:02.537 UTC | null | 1,174,421 | null | 1,174,421 | null | 1 | 42 | r|data.table | 7,803 | <p>Yes, the addition, modification, deletion of columns in <code>data.table</code>s is done by <code>reference</code>. In a sense, it is a <em>good</em> thing because a <code>data.table</code> usually holds a lot of data, and it would be very memory and time consuming to reassign it all every time a change to it is made. On the other hand, it is a <em>bad</em> thing because it goes against the <code>no-side-effect</code> functional programming approach that R tries to promote by using <code>pass-by-value</code> by default. With no-side-effect programming, there is little to worry about when you call a function: you can rest assured that your inputs or your environment won't be affected, and you can just focus on the function's output. It's simple, hence comfortable.</p>
<p>Of course it is ok to disregard John Chambers's advice if you know what you are doing. About writing "good" data.tables procedures, here are a couple rules I would consider if I were you, as a way to limit complexity and the number of side-effects:</p>
<ul>
<li>a function should not modify more than one table, i.e., modifying that table should be the only side-effect,</li>
<li>if a function modifies a table, then make that table the output of the function. Of course, you won't want to re-assign it: just run <code>do.something.to(table)</code> and not <code>table <- do.something.to(table)</code>. If instead the function had another ("real") output, then when calling <code>result <- do.something.to(table)</code>, it is easy to imagine how you may focus your attention on the output and forget that calling the function had a side effect on your table.</li>
</ul>
<p>While "one output / no-side-effect" functions are the norm in R, the above rules allow for "one output or side-effect". If you agree that a side-effect is somehow a form of output, then you'll agree I am not bending the rules too much by loosely sticking to R's one-output functional programming style. Allowing functions to have multiple side-effects would be a little more of a stretch; not that you can't do it, but I would try to avoid it if possible.</p> |
13,423,494 | Why is overriding method parameters a violation of strict standards in PHP? | <p>I know there are a couple of similar questions here in StackOverflow like <a href="https://stackoverflow.com/questions/13220489/method-overriding-and-strict-standards">this question</a>.</p>
<p>Why is overriding method parameters a violation of strict standards in PHP?
For instance:</p>
<pre><code>class Foo
{
public function bar(Array $bar){}
}
class Baz extends Foo
{
public function bar($bar) {}
}
</code></pre>
<blockquote>
<p>Strict standards: Declaration of Baz::bar() should be compatible with
that of Foo::bar()</p>
</blockquote>
<p>In other OOP programming languages you can. Why is it bad in PHP?</p> | 13,423,625 | 4 | 0 | null | 2012-11-16 19:55:09.14 UTC | 15 | 2013-10-15 06:42:53.25 UTC | 2017-05-23 12:17:39.08 UTC | null | -1 | null | 516,316 | null | 1 | 43 | php|oop | 25,883 | <p>In OOP, <a href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" rel="noreferrer">SOLID</a> stands for <strong>Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion</strong>.</p>
<p><a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov substitution</a> principle states that, in a computer program, if <strong>Bar</strong> is a subtype of <em>Foo</em>, then objects of type <em>Foo</em> may be replaced with objects of type <strong>Bar</strong> without altering any of the desirable properties of that program (correctness, task performed, etc.).</p>
<p>In strong-typed programming languages, when overriding a Foo method, if you change the signature in Bar, you are actually <em>overloading</em> since the original method and the new method are available with different signatures. Since PHP is weak typed, this is not possible to achieve, because the compiler can't know which of the methods you are actually calling. (hence the reason you can't have 2 methods with the same name, even if their signatures are different).</p>
<p>So, to avoid the violation of Liskov Substituition principle, a strict standard warning is issued, telling the programmer something might break due to the change of the method signature in the child class.</p> |
13,603,882 | Feature Selection and Reduction for Text Classification | <p>I am currently working on a project, a <strong>simple sentiment analyzer</strong> such that there will be <strong>2 and 3 classes</strong> in <strong>separate cases</strong>. I am using a <strong>corpus</strong> that is pretty <strong>rich</strong> in the means of <strong>unique words</strong> (around 200.000). I used <strong>bag-of-words</strong> method for <strong>feature selection</strong> and to reduce the number of <strong>unique features</strong>, an elimination is done due to a <strong>threshold value</strong> of <strong>frequency of occurrence</strong>. The <strong>final set of features</strong> includes around 20.000 features, which is actually a <strong>90% decrease</strong>, but <strong>not enough</strong> for intended <strong>accuracy</strong> of test-prediction. I am using <strong>LibSVM</strong> and <strong>SVM-light</strong> in turn for training and prediction (both <strong>linear</strong> and <strong>RBF kernel</strong>) and also <strong>Python</strong> and <strong>Bash</strong> in general.</p>
<p>The <strong>highest accuracy</strong> observed so far <strong>is around 75%</strong> and I <strong>need at least 90%</strong>. This is the case for <strong>binary classification</strong>. For <strong>multi-class training</strong>, the accuracy falls to <strong>~60%</strong>. I <strong>need at least 90%</strong> at both cases and can not figure how to increase it: via <strong>optimizing training parameters</strong> or <strong>via optimizing feature selection</strong>?</p>
<p>I have read articles about <strong>feature selection</strong> in text classification and what I found is that three different methods are used, which have actually a clear correlation among each other. These methods are as follows:</p>
<ul>
<li>Frequency approach of <strong>bag-of-words</strong> (BOW)</li>
<li><strong>Information Gain</strong> (IG)</li>
<li><strong>X^2 Statistic</strong> (CHI)</li>
</ul>
<p>The first method is already the one I use, but I use it very simply and need guidance for a better use of it in order to obtain high enough accuracy. I am also lacking knowledge about practical implementations of <strong>IG</strong> and <strong>CHI</strong> and looking for any help to guide me in that way.</p>
<p>Thanks a lot, and if you need any additional info for help, just let me know.</p>
<hr>
<ul>
<li><p>@larsmans: <strong>Frequency Threshold</strong>: I am looking for the occurrences of unique words in examples, such that if a word is occurring in different examples frequently enough, it is included in the feature set as a unique feature. </p></li>
<li><p>@TheManWithNoName: First of all thanks for your effort in explaining the general concerns of document classification. I examined and experimented all the methods you bring forward and others. I found <strong>Proportional Difference</strong> (PD) method the best for feature selection, where features are uni-grams and <strong>Term Presence</strong> (TP) for the weighting (I didn't understand why you tagged <strong>Term-Frequency-Inverse-Document-Frequency</strong> (TF-IDF) as an indexing method, I rather consider it as a <strong>feature weighting</strong> approach). <strong>Pre-processing</strong> is also an important aspect for this task as you mentioned. I used certain types of string elimination for refining the data as well as <strong>morphological parsing</strong> and <strong>stemming</strong>. Also note that I am working on <strong>Turkish</strong>, which has <strong>different characteristics</strong> compared to English. Finally, I managed to reach <strong>~88% accuracy</strong> (f-measure) for <strong>binary</strong> classification and <strong>~84%</strong> for <strong>multi-class</strong>. These values are solid proofs of the success of the model I used. This is what I have done so far. Now working on clustering and reduction models, have tried <strong>LDA</strong> and <strong>LSI</strong> and moving on to <strong>moVMF</strong> and maybe <strong>spherical models</strong> (LDA + moVMF), which seems to work better on corpus those have objective nature, like news corpus. If you have any information and guidance on these issues, I will appreciate. I need info especially to setup an interface (python oriented, open-source) between <strong>feature space dimension reduction</strong> methods (LDA, LSI, moVMF etc.) and <strong>clustering methods</strong> (k-means, hierarchical etc.).</p></li>
</ul> | 15,461,587 | 5 | 3 | null | 2012-11-28 11:21:59.53 UTC | 50 | 2021-08-22 07:47:42.093 UTC | 2020-05-28 03:47:32.723 UTC | null | 4,566,277 | null | 1,839,494 | null | 1 | 53 | python|nlp|svm|sentiment-analysis|feature-extraction | 31,251 | <p>This is probably a bit late to the table, but...</p>
<p>As Bee points out and you are already aware, the use of SVM as a classifier is wasted if you have already lost the information in the stages prior to classification. However, the process of text classification requires much more that just a couple of stages and each stage has significant effects on the result. Therefore, before looking into more complicated feature selection measures there are a number of much simpler possibilities that will typically require much lower resource consumption.</p>
<p>Do you pre-process the documents before performing tokensiation/representation into the bag-of-words format? Simply removing stop words or punctuation may improve accuracy considerably.</p>
<p>Have you considered altering your bag-of-words representation to use, for example, word pairs or n-grams instead? You may find that you have more dimensions to begin with but that they condense down a lot further and contain more useful information.</p>
<p>Its also worth noting that dimension reduction <strong>is</strong> feature selection/feature extraction. The difference is that feature selection reduces the dimensions in a univariate manner, i.e. it removes terms on an individual basis as they currently appear without altering them, whereas feature extraction (which I think Ben Allison is referring to) is multivaritate, combining one or more single terms together to produce higher orthangonal terms that (hopefully) contain more information and reduce the feature space.</p>
<p>Regarding your use of document frequency, are you merely using the probability/percentage of documents that contain a term or are you using the term densities found within the documents? If category one has only 10 douments and they each contain a term once, then category one is indeed associated with the document. However, if category two has only 10 documents that each contain the same term a hundred times each, then obviously category two has a much higher relation to that term than category one. If term densities are not taken into account this information is lost and the fewer categories you have the more impact this loss with have. On a similar note, it is not always prudent to only retain terms that have high frequencies, as they may not actually be providing any useful information. For example if a term appears a hundred times in every document, then it is considered a noise term and, while it looks important, there is no practical value in keeping it in your feature set.</p>
<p>Also how do you index the data, are you using the Vector Space Model with simple boolean indexing or a more complicated measure such as TF-IDF? Considering the low number of categories in your scenario a more complex measure will be beneficial as they can account for term importance for each category in relation to its importance throughout the entire dataset.</p>
<p>Personally I would experiment with some of the above possibilities first and then consider tweaking the feature selection/extraction with a (or a combination of) complex equations if you need an additional performance boost.</p>
<hr>
<p><strong>Additional</strong></p>
<p>Based on the new information, it sounds as though you are on the right track and 84%+ accuracy (F1 or BEP - precision and recall based for multi-class problems) is generally considered very good for most datasets. It might be that you have successfully acquired all information rich features from the data already, or that a few are still being pruned.</p>
<p>Having said that, something that can be used as a predictor of how good aggressive dimension reduction may be for a particular dataset is 'Outlier Count' analysis, which uses the decline of Information Gain in outlying features to determine how likely it is that information will be lost during feature selection. You can use it on the raw and/or processed data to give an estimate of how aggressively you should aim to prune features (or unprune them as the case may be). A paper describing it can be found here:</p>
<p><a href="http://www.cs.technion.ac.il/~gabr/papers/fs-svm.pdf" rel="noreferrer" title="Text Categorization with Many Redundant Features: Using Aggressive Feature Selection to Make SVMs Competitive with C4.5">Paper with Outlier Count information</a></p>
<p>With regards to describing TF-IDF as an indexing method, you are correct in it being a feature weighting measure, but I consider it to be used mostly as part of the indexing process (though it can also be used for dimension reduction). The reasoning for this is that some measures are better aimed toward feature selection/extraction, while others are preferable for feature weighting specifically in your document vectors (i.e. the indexed data). This is generally due to dimension reduction measures being determined on a per category basis, whereas index weighting measures tend to be more document orientated to give superior vector representation.</p>
<p>In respect to LDA, LSI and moVMF, I'm afraid I have too little experience of them to provide any guidance. Unfortunately I've also not worked with Turkish datasets or the python language. </p> |
13,600,319 | Run one command after another, even if I suspend the first one (Ctrl-z) | <p>I know in bash I can run one command after another by separating them by semicolons, like</p>
<pre><code>$ command1; command2
</code></pre>
<p>Or if I only want <code>command2</code> to run only if <code>command1</code> succeeds, using <code>&&</code>:</p>
<pre><code>$ command1 && command2
</code></pre>
<p>This works, but if I suspend <code>command1</code> using <code>Ctrl-z</code>, in the first case, it runs <code>command2</code> immediately, and in the second case, it doesn't run it at all. How can I run commands in sequence, but still be able to suspend the first command, but not have the second run until I have restarted it (with <code>fg</code>) and it finishes? I'd prefer something as simple to type as possible, as I would like to do this interactively. Or maybe I just need to set an option somewhere.</p>
<p>By the way, what is the proper term for what <code>Ctrl-z</code> does?</p> | 13,600,474 | 2 | 4 | null | 2012-11-28 07:53:57.17 UTC | 28 | 2018-05-01 19:16:45.063 UTC | 2018-05-01 19:16:45.063 UTC | null | 6,862,601 | null | 161,801 | null | 1 | 70 | bash|shell|command|signals|suspend | 70,544 | <p>The following should do it:</p>
<pre><code>(command1; command2)
</code></pre>
<p>Note the added parentheses.</p> |
13,688,158 | When to use <p> vs. <br> | <p>What's the verdict on when you should use another <code><p>...</p></code> instead of a <code><br /></code> tag? What's are the best practices for this kind of thing?</p>
<p>I looked around for this question, but most of the writing seems a bit old, so I'm not sure whether opinions about this topic have evolved since.</p>
<p>EDIT: to clarify the question, here is the situation that I am dealing with. Would you use <code><br></code>'s or <code><p></code>'s for the following content (imagine it's contained in a div on a homepage):</p>
<hr>
<p>Welcome to the home page.</p>
<p>Check out our stuff.</p>
<p>You really should.</p>
<hr>
<p>Now, these lines are not technically 'paragraphs'. So would you mark this up by surrounding the whole block in a <code><p></code> tag with <code><br></code>'s in between, or instead use separate <code><p></code>'s for each line?</p> | 13,688,203 | 6 | 0 | null | 2012-12-03 17:03:58.62 UTC | 9 | 2019-01-14 15:28:29.127 UTC | 2012-12-03 20:36:11.297 UTC | null | 1,311,267 | null | 1,311,267 | null | 1 | 74 | html | 107,917 | <p>They serve two different functions.</p>
<p><code><p></code> (paragraph) is a block element which is used to hold text. <code><br /></code> is used to force a line break within the <code><p></code> element.</p>
<p><strong>Example</strong></p>
<pre><code><p>Suspendisse sodales odio in felis sagittis hendrerit. Donec tempus laoreet
est bibendum sollicitudin. Etiam tristique convallis<br />rutrum. Phasellus
id mi neque. Vivamus gravida aliquam condimentum.</p>
</code></pre>
<p><strong>Result</strong></p>
<p>Suspendisse sodales odio in felis sagittis hendrerit. Donec tempus laoreet
est bibendum sollicitudin. Etiam tristique convallis<br />rutrum. Phasellus
id mi neque. Vivamus gravida aliquam condimentum.</p>
<p><strong>Update</strong></p>
<p>Based on the new requirements, I would personally use <code><p></code> to achieve the spacing as well as allow for styling. If in the future you wish to style one of these parts, it will be much easier to do so at the block level.</p>
<pre><code><p>Welcome to the home page.</p>
<p style="border: 1px solid #00ff00;">Check out our stuff.</p>
<p>You really should.</p>
</code></pre> |
20,439,788 | How to stop apache permanently on mac Mavericks? | <p>I'm trying to install zend server on mac and need to uninstall the apache server that is auto included with Mavericks so that the Apache server included with Zend is used instead. Can it be prevented from running on startup or permanently removed?</p> | 20,439,859 | 4 | 2 | null | 2013-12-07 09:30:54.603 UTC | 28 | 2018-05-02 09:22:26.64 UTC | 2014-09-16 18:31:17.693 UTC | null | 364,066 | null | 1,914,652 | null | 1 | 45 | macos|apache|osx-mavericks | 61,068 | <p>Try this:</p>
<pre><code>sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist
</code></pre>
<p>This will stop a running instance of Apache, and record that it should not be restarted. It records your preference in <code>/private/var/db/launchd.db/com.apple.launchd/overrides.plist</code>.</p> |
20,770,562 | how to get javascript return value to php variable? | <p>I have created a javascript for check the text boxes are empty. if one of text box is empty the return false. so how can i get that return value to a PHP variable ?</p> | 20,770,651 | 3 | 3 | null | 2013-12-25 08:11:59.06 UTC | 1 | 2013-12-25 08:28:35.177 UTC | 2013-12-25 08:14:41.03 UTC | null | 2,919,798 | null | 3,133,944 | null | 1 | 2 | javascript|php|html | 58,929 | <p>For linking javascript with php need to use AJAX <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">http://api.jquery.com/jQuery.ajax/</a></p>
<pre><code>$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
</code></pre> |
24,347,029 | Python NLTK: Bigrams trigrams fourgrams | <p>I have this example and i want to know how to get this result. I have text and I tokenize it then I collect the bigram and trigram and fourgram like that </p>
<pre><code>import nltk
from nltk import word_tokenize
from nltk.util import ngrams
text = "Hi How are you? i am fine and you"
token=nltk.word_tokenize(text)
bigrams=ngrams(token,2)
</code></pre>
<p>bigrams: <code>[('Hi', 'How'), ('How', 'are'), ('are', 'you'), ('you', '?'), ('?', 'i'), ('i', 'am'), ('am', 'fine'), ('fine', 'and'), ('and', 'you')]</code></p>
<pre><code>trigrams=ngrams(token,3)
</code></pre>
<p>trigrams: <code>[('Hi', 'How', 'are'), ('How', 'are', 'you'), ('are', 'you', '?'), ('you', '?', 'i'), ('?', 'i', 'am'), ('i', 'am', 'fine'), ('am', 'fine', 'and'), ('fine', 'and', 'you')]</code></p>
<pre><code>bigram [(a,b) (b,c) (c,d)]
trigram [(a,b,c) (b,c,d) (c,d,f)]
i want the new trigram should be [(c,d,f)]
which mean
newtrigram = [('are', 'you', '?'),('?', 'i','am'),...etc
</code></pre>
<p>any idea will be helpful </p> | 24,347,217 | 4 | 3 | null | 2014-06-22 00:16:28.31 UTC | 9 | 2019-07-17 07:03:51.79 UTC | 2015-11-17 07:02:30.397 UTC | null | 1,090,562 | null | 3,731,150 | null | 1 | 22 | python|nltk|n-gram | 55,582 | <p>If you apply some set theory (if I'm interpreting your question correctly), you'll see that the trigrams you want are simply elements [2:5], [4:7], [6:8], etc. of the <code>token</code> list.</p>
<p>You could generate them like this:</p>
<pre><code>>>> new_trigrams = []
>>> c = 2
>>> while c < len(token) - 2:
... new_trigrams.append((token[c], token[c+1], token[c+2]))
... c += 2
>>> print new_trigrams
[('are', 'you', '?'), ('?', 'i', 'am'), ('am', 'fine', 'and')]
</code></pre> |
24,111,813 | How can I animate a react.js component onclick and detect the end of the animation | <p>I want to have a react component flip over when a user clicks on the DOM element. I see some documentation about their animation mixin but it looks to be set up for "enter" and "leave" events. What is the best way to do this in response to some user input and be notified when the animation starts and completes? Currently I have a list item and I want it to flip over an show a few buttons like delete, edit, save. Perhaps I missed something in the docs.</p>
<p>animation mixin</p>
<p><a href="http://facebook.github.io/react/docs/animation.html">http://facebook.github.io/react/docs/animation.html</a></p> | 34,700,273 | 8 | 3 | null | 2014-06-08 23:08:02.667 UTC | 10 | 2021-12-12 01:19:26.907 UTC | null | null | null | null | 83,080 | null | 1 | 49 | javascript|reactjs | 84,702 | <p>Upon clicks you can update the state, add a class and record the <code>animationend</code> event.</p>
<pre><code>class ClickMe extends React.Component {
constructor(props) {
super(props)
this.state = { fade: false }
}
render() {
const fade = this.state.fade
return (
<button
ref='button'
onClick={() => this.setState({ fade: true })}
onAnimationEnd={() => this.setState({ fade: false })}
className={fade ? 'fade' : ''}>
Click me!
</button>
)
}
}
</code></pre>
<p>See the plnkr: <a href="https://next.plnkr.co/edit/gbt0W4SQhnZILlmQ?open=Hello.js&deferRun=1&preview" rel="noreferrer">https://next.plnkr.co/edit/gbt0W4SQhnZILlmQ?open=Hello.js&deferRun=1&preview</a></p>
<p><em>Edit</em>: Updated to reflect current React, which supports animationend events.</p> |
3,571,179 | How does X11 clipboard handle multiple data formats? | <p>It probably happened to you as well - sometimes when you copy a text from some web page into your rich-text e-mail draft in your favorite webmail client, you dislike the fact that the pasted <strong>piece</strong> has a different font/size/weight.. it somehow remembers the style (often images, when selected). How is it than that if you paste the same into your favorite text editor like Vim, there's no HTML, just the plain text?</p>
<p><img src="https://i.stack.imgur.com/QLdYA.png" alt="alt text"></p>
<p>It seems that clipboard maintains the selected data in various formats. How can one access data in any one of those formats (programmatically or with some utility)? How does the X11 clipboard work?</p> | 3,571,949 | 2 | 1 | null | 2010-08-26 00:08:15.54 UTC | 13 | 2019-11-19 07:38:39.697 UTC | 2010-09-08 07:05:11.433 UTC | null | 300,863 | null | 234,248 | null | 1 | 43 | text|clipboard|x11|xorg | 5,295 | <p>The app you copy from advertises formats (mostly identified by MIME types) it can provide. The app you paste into has to pick its preferred format and request that one from the source app.</p>
<p>The reason you may not see all style info transferred is that the apps don't both support a common format that includes the style info.</p>
<p>You can also see issues because an app may for example try to paste HTML, but not really be able to handle all HTML. Or the apps may be buggy, or may not agree on what a particular MIME type really means.</p>
<p>Almost all apps can both copy and paste plain text, of course, but beyond that it's touch and go. If you don't get what seems to make sense, you could file a bug vs. one of the apps.</p>
<p>You may notice that if you exit the app you're copying from, you can no longer paste. (Unless you're running a "clipboard manager" or something.) This is because no data actually leaves the source app until the destination app asks for a format to paste.
There are "clipboard managers" that ask for data immediately anytime you copy and store that data, so you can paste after the source app exits, but they have downsides (what if the data is huge, or is offered in 10 formats, etc.)</p>
<p>The following python code will show available formats for the currently-copied data, if you have pygtk installed. This app shows the ctrl+c copied data, not the middle-click easter egg. (See <a href="http://freedesktop.org/wiki/Specifications/ClipboardsWiki" rel="noreferrer">http://freedesktop.org/wiki/Specifications/ClipboardsWiki</a>)</p>
<pre><code>#!/usr/bin/python
import gtk;
clipboard = gtk.clipboard_get()
print("Current clipboard offers formats: " + str(clipboard.wait_for_targets()))
</code></pre> |
45,293,933 | "Could not find a version that satisfies the requirement opencv-python" | <p>I am struggling with Jetson TX2 board (aarch64).</p>
<p>I need to install python wrapper for OpenCV.</p>
<p>I can do:</p>
<pre><code>$ sudo apt-get install python-opencv
</code></pre>
<p>But I cannot do:</p>
<pre><code>$ sudo pip install opencv-python
</code></pre>
<p>Is this because there is no proper wheel file in <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv</a>?</p>
<p>Is there a way to install opencv-python through pip?</p> | 45,302,440 | 13 | 6 | null | 2017-07-25 04:27:04.467 UTC | 10 | 2021-09-22 21:07:08.167 UTC | null | null | null | null | 4,227,175 | null | 1 | 47 | opencv|pip | 172,979 | <p><code>pip</code> doesn't use <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a>, it downloads packages from <a href="https://pypi.python.org/pypi/opencv-python" rel="noreferrer">PyPI</a>.</p>
<p>The problem is that you have an unusual architecture; <code>pip</code> cannot find a package for it and there is no source code package.</p>
<p>Unfortunately I think you're on your own. You have to download source code from <a href="https://github.com/skvark/opencv-python" rel="noreferrer">https://github.com/skvark/opencv-python</a>, install compiler and necessary libraries and compile OpenCV yourself.</p> |
9,268,645 | Creating a table linked to a csv file | <p>I am trying to create a table linked to a <code>*.csv</code> file using d3, but all I get is a blank webpage.
Even with the example Crimea I get a blank page.<br>
I would be grateful to be directed or shown a working example or a suggestion of what I am doing wrong.</p> | 9,507,713 | 4 | 2 | null | 2012-02-13 21:56:41.56 UTC | 30 | 2015-05-22 05:24:22.363 UTC | 2014-01-08 01:31:08.593 UTC | null | 1,151,269 | null | 1,169,210 | null | 1 | 44 | javascript|d3.js|html-table | 31,421 | <p>If you're asking about creating an HTML table from CSV data, this is what you want:</p>
<pre><code>d3.csv("data.csv", function(data) {
// the columns you'd like to display
var columns = ["name", "age"];
var table = d3.select("#container").append("table"),
thead = table.append("thead"),
tbody = table.append("tbody");
// append the header row
thead.append("tr")
.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(column) { return column; });
// create a row for each object in the data
var rows = tbody.selectAll("tr")
.data(data)
.enter()
.append("tr");
// create a cell in each row for each column
var cells = rows.selectAll("td")
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
});
})
.enter()
.append("td")
.text(function(d) { return d.value; });
});
</code></pre>
<p>Check out the <a href="http://jsfiddle.net/7WQjr/" rel="noreferrer">working example</a>. If you're copying that code, you'll need to update the <code>tabulate()</code> function so that it either selects an existing table or a different container (rather than <code>"#container"</code>), then you can use it with CSV data like so:</p>
<pre><code>d3.csv("path/to/data.csv", function(data) {
tabulate(data, ["name", "age"]);
});
</code></pre> |
16,265,714 | Camera pose estimation (OpenCV PnP) | <p>I am trying to get a global pose estimate from an image of four fiducials with known global positions using my webcam.</p>
<p>I have checked many stackexchange questions and a few papers and I cannot seem to get a a correct solution. The position numbers I do get out are repeatable but in no way linearly proportional to camera movement. FYI I am using C++ OpenCV 2.1.</p>
<p><a href="https://i.stack.imgur.com/WRa9I.png" rel="noreferrer"><strong>At this link is pictured</strong></a> my coordinate systems and the test data used below.</p>
<pre><code>% Input to solvePnP():
imagePoints = [ 481, 831; % [x, y] format
520, 504;
1114, 828;
1106, 507]
objectPoints = [0.11, 1.15, 0; % [x, y, z] format
0.11, 1.37, 0;
0.40, 1.15, 0;
0.40, 1.37, 0]
% camera intrinsics for Logitech C910
cameraMat = [1913.71011, 0.00000, 1311.03556;
0.00000, 1909.60756, 953.81594;
0.00000, 0.00000, 1.00000]
distCoeffs = [0, 0, 0, 0, 0]
% output of solvePnP():
tVec = [-0.3515;
0.8928;
0.1997]
rVec = [2.5279;
-0.09793;
0.2050]
% using Rodrigues to convert back to rotation matrix:
rMat = [0.9853, -0.1159, 0.1248;
-0.0242, -0.8206, -0.5708;
0.1686, 0.5594, -0.8114]
</code></pre>
<p>So far, <strong>can anyone see anything wrong with these numbers</strong>? I would appreciate it if someone would check them in for example MatLAB (code above is m-file friendly).</p>
<p>From this point, I am unsure of how to get the global pose from rMat and tVec.
From what I have read in <a href="https://stackoverflow.com/questions/14515200/python-opencv-solvepnp-yields-wrong-translation-vector">this question</a>, to get the pose from rMat and tVec is simply:</p>
<pre><code>position = transpose(rMat) * tVec % matrix multiplication
</code></pre>
<p>However I suspect from other sources that I have read it is not that simple.</p>
<p><strong>To get the position of the camera in real world coordinates, what do I need to do?</strong>
As I am unsure if this is an implementation problem (however most likely a theory problem) I would like for someone who has used the solvePnP function successfully in OpenCV to answer this question, although any ideas are welcome too!</p>
<p>Thank you very much for your time.</p> | 27,858,194 | 3 | 1 | null | 2013-04-28 17:38:13.803 UTC | 12 | 2016-07-26 07:16:36.627 UTC | 2017-05-23 12:17:05.72 UTC | null | -1 | null | 2,329,503 | null | 1 | 17 | opencv|computational-geometry|camera-calibration|pose-estimation|extrinsic-parameters | 20,863 | <p>I solved this a while ago, apologies for the year delay.</p>
<p>In the python OpenCV 2.1 I was using, and the newer version 3.0.0-dev, I have verified that to get the pose of the camera in the global frame you must:</p>
<pre><code>_, rVec, tVec = cv2.solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs)
Rt = cv2.Rodrigues(rvec)
R = Rt.transpose()
pos = -R * tVec
</code></pre>
<p>Now pos is the position of the camera expressed in the global frame (the same frame the objectPoints are expressed in).
R is an attitude matrix DCM which is a good form to store the attitude in.
If you require Euler angles then you can convert the DCM to Euler angles given an XYZ rotation sequence using:</p>
<pre><code>roll = atan2(-R[2][1], R[2][2])
pitch = asin(R[2][0])
yaw = atan2(-R[1][0], R[0][0])
</code></pre> |
16,253,215 | Open and modify Word Document | <p>I want to open a word file saved in my server using "Microsoft.Office.Interop.Word".
This is my code:</p>
<pre><code> object missing = System.Reflection.Missing.Value;
object readOnly = false;
object isVisible = true;
object fileName = "http://localhost:52099/modelloBusta/prova.dotx";
Microsoft.Office.Interop.Word.ApplicationClass applicationWord = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document modelloBusta = new Microsoft.Office.Interop.Word.Document();
try
{
modelloBusta = applicationWord.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible,ref missing, ref missing, ref missing, ref missing);
modelloBusta.Activate();
}
catch (COMException eccezione){
Console.Write(eccezione);
modelloBusta.Application.Quit(ref missing, ref missing, ref missing);
}
</code></pre>
<p>In the windows task manager the process is present, but the "word document" doesn't appear (the application does not start).
What is the problem?
Thanks in advance.</p> | 16,298,284 | 3 | 5 | null | 2013-04-27 14:26:30.26 UTC | 5 | 2016-09-04 00:39:55.93 UTC | 2014-03-31 20:10:15.333 UTC | null | 881,229 | null | 2,310,390 | null | 1 | 19 | c#|asp.net|ms-word|ms-office | 94,953 | <p>You need to make sure that the Word application window actually is made visible when automating Word like that:</p>
<pre><code>var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;
</code></pre> |
16,052,704 | How to pass dynamic value in @Url.Action? | <p>I have written following jquery in my partial view:</p>
<pre><code> $.ajax({
type: "POST",
url: '@Url.Action("PostActionName", "ControllerName")',
data: { Id: "01" },
success: function(data)
{
if (data.success="true")
{
window.location = '@Url.Action("GetActionName", "ControllerName")'
}
}
});
</code></pre>
<p>The Action name and Controller name are not fixed, they are bound to change depending upon the view wherein this partial view is placed. I have functions to fetch invoking action and controller names, but not sure how I can pass them in @Url.Action.</p>
<p>Following are Javascript functions to fetch action and controller names:</p>
<pre><code>function ControllerName() {
var pathComponents = window.location.pathname.split('/');
var controllerName;
if (pathComponents.length >= 2) {
if (pathComponents[0] != '') {
controllerName = pathComponents[0];
}
else {
controllerName = pathComponents[1];
}
}
return controllerName;
}
function ActionName() {
var pathComponents = window.location.pathname.split('/');
var actionName;
if (pathComponents.length >= 2) {
if (pathComponents[0] != '') {
actionName = pathComponents[1];
}
else {
actionName = pathComponents[2];
}
}
return actionName;
}
</code></pre> | 16,052,759 | 3 | 3 | null | 2013-04-17 06:03:49.253 UTC | 5 | 2018-08-24 10:50:38.357 UTC | 2013-04-17 06:12:53.583 UTC | null | 1,480,090 | null | 1,480,090 | null | 1 | 22 | jquery|asp.net-mvc-4|url.action | 90,051 | <blockquote>
<p>I have functions to fetch invoking action and controller names, but
not sure how I can pass them in @Url.Action</p>
</blockquote>
<p>Well, you could call those functions. For example if they are extension methods to the UrlHelper class:</p>
<pre><code>window.location = '@Url.Action(Url.MyFunction1(), Url.MyFunction2())'
</code></pre>
<p>or if they are just static functions:</p>
<pre><code>window.location = '@Url.Action(SomeClass.MyFunction1(), SomeClass.MyFunction2())'
</code></pre>
<p>If on the other hand the values that need to be passed are known only on the client you could do the following:</p>
<pre><code>var param = 'some dynamic value known on the client';
var url = '@Url.Action("SomeAction", "SomeController", new { someParam = "__param__" })';
window.location.href = url.replace('__param__', encodeURIComponent(param));
</code></pre>
<hr>
<p>UPDATE:</p>
<p>It seems that you are just trying to fetch the current controller and action which could be achieved like that:</p>
<pre><code>@{
string currentAction = Html.ViewContext.RouteData.GetRequiredString("action");
string currentController = Html.ViewContext.RouteData.GetRequiredString("controller");
}
</code></pre>
<p>and then:</p>
<pre><code>window.location.href = '@Url.Action(currentAction, currentController)';
</code></pre> |
16,296,351 | How to delete an item from UICollectionView with indexpath.row | <p>I have a collection view,and I tried to delete a cell from collection view on didSelect method.I succeeded in that using the following method </p>
<pre><code> [colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
</code></pre>
<p>But now I need to delete the item on button click from CollectionView Cell.Here I get only the indexpath.row.
From this I am not able to delete the Item.
I tried like this.</p>
<pre><code>-(void)remove:(int)i {
NSLog(@"index path%d",i);
[array removeObjectAtIndex:i];
NSIndexPath *indexPath =[NSIndexPath indexPathForRow:i inSection:0];
[colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
[colleVIew reloadData];
}
</code></pre>
<p>But it needs to reload the CollectionView.So the animation of cell arrangement after deletion is not there.
Please suggest an idea..thanks in advance</p> | 16,297,327 | 7 | 0 | null | 2013-04-30 09:19:39.407 UTC | 8 | 2020-06-24 02:22:40.937 UTC | null | null | null | user2000452 | null | null | 1 | 23 | iphone|ios|uicollectionview|uicollectionviewcell | 44,718 | <pre><code>-(void)remove:(int)i {
[self.collectionObj performBatchUpdates:^{
[array removeObjectAtIndex:i];
NSIndexPath *indexPath =[NSIndexPath indexPathForRow:i inSection:0];
[self.collectionObj deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
} completion:^(BOOL finished) {
}];
}
</code></pre>
<p>Try this. It may work for you.</p> |
16,534,277 | Can an INSERT operation result in a deadlock? | <p>Assuming:</p>
<ul>
<li>I am using REPEATABLE_READ or SERIALIZABLE transaction isolation (locks get retained every time I access a row)</li>
<li>We are talking about multiple threads accessing multiple tables simultaneously.</li>
</ul>
<p>I have the following questions:</p>
<ol>
<li><strong>Is it possible for an <code>INSERT</code> operation to cause a deadlock?</strong> If so, please provide a detailed scenario demonstrating how a deadlock may occur (e.g. Thread 1 does this, Thread 2 does that, ..., deadlock).</li>
<li>For bonus points: answer the same question for all other operations (e.g. SELECT, UPDATE, DELETE).</li>
</ol>
<p><strong>UPDATE</strong>:
3. For super bonus points: how can I avoid a deadlock in the following scenario?</p>
<p>Given tables:</p>
<ul>
<li>permissions<code>[id BIGINT PRIMARY KEY]</code></li>
<li>companies<code>[id BIGINT PRIMARY KEY, name VARCHAR(30), permission_id BIGINT NOT NULL, FOREIGN KEY (permission_id) REFERENCES permissions(id))</code></li>
</ul>
<p>I create a new Company as follows:</p>
<ul>
<li>INSERT INTO permissions; -- Inserts permissions.id = 100</li>
<li>INSERT INTO companies (name, permission_id) VALUES ('Nintendo', 100); -- Inserts companies.id = 200</li>
</ul>
<p>I delete a Company as follows:</p>
<ul>
<li>SELECT permission_id FROM companies WHERE id = 200; -- returns permission_id = 100</li>
<li>DELETE FROM companies WHERE id = 200;</li>
<li>DELETE FROM permissions WHERE id = 100;</li>
</ul>
<p>In the above example, the INSERT locking order is [permissions, companies] whereas the DELETE locking order is [companies, permissions]. Is there a way to fix this example for <code>REPEATABLE_READ</code> or <code>SERIALIZABLE</code> isolation?</p> | 16,534,802 | 3 | 5 | null | 2013-05-14 02:42:11.527 UTC | 9 | 2017-01-28 17:06:05.257 UTC | 2017-01-28 17:06:05.257 UTC | null | 2,263,517 | null | 14,731 | null | 1 | 28 | sql|insert|deadlock | 45,298 | <p>Generally all modifications can cause a deadlock and selects will not (get to that later). So</p>
<ol>
<li>No you cannot ignore these.</li>
<li>You can somewhat ignore select depending on your database and settings but the others will give you deadlocks.</li>
</ol>
<p>You don't even need multiple tables.</p>
<p>The best way to create a deadlock is to do the same thing in a different order.</p>
<p>SQL Server examples:</p>
<pre><code>create table A
(
PK int primary key
)
</code></pre>
<p>Session 1:</p>
<pre><code>begin transaction
insert into A values(1)
</code></pre>
<p>Session 2:</p>
<pre><code>begin transaction
insert into A values(7)
</code></pre>
<p>Session 1:</p>
<pre><code>delete from A where PK=7
</code></pre>
<p>Session 2:</p>
<pre><code>delete from A where PK=1
</code></pre>
<p>You will get a deadlock. So that proved inserts & deletes can deadlock.</p>
<p>Updates are similar:</p>
<p>Session 1:</p>
<pre><code>begin transaction
insert into A values(1)
insert into A values(2)
commit
begin transaction
update A set PK=7 where PK=1
</code></pre>
<p>Session 2:</p>
<pre><code>begin transaction
update A set pk=9 where pk=2
update A set pk=8 where pk=1
</code></pre>
<p>Session 1:</p>
<pre><code>update A set pk=9 where pk=2
</code></pre>
<p>Deadlock!</p>
<p>SELECT should never deadlock but on some databases it will because the locks it uses interfere with consistent reads. That's just crappy database engine design though. </p>
<p>SQL Server will not lock on a SELECT if you use SNAPSHOT ISOLATION. Oracle & I think Postgres will never lock on SELECT (unless you have FOR UPDATE which is clearly reserving for an update anyway).</p>
<p>So basically I think you have a few incorrect assumptions. I think I've proved:</p>
<ol>
<li>Updates can cause deadlocks</li>
<li>Deletes can cause deadlocks</li>
<li>Inserts can cause deadlocks</li>
<li>You do not need more than one table</li>
<li>You <strong>do</strong> need more than one session</li>
</ol>
<p>You'll just have to take my word on SELECT ;) but it will depend on your DB and settings.</p> |
16,344,756 | Auto reloading python Flask app upon code changes | <p>I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight <a href="https://flask.palletsprojects.com/en/1.1.x/" rel="noreferrer">Flask framework</a>. Time will tell if this was the right choice.</p>
<p>So, now I've set up an Apache server with mod_wsgi, and my test site is running fine. However, I'd like to speed up the development routine by making the site automatically reload upon any changes in py or template files I make. I see that any changes in site's .wsgi file causes reloading (even without WSGIScriptReloading On in the apache config file), but I still have to prod it manually (ie, insert extra linebreak, save). Is there some way how to cause reload when I edit some of the app's py files? Or, I am expected to use IDE that refreshes the .wsgi file for me?</p> | 40,150,705 | 12 | 0 | null | 2013-05-02 18:04:10.81 UTC | 84 | 2022-08-02 13:26:00.577 UTC | 2022-01-12 21:09:44.2 UTC | null | 4,294,399 | null | 640,694 | null | 1 | 345 | python|apache|flask | 267,621 | <p>Run the <code>flask run</code> CLI command with <a href="https://flask.palletsprojects.com/quickstart/#debug-mode" rel="noreferrer">debug mode</a> enabled, which will automatically enable the reloader. As of Flask 2.2, you can pass <code>--app</code> and <code>--debug</code> options on the command line.</p>
<pre><code>$ flask --app main.py --debug run
</code></pre>
<p><code>--app</code> can also be set to <code>module:app</code> or <code>module:create_app</code> instead of <code>module.py</code>. <a href="https://flask.palletsprojects.com/cli/#application-discovery" rel="noreferrer">See the docs for a full explanation.</a></p>
<p>More options are available with:</p>
<pre><code>$ flask run --help
</code></pre>
<p>Prior to Flask 2.2, you needed to set the <code>FLASK_APP</code> and <code>FLASK_ENV=development</code> environment variables.</p>
<pre><code>$ export FLASK_APP=main.py
$ export FLASK_ENV=development
$ flask run
</code></pre>
<p>It is still possible to set <code>FLASK_APP</code> and <code>FLASK_DEBUG=1</code> in Flask 2.2.</p> |
16,177,056 | Changing three.js background to transparent or other color | <p>I've been trying to change what seems to be the default background color of my canvas from black to transparent / any other color - but no luck.</p>
<p>My HTML:</p>
<pre><code><canvas id="canvasColor">
</code></pre>
<p>My CSS:</p>
<pre><code><style type="text/css">
#canvasColor {
z-index: 998;
opacity:1;
background: red;
}
</style>
</code></pre>
<p>As you can see in the following online example I have some animation appended to the canvas, so cant just do a opacity: 0; on the id.</p>
<p>Live preview:
<a href="http://devsgs.com/preview/test/particle/">http://devsgs.com/preview/test/particle/</a></p>
<p>Any ideas how to overwrite the default black?</p> | 16,177,178 | 7 | 1 | null | 2013-04-23 18:53:35.56 UTC | 31 | 2021-12-07 13:42:52.083 UTC | 2013-06-13 18:40:16.507 UTC | null | 2,287,470 | null | 1,231,561 | null | 1 | 153 | css|html|canvas|html5-canvas|three.js | 173,822 | <p>I came across this when I started using three.js as well. It's actually a javascript issue. You currently have: </p>
<pre><code>renderer.setClearColorHex( 0x000000, 1 );
</code></pre>
<p>in your <code>threejs</code> init function. Change it to:</p>
<pre><code>renderer.setClearColorHex( 0xffffff, 1 );
</code></pre>
<p><strong>Update:</strong> Thanks to HdN8 for the updated solution:</p>
<pre><code>renderer.setClearColor( 0xffffff, 0);
</code></pre>
<p><strong>Update #2:</strong> As pointed out by WestLangley in <a href="https://stackoverflow.com/questions/20495302/transparent-background-with-three-js">another, similar question</a> - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the <code>setClearColor()</code> function:</p>
<pre><code>var renderer = new THREE.WebGLRenderer({ alpha: true });
</code></pre>
<p><strong>Update #3:</strong> Mr.doob points out that since <a href="https://github.com/mrdoob/three.js/releases/tag/r78" rel="noreferrer"><code>r78</code></a> you can alternatively use the code below to set your scene's background colour:</p>
<pre><code>var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );
</code></pre> |
28,942,758 | How do I get the dimensions (nestedness) of a nested vector (NOT the size)? | <p>Consider the following declarations:</p>
<pre><code>vector<vector<int> > v2d;
vector<vector<vector<string>> > v3d;
</code></pre>
<p>How can I find out the "dimensionality" of the vectors in subsequent code? For example, 2 for v2d and 3 for v3d?</p> | 28,943,178 | 2 | 9 | null | 2015-03-09 13:07:23.92 UTC | 6 | 2015-08-06 14:45:23.79 UTC | 2015-03-10 08:32:21.35 UTC | null | 1,025,391 | null | 1,586,860 | null | 1 | 31 | c++|vector | 1,845 | <p>Something on these lines:</p>
<pre><code>template<class Y>
struct s
{
enum {dims = 0};
};
template<class Y>
struct s<std::vector<Y>>
{
enum {dims = s<Y>::dims + 1};
};
</code></pre>
<p>Then for example,</p>
<pre><code>std::vector<std::vector<double> > x;
int n = s<decltype(x)>::dims; /*n will be 2 in this case*/
</code></pre>
<p>Has the attractive property that all the evaluations are at <em>compile time</em>.</p> |
58,305,567 | How to set GOPRIVATE environment variable | <p>I started working on a <code>Go</code> project and it uses some private modules from Github private repos and whenever I try to run <code>go run main.go</code> it gives me a below <code>410 Gone</code> error:</p>
<blockquote>
<p>verifying github.com/repoURL/[email protected]+incompatible/go.mod: github.com/repoURL/[email protected]+incompatible/go.mod: reading <a href="https://sum.golang.org/lookup/github.com/!repoURL/[email protected]+incompatible" rel="noreferrer">https://sum.golang.org/lookup/github.com/!repoURL/[email protected]+incompatible</a>: 410 Gone</p>
</blockquote>
<p>I can easily clone private repo from terminal which means my <code>ssh</code> keys are configured correctly. I read <a href="https://tip.golang.org/cmd/go/#hdr-Module_configuration_for_non_public_modules" rel="noreferrer">here</a> that I need to set <code>GOPRIVATE</code> environment variable but I am not sure how to do that.</p>
<p>Can anyone answer or point to the relevant tutorial?</p>
<p><strong>Go:</strong> v1.13, <strong>OS:</strong> macOS Mojave</p> | 58,306,008 | 3 | 6 | null | 2019-10-09 13:42:08.55 UTC | 38 | 2022-05-16 08:55:28.083 UTC | 2020-04-07 07:49:04.04 UTC | null | 5,198,756 | null | 4,704,510 | null | 1 | 91 | go|environment-variables|go-modules | 92,695 | <h3>Short Answer:</h3>
<pre class="lang-sh prettyprint-override"><code>go env -w GOPRIVATE=github.com/repoURL/private-repo
</code></pre>
<p><strong>OR</strong></p>
<p>If you want to allow all private repos from your organization</p>
<pre class="lang-sh prettyprint-override"><code>go env -w GOPRIVATE=github.com/<OrgNameHere>/*
</code></pre>
<hr />
<h3>Long Answer:</h3>
<p>Check <a href="https://pkg.go.dev/cmd/go#hdr-Configuration_for_downloading_non_public_code" rel="noreferrer">"Module configuration for non-public modules"</a> for more information:</p>
<blockquote>
<p>The GOPRIVATE environment variable controls which modules the go command considers to be private (not available publicly) and should therefore not use the proxy or checksum database. The variable is a comma-separated list of glob patterns (in the syntax of Go's path.Match) of module path prefixes. For example,</p>
<pre><code> GOPRIVATE=*.corp.example.com,rsc.io/private
</code></pre>
<p>causes the go command to treat as private any module with a path prefix matching either pattern, including git.corp.example.com/xyzzy, rsc.io/private, and rsc.io/private/quux.</p>
</blockquote>
<p>.
.</p>
<blockquote>
<p>The 'go env -w' command (see 'go help env') can be used to set these variables for future go command invocations.</p>
</blockquote>
<hr />
<h3>Note on the usage of ssh:</h3>
<p>If you use <strong>ssh</strong> to access git repo (locally hosted), you might want to add the following to your <code>~/.gitconfig</code>:</p>
<pre class="lang-sh prettyprint-override"><code>[url "ssh://[email protected]/"]
insteadOf = https://git.local.intranet/
</code></pre>
<p>for the <code>go</code> commands to be able to access the git server.</p> |
22,403,650 | Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified | <p>I have a small MVC app that I use for practice reasons, but now I am encountering an error every time I try to debug:</p>
<pre><code>Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies.
The system cannot find the path specified.
</code></pre>
<p>I've googled but cannot find a solution. I'm using .NET 4.5.</p>
<p>It can't be the DLL file because I'm using .Net 4.5.</p> | 22,404,145 | 20 | 2 | null | 2014-03-14 11:24:11.247 UTC | 39 | 2021-07-16 09:40:23.057 UTC | 2016-10-25 13:42:31.263 UTC | null | 4,211,135 | null | 3,322,193 | null | 1 | 178 | c#|asp.net|.net|asp.net-mvc-4 | 238,711 | <p>Whenever I have a NuGet error such as these I usually take these steps:</p>
<ol>
<li>Go to the packages folder in the Windows Explorer and delete it.</li>
<li>Open Visual Studio and Go to <em>Tools</em> > <em>Library Package Manager</em> > <em>Package Manager Settings</em> and under the Package Manager item on the left hand side there is a "Clear Package Cache" button. Click this button and make sure that the check box for "Allow NuGet to download missing packages during build" is checked.</li>
<li>Clean the solution</li>
<li>Then right click the solution in the Solution Explorer and enable NuGet Package Restore</li>
<li>Build the solution</li>
<li>Restart Visual Studio</li>
</ol>
<p>Taking all of these steps almost always restores all the packages and dll's I need for my MVC program.</p>
<hr>
<p><strong>EDIT >>></strong></p>
<p>For Visual Studio 2013 and above, step 2) should read:</p>
<ol start="2">
<li>Open Visual Studio and go to <em>Tools</em> > <em>Options</em> > <em>NuGet Package Manager</em> and on the right hand side there is a "Clear Package Cache button". Click this button and make sure that the check boxes for "Allow NuGet to download missing packages" and "Automatically check for missing packages during build in Visual Studio" are checked.</li>
</ol> |
22,342,285 | summing two columns in a pandas dataframe | <p>when I use this syntax it creates a series rather than adding a column to my new dataframe <code>sum</code>.</p>
<p>My code:</p>
<pre><code>sum = data['variance'] = data.budget + data.actual
</code></pre>
<p>My dataframe <code>data</code> currently has everything except the <code>budget - actual</code> column. How do I create a <code>variance</code> column?</p>
<pre><code> cluster date budget actual budget - actual
0 a 2014-01-01 00:00:00 11000 10000 1000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
</code></pre> | 22,342,344 | 7 | 3 | null | 2014-03-12 04:51:03.453 UTC | 12 | 2022-05-26 04:41:04.253 UTC | 2022-05-07 18:08:11.807 UTC | null | 18,145,256 | null | 3,098,818 | null | 1 | 58 | python|pandas | 238,224 | <p>I think you've misunderstood some python syntax, the following does two assignments:</p>
<pre><code>In [11]: a = b = 1
In [12]: a
Out[12]: 1
In [13]: b
Out[13]: 1
</code></pre>
<p>So in your code it was as if you were doing:</p>
<pre><code>sum = df['budget'] + df['actual'] # a Series
# and
df['variance'] = df['budget'] + df['actual'] # assigned to a column
</code></pre>
<p>The latter creates a new column for df:</p>
<pre><code>In [21]: df
Out[21]:
cluster date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
In [22]: df['variance'] = df['budget'] + df['actual']
In [23]: df
Out[23]:
cluster date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
</code></pre>
<p><em>As an aside, you shouldn't use <code>sum</code> as a variable name as the overrides the built-in sum function.</em></p> |
37,311,042 | Call django urls inside javascript on click event | <p>I got a javascript onclick event inside a template, and I want to call one of my Django urls with an id parameter from it, like this :</p>
<pre><code>$(document).on('click', '.alink', function () {
var id = $(this).attr('id');
document.location.href ="{% url 'myapp:productdetailorder' id %}"
});
</code></pre>
<p>Course this is not working at all. Any idea ?</p>
<p>Thanks in advance !!</p> | 49,824,680 | 5 | 3 | null | 2016-05-18 22:21:02.887 UTC | 7 | 2021-06-01 10:24:16.893 UTC | 2021-02-26 18:36:10.943 UTC | null | 5,682,919 | null | 5,682,919 | null | 1 | 11 | javascript|jquery|django|location-href | 38,097 | <p>I think the best way to do this is to create a html <code>data-*</code> attribute with the URL rendered in a template and then use javascript to retrieve that. </p>
<p>This way you avoid mixing js/django template stuff together. Also, I keep all of my JS in a separate file outside the view (which is a much better practice in general), and therefore trying to mix these two won't work.</p>
<p>For instance, if you have a url you want, just create an html hidden element:</p>
<pre class="lang-html prettyprint-override"><code><input type="hidden" id="Url" data-url="{% url 'myapp:productdetail' id %}" />
</code></pre>
<p>Then, in your JS:</p>
<pre class="lang-js prettyprint-override"><code>$(document).on('click', '.alink', function () {
var url = $("#Url").attr("data-url");
});
</code></pre>
<p>I frequently use this pattern for dropdown lists so that I don't have to serve all of the options when I first render the page (and this usually speeds it up).</p> |
17,564,608 | What does the 'array name' mean in case of array of char pointers? | <p>In my code: </p>
<pre><code> char *str[] = {"forgs", "do", "not", "die"};
printf("%d %d", sizeof(str), sizeof(str[0]));
</code></pre>
<p>I'm getting the output as <code>12 2</code>, so my doubts are: </p>
<ol>
<li>Why is there a difference? </li>
<li>Both <code>str</code> and <code>str[0]</code> are char pointers, right?</li>
</ol> | 17,564,886 | 4 | 17 | null | 2013-07-10 07:19:21.15 UTC | 24 | 2014-01-01 08:54:58.53 UTC | 2013-08-20 18:48:18.133 UTC | null | 1,673,391 | null | 1,587,061 | null | 1 | 24 | c|pointers|sizeof | 5,795 | <p>In most cases, an array name will decay to the value of the address of its first element, and with type being the same as a pointer to the element type. So, you would expect a bare <code>str</code> to have the value equal to <code>&str[0]</code> with type pointer to pointer to <code>char</code>.</p>
<p>However, this is not the case for <code>sizeof</code>. In this case, the array name maintains its type for <code>sizeof</code>, which would be array of 4 pointer to <code>char</code>.</p>
<p>The return type of <code>sizeof</code> is a <code>size_t</code>. If you have a C99 compiler, you can use <code>%zu</code> in the format string to print the value returned by <code>sizeof</code>.</p> |
18,500,611 | Android: How to use "adb shell wm" to simulate other devices | <p>So I bought a Nexus 10 for development and was super excited by the prospect of being able to simulate other devices using the "adb shell wm" command, with its size, density, and overscan subcommands.</p>
<p>However, I've had a few problems making this work. I'd like to see if anyone else has encountered/overcome these. For the sake of this discussion, let's say I'm trying to simulate a typical phone, running the following:</p>
<pre><code>adb shell wm size 800x480
adb shell wm density 240
adb shell wm overscan reset
</code></pre>
<p>First, setting the size messes up the menu bar. In portrait mode, only some of the buttons will be present and at the wrong scale, and in landscape mode, the menu bar is completely missing. In fact, even after you reset everything, it's still missing until you restart the device. Any workaround for this? </p>
<p>Secondly, what does the overscan command do? I can't find any documentation for it anywhere.</p>
<p>Thirdly, is there any way to make the device render the screen using 1 pixel of the new size to 1 pixel of the physical screen? That is to say, if I set the size to 800x480, I'd like to see the new screen take up exactly that much space. Instead, what seems to happen is the 800x480 screen is stretched so that the longest side just fits on the physical display. I suspect that overscan might be the answer, but when I tried to set it to 0,0,800,480, it permanently hung my system and I had to reset to the factory image to recover.</p>
<p>Finally, is there any way to cause the tablet to simulate a phone in terms of what happens to the menu bar during an orientation change? On a tablet, the menu bar goes to new bottom of the screen, but on a phone, it stays where it is. </p>
<p>I like this device so far, but if I could just get this device simulation stuff working, I'd love it! Thanks in advance for any pointers.</p> | 19,922,688 | 3 | 7 | null | 2013-08-29 00:46:47.703 UTC | 13 | 2022-01-05 19:41:37.473 UTC | null | null | null | null | 912,961 | null | 1 | 39 | android|adb | 65,607 | <p>Okay, I think I figured out enough of this to be useful. I will attempt to answer each of the questions I raised in my original post. Then I'll share a few other things I've learned about how to use this effectively.</p>
<ul>
<li>Is there any way to avoid messing up the menu bar when at the home screen?</li>
</ul>
<p>Not that I've discovered, and changing the settings seems to have a cumulative effect that will usually royally screw up the home screen until you restart the device. However, you can usually at least unlock the device, which is enough to be useful. The key is to start your app first, then adjust the size and density while already running it. Simply press the power button to turn off the screen, adjust the size and density as you like, then power the screen back on, unlock, and you're app will be running properly at the new size and density.</p>
<ul>
<li>What does the overscan command do?</li>
</ul>
<p>I've found only oblique references to this, but the best I can determine, it's for TVs or other displays where not all of the screen is guaranteed to be usable/visible. I don't think it really applies to a regular phone or tablet.</p>
<ul>
<li>Is there any way to make the device render the screen using 1 pixel of the new size to 1 pixel of the physical screen?</li>
</ul>
<p>Not that I've discovered. But it probably doesn't matter. I think the main point of using the adb shell wm commands is to test layout, not to see pixel-perfect graphics. (And believe me, what you get is the farthest thing possible from pixel-perfect.)</p>
<ul>
<li>Is there any way to cause the tablet to simulate a phone in terms of what happens to the menu bar during an orientation change?</li>
</ul>
<p>Maybe I'm doing it wrong, but for me, the menu bar behaves in bizarre and unpredictable ways. Sometimes it's massive, sometimes it's just missing. Don't count on being able to use it. Yes, this sucks. Someone please chime in if there's a solution to this.</p>
<ul>
<li>So how do I use "adb shell wm" effectively?</li>
</ul>
<p>I'm not sure why, but it took me a little while to grasp this. That's probably because when I first started this, my mind was not accustomed to the Android way of thinking about things. But it's actually pretty simple.</p>
<p>First, set the size you want in pixels. For this discussion, let's say we're going to use 1024x600.</p>
<p>Next, set the DPI. But what should you set it to?</p>
<p>That's the tricky part (well, the part I didn't get at first). When you set the DPI, you're setting the other half of the equation that will determine the dimensions in DP of the virtual application space, which the app will use to render itself. (Duh, I know, but I at first thought the specified DPI would be used mainly to select resources, which indeed it also does.)</p>
<p>Let's take a look at the consequences of using various densities with a screen size of 1024x600.</p>
<p>First, keep in mind that</p>
<pre><code>dp = px * (160 / dpi)
</code></pre>
<p>That means if we specify our dpi at 160, the app will believe that the available space is 1024dp x 600dp. If instead we use 240, that changes to a meager 683dp x 400 dp, and conversely, if we use 120, we get an impressive 1365 dp x 800 dp. Set it to 80, and now you're rocking 2048dp x 1200dp. </p>
<p>The counter-intuitive part is realizing that specifying a low density results an image that appears like what you might see in an ultra-hi-res monitor -- everything is tiny. But that's because the app is now treating the same physical space as though it were a very large size <em>in dp.</em> </p>
<p>So going back to the example of a density of 80, we have a virtual area of 2048dp x 1200dp, but it is being scrunched onto whatever sized physical screen you're actually using. Since 160dp is supposed to be about 1 inch, that would be an almost otherworldly tablet with a width of 12.8 inches. But that entire thing is scrunched down to the actual size of your tablet, making your generously sized 30dp text appear pretty puny. </p>
<p>Maybe I'm just the slowest kid in the room, but it took me a while to really grok this. I hope it helps someone else out there.</p> |
26,175,661 | Intellij git revert a commit | <p>I was using <code>Eclipse</code> and <code>Egit</code> for a long time and decided to try <code>Intellij</code>.<br/> So far so good, except one thing...<br/> I can't find an easy way to revert an old commit from my repo!!!</p>
<p>In Eclipse the standard process was: <code>Go to Git Workspace -> Click Show History(Right Click Project) -> RIght-Click on the commit I want to revert and press Revert Commit.</code> <br/></p>
<p>In Intellij I can't find anything equivalent. Tried <code>VCS -> Show Changes View</code> but there I can only <code>cherry pick</code> a commit. I also played with the revert option under <code>VCS -> git</code> but got confused by the <code>changelist</code> thing(That may hide the answer, but I don't understand how it works).</p>
<p>I can still revert the commit by issuing <code>git revert <sha></code> from terminal but that's what I was trying to avoid in the first place by using git from Intellij and not pure terminal.<br/></p>
<p>Is there a way to do easily the revert in Intellij?</p> | 29,964,756 | 4 | 2 | null | 2014-10-03 08:26:42.57 UTC | 9 | 2017-06-13 11:37:52.343 UTC | null | null | null | null | 1,499,705 | null | 1 | 57 | git|intellij-idea | 75,155 | <p>If you go to Changelist -> Log, and there select the commit, you've got a change detail in the right panel.
There you can select all and click a button (or right click -> revert selected changes).</p> |
23,199,416 | 5 dimensional plot in r | <p>I am trying to plot a 5 dimensional plot in R. I am currently using the <code>rgl</code> package to plot my data in 4 dimensions, using 3 variables as the x,y,z, coordinates, another variable as the color. I am wondering if I can add a fifth variable using this package, like for example the size or the shape of the points in the space. Here's an example of my data, and my current code:</p>
<pre><code>set.seed(1)
df <- data.frame(replicate(4,sample(1:200,1000,rep=TRUE)))
addme <- data.frame(replicate(1,sample(0:1,1000,rep=TRUE)))
df <- cbind(df,addme)
colnames(df) <- c("var1","var2","var3","var4","var5")
require(rgl)
plot3d(df$var1, df$var2, df$var3, col=as.numeric(df$var4), size=0.5, type='s',xlab="var1",ylab="var2",zlab="var3")
</code></pre>
<p>I hope it is possible to do the 5th dimension.
Many thanks,</p> | 23,199,753 | 1 | 9 | null | 2014-04-21 14:27:43.343 UTC | 13 | 2018-08-09 16:14:35.227 UTC | 2014-04-21 15:02:46.993 UTC | null | 1,826,552 | null | 1,826,552 | null | 1 | 13 | r|plot|rgl|multi-dimensional-scaling | 6,660 | <p>Here is a <code>ggplot2</code> option. I usually shy away from 3D plots as they are hard to interpret properly. I also almost never put in 5 continuous variables in the same plot as I have here...</p>
<pre><code>ggplot(df, aes(x=var1, y=var2, fill=var3, color=var4, size=var5^2)) +
geom_point(shape=21) +
scale_color_gradient(low="red", high="green") +
scale_size_continuous(range=c(1,12))
</code></pre>
<p><img src="https://i.stack.imgur.com/Jtif8.png" alt="enter image description here"></p>
<p>While this is a bit messy, you can actually reasonably read all 5 dimensions for most points.</p>
<p>A better approach to multi-dimensional plotting opens up if some of your variables are categorical. If all your variables are continuous, you can turn some of them to categorical with <code>cut</code> and then use <code>facet_wrap</code> or <code>facet_grid</code> to plot those.</p>
<p>For example, here I break up <code>var3</code> and <code>var4</code> into quintiles and use <code>facet_grid</code> on them. Note that I also keep the color aesthetics as well to highlight that most of the time turning a continuous variable to categorical in high dimensional plots is good enough to get the key points across (here you'll notice that the fill and border colors are pretty uniform within any given grid cell):</p>
<pre><code>df$var4.cat <- cut(df$var4, quantile(df$var4, (0:5)/5), include.lowest=T)
df$var3.cat <- cut(df$var3, quantile(df$var3, (0:5)/5), include.lowest=T)
ggplot(df, aes(x=var1, y=var2, fill=var3, color=var4, size=var5^2)) +
geom_point(shape=21) +
scale_color_gradient(low="red", high="green") +
scale_size_continuous(range=c(1,12)) +
facet_grid(var3.cat ~ var4.cat)
</code></pre>
<p><img src="https://i.stack.imgur.com/NhasC.png" alt="enter image description here"></p> |
5,107,368 | how to null a variable of type float | <p>My code is working if my float variable is set to 0, but I want my code to work if my variable is null. How could I do that? Here is a code snippet I wrote:</p>
<pre><code>float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString()));
if(oikonomia==0){
</code></pre>
<p>I have tied <code>if(oikonomia==null)</code> or <code>if(oikonomia=null)</code> but it is not working.</p>
<p>P.S.: Another way would be to initially set <code>oikonomia=0;</code> and, if the users change it, go to my if session. This is not working either.</p>
<p>Float oikonomia = Float.valueOf(vprosvasis7.getText().toString());</p>
<pre><code> if(oikonomia.toString() == " "){
float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString()));
oikonomia=0;
if(oikonomia==0){
</code></pre>
<p>that way is not working too:</p>
<pre><code>Float oikonomia = Float.valueOf(vprosvasis7.getText().toString());
if(oikonomia.toString() == " "){
</code></pre> | 5,107,399 | 4 | 0 | null | 2011-02-24 16:20:13.123 UTC | null | 2011-02-24 17:46:21.92 UTC | 2011-02-24 16:35:25.657 UTC | null | 519,526 | null | 519,526 | null | 1 | 7 | java|android | 45,842 | <p>If you want a nullable float, then try <code>Float</code> instead of <code>float</code></p>
<pre><code>Float oikonomia= new Float(vprosvasis7.getText().toString());
</code></pre>
<p>But it will never be <code>null</code> that way as in your example...</p>
<p><strong>EDIT</strong>: Aaaah, I'm starting to understand what your problem is. You really don't know what <code>vprosvasis7</code> contains, and whether it is correctly initialised as a number. So try this, then:</p>
<pre><code>Float oikonomia = null;
try {
oikonomia = new Float(vprosvasis7.getText().toString());
}
catch (Exception ignore) {
// We're ignoring potential exceptions for the example.
// Cleaner solutions would treat NumberFormatException
// and NullPointerExceptions here
}
// This happens when we had an exception before
if (oikonomia == null) {
// [...]
}
// This happens when the above float was correctly parsed
else {
// [...]
}
</code></pre>
<p>Of course there are lots of ways to simplify the above and write cleaner code. But I think this should about explain how you should correctly and safely parse a <code>String</code> into a <code>float</code> without running into any Exceptions...</p> |
9,494,283 | jquery how to get the pasted content | <p>I have a little trouble catching a pasted text into my input:</p>
<pre><code> <input type="text" id="myid" val="default">
$('#myid').on('paste',function(){
console.log($('#myid').val());
});
</code></pre>
<p>console.log shows:</p>
<pre><code>default
</code></pre>
<p>How I <code>catch</code> the pasted text and get ready to use?</p> | 9,494,891 | 6 | 3 | null | 2012-02-29 06:03:57.457 UTC | 8 | 2020-05-12 06:25:04.83 UTC | null | null | null | null | 379,437 | null | 1 | 34 | jquery|paste | 45,227 | <p>Because the <code>paste</code> event is triggered before the inputs value is updated, the solution is to either:</p>
<ol>
<li><p>Capture the data from the clipboard instead, as the clipboards data will surely be the same as the data being pasted into the input at that exact moment.</p></li>
<li><p>Wait until the value <em>has</em> updated using a timer</p></li>
</ol>
<p>Luckily, years after the original answer was posted, most modern browsers now support the fantastic <a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API" rel="noreferrer">Clipboard API</a>, a much more elegant solution to capturing data from the clipboard.</p>
<p>For browsers that don't support the Clipboard API, we could fall back to the unreliable <code>event.clipboardData</code> if we do some checking as to which version, if any, is supported in the browser.</p>
<p>As a final fallback, using a timer to delay until the inputs value is updated, will work in all browsers, making this a truly cross-browser solution.</p>
<p>I've made a convenient function that handles everything</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function catchPaste(evt, elem, callback) {
if (navigator.clipboard && navigator.clipboard.readText) {
// modern approach with Clipboard API
navigator.clipboard.readText().then(callback);
} else if (evt.originalEvent && evt.originalEvent.clipboardData) {
// OriginalEvent is a property from jQuery, normalizing the event object
callback(evt.originalEvent.clipboardData.getData('text'));
} else if (evt.clipboardData) {
// used in some browsers for clipboardData
callback(evt.clipboardData.getData('text/plain'));
} else if (window.clipboardData) {
// Older clipboardData version for Internet Explorer only
callback(window.clipboardData.getData('Text'));
} else {
// Last resort fallback, using a timer
setTimeout(function() {
callback(elem.value)
}, 100);
}
}
// to be used as
$('#myid').on('paste', function(evt) {
catchPaste(evt, this, function(clipData) {
console.log(clipData);
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myid" /></code></pre>
</div>
</div>
</p>
<p>Note that getting the data from the clipboard only gets you the pasted text, while waiting for the inputs value to update is the only solution above that actually gets the entire value of the input, including the newly pasted text.</p> |
9,335,434 | What's the difference between performSelectorOnMainThread: and dispatch_async() on main queue? | <p>I was having problems modifying a view inside a thread. I tried to add a subview but it took around 6 or more seconds to display. I finally got it working, but I don't know how exactly. So I was wondering why it worked and what's the difference between the following methods:</p>
<ol>
<li>This worked -added the view instantly:</li>
</ol>
<pre><code>dispatch_async(dispatch_get_main_queue(), ^{
//some UI methods ej
[view addSubview: otherView];
}
</code></pre>
<ol start="2">
<li>This took around 6 or more seconds to display:</li>
</ol>
<pre><code>[viewController performSelectorOnMainThread:@selector(methodThatAddsSubview:) withObject:otherView
waitUntilDone:NO];
</code></pre>
<ol start="3">
<li><code>NSNotification</code> methods - took also around 6 seconds to display the observer was in the viewController I wanted to modify paired to a method to add a subview.</li>
</ol>
<pre><code>[[NSNotificationCenter defaultCenter] postNotificationName:
@"notification-identifier" object:object];
</code></pre>
<p>For reference these were called inside this <code>CompletionHandler</code> of the class <code>ACAccountStore</code>.</p>
<pre><code>accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
// my methods were here
}
}
</code></pre> | 9,336,253 | 3 | 4 | null | 2012-02-17 21:10:14.653 UTC | 21 | 2020-07-31 15:16:01.467 UTC | 2020-07-31 15:16:01.467 UTC | null | 3,841,734 | null | 572,978 | null | 1 | 57 | objective-c|ios|multithreading|uikit|grand-central-dispatch | 22,442 | <p>By default, <code>-performSelectorOnMainThread:withObject:waitUntilDone:</code> only schedules the selector to run in the default run loop mode. If the run loop is in another mode (e.g. the tracking mode), it won't run until the run loop switches back to the default mode. You can get around this with the variant <code>-performSelectorOnMainThread:withObject:waitUntilDone:modes:</code> (by passing all the modes you want it to run in).</p>
<p>On the other hand, <code>dispatch_async(dispatch_get_main_queue(), ^{ ... })</code> will run the block as soon as the main run loop returns control flow back to the event loop. It doesn't care about modes. So if you don't want to care about modes either, <code>dispatch_async()</code> may be the better way to go.</p> |
18,305,844 | C++, best way to change a string at a particular index | <p>I want to change a C++ string at a particular index like this:</p>
<pre><code>string s = "abc";
s[1] = 'a';
</code></pre>
<p>Is the following code valid? Is this an acceptable way to do this?</p>
<p>I didn't find any reference which says it is valid:</p>
<p><a href="http://www.cplusplus.com/reference/string/string/">http://www.cplusplus.com/reference/string/string/</a></p>
<p>Which says that through "overloaded [] operator in string" we can perform the write operation.</p> | 18,305,897 | 4 | 5 | null | 2013-08-19 03:03:40.25 UTC | 12 | 2021-12-20 14:55:22.98 UTC | 2013-08-19 03:10:03.84 UTC | null | 445,131 | null | 690,639 | null | 1 | 39 | c++|string | 81,096 | <p>Assigning a character to an <code>std::string</code> at an index will produce the correct result, for example:</p>
<pre><code>#include <iostream>
int main() {
std::string s = "abc";
s[1] = 'a';
std::cout << s;
}
</code></pre>
<p>For those of you below doubting my IDE/library setup, see jdoodle demo: <a href="http://jdoodle.com/ia/ljR" rel="noreferrer">http://jdoodle.com/ia/ljR</a>, and screenshot: <a href="https://imgur.com/f21rA5R" rel="noreferrer">https://imgur.com/f21rA5R</a></p>
<p>Which prints <code>aac</code>. The drawback is you risk accidentally writing to un-assigned memory if string s is blankstring or you write too far. C++ will gladly write off the end of the string, and that causes undefined behavior.</p>
<p>A safer way to do this would be to use <code>string::replace</code>: <a href="http://cplusplus.com/reference/string/string/replace" rel="noreferrer">http://cplusplus.com/reference/string/string/replace</a></p>
<p>For example</p>
<pre><code>#include <iostream>
int main() {
std::string s = "What kind of king do you think you'll be?";
std::string s2 = "A good king?";
// pos len str_repl
s.replace(40, 1, s2);
std::cout << s;
//prints: What kind of king do you think you'll beA good king?
}
</code></pre>
<p>The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there's no undefined behavior.</p> |
18,485,378 | Vertically centering text within an inline-block | <p>I'm trying to create some buttons for a website using styled hyperlinks. I have managed to get the button looking how I want, bar one slight issue. I can't get the text ('Link' in the source code below) to vertically center.</p>
<p>Unfortunately there may be more than one line of text as demonstrated with the second button so I can't use <code>line-height</code> to vertically center it.</p>
<p>My initial solution was to use <code>display: table-cell;</code> rather than <code>inline-block</code>, and that sorts the issue in Chrome, Firefox and Safari but not in Internet Explorer so I'm thinking I need to stick to inline-block.</p>
<p>How would I go about vertically centering the link text within the <code>57px</code> x <code>100px</code> <code>inline-block</code>, and have it cater to multiple lines of text? Thanks in advance.</p>
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code>.button {
background-image:url(/images/categorybutton-off.gif);
color:#000;
display:inline-block;
height:57px;
width:100px;
font-family:Verdana, Geneva, sans-serif;
font-size:10px;
font-weight:bold;
text-align:center;
text-decoration:none;
vertical-align:middle;
}
.button:hover {
background-image:url(/images/categorybutton-on.gif);
}
.button:before {
content:"Click Here For\A";
font-style:italic;
font-weight:normal !important;
white-space:pre;
}
</code></pre>
<p><strong>HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><a href="/" class="button">Link</a>
<a href="/" class="button">Link<br />More Details</a>
</code></pre> | 18,485,534 | 4 | 0 | null | 2013-08-28 10:28:13.27 UTC | 10 | 2022-06-08 00:06:18.577 UTC | 2013-08-28 11:48:04.53 UTC | null | 1,725,764 | null | 2,724,946 | null | 1 | 33 | html|vertical-alignment|centering|css | 42,961 | <p>Wrap your text with a span (Centered), and write another empty span just before it(Centerer) like this.</p>
<p><strong>HTML:</strong></p>
<pre><code><a href="..." class="button">
<span class="Centerer"></span>
<span class='Centered'>Link</span>
</a>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.Centered
{
vertical-align: middle;
display: inline-block;
}
.Centerer
{
display: inline-block;
height: 100%;
vertical-align: middle;
}
</code></pre>
<p>Take a look here: <a href="http://jsfiddle.net/xVnQ6/" rel="noreferrer">http://jsfiddle.net/xVnQ6/</a></p> |
18,310,007 | Add html link in anyone of ng-grid | <p>I want to add link to ng-grid.
Here is my code for your reference </p>
<pre><code><html ng-app="myApp">
<head lang="en">
<meta charset="utf-8">
<title>Getting Started With ngGrid Example</title>
<link href="../../Content/ng-grid.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="../../Scripts/angular.js" type="text/javascript"></script>
<script src="../../Scripts/ng-grid.js" type="text/javascript"></script>
<script src="../../Scripts/main.js" type="text/javascript"></script>
<script type="text/javascript">
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [{ name: "RK.PRABAKAR", age: 25, href: "<a href='#'>Link1</a>" },
{ name: "Yoga", age: 27, href: "<a href='#'>Link1</a>" },
{ name: "James", age: 27, href: "<a href='#'>Link1</a>" },
{ name: "Siva", age: 35, href: "<a href='#'>Link1</a>" },
{ name: "KK", age: 27, href: "<a href='#'>Link1</a>"}];
$scope.pagingOptions = {
pageSizes: [2, 4, 6],
pageSize: 2,
currentPage: 1
};
$scope.gridOptions = {
data: 'myData',
enablePaging: true,
showFooter: true,
enableCellSelection: true,
enableRowSelection: false,
enablePinning: true,
pagingOptions: $scope.pagingOptions,
enableCellEdit: true,
columnDefs: [{ field: 'name', displayName: 'Name', enableCellEdit: true },
{ field: 'age', displayName: 'Age', enableCellEdit: true },
{ field: 'href', displayName: 'Link', enableCellEdit: false }]
};
});
</script>
<style>
.gridStyle {
border: 1px solid rgb(212,212,212);
width: 500px;
height: 300px;
}
</style>
</head>
<body data-ng-controller="MyCtrl">
<div class="gridStyle" data-ng-grid="gridOptions"></div>
</body>
</code></pre>
<p></p>
<p>Right now data grid is working fine except href link in grid.
Link is not rendered to html tag it is displayed as normal string.
I want to add link to ng-grid from myData</p> | 18,318,804 | 5 | 0 | null | 2013-08-19 09:02:31.72 UTC | 16 | 2017-12-04 14:08:45.073 UTC | 2013-08-19 10:34:57.183 UTC | null | 1,616,483 | null | 1,616,483 | null | 1 | 19 | angular-ui|ng-grid | 29,648 | <p><strong>Update:</strong></p>
<p>It has been noted that this answer does not work with <code>ui-grid</code>. This is understandable since at the time of the answer only <code>ng-grid</code> existed; however, substituting <code>{{COL_FIELD}}</code> in place of <code>{{row.getProperty(col.field)}}</code> allows the solution to be valid for both <code>ng-grid</code> and <code>ui-grid</code>.</p>
<p>I know I used <code>COL_FIELD</code> in these situations around the time I wrote this answer, so I'm not sure of my rationale for answering with the longer <code>row.getProperty(col.field)</code>…but in any event, use <code>COL_FIELD</code> and you should be good to go with <code>ng-grid</code> and <code>ui-grid</code>.</p>
<p><strong>Original</strong> (unchanged) <strong>Answer:</strong></p>
<p>You just need to define a cell template for the Link field…</p>
<p>You can do this inline:</p>
<pre><code>{
field: 'href',
displayName: 'Link',
enableCellEdit: false,
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><a href="{{row.getProperty(col.field)}}">Visible text</a></div>'
}
</code></pre>
<p>Or you can do this by using a variable (to keep your gridOptions a little cleaner:</p>
<pre><code>var linkCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()">' +
' <a href="{{row.getProperty(col.field)}}">Visible text</a>' +
'</div>';
{
field: 'href',
displayName: 'Link',
enableCellEdit: false,
cellTemplate: linkCellTemplate
}
</code></pre>
<p>Or you could even put your template in an external HTML file and point to the URL:</p>
<pre><code>{
field: 'href',
displayName: 'Link',
enableCellEdit: false,
cellTemplate: 'linkCellTemplate.html'
}
</code></pre>
<p>…and you only need to store the URL as <code>href</code> in <code>myData</code> to work with this solution :)</p>
<p><a href="http://angular-ui.github.io/ng-grid/#templates">Look here for an example of a cell template.</a></p> |
19,902,644 | DIV table-cell width 100% | <p>Here is my code:</p>
<pre><code><div style='display: table'>
<div style='height:200px; width:100%; text-align: center; display: table-cell; vertical-align: middle'>No result found</div>
</div>
</code></pre>
<p>Why is that the <code>width:100%</code> is not working? How can I solve it?</p> | 19,902,699 | 3 | 2 | null | 2013-11-11 09:15:01.457 UTC | 2 | 2019-03-28 18:25:10.35 UTC | null | null | null | null | 1,995,781 | null | 1 | 8 | html|css | 41,589 | <p>Try giving <code>width: 100%</code> to parent so that the child has full width.</p>
<pre><code><div style='display: table; width:100%; background:#f00;'>
<div style='height:200px; width:100%; text-align: center; display: table-cell; vertical-align: middle'>No result found</div>
</div>
</code></pre> |
19,857,749 | What is the reliable method to find most time consuming part of the code? | <p>Along my source code I try to capture and measure the time release of a segment in Python. How can I measure that segment pass time in a convenient way with good precision?</p> | 19,857,889 | 1 | 2 | null | 2013-11-08 11:16:11.667 UTC | 10 | 2014-01-31 11:31:18.893 UTC | 2013-11-14 20:41:43.637 UTC | null | 2,622,293 | null | 648,896 | null | 1 | 27 | python|profiling|performance | 6,357 | <p>Use a <strong>profiler</strong>.</p>
<p>Python's <a href="http://docs.python.org/2/library/profile.html#module-cProfile" rel="noreferrer"><code>cProfile</code></a> is included in the standard libary.</p>
<p>For an even more convenient way, use the package <a href="https://pypi.python.org/pypi/profilestats/" rel="noreferrer"><code>profilestats</code></a>. Then you can use a decorator to just decorate the functions you want to profile:</p>
<pre><code>from profilestats import profile
@profile
def my_function(args, etc):
pass
</code></pre>
<p>This will cause a summary like this to be printed on STDOUT:</p>
<pre><code> 6 function calls in 0.026 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.026 0.026 some_code.py:3(some_func)
2 0.019 0.010 0.026 0.013 some_code.py:9(expensive_func)
2 0.007 0.003 0.007 0.003 {range}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
</code></pre>
<p>The much more useful info however is in the <code>cachegrind.out.profilestats</code> file generated. You can open this file with a tools that can visualize cachegrind statistics, for example <a href="http://www.vrplumber.com/programming/runsnakerun/" rel="noreferrer">RunSnakeRun</a> and get nice, easy (or easier) to read visualizations of your call stack like this:</p>
<p><a href="https://i.imgur.com/YL6qcCb.png" rel="noreferrer"><img src="https://i.imgur.com/YL6qcCb.png" alt="RunSnakeRun" /></a></p>
<p><strong>Update</strong>: Both pull requests for <a href="https://github.com/hannosch/profilestats/pull/1" rel="noreferrer"><code>profilestats</code></a> and <a href="https://github.com/pwaller/pyprof2calltree/pull/2" rel="noreferrer"><code>pyprof2calltree</code></a> have been merged, so they now support Python 3.x as well.</p> |
19,858,251 | HTTP status code 0 - Error Domain=NSURLErrorDomain? | <p>I am working on an iOS project. </p>
<p>In this application, I am downloading images from the server.</p>
<p><strong>Problem:</strong></p>
<p>While downloading images I am getting <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">Request Timeout</a>. According to documentation HTTP status code of request timeout is <code>408</code>.</p>
<p>But in my application, I am getting HTTP status code <code>0</code> with the following error</p>
<blockquote>
<p>Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
UserInfo=0xb9af710
{NSErrorFailingURLStringKey=<a href="http://xxxx.com/resources/p/PNG/1383906967_5621_63.jpg" rel="noreferrer">http://xxxx.com/resources/p/PNG/1383906967_5621_63.jpg</a>,
NSErrorFailingURLKey=<a href="http://xxxx.com/resources/p/PNG/1383906967_5621_63.jpg" rel="noreferrer">http://xxxx.com/resources/p/PNG/1383906967_5621_63.jpg</a>,
NSLocalizedDescription=The request timed out.,
NSUnderlyingError=0x13846870 "The request timed out."}</p>
</blockquote>
<p>During a search, over internet, I found no information about HTTP Status Code 0. </p>
<p>Can anyone explain this to me?</p> | 19,862,540 | 13 | 3 | null | 2013-11-08 11:40:05.027 UTC | 16 | 2022-03-30 07:17:47.26 UTC | 2019-01-18 10:03:17.787 UTC | null | 9,215,780 | null | 1,058,406 | null | 1 | 107 | http|download|http-status-codes|nserror | 371,311 | <p>There is no HTTP status code 0. What you see is a 0 returned by the API/library that you are using. You will have to check the documentation for that.</p> |
27,599,311 | Tkinter.PhotoImage doesn't not support png image | <p>I am using Tkinter to write a GUI and want to display a png file in a <code>Tkiner.Label</code>.
So I have some code like this:</p>
<pre><code>self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)
</code></pre>
<p>This code <strong>runs correctly on my Linux machine</strong>. But when I run it on my windows machine, it fails. I also tested on several other machines (include windows and linux), it failed all the time.</p>
<p>The Traceback is:</p>
<pre class="lang-none prettyprint-override"><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
SignupBox(self, self.server)
File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
self.refresh_vcode()
File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported
</code></pre>
<p>If I delete <code>format='png'</code> in the source code, the traceback will become:</p>
<pre class="lang-none prettyprint-override"><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
SignupBox(self, self.server)
File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
self.refresh_vcode()
File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
self.vcode.img = PhotoImage(data=open('test.png').read())
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data
</code></pre>
<p>So, what should I do to make it support png files?</p> | 27,601,573 | 8 | 6 | null | 2014-12-22 08:49:15.743 UTC | null | 2022-02-13 14:06:07.127 UTC | 2019-01-15 23:33:16.58 UTC | null | 355,230 | null | 3,745,963 | null | 1 | 5 | python|linux|tkinter|tk | 52,611 | <p>tkinter only supports 3 file formats off the bat which are GIF, PGM, and PPM. You will either need to convert the files to .GIF then load them (Far easier, but as jonrsharpe said, nothing will work without converting the file first) or you can port your program to Python 2.7 and use the Python Imaging Library (PIL) and its tkinter extensions to use a PNG image.</p>
<p>A link that you might find useful: <a href="http://effbot.org/tkinterbook/photoimage.htm" rel="noreferrer">http://effbot.org/tkinterbook/photoimage.htm</a></p> |
27,652,227 | Add placeholder text inside UITextView in Swift? | <p>How can I add a placeholder in a <code>UITextView</code>, similar to the one you can set for <code>UITextField</code>, in <code>Swift</code>?</p> | 27,652,289 | 44 | 10 | null | 2014-12-26 02:12:05.47 UTC | 162 | 2022-07-21 12:06:49.5 UTC | 2020-09-25 15:37:11.813 UTC | user7219949 | 14,016,301 | null | 4,392,705 | null | 1 | 393 | ios|swift|uitextview|placeholder | 342,100 | <p><strong>Updated for Swift 4</strong></p>
<p><code>UITextView</code> doesn't inherently have a placeholder property so you'd have to create and manipulate one programmatically using <code>UITextViewDelegate</code> methods. I recommend using either solution #1 or #2 below depending on the desired behavior.</p>
<p><strong>Note: For either solution, add <code>UITextViewDelegate</code> to the class and set <code>textView.delegate = self</code> to use the text view’s delegate methods.</strong></p>
<hr>
<p><strong><em>Solution #1</strong> - If you want the placeholder to disappear as soon as the user selects the text view:</em></p>
<p>First set the <code>UITextView</code> to contain the placeholder text and set it to a light gray color to mimic the look of a <code>UITextField</code>'s placeholder text. Either do so in the <code>viewDidLoad</code> or upon the text view's creation.</p>
<pre><code>textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
</code></pre>
<p>Then when the user begins to edit the text view, if the text view contains a placeholder (i.e. if its text color is light gray) clear the placeholder text and set the text color to black in order to accommodate the user's entry.</p>
<pre><code>func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
</code></pre>
<p>Then when the user finishes editing the text view and it's resigned as the first responder, if the text view is empty, reset its placeholder by re-adding the placeholder text and setting its color to light gray.</p>
<pre><code>func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
}
}
</code></pre>
<hr>
<p><strong><em>Solution #2</strong> - If you want the placeholder to show whenever the text view is empty, even if the text view’s selected:</em></p>
<p>First set the placeholder in the <code>viewDidLoad</code>:</p>
<pre><code>textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
textView.becomeFirstResponder()
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
</code></pre>
<p>(Note: Since the OP wanted to have the text view selected as soon as the view loads, I incorporated text view selection into the above code. If this is not your desired behavior and you do not want the text view selected upon view load, remove the last two lines from the above code chunk.)</p>
<p>Then utilize the <code>shouldChangeTextInRange</code> <code>UITextViewDelegate</code> method, like so:</p>
<pre><code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Combine the textView text and the replacement text to
// create the updated text string
let currentText:String = textView.text
let updatedText = (currentText as NSString).replacingCharacters(in: range, with: text)
// If updated text view will be empty, add the placeholder
// and set the cursor to the beginning of the text view
if updatedText.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
// Else if the text view's placeholder is showing and the
// length of the replacement string is greater than 0, set
// the text color to black then set its text to the
// replacement string
else if textView.textColor == UIColor.lightGray && !text.isEmpty {
textView.textColor = UIColor.black
textView.text = text
}
// For every other case, the text should change with the usual
// behavior...
else {
return true
}
// ...otherwise return false since the updates have already
// been made
return false
}
</code></pre>
<p>And also implement <code>textViewDidChangeSelection</code> to prevent the user from changing the position of the cursor while the placeholder's visible. (Note: <code>textViewDidChangeSelection</code> is called before the view loads so only check the text view's color if the window is visible):</p>
<pre><code>func textViewDidChangeSelection(_ textView: UITextView) {
if self.view.window != nil {
if textView.textColor == UIColor.lightGray {
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
}
}
</code></pre> |
15,326,792 | Select column 2 to last column in R | <p>I have a data frame with multiple columns. Now, I want to get rid of the row.names column (column 1), and thus I try to select all the other columns.</p>
<p>E.g., </p>
<pre><code>newdata <- olddata[,2:10]
</code></pre>
<p>is there a default symbol for the last column so I don't have to count all the columns?
I tried</p>
<pre><code>newdata <- olddata[,2:]
</code></pre>
<p>but it didn't work.</p> | 15,326,846 | 4 | 6 | null | 2013-03-10 19:53:19.06 UTC | 3 | 2021-11-22 02:32:39.17 UTC | 2013-03-10 20:11:40.74 UTC | null | 559,784 | user2015601 | null | null | 1 | 20 | r|dataframe|multiple-columns | 64,300 | <p>I think it's better to focus on <em>wanting to get rid of one column of data</em> and not wanting to select every other column. You can do this as @Arun suggested:</p>
<pre><code>olddata[,-1]
</code></pre>
<p>Or:</p>
<pre><code>olddata$ColNameToDelete <- NULL
</code></pre> |
43,755,888 | How to convert a boto3 Dynamo DB item to a regular dictionary in Python? | <p>In Python, when an item is retrieved from Dynamo DB using boto3, a schema like the following is obtained.</p>
<pre><code>{
"ACTIVE": {
"BOOL": true
},
"CRC": {
"N": "-1600155180"
},
"ID": {
"S": "bewfv43843b"
},
"params": {
"M": {
"customer": {
"S": "TEST"
},
"index": {
"N": "1"
}
}
},
"THIS_STATUS": {
"N": "10"
},
"TYPE": {
"N": "22"
}
}
</code></pre>
<p>Also when inserting or scanning, dictionaries have to be converted in this fashion. I haven't been able to find a wrapper that takes care of such conversion. Since apparently boto3 does not support this, are there better alternatives than implementing code for it? </p> | 46,738,251 | 3 | 5 | null | 2017-05-03 09:17:17.98 UTC | 18 | 2021-06-28 14:16:43.773 UTC | null | null | null | null | 5,356,688 | null | 1 | 50 | python|amazon-web-services|dictionary|amazon-dynamodb|boto3 | 32,565 | <p>In order to understand how to solve this, it's important to recognize that boto3 has two basic modes of operation: one that uses the low-level <a href="http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#client" rel="noreferrer">Client</a> API, and one that uses higher level abstractions like <a href="http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#table" rel="noreferrer">Table</a>. The data structure shown in the question is an example of what is consumed/produced by the low-level API, which is also used by the AWS CLI and the dynamodb web services.</p>
<p>To answer your question - if you can work exclusively with the high-level abstractions like <em>Table</em> when using boto3 then things will be quite a bit easier for you, as the comments suggest. Then you can sidestep the whole problem - python types are marshaled to and from the low-level data format for you.</p>
<p>However, there are some times when it's not possible to use those high-level constructs exclusively. I specifically ran into this problem when dealing with DynamoDB streams attached to Lambdas. The inputs to the lambda are always in the low-level format, and that format is harder to work with IMO.</p>
<p>After some digging I found that boto3 itself has some nifty features tucked away for doing conversions. These features are used implicitly in all of the internal conversions mentioned previously. To use them directly, import the TypeDeserializer/TypeSerializer classes and combine them with dict comprehensions like so:</p>
<pre><code>import boto3
low_level_data = {
"ACTIVE": {
"BOOL": True
},
"CRC": {
"N": "-1600155180"
},
"ID": {
"S": "bewfv43843b"
},
"params": {
"M": {
"customer": {
"S": "TEST"
},
"index": {
"N": "1"
}
}
},
"THIS_STATUS": {
"N": "10"
},
"TYPE": {
"N": "22"
}
}
# Lazy-eval the dynamodb attribute (boto3 is dynamic!)
boto3.resource('dynamodb')
# To go from low-level format to python
deserializer = boto3.dynamodb.types.TypeDeserializer()
python_data = {k: deserializer.deserialize(v) for k,v in low_level_data.items()}
# To go from python to low-level format
serializer = boto3.dynamodb.types.TypeSerializer()
low_level_copy = {k: serializer.serialize(v) for k,v in python_data.items()}
assert low_level_data == low_level_copy
</code></pre> |
38,418,482 | RecyclerView.ViewHolder unable to bind view with ButterKnife | <p>I'm using <code>ButterKnife</code> to bind my views on my <code>ViewHolder</code>. My code is below:</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<DataObject> data;
public MyAdapter(List<DataObject> data) {
this.data = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
return new ViewHolder(view);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.row_header_view) View rowHeaderView;
@BindView(R.id.row_header_view_text) TextView headerTextView;
@BindView(R.id.row_data_view) View rowDataView;
@BindView(R.id.row_data_view_text) TextView rowDataTextView;
@BindView(R.id.row_data_view_detail_text) TextView rowDataDetailTextView;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
</code></pre>
<p>For some reason in my <code>ViewHolder</code> all of the <code>BindView</code>'s do nothing. They are all null. I can confirm with certainty they are in my layout. What is wrong with my above code? I have used it as per the documentation listed here:</p>
<p><a href="http://jakewharton.github.io/butterknife/#reset">http://jakewharton.github.io/butterknife/#reset</a></p>
<p>Is there anything else required? I'm using <code>ButterKnife</code> version:</p>
<pre><code>compile 'com.jakewharton:butterknife:8.2.1'
</code></pre>
<p>If I add the below line:</p>
<pre><code>rowHeaderView = view.findViewById(R.id.row_header_view);
</code></pre>
<p>It's able to get the view properly. But how does this make sense? Isn't <code>ButterKnife</code> usable where <code>findViewById</code> is usable?</p> | 38,419,000 | 2 | 3 | null | 2016-07-17 06:16:28.683 UTC | 1 | 2017-01-02 11:27:52.577 UTC | 2016-07-17 08:21:24.57 UTC | null | 1,233,366 | null | 1,233,366 | null | 1 | 29 | android|android-layout|data-binding|android-adapter|butterknife | 17,545 | <p>Make sure that if you have use <code>ButterKnife</code> library to use this way</p>
<p><strong>build.gradle</strong> file of Project</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
</code></pre>
<p>Then, apply the <code>'android-apt'</code> plugin in your <code>module-level build.gradle</code> and add the Butter Knife dependencies:</p>
<pre><code>apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.2.1'
apt 'com.jakewharton:butterknife-compiler:8.2.1'
}
</code></pre> |
19,325,240 | Difference between char **p,char *p[],char p[][] | <pre><code>char *p = "some string"
</code></pre>
<p>creates a pointer p pointing to a block containing the string.</p>
<pre><code>char p[] = "some string"
</code></pre>
<p>creates a character array and with literals in it.</p>
<p>And the first one is a constant declaration.Is it the same of two-dimensional arrays?</p>
<p>what is the difference between </p>
<pre><code>char **p,char *p[],char p[][].
</code></pre>
<p>I read a bit about this that char **p creates an array of pointers so it has an overhead compared to <code>char p[][]</code> for storing the pointer values.</p>
<p>the first two declarations create constant arrays.i did not get any run time error when i tried to modify the contents of <code>argv</code> in <code>main(int argc,char **argv)</code>. Is it because they are declared in function prototype?</p> | 19,325,640 | 3 | 8 | null | 2013-10-11 18:52:23.61 UTC | 16 | 2022-03-29 09:31:20.43 UTC | 2013-10-11 18:57:29.79 UTC | null | 1,885,193 | null | 2,811,020 | null | 1 | 15 | c | 18,549 | <h2>Normal Declarations (Not Function Parameters)</h2>
<p><code>char **p;</code> declares a pointer to a pointer to <code>char</code>. It reserves space for the pointer. It does not reserve any space for the pointed-to pointers or any <code>char</code>.</p>
<p><code>char *p[N];</code> declares an array of <em>N</em> pointers to <code>char</code>. It reserves space for <em>N</em> pointers. It does not reserve any space for any <code>char</code>. <code>N</code> must be provided explicitly or, in a definition with initializers, implicitly by letting the compiler count the initializers.</p>
<p><code>char p[M][N];</code> declares an array of <em>M</em> arrays of <em>N</em> <code>char</code>. It reserves space for <em>M</em>•<i>N</i> <code>char</code>. There are no pointers involved. <code>N</code> must be provided explicitly. <code>M</code> must be provided explicitly or, in a definition with initializers, implicitly by letting the compiler count the initializers.</p>
<h2>Declarations in Function Parameters</h2>
<p><code>char **p</code> declares a pointer to a pointer to <code>char</code>. When the function is called, space is provided for that pointer (typically on a stack or in a processor register). No space is reserved for the pointed-to-pointers or any <code>char</code>.</p>
<p><code>char *p[N]</code> is adjusted to be <code>char **p</code>, so it is the same as above. The value of <code>N</code> is ignored, and <code>N</code> may be absent. (Some compilers may evaluate <code>N</code>, so, if it is an expression with side effects, such as <code>printf("Hello, world.\n")</code>, these effects may occur when the function is called. The C standard is unclear on this.)</p>
<p><code>char p[M][N]</code> is adjusted to be <code>char (*p)[N]</code>, so it is a pointer to an array of <em>N</em> <code>char</code>. The value of <code>M</code> is ignored, and <code>M</code> may be absent. <code>N</code> must be provided. When the function is called, space is provided for the pointer (typically on a stack or in a processor register). No space is reserved for the array of <em>N</em> <code>char</code>.</p>
<h2>argv</h2>
<p><code>argv</code> is created by the special software that calls <code>main</code>. It is filled with data that the software obtains from the “environment”. You are allowed to modify the <code>char</code> data in it.</p>
<p>In your definition <code>char *p = "some string";</code>, you are not permitted to modify the data that <code>p</code> points to because the C standard says that characters in a string literal may not be modified. (Technically, what it says is that it does not define the behavior if you try.) In this definition, <code>p</code> is not an array; it is a pointer to the first <code>char</code> in an array, and those <code>char</code> are inside a string literal, and you are not permitted to modify the contents of a string literal.</p>
<p>In your definition <code>char p[] = "some string";</code>, you may modify the contents of <code>p</code>. They are not a string literal. In this case, the string literal effectively does not exist at run-time; it is only something used to specify how the array <code>p</code> is initialized. Once <code>p</code> is initialized, you may modify it.</p>
<p>The data set up for <code>argv</code> is set up in a way that allows you to modify it (because the C standard specifies this).</p> |
8,971,152 | Is text-indent: -9999px a bad technique for replacing text with images, and what are the alternatives? | <p><a href="http://luigimontanez.com/2010/stop-using-text-indent-css-trick/" rel="noreferrer">This article</a> say we should avoid using this technique. <a href="http://aext.net/2010/02/css-text-indent-style-your-html-form/" rel="noreferrer">This one</a> says it's awesome. Is it true that Google looks inside CSS files for <code>text-indent: -9999px;</code> and punishes you? :|</p>
<p>I'm using that property <strong>a lot</strong> to hide text. For example, I have a button that is represented by an icon:</p>
<p><code><a href="#" class="mybutton">do Stuff</a></code></p>
<p>The CSS:</p>
<pre><code>.mybutton{
text-indent: -9999px;
background: transparent url(images/SpriteWithButtons.png) no-repeat 20px 20px;
display: block;
width: 16px;
height: 16px;
}
</code></pre>
<p>I don't see any alternative to my code. If I replace that with an image I automatically get +20 HTTP requests for each button image.</p>
<p>If I make the link empty, it is less accessibile because screen readers won't know what that is. And empty links look weird, probably Google doesn't like that either...</p>
<p>So what's the best way to handle such situations?</p> | 12,286,560 | 5 | 3 | null | 2012-01-23 11:51:19.577 UTC | 12 | 2012-11-09 13:58:04.483 UTC | 2012-01-23 12:14:09.957 UTC | null | 20,578 | null | 376,947 | null | 1 | 26 | html|css|seo|text-indent | 15,053 | <p>A good reason not to use the -9999px method is that the browser has to draw a 9999px box for each element that this is applied to. Obviously, that potentially creates quite a performance hit, especially if you're applying it to multiple elements.</p>
<p>Alternative methods include this one (from <a href="http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/" rel="noreferrer">zeldman.com</a>):</p>
<pre><code>text-indent: 100%; white-space: nowrap; overflow: hidden;
</code></pre>
<p>...or alternatively (from <a href="http://bustoutsolutions.com/blog/2009/10/08/better-alternative-to-text-indent-9999px" rel="noreferrer">here</a>):</p>
<pre><code>height: 0; overflow: hidden; padding-top: 20px;
</code></pre>
<p>(where 'padding-top' is the height you want the element to be).</p>
<p>I think the first method is neater, since it lets you set height in the normal way, but I've found the second one to work better in IE7</p> |
8,941,098 | Full-width Spinner in ActionBar | <p>I'd really like my app to have a Spinner which stretches the entire length of my ActionBar, like the one in Gmail 4.0. Anyone know how to achieve this? Even if I set "match_parent" in the Spinner layout resource, it doesn't fill the entire bar. Preferably, I'd like to be able to have it fill the entire bar except for my action items, rather than using the split actionbar as well.</p>
<p><strong>EDIT</strong>: see my answer below for an implementation using the built-in actionbar, or hankystyles' when using a custom view</p>
<p><img src="https://i.stack.imgur.com/FhHRJ.png" alt="enter image description here"></p> | 9,193,240 | 4 | 3 | null | 2012-01-20 11:58:44.537 UTC | 20 | 2013-05-25 20:52:02.543 UTC | 2013-05-25 20:52:02.543 UTC | null | 428,665 | null | 428,665 | null | 1 | 29 | android|android-layout|android-actionbar | 15,957 | <p>Bit annoying that I've just done it, but here is a method of doing it using the built-in Spinner in the action bar. All you need to do is make your spinner item's main container a <code>RelativeLayout</code> and set its gravity to fillHorizontal, like so:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal"
android:orientation="vertical" >
<TextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="-4dip"
android:text="@string/gen_placeholder"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/TextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@android:id/text1"
android:text="@string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</code></pre>
<p>And initialising the Adapter as so:</p>
<pre><code>ArrayAdapter<CharSequence> barAdapter = new ArrayAdapter<CharSequence>(this, R.layout.subtitled_spinner_item,
android.R.id.text1, getResources().getStringArray(R.array.actionList));
barAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
</code></pre>
<p>which then gives the required spinner spanning the entire actionbar (except for the action buttons): </p>
<p><img src="https://i.stack.imgur.com/8RBGW.png" alt="Spanned actionbar"></p> |
5,391,280 | How to insert a column in a specific position in oracle without dropping and recreating the table? | <p>I have a specific scenario where i have to insert two new columns in an existing table in Oracle. I can not do the dropping and recreating the table. So can it be achieved by any means??</p> | 5,392,204 | 4 | 5 | null | 2011-03-22 12:34:40.967 UTC | 6 | 2021-05-18 07:35:33.483 UTC | 2011-04-04 06:06:11.293 UTC | null | 409,172 | null | 239,999 | null | 1 | 32 | oracle|oracle11g | 127,382 | <p>Amit-</p>
<p>I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:</p>
<pre><code>CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
</code></pre>
<p>Drop the table you want to add columns to:</p>
<pre><code>DROP TABLE TABLE_TO_CHANGE;
</code></pre>
<p>It's at the point you could rebuild the existing table from scratch adding in the columns where you wish.
Let's assume for this exercise you want to add the columns named "COL2 and COL3".</p>
<p>Now insert the data back into the new table: </p>
<pre><code>INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
</code></pre>
<p>When the data is inserted into your "new-old" table, you can drop the temp table.</p>
<pre><code>DROP TABLE MY_TEMP_TABLE;
</code></pre>
<p>This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.</p>
<p>-CJ</p> |
5,478,848 | Does Apple reject "mobile web shell" applications? | <p>I'm not sure how to word this correctly, so I'm going to be a little verbose:</p>
<p>I'm tasked with building an app for my company that will just load a mobile website into a barebones browser with no address bar or anything. So basically the app will be just the same as if the user had navigated there in Safari (sans normal browser controls).</p>
<p>My question is: does Apple reject this sort of app because of it just being a wrapper around a mobile site? I'm totally lost on this, as I've never developed for iOS before and have no idea what kinds of roadblocks i might hit.</p> | 5,478,893 | 4 | 1 | null | 2011-03-29 20:59:02.863 UTC | 11 | 2019-07-11 07:06:53.36 UTC | null | null | null | null | 462,252 | null | 1 | 43 | iphone|ipad | 21,857 | <p>Apple may reject your app if all it does is wrap a web site in a UIWebView. You need to have more functionality in your app than just loading a web page.</p>
<p>From the <a href="https://developer.apple.com/app-store/review/guidelines/" rel="nofollow noreferrer">app review guidelines</a> for iOS:</p>
<blockquote>
<h3>4.2 Minimum Functionality</h3>
<p>Your app should include features, content, and UI that elevate it <strong>beyond a repackaged website</strong>. If your app is not particularly useful, unique, or “app-like,” it doesn’t belong on the App Store. If your App doesn’t provide some sort of lasting entertainment value, it may not be accepted.</p>
</blockquote>
<p>You may want to investigate developing your company's app as a mobile web app. There's plenty of <a href="https://developer.apple.com/safari/" rel="nofollow noreferrer">information published by Apple</a> (and others) about how to write mobile web apps that function similarly to native iOS apps.</p> |
5,398,772 | Firefox 4 onBeforeUnload custom message | <p>In Firefox <strong>3</strong>, I was able to write a custom confirmation popup with:</p>
<pre><code>window.onbeforeunload = function() {
if (someCondition) {
return 'Your stream will be turned off';
}
}
</code></pre>
<p>Now in Firefox <strong>4</strong>, it does not show my custom message. The default message that it provides is not even accurate to what my application does.</p>
<p><img src="https://i.stack.imgur.com/4gaoU.png" alt="firefox 4 confirm"></p>
<p>Can this default message be overridden?</p> | 5,398,788 | 4 | 1 | null | 2011-03-22 22:44:42.1 UTC | 10 | 2015-05-20 16:40:35.367 UTC | null | null | null | null | 459,987 | null | 1 | 70 | javascript|firefox|firefox4 | 49,650 | <p>From <a href="https://developer.mozilla.org/en/DOM/window.onbeforeunload" rel="noreferrer">MDN</a>:</p>
<blockquote>
<p>Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=588292" rel="noreferrer">588292</a>.</p>
</blockquote>
<p>This "Bug" is actually a (imho questionable) feature.. so there's no way to display the message in Firefox 4. If you think it should be changed, comment on that bug so the Firefox developers will know that people actually want to be able to show a custom string.</p> |
5,495,965 | how can I set visible back to true in jquery | <p>I am using the following code to hide a dropdown box:</p>
<pre><code> <asp:DropDownList ID="test1" runat="server" DataSourceID="dsTestType" CssClass="maptest1" visible="false"
DataValueField="test_code" DataTextField="test_desc" AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</code></pre>
<p>Somehow I try to show this dropdown by using the following code, but this is just not working for me. Anyone know why?</p>
<pre><code>$("#test1").show();
</code></pre> | 5,496,021 | 8 | 0 | null | 2011-03-31 06:19:25.78 UTC | 3 | 2019-05-27 03:09:09.2 UTC | 2011-03-31 06:24:32.297 UTC | null | 534,109 | null | 52,745 | null | 1 | 22 | jquery | 158,990 | <p>Using ASP.NET's <code>visible="false"</code> property will set the <code>visibility</code> attribute where as I think when you call <code>show()</code> in jQuery it modifies the <code>display</code> attribute of the CSS style.</p>
<p>So doing the latter won't rectify the former.</p>
<p>You need to do this:</p>
<pre><code>$("#test1").attr("visibility", "visible");
</code></pre> |
5,366,285 | Parse string to DateTime in C# | <p>I have <strong>date and time</strong> in a string formatted like that one:</p>
<pre><code>"2011-03-21 13:26" //year-month-day hour:minute
</code></pre>
<p>How can I parse it to <code>System.DateTime</code>?</p>
<p>I want to use functions like <code>DateTime.Parse()</code> or <code>DateTime.ParseExact()</code> if possible, to be able to specify the format of the date manually.</p> | 5,366,311 | 9 | 3 | null | 2011-03-20 01:58:54.587 UTC | 25 | 2022-09-12 07:22:32.617 UTC | 2018-06-20 07:18:35.253 UTC | null | 1,016,343 | null | 465,408 | null | 1 | 209 | c#|.net|string|parsing|datetime | 396,484 | <p><code>DateTime.Parse()</code> will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use <code>ParseExact()</code>:</p>
<pre><code>string s = "2011-03-21 13:26";
DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
</code></pre>
<p>(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)</p>
<p>Make sure to check <a href="https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx" rel="noreferrer">Custom Date and Time Format Strings</a> when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).</p>
<p>Another useful resource for C# format strings is <a href="http://blog.stevex.net/string-formatting-in-csharp/" rel="noreferrer">String Formatting in C#</a></p> |
5,181,401 | VS 2008 breakpoint will not currently be hit. No symbols have been loaded for this document | <p>I am struggling to overcome this obstacle and I have high hopes that someone on SO can help. </p>
<p><img src="https://i.stack.imgur.com/Mtk3H.png" alt="enter image description here"></p>
<p>When I set a breakpoint in my <em>class library</em> project. It appears as a normal breakpoint. When I start debugging my solution the <a href="http://msdn.microsoft.com/en-us/library/5557y8b4(v=vs.90).aspx" rel="noreferrer">breakpoint becomes hollowed out and has a yellow triangle with an exclamation point</a> inside. The tooltip displayed when I pan over the breakpoint is, "<strong>The Breakpoint will not currently be hit. No Symbols have been loaded for this document.</strong>"</p>
<p>This project is not an ASP.NET application, it is simply a winForms application.</p>
<p>I have taken over an existing winForms application with multiple projects in the solution. I have the project built and running in debug mode. I can stop at breakpoints in some projects but, I am unable to hit the breakpoints in other projects specifically my project that is of type <em>class library</em>. </p>
<p><strong>What I have done thus far:</strong></p>
<ul>
<li>I have deleted all debug and release folders, </li>
<li>I have deleted the obj folder, and have rebuilt the solution afterwards.</li>
<li>I have restarted the VS2008 IDE.</li>
<li>I have restarted my computer.</li>
<li>I checked the Configuration Manager for the solution to ensure that my <em>class project</em> is included in the debug build, and it is.</li>
<li>I have checked the debug/modules for dll, although I am not trying to reference a dll.</li>
</ul>
<p><strong>Furthermore, I have followed the troubleshooting steps outlined in the SO posts:</strong></p>
<p><a href="https://stackoverflow.com/questions/3013337/the-breakpoint-will-not-currently-be-hit-no-symbols-loaded">the breakpoint will not currently be hit no symbols loaded</a></p>
<p><a href="https://stackoverflow.com/questions/3076807/vs-2010-nunit-and-the-breakpoint-will-not-currently-be-hit-no-symbols-have-be">VS 2010, NUNit, and “The breakpoint will not currently be hit. No symbols have been loaded for this document”</a></p>
<p><a href="https://stackoverflow.com/questions/2301216/the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loaded-for-this-do">The breakpoint will not currently be hit. No symbols have been loaded for this document.</a></p>
<p><a href="https://stackoverflow.com/questions/389290/cant-debug-the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loa">Can't debug - “The breakpoint will not currently be hit. No symbols have been loaded for this document”</a></p>
<p><a href="https://stackoverflow.com/questions/2155930/fixing-the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loaded-for">Fixing “The breakpoint will not currently be hit. No symbols have been loaded for this document.”</a></p>
<p><strong>Additionally, I have read numerous posts found on <a href="http://www.google.com" rel="noreferrer">Google</a> from both <a href="http://www.msdn.com" rel="noreferrer">MSDN</a> and other locations, none of which fit my specific needs.</strong></p>
<p>Some of these posts are:</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/4a641246-72d4-4841-ae81-17469cb3ac71" rel="noreferrer">Visual Studio 2008 "The breakpoint will not be currently hit. No symbols have been loaded for this document"</a></p>
<p><a href="http://social.msdn.microsoft.com/Forums/en/vbide/thread/5ba1d641-214b-451a-949c-d08ddf030aa6" rel="noreferrer">The breakpoint will not currently be hit. No symbols have been loaded for this document</a></p>
<p><a href="http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/4f7b3eb5-67b5-4066-8299-fe7635cc1d82" rel="noreferrer">Breakpoint will not currently be hit. No symbols loaded for this document.</a></p>
<p><a href="http://social.msdn.microsoft.com/forums/en/vbide/thread/557fdedb-268e-48a8-9944-29b2b4e0dec2" rel="noreferrer">Debugger problem "The breakpoint will not currently be hit. No symbols have been loaded for this document</a></p>
<p><a href="http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_24366816.html" rel="noreferrer">The Breakpoint will not currently be hit. No Symbols have been loaded for this document.</a></p>
<p>All of the posts I have read have been very informative, but none of the suggested solutions have fit my specific needs. Please let me know if more information is warranted. I have more links I can provide as references to what has not worked. As well as additional steps I have taken to attempt to solve this issue.</p>
<p>I am posting this follow-up to keep everyone aprised. I followed @Hans @ suggestion to call the project file in question.</p>
<p>I placed a dim frm as form = new ProjectInQuestion.FormInQuestion</p>
<p>and</p>
<p>this now has the assembly loading in the debug--> Windows->Modules</p>
<p>The new problem is more perplexing than my original issue. My breakpoints look fine, but are being skipped. There are no error evident at the breakpoint.</p>
<p><img src="https://i.stack.imgur.com/4LVzP.png" alt="enter image description here"></p> | 7,338,377 | 13 | 1 | null | 2011-03-03 13:35:10.17 UTC | 4 | 2018-01-20 10:27:25.517 UTC | 2017-05-23 11:46:39.687 UTC | null | -1 | null | 437,301 | null | 1 | 31 | vb.net|visual-studio-2008|breakpoints | 23,130 | <p>This may be an old question, but I wanted to answer it after I found a solution for this very problem because it was one of the most complete questions asked in regards to this topic.</p>
<p><strong>Intro</strong></p>
<p>My project is an ASP.NET application, but the base problem will happen on WinForms as well. The problem arises when a DLL is missing from the assemblies output. However, this same exception occurs if the DLL you are referencing then references another DLL that is not in the assemblies. Due to the way the operating system loads DLLs, the referenced DLL must be in the environment path, and not in your output assemblies.</p>
<p>Project A references DLL D.
DLL D references DLL X.
DLL D may be in your output assemblies.
DLL X must be in your environment path.</p>
<blockquote>
<p>The core cause to this problem is in the way the operating system loads native DLL's at >runtime. Native DLL's are loaded using the following logic which does not include the >Temporary ASP.net Files nor the applications /bin folder. This problem will also occur in >any .Net application if the Native DLL is not included in the /bin folder with the .EXE >file or if the DLL is not in the Path Environment Variable.</p>
</blockquote>
<p><strong>Personal Solution</strong></p>
<p>I was using a DLL called DivaAPIWrapper.dll (Managed DLL for C#). I knew, however, that DivaAPIWrapper.dll needed DivaAPI.dll (Unmanaged C++) to operate. I placed DivaAPI.dll in all my output paths but I kept receiving this error. Only after I placed DivaAPI.dll in my environment path (C:\windows\Microsoft.Net\Framework\v2.0.50727) did it work. <em>Please note: your path may be different if you're using a newer version of the .NET framework!</em></p>
<p><strong>Complete Solution by Jerry Orman</strong></p>
<p>See Link Here: <a href="http://blogs.msdn.com/b/jorman/archive/2007/08/31/loading-c-assemblies-in-asp-net.aspx" rel="noreferrer">http://blogs.msdn.com/b/jorman/archive/2007/08/31/loading-c-assemblies-in-asp-net.aspx</a></p> |
29,592,924 | Find offset relative to parent scrolling div instead of window | <p>I have a scrolling element inside a window.</p>
<p>Say a division having a class "currentContainer" with overflow auto and that division contains huge amount of text so that it is definitely large enough to be scrolling.</p>
<p>Now I have to do some calculations based on how much the "currentContainer" has scrolled down + what is the offset of a specific element from its parent scrolling div (that is "currentCoantainer").</p>
<p>But while calculating offset I always get the offset of the inner child element with regard to window not with the "currentContainer".</p>
<p><a href="http://jsfiddle.net/arpitajain/677phzuq/" rel="noreferrer">JS FIDDLE</a></p>
<p>@Shikkediel I also tried using <code>position().top</code> instead of <code>offset().top</code> but is is also giving the same result. Have a look at it :</p>
<p><a href="http://jsfiddle.net/arpitajain/97weogv9/" rel="noreferrer">JS FIDDLE 2</a></p>
<p>Please do not suggest using :</p>
<pre><code>$("<reference of scrolling element").scrollTop()
+
$("<reference of child element whose offset I want to calculate>").offset().top
</code></pre>
<p>Because this is going to complicate my actual calculations which I am about to do beyond this.</p>
<p>Reason for why I do not want to use the above mentioned approach is that I am trying to modify an existing code which is already too messy but is working perfectly with regard to window I just have to update it so that it starts working relative to its parent scrolling div.</p>
<p>I tried using above mentioned approach but it opened a box of crabs for me. because functions are too much tightly coupled. So I think if I can get simple and straight solution i.e. replacing <code>.offset().top</code> with something else.</p>
<hr>
<p>I tried debugging the code and still no luck I have added the actual code at <a href="http://jsfiddle.net/arpitajain/kwkm7com/" rel="noreferrer">http://jsfiddle.net/arpitajain/kwkm7com/</a></p>
<p>P.S. It is actual code but not complete I think The rest of the code was not needed for this error.</p> | 29,599,312 | 4 | 6 | null | 2015-04-12 18:21:37.043 UTC | 2 | 2022-04-11 07:10:32.81 UTC | 2015-04-15 00:16:45.733 UTC | null | 2,686,013 | null | 2,357,882 | null | 1 | 27 | jquery|css|scroll|overflow|scrolltop | 40,852 | <p>You could just subtract the offset of the parent element from the offset of the child element. Will that complicate the other things you need to do as well?</p>
<pre><code>$(".getoffset").offset().top - $(".getoffset").offsetParent().offset().top
</code></pre>
<p><a href="http://jsfiddle.net/kmLr07oh/2/" rel="noreferrer">http://jsfiddle.net/kmLr07oh/2/</a></p> |
12,059,424 | About MySQLdb conn.autocommit(True) | <p>I have installed python 2.7 64bit,MySQL-python-1.2.3.win-amd64-py2.7.exe.</p>
<p>I use the following code to insert data :</p>
<pre><code>class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
cursor.close()
conn.close()
if n:
raise web.seeother('/')
</code></pre>
<p>This results in printing n as 1, but in mysql client data aren't visible.</p>
<p>google says I must add <code>conn.autocommit(True)</code>.</p>
<p>but I don't know why MySQLdb turns it off;</p> | 12,059,473 | 3 | 2 | null | 2012-08-21 16:42:20.11 UTC | 3 | 2021-01-21 19:19:39.35 UTC | 2012-08-21 16:47:29.373 UTC | null | 263,525 | null | 1,609,714 | null | 1 | 11 | python|mysql-python | 40,969 | <p>I don't know if there's a specific reason to use autocommit with GAE (assuming you are using it). Otherwise, you can just manually commit.</p>
<pre><code>class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
conn.commit() # This right here
cursor.close()
conn.close()
if n:
raise web.seeother('/')
</code></pre>
<p>Note that you probably should check if the insert happened successfully, and if not, rollback the commit.</p> |
12,116,413 | How do I style a Qt Widget not its children with stylesheets? | <p>I have a: </p>
<pre><code>class Box : public QWidget
</code></pre>
<p>and it has </p>
<pre><code>this->setLayout(new QGridLayout(this));
</code></pre>
<p>I tried doing: </p>
<pre><code>this->setStyleSheet( "border-radius: 5px; "
"border: 1px solid black;"
"border: 2px groove gray;"
"background-color:blue;");
this->setStyleSheet( "QGridLayout{"
"background-color:blue;"
"border-radius: 5px; "
"border: 1px solid black;"
"border: 2px groove gray;"
"}"
);
this->setObjectName(QString("Box"));
this->setStyleSheet( "QWidget#Box {"
"background-color:blue;"
"border-radius: 5px; "
"border: 1px solid black;"
"border: 2px groove gray;"
"}"
);
</code></pre>
<p>but the first affects only the items that are added, the other two do nothing. I want the box itself to have rounded corners and a border (bonus for how to do lines between rows).</p>
<p>How do I get the stylesheet to affect the Box widget, not its children?</p> | 12,117,468 | 3 | 0 | null | 2012-08-24 20:46:15.887 UTC | 11 | 2022-01-14 03:23:38.327 UTC | 2012-08-24 21:16:37.4 UTC | null | 516,813 | null | 516,813 | null | 1 | 13 | c++|qt|widget | 21,016 | <p>To be more precise I could have used:</p>
<pre><code>QWidget#idName {
border: 1px solid grey;
}
</code></pre>
<p>or</p>
<pre><code>Box {
border: 1px solid grey;
}
</code></pre>
<p>The latter is easier, in my opinion, as it doesn't require the use of id names.</p>
<p>The main problem with why these weren't working though is because this is considered a custom widget and therefore needs a custom paint event: </p>
<pre><code> void Box::paintEvent(QPaintEvent *) {
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
</code></pre>
<p>This was taken from: <a href="https://stackoverflow.com/questions/7276330/qt-stylesheet-for-custom-widget">Qt Stylesheet for custom widget</a></p> |
12,461,117 | jQuery Mobile get current page | <p>I am using jQuery Mobile 1.1.1 and Apache Cordova 2.0.0. I want my app to exit when I press back button but only if current page have ID = feedZive. I am using following code to do it:</p>
<pre><code>function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(){
if ($.mobile.activePage.is("#feedZive")){
navigator.app.exitApp();
}
else{
navigator.app.backHistory();
}
}
};
</code></pre>
<p>However it looks like I can't get the current page because I have tried the following code:</p>
<pre><code>var activePage = $.mobile.activePage;
alert(activePage);
</code></pre>
<p>and my alert is showing undefined. I have also tried to change <code>$.mobile.activePage</code> to <code>$.mobile.activePage.attr("id")</code> but it didn't work.</p> | 12,564,089 | 8 | 0 | null | 2012-09-17 14:11:16.833 UTC | 6 | 2016-02-06 19:26:19.153 UTC | 2014-12-15 12:57:23.5 UTC | null | 1,771,795 | null | 1,503,758 | null | 1 | 21 | javascript|cordova|jquery-mobile | 51,239 | <pre><code>$(document).live('pagebeforeshow', function() {
alert($.mobile.activePage.attr('id'));
});
</code></pre>
<p><a href="http://jsfiddle.net/ajD6w/5/">http://jsfiddle.net/ajD6w/5/</a></p> |
12,495,723 | Using XPath wildcards in attributes in Selenium WebDriver | <p>I want to use Wildcards in my attributes. For example, this is my regular XPath: </p>
<pre><code>//input[@id='activation:j_idt84:voId:1']`
</code></pre>
<p>I want to replace the <code>j_idt</code> number with a wildcard because the number is dynamic. I'm looking for something like this:</p>
<pre><code>//input[@id='activation:*:voId:1']
</code></pre>
<p>I don't know how to solve that issue. Is my idea even possible?</p> | 12,495,992 | 2 | 0 | null | 2012-09-19 13:26:10.547 UTC | 3 | 2018-07-16 20:05:08.077 UTC | 2017-01-05 22:01:45.633 UTC | null | 4,816,518 | null | 1,635,326 | null | 1 | 21 | selenium|xpath | 38,328 | <p>Unfortunately there's no string wildcards in XPath. However you can use multiple <code>contains()</code> and <code>starts-with()</code> to filter things like this.</p>
<pre><code>//input[starts-with(@id, 'activation:') and contains(@id, ':voId:1')]
</code></pre>
<p>Also, this answer could be useful too: <a href="https://stackoverflow.com/questions/2007367/selenium-is-it-possible-to-use-the-regexp-in-selenium-locators/2007531#2007531">selenium: Is it possible to use the regexp in selenium locators</a></p> |
12,100,157 | How to reuse SqlCommand parameter through every iteration? | <p>I want to implement a simple delete button for my database. The event method looks something like this:</p>
<pre><code>private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "delete users",MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
command = new SqlCommand();
try
{
User.connection.Open();
command.Connection = User.connection;
command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id";
int flag;
foreach (DataGridViewRow row in dgvUsers.SelectedRows)
{
int selectedIndex = row.Index;
int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString());
command.Parameters.AddWithValue("@id", rowUserID);
flag = command.ExecuteNonQuery();
if (flag == 1) { MessageBox.Show("Success!"); }
dgvUsers.Rows.Remove(row);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (ConnectionState.Open.Equals(User.connection.State))
User.connection.Close();
}
}
else
{
return;
}
}
</code></pre>
<p>but I get this message:</p>
<blockquote>
<p>A variable @id has been declared. Variable names must be unique within
a query batch or stored procedure.</p>
</blockquote>
<p>Is there any way to reuse this variable?</p> | 12,100,248 | 4 | 0 | null | 2012-08-23 21:21:38.983 UTC | 4 | 2019-11-12 15:54:33.603 UTC | 2015-05-17 07:39:37.28 UTC | null | 1,402,846 | null | 1,600,108 | null | 1 | 22 | c#|sql-server|ado.net | 40,022 | <p><code>Parameters.AddWithValue</code> adds a new Parameter to the command. Since you're doing that in a loop with the same name, you're getting the exception <em>"Variable names must be unique"</em>.</p>
<p>So you only need one parameter, add it before the loop and change only it's value in the loop.</p>
<pre><code>command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id";
command.Parameters.Add("@id", SqlDbType.Int);
int flag;
foreach (DataGridViewRow row in dgvUsers.SelectedRows)
{
int selectedIndex = row.Index;
int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString());
command.Parameters["@id"].Value = rowUserID;
// ...
}
</code></pre>
<p>Another way is to use <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.clear%28v=vs.110%29.aspx"><code>command.Parameters.Clear();</code></a> first. Then you can also add the parameter(s) in the loop without creating the same parameter twice.</p> |
12,369,295 | Flask SQLAlchemy display queries for debug | <p>I am developing an app with flask and SQL Alchemy.
I need to display the queries executed to generate a page alongside the time each query took for debugging</p>
<p>What's the best way to do it?</p> | 12,369,681 | 9 | 0 | null | 2012-09-11 12:03:33.293 UTC | 5 | 2022-08-02 13:56:12.453 UTC | null | null | null | null | 615,110 | null | 1 | 60 | sqlalchemy|flask | 45,354 | <p>I haven't used it myself, but it seems that Flask Debug-toolbar may help with this.</p>
<p><a href="https://github.com/mgood/flask-debugtoolbar">https://github.com/mgood/flask-debugtoolbar</a></p>
<p>It's a port of the django-debug-toolbar, which can be used for profiling queries.
The documentation of Flask Debug-toolbar doesn't mention it, but there is code for a SQLAlchemyDebugPanel.<br>
So I think it may be well worth to take a look at the project, and see if it does what you need.</p> |
12,381,563 | How can I stop the browser back button using JavaScript? | <p>I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.</p>
<p>I have tried the following script, but it stops my timer.</p>
<p>What should I do?</p>
<p>The timer is stored in file <em>cdtimer.js</em>.</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
window.history.forward();
function noBack()
{
window.history.forward();
}
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">
</code></pre>
<p>I have the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?</p> | 12,381,610 | 37 | 1 | null | 2012-09-12 05:09:11.44 UTC | 110 | 2022-06-25 04:36:46.26 UTC | 2020-12-14 22:53:13.517 UTC | null | 63,550 | null | 1,656,134 | null | 1 | 223 | javascript|browser | 721,204 | <p>There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:</p>
<pre><code>window.onbeforeunload = function() { return "Your work will be lost."; };
</code></pre>
<p>This page does list a number of ways you <em>could</em> try to disable the back button, but none are guaranteed:</p>
<p><a href="http://www.irt.org/script/311.htm" rel="noreferrer">http://www.irt.org/script/311.htm</a></p> |
44,026,548 | Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries | <p>I have two classes in my sqlite database, a parent table named <code>Categorie</code> and the child table called <code>Article</code>. I created first the child table class and addes entries. So first I had this:</p>
<pre><code>class Article(models.Model):
titre=models.CharField(max_length=100)
auteur=models.CharField(max_length=42)
contenu=models.TextField(null=True)
date=models.DateTimeField(
auto_now_add=True,
auto_now=False,
verbose_name="Date de parution"
)
def __str__(self):
return self.titre
</code></pre>
<p>And after I have added parent table, and now my <code>models.py</code> looks like this:</p>
<pre><code>from django.db import models
# Create your models here.
class Categorie(models.Model):
nom = models.CharField(max_length=30)
def __str__(self):
return self.nom
class Article(models.Model):
titre=models.CharField(max_length=100)
auteur=models.CharField(max_length=42)
contenu=models.TextField(null=True)
date=models.DateTimeField(
auto_now_add=True,
auto_now=False,
verbose_name="Date de parution"
)
categorie = models.ForeignKey('Categorie')
def __str__(self):
return self.titre
</code></pre>
<p>So when I run <code>python manage.py makemigrations <my_app_name></code>, I get this error:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 354, in execute_from_command_line
utility.execute()
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 330, in execute
django.setup()
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\lislis\Django\mon_site\blog\models.py", line 6, in <module>
class Article(models.Model):
File "C:\Users\lislis\Django\mon_site\blog\models.py", line 16, in Article
categorie = models.ForeignKey('Categorie')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
</code></pre>
<p>I've seen some similar issues in stackoverflow, but it seems to not be the same problem: <a href="https://stackoverflow.com/questions/39231476/init-missing-1-required-positional-argument-quantity">__init__() missing 1 required positional argument: 'quantity'</a></p> | 44,026,807 | 12 | 4 | null | 2017-05-17 13:39:11.477 UTC | 42 | 2022-06-04 08:34:10.783 UTC | 2022-06-04 08:34:10.783 UTC | null | 8,172,439 | null | 6,137,017 | null | 1 | 126 | python|python-3.x|django|django-models|django-2.0 | 205,903 | <p>You can change the property <code>categorie</code> of the class <code>Article</code> like this:</p>
<pre><code>categorie = models.ForeignKey(
'Categorie',
on_delete=models.CASCADE,
)
</code></pre>
<p>and the error should disappear.</p>
<p>Eventually you might need another option for <code>on_delete</code>, check the documentation for more details:</p>
<p><a href="https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey" rel="noreferrer">https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey</a></p>
<p>EDIT:</p>
<p>As you stated in your comment, that you don't have any special requirements for <code>on_delete</code>, you could use the option <code>DO_NOTHING</code>:</p>
<pre><code># ...
on_delete=models.DO_NOTHING,
# ...
</code></pre> |
24,297,273 | openURL not work in Action Extension | <p>I add following code:</p>
<pre><code>- (IBAction)done {
// Return any edited content to the host app.
// This template doesn't do anything, so we just echo the passed in items.
NSURL *url = [NSURL URLWithString:@"lister://today"];
[self.extensionContext openURL:url completionHandler:^(BOOL success) {
NSLog(@"fun=%s after completion. success=%d", __func__, success);
}];
[self.extensionContext completeRequestReturningItems:self.extensionContext.inputItems completionHandler:nil];
}
</code></pre>
<p>after I create the Action Extension target. But it can not work.</p>
<p>My purpose is that: when user view a photo in Photos.app (the iOS's default Photos.app or called gallery), and he click the share button to launch our extension view.
We can transfer the image from Photos.app to my own app and deal or upload the image in my app.</p>
<p>I also try "CFBundleDocumentTypes" but it also can not work.</p>
<p>Any help will be appreciated.</p> | 24,709,883 | 17 | 4 | null | 2014-06-19 01:08:19.793 UTC | 40 | 2020-08-17 08:56:12.153 UTC | 2014-06-19 15:20:30.817 UTC | null | 2,446,155 | null | 712,823 | null | 1 | 54 | ios|ios8|ios-app-extension | 34,695 | <p>This is by design. We don't want Custom Actions to become app launchers.</p> |
24,100,602 | Developing Python applications in Qt Creator | <p>I've developed a few Qt projects in C++ using Qt Creator in the past, but now I want to experiment with the Python implementation of Qt. I discovered that Qt Creator 2.8 and higher <a href="http://blog.qt.digia.com/blog/2013/07/11/qt-creator-2-8-0-released/">support Python</a>, but I haven't been able to figure out how to create a Qt application in Python with it so far. Online documentation about it appears to be scarce.</p>
<p>How do I set up such a project in Qt Creator? Ideally I'm looking for a simple "Hello World" project that I can open in Qt Creator and use that as a starting point to build something.</p> | 24,121,860 | 2 | 6 | null | 2014-06-07 19:00:14.903 UTC | 31 | 2018-09-16 19:39:08.607 UTC | null | null | null | null | 217,649 | null | 1 | 48 | python|qt | 83,249 | <p>Currently, <code>Qt Creator</code> allows you to create Python files (not projects) and run them. It also has syntax highlighting, but it lacks more complex features such as autocomplete. <br></p>
<p>Running scripts requires some configuration (I used <a href="http://ceg.developpez.com/tutoriels/python/configurer-qtcreator-pour-python/" rel="noreferrer">this</a> tutorial). Open <code>Qt Creator</code> and go to <code>Tools->Options->Environment->External Tools</code>. Click <code>Add->Add category</code> and create a new category (for example, <code>Python</code>). Then, select the created category and click <code>Add->Add Tool</code> to create a new tool - <code>RunPy</code> for example. Select the created tool and fill the fields on the right:</p>
<ol>
<li>Description - any value </li>
<li>Executable - path to <code>python.exe</code></li>
<li>Arguments - <code>%{CurrentDocument:FilePath}</code></li>
<li>Working directory - <code>%{CurrentDocument:Path}</code></li>
<li>Environment - <code>QT_LOGGING_TO_CONSOLE=1</code></li>
</ol>
<p>You get something like this:</p>
<p><img src="https://i.stack.imgur.com/Mv0Ic.png" alt="enter image description here"></p>
<p>Now, go to <code>File->New File or Project->Python</code> and select <code>Python source file</code>. To run the created script: <code>Tools->External->Python->RunPy</code>.</p>
<p>You can also add pyuic to it the same way:
Click again on the <code>Add->Add Tool</code> button to create a new tool - <code>PyUic</code> now. Select it again and fill the fields on the right:</p>
<ol>
<li>Description - any value</li>
<li>Executable - path to <code>pyuic5</code></li>
<li>Arguments - <code>-o UI%{CurrentDocument:FileBaseName}.py -x %{CurrentDocument:FilePath}</code></li>
<li>Working directory - <code>%{CurrentDocument:Path}</code></li>
<li>Environment - <code>QT_LOGGING_TO_CONSOLE=1</code></li>
</ol>
<p>Then you should have PyUic connected as well.</p> |
3,749,200 | Cannot find class in same package | <p>I am trying to compile Board.java, which is in the same package (and directory) as Hexagon.java, but I get this error:</p>
<pre><code>Board.java:12: cannot find symbol
symbol : class Hexagon
location: class oadams_atroche.Board
private Hexagon[][] tiles;
</code></pre>
<p>The first few lines of Board.java:</p>
<pre><code>package oadams_atroche;
import java.util.LinkedList;
import java.util.Queue;
import java.io.PrintStream;
import p323.hex.*;
public class Board implements Piece{
>---//Fields
>---private int n;
>---private Hexagon[][] tiles;
</code></pre>
<p>The first few lines of Hexagon.java:</p>
<pre><code>package oadams_atroche;
import p323.hex.*;
public class Hexagon implements Piece{
</code></pre>
<p>I just cannot see what I am doing wrong. Any ideas?</p>
<p>Thanks</p> | 3,749,272 | 3 | 6 | null | 2010-09-20 06:51:59.503 UTC | 4 | 2021-07-05 16:43:48.81 UTC | 2010-09-20 07:02:22.49 UTC | null | 328,764 | null | 328,764 | null | 1 | 26 | java | 39,166 | <p>I'm quite sure you're compiling from within the wrong directory. <strong>You should compile from the</strong> source root-directory, and not from within the oadams_atroches directory.</p>
<p>Have a look at this bash-session:</p>
<pre><code>aioobe@r60:~/tmp/hex/oadams_atroche$ ls
Board.java Hexagon.java
aioobe@r60:~/tmp/hex/oadams_atroche$ javac Board.java
Board.java:12: cannot find symbol
symbol : class Hexagon
location: class oadams_atroche.Board
private Hexagon[][] tiles;
^
1 error
</code></pre>
<p>While if I go up one directory...</p>
<pre><code>aioobe@r60:~/tmp/hex/oadams_atroche$ cd ..
</code></pre>
<p>... and compile:</p>
<pre><code>aioobe@r60:~/tmp/hex$ javac oadams_atroche/Board.java
aioobe@r60:~/tmp/hex$
</code></pre> |
3,597,781 | Dr Racket problems with SICP | <p>I'm working through SICP. Currently, in the first chapter, I'm having problems getting Racket to let me redefine "primitives". For instance, I was under the impression that I should be able to arbitrarily do <code>(define + 5)</code> and that would be fine, or redefine the <code>sqrt</code> procedure. Instead, I get this:</p>
<pre><code>define-values: cannot change constant variable: +
</code></pre>
<p>I have the language currently set to R5RS, which I was under the impression would take care of the compatibility issues with SICP.</p> | 3,598,093 | 3 | 1 | null | 2010-08-30 03:58:45.19 UTC | 16 | 2017-11-28 06:07:37.853 UTC | 2017-11-28 06:07:37.853 UTC | user7387082 | null | null | 392,119 | null | 1 | 32 | lisp|scheme|racket|sicp | 10,949 | <p>Even if possible, such redefinitions are not something that you should do without really understanding how the system will react to this. For example, if you redefine <code>+</code>, will any other code break? The answer to that in Racket's case is "no" -- but this is because you don't really get to redefine <code>+</code>: instead, you define a <em>new</em> <code>+</code>, which only your code can use.</p>
<p>As for the language choice -- Rackets R5RS mode is a very strict one, and it's not something that you'd usually want to use. For a <em>much</em> more SICP-friendly environment, see Neil Van Dyke's <a href="http://www.neilvandyke.org/racket-sicp/" rel="noreferrer">SICP Support page</a> which will provide you with a language specifically made for the book. (IIRC, it even has the graphical language that the books shows off.)</p> |
3,473,552 | c# - should I use "ref" to pass a collection (e.g. List) by reference to a method? | <p>Should I use "ref" to pass a list variable by reference to a method?</p>
<p>Is the answer that "ref" is not needed (as the list would be a reference variable), however for ease in readability put the "ref" in? </p> | 3,473,560 | 3 | 1 | null | 2010-08-13 02:52:56.597 UTC | 7 | 2010-08-13 02:58:36.08 UTC | null | null | null | null | 173,520 | null | 1 | 44 | c#|methods|pass-by-reference | 42,054 | <p>No, don't use a ref unless you want to change what list the variable is referencing. If you want to just access the list, do it without ref.</p>
<p>If you make a parameter ref, you are saying that the caller should expect that the parameter they pass in could be assigned to another object. If you aren't doing that, then it's not conveying the correct information. You should assume that all C# developers understand that an object reference is being passed in.</p> |
3,516,823 | What's the difference between the index, cached, and staged in git? | <p>Are these the same thing? If so, why are there so many terms?!</p>
<p>Also, I know there is this thing called git stash, which is a place where you can temporarily store changes to your working copy without committing them to the repo. I find this tool really useful, but again, the name is very similar to a bunch of other concepts in git -> this is very confusing!!</p> | 3,516,845 | 3 | 3 | null | 2010-08-18 21:23:01.457 UTC | 10 | 2022-08-02 04:00:04.193 UTC | null | null | null | null | 62,163 | null | 1 | 54 | git | 9,173 | <p>The index/stage/cache are the same thing - as for why so many terms, I think that index was the 'original' term, but people found it confusing, so the other terms were introduced. And I agree that it makes things a bit confusing sometimes at first.</p>
<p>The <code>stash</code> facility of git is a way to store 'in-progress' work that you don't want to commit right now in a commit object that gets stored in a particular stash directory/database). The basic <code>stash</code> command will store uncommitted changes made to the working directory (both cached/staged and uncached/unstaged changes) and will then revert the working directory to HEAD.</p>
<p>It's not really related to the index/stage/cache except that it'll store away uncommitted changes that are in the cache.</p>
<p>This lets you quickly save the state of a dirty working directory and index so you can perform different work in a clean environment. Later you can get back the information in the stash object and apply it to your working directory (even if the working directory itself is in a different state).</p>
<p>The official <code>git stash</code> manpage has pretty good detail, while remaining understandable. It also has good examples of scenarios of how <code>stash</code> might be used.</p> |
3,616,572 | How to position a div in bottom right corner of a browser? | <p>I am trying to place my div with some notes in the <strong>bottom right</strong> position of the screen which will be displayed all time.</p>
<p>I used following css for it:</p>
<pre><code>#foo
{
position: fixed;
bottom: 0;
right: 0;
}
</code></pre>
<p>It works fine with Chrome 3 and Firefox 3.6 but IE8 sucks... </p>
<p>what can be a suitable solution for it?</p> | 3,616,659 | 3 | 4 | null | 2010-09-01 09:21:33.94 UTC | 16 | 2014-01-04 20:20:20.96 UTC | 2013-08-01 18:28:58.167 UTC | null | 579,405 | null | 178,301 | null | 1 | 90 | css|cross-browser | 261,541 | <p>This snippet works in IE7 at least</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
</code></pre> |
8,507,561 | What is the implementing class for IGrouping? | <p>I am trying create a WCF Data Services ServiceOperation that does grouping on the server side and then sends the data down to the client.</p>
<p>When I try to call it (or even connect to the service) I get an error. It says that it can't construct an interface.</p>
<p>The only interface I am using is IGrouping. </p>
<p>What is a/the actual class for this interface?</p>
<hr>
<p><strong>Update:</strong></p>
<p>I checked the type while debugging a sample app and it told me it was:</p>
<pre><code>System.Linq.Lookup<TKey,TElement>.Grouping
</code></pre>
<p>But what assembly is it in? </p> | 8,508,212 | 3 | 8 | null | 2011-12-14 16:01:05.333 UTC | 5 | 2015-03-20 04:08:35.31 UTC | 2011-12-14 16:13:32.073 UTC | null | 16,241 | null | 16,241 | null | 1 | 28 | c#|.net|wcf-data-services | 18,758 | <p>Several types in the BCL implement <code>IGrouping</code>, however they are all internal and cannot be accessed except by the <code>IGrouping</code> interface.</p>
<p>But an <code>IGrouping</code> is merely an <code>IEnumerable<TElement></code> with an associated key. You can easily implement an <code>IGrouping</code> that is backed by a <code>List<TElement></code> and that should not be hard to serialize across a call boundary:</p>
<pre><code>public class Grouping<TKey, TElement> : IGrouping<TKey, TElement> {
readonly List<TElement> elements;
public Grouping(IGrouping<TKey, TElement> grouping) {
if (grouping == null)
throw new ArgumentNullException("grouping");
Key = grouping.Key;
elements = grouping.ToList();
}
public TKey Key { get; private set; }
public IEnumerator<TElement> GetEnumerator() {
return this.elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
</code></pre>
<p>After applying the <code>GroupBy</code> operator you can create a list of <code>Grouping</code> instances:</p>
<pre><code>var listOfGroups =
source.GroupBy(x => ...).Select(g => new Grouping<TKey, TElement>(g)).ToList();
</code></pre> |
8,924,149 | Should std::bind be compatible with boost::asio? | <p>I am trying to adapt one of the boost::asio examples to use c++11 / TR1 libraries where possible. The original code looks like this:</p>
<pre><code>void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
</code></pre>
<p>If I replace <code>boost::bind</code> with <code>std::bind</code> as follows:</p>
<pre><code>void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
std::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error ) );
// std::bind(&tcp_server::handle_accept, this, new_connection, _1 ) );
}
</code></pre>
<p>I get a large error message, with ends with:</p>
<pre><code>/usr/include/c++/4.4/tr1_impl/functional:1137: error: return-statement with a value, in function returning 'void'
</code></pre>
<p>I am using gcc version 4.4 with boost version 1.47</p>
<p>I expected boost::bind and std::bind to be interchangeable. </p> | 9,536,984 | 1 | 9 | null | 2012-01-19 10:04:48.823 UTC | 8 | 2012-10-26 14:53:45.69 UTC | 2012-03-02 16:39:36.797 UTC | null | 926,751 | null | 926,751 | null | 1 | 44 | c++|boost|c++11|boost-asio | 7,148 | <p><strong>I now have a solution</strong></p>
<p>The problem is that when I first tried to switch to <a href="http://en.cppreference.com/w/cpp/utility/functional/bind" rel="noreferrer"><code>std::bind</code></a> and <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>std::shared_ptr</code></a> I was still using the <code>boost::asio::placeholders</code> with <code>std::bind</code>, this resulted in a large amount of template compiler errors, so I then tried to switch piecemeal.</p>
<p>I first tried switching just <code>boost::shared_ptr</code> to <code>std::shared_ptr</code>, this failed because <code>boost::bind</code> will not work with <code>std::shared_ptr</code> with out a specialisation of the template <code>get_pointer<typename T></code> for <code>std::shared_ptr</code> (see: <a href="https://stackoverflow.com/questions/4682343/how-to-resolve-conflict-between-boostshared-ptr-and-using-stdshared-ptr">How to resolve conflict between boost::shared_ptr and using std::shared_ptr?</a>). </p>
<p>After switching to std::shared_ptr I then switched to <code>std::bind</code>, this time using the <a href="http://en.cppreference.com/w/cpp/utility/functional/placeholders" rel="noreferrer"><code>std::placeholders</code></a>, (thanks richard) the example code now compiles and works correctly.</p>
<p><strong>In order to use <code>std::bind</code> with <code>boost::asio</code> make sure that <code>std::shared_ptr</code> and the <code>std::placeholders</code> are also used.</strong></p> |
11,242,224 | Junit difference between assertEquals(Double, Double) and assertEquals(double, double, delta) | <p>I had a junit test asserting two Double objects with the following:</p>
<pre><code>Assert.assertEquals(Double expected, Double result);
</code></pre>
<p>This was was fine then I decided to change it to use the primitive double instead which turned out to be deprecated unless you also provide a delta.</p>
<p>so what I am wondering is what is the difference between using the Double object or the primitive type in this assertEquals? Why is using the objects without a delta ok but then using the primitives without a delta is deprecated? Is Java doing something in the background which already has a default delta value taken into account?</p>
<p>Thanks.</p> | 11,242,313 | 6 | 0 | null | 2012-06-28 10:02:26.333 UTC | 2 | 2021-02-28 00:07:10.42 UTC | 2012-06-28 20:55:31.593 UTC | null | 265,143 | null | 1,424,675 | null | 1 | 14 | java|unit-testing|junit | 49,617 | <p>There is NO <a href="http://junit.sourceforge.net/javadoc/org/junit/Assert.html" rel="noreferrer">assert method in JUnit</a> with the signature</p>
<pre><code>assertEquals(Double expected, Double result);
</code></pre>
<p>There is one, however, generic for objects:</p>
<pre><code>assertEquals(Object expected, Object result);
</code></pre>
<p>This calls the objects' <code>equals</code> method and as you can expect, it is not recommended to use this for comparing <code>Double</code> objects.</p>
<p>For doubles, as you observed, it is absolutely necessary to use a delta for comparison, to avoid issues with floating-point rounding (explained already in some other answers). If you use the 3-argument version of <code>assertEquals</code> with <code>double</code> arguments</p>
<pre><code>assertEquals(double expected, double actual, double delta);
</code></pre>
<p>your <code>Double</code>s will get silently unboxed to <code>double</code> and everything will work fine (and your tests won't fail unexpectedly :-).</p> |
11,282,846 | Redirect One Controller to another Controller | <p>I have two controllers users & movies. All, I want to do, redirect from user#something to movie#something. is it possible??</p> | 11,282,852 | 2 | 0 | null | 2012-07-01 14:40:41.137 UTC | 4 | 2021-09-06 13:57:45.837 UTC | null | null | null | null | 1,055,090 | null | 1 | 16 | ruby-on-rails|ruby|ruby-on-rails-3|ruby-on-rails-3.1 | 39,919 | <p>Yes. Look at redirect_to.
<a href="http://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to" rel="noreferrer">http://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to</a></p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.