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
31,747,115
PowerShell Desktop Variable
<p>I am trying to write a PowerShell script to remove the desktop icon for Chrome after installing through sccm. However, certain users in the network have their desktop directed to different folders on the network. <strong>Is there a variable in PowerShell that stores the location of the desktop?</strong></p> <p>I have looked online and searched using <code>Get-Variable | Out-String</code>, but I didn't find anything. The finished code should look like:</p> <pre><code>If (Test-Path "$DesktopLocation\Google Chrome.lnk"){ Remove-Item "$DesltopLocation\Google Chrome.lnk" } </code></pre>
31,747,246
3
0
null
2015-07-31 13:16:00.46 UTC
4
2022-03-30 10:06:53.727 UTC
2017-06-04 11:36:50.34 UTC
null
63,550
null
5,177,958
null
1
41
powershell|desktop
80,124
<p>You can use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.environment.getfolderpath" rel="noreferrer"><code>Environment.GetFolderPath()</code> method</a> to get the full path to special folders:</p> <pre><code>$DesktopPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop) </code></pre> <p>This can be shortened to:</p> <pre><code>$DesktopPath = [Environment]::GetFolderPath(&quot;Desktop&quot;) </code></pre> <hr /> <p>You can also get the &quot;AllUsers&quot; shared desktop folder (if the shortcut file is shared among all users):</p> <pre><code>[Environment]::GetFolderPath(&quot;CommonDesktopDirectory&quot;) </code></pre> <p>Check out the full list of values for the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.environment.specialfolder#fields" rel="noreferrer"><code>SpecialFolder</code> Enum</a>.</p>
1,146,934
Create Great Parser - Extract Relevant Text From HTML/Blogs
<p>I'm trying to create a generalized HTML parser that works well on Blog Posts. I want to point my parser at the specific entrie's URL and get back clean text of the post itself. My basic approach (from python) has been to use a combination of BeautifulSoup / Urllib2, which is okay, but it assumes you know the proper tags for the blog entry. Does anyone have any better ideas?</p> <p>Here are some thoughts maybe someone could expand upon, that I don't have enough knowledge/know-how yet to implement.</p> <ol> <li><p>The unix program 'lynx' seems to parse blog posts especially well - what parser do they use, or how could this be utilized?</p></li> <li><p>Are there any services/parsers that automatically remove junk ads, etc?</p></li> <li><p>In this case, i had a vague notion that it may be an okay assumption that blog posts are usually contained in a certain defining tag with class="entry" or something similar. Thus, it may be possible to create an algorithm that found the enclosing tags with the most clean text between them - any ideas on this?</p></li> </ol> <p>Thanks!</p>
1,147,016
2
1
null
2009-07-18 07:27:45.763 UTC
15
2011-05-01 09:19:39.063 UTC
2010-01-02 20:14:18.76 UTC
null
222,815
nartz
null
null
1
22
html|parsing|text-parsing|html-content-extraction
5,920
<p>Boy, do I have the <em>perfect</em> solution for you.</p> <p>Arc90's readability algorithm does exactly this. Given HTML content, it picks out the content of the main blog post text, ignoring headers, footers, navigation, etc.</p> <p>Here are implementations in:</p> <ul> <li><a href="http://code.google.com/p/arc90labs-readability/" rel="noreferrer">JavaScript</a></li> <li><a href="http://search.cpan.org/dist/HTML-ExtractMain/" rel="noreferrer">Perl</a></li> <li><a href="http://www.keyvan.net/2010/08/php-readability/" rel="noreferrer">PHP</a></li> <li><a href="http://nirmalpatel.com/fcgi/hn.py" rel="noreferrer">Python</a></li> <li><a href="https://github.com/iterationlabs/ruby-readability" rel="noreferrer">Ruby</a></li> <li><a href="https://github.com/marek-stoj/NReadability" rel="noreferrer">C#</a></li> </ul> <p><strike>I'll be releasing a Perl port to CPAN in a couple of days.</strike> Done.</p> <p>Hope this helps!</p>
3,194,516
Replace special characters with ASCII equivalent
<p>Is there any lib that can replace special characters to ASCII equivalents, like:</p> <pre><code>"Cześć" </code></pre> <p>to:</p> <pre><code>"Czesc" </code></pre> <p>I can of course create map:</p> <pre><code>{'ś':'s', 'ć': 'c'} </code></pre> <p>and use some replace function. But I don't want to hardcode all equivalents into my program, if there is some function that already does that.</p>
3,194,567
6
3
null
2010-07-07 12:12:48.773 UTC
12
2020-06-02 10:37:04.807 UTC
2015-05-28 10:34:16.853 UTC
null
3,621,464
null
377,095
null
1
43
python|unicode
26,370
<pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import unicodedata text = u'Cześć' print unicodedata.normalize('NFD', text).encode('ascii', 'ignore') </code></pre>
2,378,572
Hibernate Session is closed
<p>When I call the method session.begin transaction as follows:</p> <pre><code>//session factory is instantiated via a bean Session session = this.getSessionFactory().getCurrentSession(); session.beginTransaction(); </code></pre> <p>Then I get the following exception message</p> <pre><code>6:13:52,217 ERROR [STDERR] org.hibernate.SessionException: Session is closed! at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:49) at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1319) </code></pre> <p>What could be the cause of this error ?</p>
2,378,667
8
3
null
2010-03-04 10:45:58.703 UTC
4
2019-12-11 22:22:31.28 UTC
2012-09-23 15:51:45.347 UTC
null
246,246
null
226,906
null
1
16
hibernate|session
80,762
<p><strong>Update:</strong> I guess that calling <code>getCurrentSession()</code> does not guarantee that the session is actually open. For the very first time, you should use</p> <pre><code>Session session = this.getSessionFactory().openSession(); session.beginTransaction(); </code></pre> <p>instead. This suggestion is actually consistent with the page you found.</p> <p><strong>Earlier:</strong></p> <p>Based on the information available so far, we can conclude that the cause of the error is the session not being open ;-)</p>
2,823,808
Android button font size
<p>I;ve been trying to create a custom button in android using this tutorial - <a href="http://www.gersic.com/blog.php?id=56" rel="noreferrer">http://www.gersic.com/blog.php?id=56</a></p> <p>It works well but it doesn't say how to change the font size or weighting. Any ideas?</p> <p>There was another question on here and the only answer was to use html styling but you can't change a font size in html without using css (or the deprecated font tag). There must be a better way of setting the pixel size of the font used on buttons?</p>
2,823,935
8
1
null
2010-05-13 00:51:27.837 UTC
3
2019-10-15 15:49:38.937 UTC
null
null
null
null
56,007
null
1
42
android
124,138
<p>You define these attributes in xml as you would anything else, for example:</p> <pre><code>&lt;Button android:id="@+id/next_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/next" android:background="@drawable/mybutton_background" android:textSize="10sp" /&gt; &lt;!-- Use SP(Scale Independent Pixel) --&gt; </code></pre> <p>You can find the allowed attributes in the <a href="http://developer.android.com/reference/android/widget/Button.html" rel="noreferrer">api</a>.</p> <p>Or, if you want this to apply to all buttons in your application, create a style. See the <a href="http://developer.android.com/guide/topics/ui/themes.html" rel="noreferrer">Styles and Themes</a> development documentation.</p>
2,801,008
mongodb: insert if not exists
<p>Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist.</p> <ul> <li>I also want to keep track of the first time I inserted them, and the last time I saw them in an update. </li> <li>I don't want to have duplicate documents. </li> <li>I don't want to remove a document which has previously been saved, but is not in my update. </li> <li>95% (estimated) of the records are unmodified from day to day.</li> </ul> <p>I am using the Python driver (pymongo).</p> <p>What I currently do is (pseudo-code):</p> <pre><code>for each document in update: existing_document = collection.find_one(document) if not existing_document: document['insertion_date'] = now else: document = existing_document document['last_update_date'] = now my_collection.save(document) </code></pre> <p>My problem is that it is very slow (40 mins for less than 100 000 records, and I have millions of them in the update). I am pretty sure there is something builtin for doing this, but the document for update() is mmmhhh.... a bit terse.... (<a href="http://www.mongodb.org/display/DOCS/Updating" rel="noreferrer">http://www.mongodb.org/display/DOCS/Updating</a> )</p> <p>Can someone advise how to do it faster?</p>
2,923,719
9
0
null
2010-05-10 07:33:32.33 UTC
35
2022-09-01 19:10:05.057 UTC
2015-06-07 03:20:53.827 UTC
null
1,832,942
null
151,353
null
1
184
python|mongodb|bulkinsert|mongodb-query
241,611
<p>Sounds like you want to do an <code>upsert</code>. MongoDB has built-in support for this. Pass an extra parameter to your <code>update()</code> call: <code>{upsert:true}</code>. For example:</p> <pre><code>key = {'key':'value'} data = {'key2':'value2', 'key3':'value3'}; coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument </code></pre> <p>This replaces your if-find-else-update block entirely. It will insert if the key doesn't exist and will update if it does.</p> <p>Before:</p> <pre><code>{&quot;key&quot;:&quot;value&quot;, &quot;key2&quot;:&quot;Ohai.&quot;} </code></pre> <p>After:</p> <pre><code>{&quot;key&quot;:&quot;value&quot;, &quot;key2&quot;:&quot;value2&quot;, &quot;key3&quot;:&quot;value3&quot;} </code></pre> <p>You can also specify what data you want to write:</p> <pre><code>data = {&quot;$set&quot;:{&quot;key2&quot;:&quot;value2&quot;}} </code></pre> <p>Now your selected document will update the value of <code>key2</code> only and leave everything else untouched.</p>
2,717,294
Create a simple HTTP server with Java?
<p>What's the easiest way to create a simple HTTP server with Java? Are there any libraries in commons to facilitate this? I only need to respond to <code>GET/POST</code>, and I can't use an application server.</p> <p>What's the easiest way to accomplish this?</p>
2,717,309
13
2
null
2010-04-26 22:14:06.58 UTC
24
2021-01-08 14:45:29.253 UTC
null
null
null
null
78,182
null
1
67
java|http|post|get
143,269
<p>Use <a href="https://github.com/eclipse/jetty.project" rel="nofollow noreferrer">Jetty</a>. Here's the official example for <a href="https://www.eclipse.org/jetty/documentation/jetty-11/programming-guide/index.html#configuring-embedded-jetty-with-maven" rel="nofollow noreferrer">embedding Jetty</a>. (Here's an <a href="http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty" rel="nofollow noreferrer">outdated tutorial</a>.)</p> <p>Jetty is pretty lightweight, but it does provide a servlet container, which may contradict your requirement against using an &quot;application server&quot;.</p> <p>You can embed the Jetty server into your application. Jetty allows EITHER embedded OR servlet container options.</p> <p>Here is one more quick <a href="https://www.baeldung.com/jetty-embedded" rel="nofollow noreferrer">get started tutorial</a> along with the <a href="https://github.com/eugenp/tutorials/tree/master/libraries-server/src/main/java/com/baeldung/jetty" rel="nofollow noreferrer">source code</a>.</p>
2,504,178
LRU cache design
<p>Least Recently Used (LRU) Cache is to discard the least recently used items first How do you design and implement such a cache class? The design requirements are as follows:</p> <p>1) find the item as fast as we can</p> <p>2) Once a cache misses and a cache is full, we need to replace the least recently used item as fast as possible.</p> <p>How to analyze and implement this question in terms of design pattern and algorithm design?</p>
2,504,317
14
1
null
2010-03-23 22:48:53.757 UTC
64
2022-05-17 01:05:49.34 UTC
2019-03-03 21:21:58.91 UTC
user3133925
null
null
297,850
null
1
85
c++|algorithm|data-structures|lru
72,670
<p>A linked list + hashtable of pointers to the linked list nodes is the usual way to implement LRU caches. This gives O(1) operations (assuming a decent hash). Advantage of this (being O(1)): you can do a multithreaded version by just locking the whole structure. You don't have to worry about granular locking etc.</p> <p>Briefly, the way it works:</p> <p>On an access of a value, you move the corresponding node in the linked list to the head.</p> <p>When you need to remove a value from the cache, you remove from the tail end.</p> <p>When you add a value to cache, you just place it at the head of the linked list.</p> <p>Thanks to doublep, here is site with a C++ implementation: <a href="https://launchpad.net/libmct" rel="noreferrer">Miscellaneous Container Templates</a>.</p>
2,547,402
How to find the statistical mode?
<p>In R, <code>mean()</code> and <code>median()</code> are standard functions which do what you'd expect. <code>mode()</code> tells you the internal storage mode of the object, not the value that occurs the most in its argument. But is there is a standard library function that implements the statistical mode for a vector (or list)?</p>
8,189,441
35
2
null
2010-03-30 17:55:07.803 UTC
130
2022-05-24 19:29:58.17 UTC
2020-08-20 13:47:20.947 UTC
null
903,061
null
5,222
null
1
475
r|statistics|r-faq
357,190
<p>One more solution, which works for both numeric &amp; character/factor data:</p> <pre><code>Mode &lt;- function(x) { ux &lt;- unique(x) ux[which.max(tabulate(match(x, ux)))] } </code></pre> <p>On my dinky little machine, that can generate &amp; find the mode of a 10M-integer vector in about half a second.</p> <p>If your data set might have multiple modes, the above solution takes the same approach as <code>which.max</code>, and returns the <em>first-appearing</em> value of the set of modes. To return <em>all</em> modes, use this variant (from @digEmAll in the comments):</p> <pre><code>Modes &lt;- function(x) { ux &lt;- unique(x) tab &lt;- tabulate(match(x, ux)) ux[tab == max(tab)] } </code></pre>
42,235,175
How do I add contents of text file as a section in an ELF file?
<p>I have a NASM assembly file that I am assembling and linking (on Intel-64 Linux).</p> <p>There is a text file, and I want the contents of the text file to appear in the resulting binary (as a string, basically). The binary is an ELF executable.</p> <p>My plan is to create a new readonly data section in the ELF file (equivalent to the conventional <code>.rodata</code> section).</p> <p>Ideally, there would be a tool to add a file verbatim as a new section in an elf file, or a linker option to include a file verbatim.</p> <p>Is this possible?</p>
42,238,374
1
0
null
2017-02-14 20:02:24.753 UTC
17
2017-11-21 19:49:25.027 UTC
2017-02-15 00:31:33.41 UTC
null
3,857,942
null
242,457
null
1
17
linker|x86|nasm|elf|objcopy
8,093
<p>This is possible and most easily done using <a href="https://sourceware.org/binutils/docs/binutils/objcopy.html" rel="noreferrer"><em>OBJCOPY</em></a> found in <em>BINUTILS</em>. You effectively take the data file as binary input and then output it to an object file format that can be linked to your program.</p> <p><em>OBJCOPY</em> will even produce a start and end symbol as well as the size of the data area so that you can reference them in your code. The basic idea is that you will want to tell it your input file is binary (even if it is text); that you will be targeting an x86-64 object file; specify the input file name and the output file name.</p> <p>Assume we have an input file called <code>myfile.txt</code> with the contents:</p> <pre><code>the quick brown fox jumps over the lazy dog </code></pre> <p>Something like this would be a starting point:</p> <pre><code>objcopy --input binary \ --output elf64-x86-64 \ --binary-architecture i386:x86-64 \ myfile.txt myfile.o </code></pre> <p>If you wanted to generate 32-bit objects you could use:</p> <pre><code>objcopy --input binary \ --output elf32-i386 \ --binary-architecture i386 \ myfile.txt myfile.o </code></pre> <p>The output would be an object file called <code>myfile.o</code> . If we were to review the headers of the object file using <em>OBJDUMP</em> and a command like <code>objdump -x myfile.o</code> we would see something like this:</p> <pre><code>myfile.o: file format elf64-x86-64 myfile.o architecture: i386:x86-64, flags 0x00000010: HAS_SYMS start address 0x0000000000000000 Sections: Idx Name Size VMA LMA File off Algn 0 .data 0000002c 0000000000000000 0000000000000000 00000040 2**0 CONTENTS, ALLOC, LOAD, DATA SYMBOL TABLE: 0000000000000000 l d .data 0000000000000000 .data 0000000000000000 g .data 0000000000000000 _binary_myfile_txt_start 000000000000002c g .data 0000000000000000 _binary_myfile_txt_end 000000000000002c g *ABS* 0000000000000000 _binary_myfile_txt_size </code></pre> <p>By default it creates a <code>.data</code> section with contents of the file and it creates a number of symbols that can be used to reference the data. </p> <pre><code>_binary_myfile_txt_start _binary_myfile_txt_end _binary_myfile_txt_size </code></pre> <p>This is effectively the address of the start byte, the end byte, and the size of the data that was placed into the object from the file <code>myfile.txt</code>. <em>OBJCOPY</em> will base the symbols on the input file name. <code>myfile.txt</code> is mangled into <code>myfile_txt</code> and used to create the symbols.</p> <p>One problem is that a <code>.data</code> section is created which is read/write/data as seen here:</p> <pre><code>Idx Name Size VMA LMA File off Algn 0 .data 0000002c 0000000000000000 0000000000000000 00000040 2**0 CONTENTS, ALLOC, LOAD, DATA </code></pre> <p>You specifically are requesting a <code>.rodata</code> section that would also have the <em>READONLY</em> flag specified. You can use the <code>--rename-section</code> option to change <code>.data</code> to <code>.rodata</code> and specify the needed flags. You could add this to the command line:</p> <pre><code>--rename-section .data=.rodata,CONTENTS,ALLOC,LOAD,READONLY,DATA </code></pre> <p>Of course if you want to call the section something other than <code>.rodata</code> with the same flags as a read only section you can change <code>.rodata</code> in the line above to the name you want to use for the section.</p> <p>The final version of the command that should generate the type of object you want is:</p> <pre><code>objcopy --input binary \ --output elf64-x86-64 \ --binary-architecture i386:x86-64 \ --rename-section .data=.rodata,CONTENTS,ALLOC,LOAD,READONLY,DATA \ myfile.txt myfile.o </code></pre> <p>Now that you have an object file, how can you use this in <em>C</em> code (as an example). The symbols generated are a bit unusual and there is a reasonable explanation on the <a href="http://wiki.osdev.org/Using_Linker_Script_Values" rel="noreferrer"><em>OS Dev Wiki</em></a>:</p> <blockquote> <p>A common problem is getting garbage data when trying to use a value defined in a linker script. This is usually because they're dereferencing the symbol. A symbol defined in a linker script (e.g. _ebss = .;) is only a symbol, not a variable. If you access the symbol using extern uint32_t _ebss; and then try to use _ebss the code will try to read a 32-bit integer from the address indicated by _ebss.</p> <p>The solution to this is to take the address of _ebss either by using it as &amp;_ebss or by defining it as an unsized array (extern char _ebss[];) and casting to an integer. (The array notation prevents accidental reads from _ebss as arrays must be explicitly dereferenced)</p> </blockquote> <p>Keeping this in mind we could create this <em>C</em> file called <code>main.c</code>:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; /* These are external references to the symbols created by OBJCOPY */ extern char _binary_myfile_txt_start[]; extern char _binary_myfile_txt_end[]; extern char _binary_myfile_txt_size[]; int main() { char *data_start = _binary_myfile_txt_start; char *data_end = _binary_myfile_txt_end; size_t data_size = (size_t)_binary_myfile_txt_size; /* Print out the pointers and size */ printf ("data_start %p\n", data_start); printf ("data_end %p\n", data_end); printf ("data_size %zu\n", data_size); /* Print out each byte until we reach the end */ while (data_start &lt; data_end) printf ("%c", *data_start++); return 0; } </code></pre> <p>You can compile and link with:</p> <pre><code>gcc -O3 main.c myfile.o </code></pre> <p>The output should look something like:</p> <pre><code>data_start 0x4006a2 data_end 0x4006ce data_size 44 the quick brown fox jumps over the lazy dog </code></pre> <hr> <p>A <em>NASM</em> example of usage is similar in nature to the <em>C</em> code. The following assembly program called <code>nmain.asm</code> writes the same string to standard output using <a href="http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/" rel="noreferrer">Linux x86-64 System Calls</a>:</p> <pre><code>bits 64 global _start extern _binary_myfile_txt_start extern _binary_myfile_txt_end extern _binary_myfile_txt_size section .text _start: mov eax, 1 ; SYS_Write system call mov edi, eax ; Standard output FD = 1 mov rsi, _binary_myfile_txt_start ; Address to start of string mov rdx, _binary_myfile_txt_size ; Length of string syscall xor edi, edi ; Return value = 0 mov eax, 60 ; SYS_Exit system call syscall </code></pre> <p>This can be assembled and linked with:</p> <pre><code>nasm -f elf64 -o nmain.o nmain.asm gcc -m64 -nostdlib nmain.o myfile.o </code></pre> <p>The output should appear as:</p> <pre><code>the quick brown fox jumps over the lazy dog </code></pre>
10,539,483
Is there a better way to count the lines in a text file?
<p>Below is what I've been using. While it does work, my program locks up when trying to count a rather large file, say 10,000 or more lines. Smaller files run in no time.</p> <p>Is there a better or should I say faster way to count the lines in a text file?</p> <p>Here's what I'm currently using:</p> <pre><code> Dim selectedItems = (From i In ListBox1.SelectedItems).ToArray() For Each selectedItem In selectedItems ListBox2.Items.Add(selectedItem) ListBox1.Items.Remove(selectedItem) Dim FileQty = selectedItem.ToString 'reads the data file and returns the qty Dim intLines As Integer = 0 'Dim sr As New IO.StreamReader(OpenFileDialog1.FileName) Dim sr As New IO.StreamReader(TextBox1_Path.Text + "\" + FileQty) Do While sr.Peek() &gt;= 0 TextBox1.Text += sr.ReadLine() &amp; ControlChars.CrLf intLines += 1 Loop ListBox6.Items.Add(intLines) Next </code></pre>
10,539,529
3
0
null
2012-05-10 17:44:41.693 UTC
1
2015-08-01 00:40:57.56 UTC
null
null
null
null
1,221,294
null
1
11
vb.net|visual-studio-2010|text-files|streamreader
59,293
<pre><code>Imports System.IO.File 'At the beginning of the file Dim lineCount = File.ReadAllLines("file.txt").Length </code></pre> <p>See <a href="https://stackoverflow.com/questions/119559/determine-the-number-of-lines-within-a-text-file">this</a> question.</p>
10,478,625
How can I check that if synonym already exist then don't create synonym
<p>I am using Oracle SQL developer 2.1 for creating a synonym.</p> <pre><code>CREATE OR REPLACE SYNONYM "ETKS_PR_RW"."SQ_CLDOS_ATCHMNT_ID" FOR "CLDOS_ONLINE_DBA"."SQ_CLDOS_ATCHMNT_ID"; </code></pre> <p>How can I check that if this synonym already exists then don't create the synonym if it does.</p>
10,479,898
2
0
null
2012-05-07 07:59:38.163 UTC
1
2012-05-07 10:36:14.7 UTC
2012-05-07 09:37:38.99 UTC
null
330,315
null
389,200
null
1
14
sql|oracle|synonym
97,846
<p>As you're using the <code>replace</code> keyword there is no need to check whether the synonym exists first. You will over-write whatever synonym existed with the previous name. </p> <p>The only reason to be wary of using <code>replace</code> is if you might have a different synonym with the same name. If your database is organised well this shouldn't happen. You should always know what all of your objects are and where the synonyms point.</p> <p>However, if you do want to there are a couple of options:</p> <ol> <li>Remove <code>replace</code>. The statement will throw an error if the synonym already exists and won't get over-written.</li> <li><p>Query the data-dictionary, as you're in multiple schemas <a href="http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_2100.htm#REFRN20273"><code>all_synonyms</code></a> seems like the best bet.</p> <pre><code>select * from all_synonyms where owner = 'ETKS_PR_RW' and synonym_name = 'SQ_CLDOS_ATCHMNT_ID'; </code></pre></li> </ol> <p>If you want to combine these into a single block then you can do something like this:</p> <pre><code>declare l_exists number; begin -- check whether the synonym exists select 1 into l_exists from all_synonyms where owner = 'ETKS_PR_RW' and synonym_name = 'SQ_CLDOS_ATCHMNT_ID'; -- an error gets raise if it doesn-t. exception when no_data_found then -- DDL has to be done inside execute immediate in a block. execute immediate 'CREATE OR REPLACE SYNONYM ETKS_PR_RW.SQ_CLDOS_ATCHMNT_ID FOR CLDOS_ONLINE_DBA.SQ_CLDOS_ATCHMNT_ID'; end; / </code></pre> <p>On a slightly separate not <em>please do not</em> quote your object names. Oracle can have cased objects, but it is very, very rarely worth the hassle. All objects will be upper-cased automatically so you don't need the <code>"</code>.</p>
10,759,577
Underscore issues: Jekyll + redcarpet == Github flavored markdown?
<p>I'm buliding a site with github pages and do <em>not</em> want underscores within words to italicize portions of those words. E.g. <code>function_name_here</code> should not render with <em><code>name</code></em> italicized. I understand github flavored markdown is supposed to be smart like this; but I'm still seeing italics in my rendered page. </p> <p>I have set in my <code>_config.yml</code></p> <pre><code>markdown: redcarpet </code></pre> <p>... anything else I need to do to get Github flavored markdown behavior?</p>
10,790,731
1
0
null
2012-05-25 18:23:44.87 UTC
9
2014-12-24 20:08:13.37 UTC
2014-12-24 20:08:13.37 UTC
null
318,206
null
318,206
null
1
18
github|markdown|jekyll|github-pages|redcarpet
5,475
<p>The version of Jekyll available on github's gh-pages does not run the latest version of redcarpet (redcarpet2) which supports these features. <a href="https://github.com/nono/Jekyll-plugins" rel="noreferrer">There's a plugin to provide the latest version of redcarpet to Jekyll</a>, in which you can then configure to the behaviour you want, i.e. then add this to your <code>_config.yml</code></p> <pre><code>markdown: redcarpet2 redcarpet: extensions: ["no_intra_emphasis", "fenced_code_blocks", "autolink", "tables", "with_toc_data"] </code></pre> <p>Yes, I agree it seems crazy that github doesn't run the same markdown parser on gh-pages as it uses for its github-flavored-markdown everywhere else on the site. </p>
10,782,054
What does the "~" (tilde/squiggle/twiddle) CSS selector mean?
<p>Searching for the <code>~</code> character isn't easy. I was looking over some CSS and found this</p> <pre><code>.check:checked ~ .content { } </code></pre> <p>What does it mean?</p>
10,782,297
3
0
null
2012-05-28 09:10:00.95 UTC
149
2022-08-22 14:19:32.643 UTC
2020-04-17 18:35:18.317 UTC
null
2,756,409
null
950,147
null
1
1,053
css|css-selectors
353,163
<p>The <code>~</code> selector is in fact the <a href="https://www.w3.org/TR/selectors-3/#general-sibling-combinators" rel="noreferrer">subsequent-sibling combinator</a> (previously called general sibling combinator <a href="https://github.com/w3c/csswg-drafts/issues/1382" rel="noreferrer">until 2017</a>):</p> <blockquote> <p>The subsequent-sibling combinator is made of the &quot;tilde&quot; (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.</p> </blockquote> <p>Consider the following example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.a ~ .b { background-color: powderblue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li class="b"&gt;1st&lt;/li&gt; &lt;li class="a"&gt;2nd&lt;/li&gt; &lt;li&gt;3rd&lt;/li&gt; &lt;li class="b"&gt;4th&lt;/li&gt; &lt;li class="b"&gt;5th&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p><code>.a ~ .b</code> matches the 4th and 5th list item because they:</p> <ul> <li>Are <code>.b</code> elements</li> <li>Are siblings of <code>.a</code></li> <li>Appear after <code>.a</code> in HTML source order.</li> </ul> <p>Likewise, <code>.check:checked ~ .content</code> matches all <code>.content</code> elements that are siblings of <code>.check:checked</code> and appear after it.</p>
10,326,762
Objective-C Simplest way to create comma separated string from an array of objects
<p>So I have a nsmutablearray with a bunch of objects in it. I want to create a comma separated string of the id value of each object.</p>
10,326,807
4
0
null
2012-04-26 03:19:15.513 UTC
13
2021-02-11 11:15:05.087 UTC
2014-12-17 16:43:13.353 UTC
null
1,485,701
null
177,308
null
1
67
objective-c|arrays|swift|nsmutablearray
39,128
<p>Use the <code>NSArray</code> instance method <code>componentsJoinedByString:</code>.</p> <p>In Objective-C:</p> <pre><code>- (NSString *)componentsJoinedByString:(NSString *)separator </code></pre> <p>In Swift:</p> <pre><code>func componentsJoinedByString(separator: String) -&gt; String </code></pre> <p><strong>Example:</strong></p> <p>In Objective-C:</p> <pre><code>NSString *joinedComponents = [array componentsJoinedByString:@","]; </code></pre> <p>In Swift:</p> <pre><code>let joinedComponents = array.joined(seperator: ",") </code></pre>
6,006,980
Cannot connect to SQL Server express from SSMS
<p><img src="https://i.stack.imgur.com/VEcKQ.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/QV1I0.png" alt="enter image description here"></p> <p>I have installed SQL Server Management Studio 2005. I can't find my server name when I click browse for more but i know that my server name will be the same as the user name as in the picture below.</p>
6,006,997
2
4
null
2011-05-15 06:58:40.747 UTC
3
2020-09-02 01:53:58.17 UTC
2014-03-15 10:20:38.127 UTC
null
330,315
null
485,880
null
1
20
sql|sql-server|sql-server-2005|ssms
42,775
<p>Use <code>.</code> or <code>(local)</code> or <code>localhost</code> for server name if you installed the server as default instance.<br></p> <p>Use <code>.\sqlexpress</code> or <code>localhost\sqlexpress</code> if you have SQL Express.</p> <p>The server name syntax is</p> <p><code>Servername\InstanceName</code></p> <p>If the instance is default you use just Servername.<br> For SQL Express, instance name is sqlexpress by default.</p>
5,825,820
how to capture the '#' character on different locale keyboards in WPF/C#?
<p>My WPF application handles keyboard presses and specifically the # and * character as it is a VoIP phone.</p> <p>I have a bug though with international keyboards, and in particular the British english keyboard. Normally I listen for the 3 key and if the shift key modifier is down we fire off an event to do stuff. However on the British keyboard this is the '£' character. I found that the UK english keyboard has a dedicated key for '#'. Obviously we could just listen for that particular key, but that doesn't solve the case for US english which is shift-3 and all the countless other keyboards that put it somewhere else.</p> <p>Long story short, how do I listen for a particular character from a key press, whether it's a key combo or single key and react to it?</p>
5,826,175
2
0
null
2011-04-28 22:34:45.207 UTC
11
2019-09-24 20:22:42.573 UTC
2012-05-04 16:56:18.303 UTC
null
1,079,354
null
36,234
null
1
34
c#|wpf|keypress
31,998
<p>The function below, GetCharFromKey(Key key) will do the trick.</p> <p>It uses a series of win32 calls to decode the key pressed:</p> <ol> <li><p>get the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.keyinterop.virtualkeyfromkey.aspx" rel="noreferrer">virtual key from WPF key</a></p></li> <li><p>get the <a href="http://msdn.microsoft.com/en-us/library/ms646306.aspx" rel="noreferrer">scan code from the virtual key</a></p></li> <li><p>get <a href="http://msdn.microsoft.com/en-us/library/ms646320.aspx" rel="noreferrer">your unicode character </a></p></li> </ol> <p>This <a href="http://web.archive.org/web/20111225141637/http://huddledmasses.org:80/how-to-get-the-character-and-virtualkey-from-a-wpf-keydown-event/" rel="noreferrer">old post</a> describes it in a bit more detail.</p> <pre><code> public enum MapType : uint { MAPVK_VK_TO_VSC = 0x0, MAPVK_VSC_TO_VK = 0x1, MAPVK_VK_TO_CHAR = 0x2, MAPVK_VSC_TO_VK_EX = 0x3, } [DllImport("user32.dll")] public static extern int ToUnicode( uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] StringBuilder pwszBuff, int cchBuff, uint wFlags); [DllImport("user32.dll")] public static extern bool GetKeyboardState(byte[] lpKeyState); [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint uCode, MapType uMapType); public static char GetCharFromKey(Key key) { char ch = ' '; int virtualKey = KeyInterop.VirtualKeyFromKey(key); byte[] keyboardState = new byte[256]; GetKeyboardState(keyboardState); uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC); StringBuilder stringBuilder = new StringBuilder(2); int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0); switch (result) { case -1: break; case 0: break; case 1: { ch = stringBuilder[0]; break; } default: { ch = stringBuilder[0]; break; } } return ch; } </code></pre>
60,645,401
Xcode logging: "Metal API Validation Enabled"
<p>I'm building a macOS app via Xcode. Every time I build, I get the log output:</p> <blockquote> <p>Metal API Validation Enabled</p> </blockquote> <p>To my knowledge my app is not using any Metal features. I'm not using hardware-accelerated 3D graphics or shaders or video game features or anything like that.</p> <p>Why is Xcode printing Metal API log output?</p> <p>Is Metal being used in my app? Can I or should I disable it?</p> <p>How can I <strong>disable</strong> this "Metal API Validation Enabled" log message?</p>
60,645,489
4
0
null
2020-03-11 22:49:10.413 UTC
4
2022-01-16 08:43:24.46 UTC
null
null
null
null
1,265,393
null
1
29
ios|xcode|macos|metal|oslog
23,779
<p>Toggle Metal API Validation via your Xcode Scheme:</p> <blockquote> <p>Scheme &gt; Edit Scheme... &gt; Run &gt; Diagnostics &gt; Metal API Validation.</p> </blockquote> <p>It's a checkbox, so the possible options are <code>Enabled</code> or <code>Disabled</code>.</p> <p>Disabling sets the key <code>enableGPUValidationMode = 1</code> in your <code>.xcscheme</code> file.</p> <p>After disabling, Xcode no longer logs the &quot;Metal API Validation Enabled&quot; log message.</p> <p><strong>Note:</strong> In Xcode 11 and below, the option appears in the &quot;Options&quot; tab of the Scheme Editor (instead of the &quot;Diagnostics&quot; tab).</p>
19,632,933
AngularJS group check box validation
<p>I have a list of check boxes, of which at least one is compulsory. I have tried to achieve this via AngularJS validation, but had a hard time. Below is my code:</p> <pre class="lang-js prettyprint-override"><code>// Code goes here for js var app = angular.module('App', []); function Ctrl($scope) { $scope.formData = {}; $scope.formData.selectedGender = ''; $scope.gender = [{ 'name': 'Male', 'id': 1 }, { 'name': 'Female', 'id': 2 }]; $scope.formData.selectedFruits = {}; $scope.fruits = [{ 'name': 'Apple', 'id': 1 }, { 'name': 'Orange', 'id': 2 }, { 'name': 'Banana', 'id': 3 }, { 'name': 'Mango', 'id': 4 }, ]; $scope.submitForm = function() { } } </code></pre> <pre class="lang-html prettyprint-override"><code>// Code goes here for html &lt;!doctype html&gt; &lt;html ng-app="App"&gt; &lt;head&gt; &lt;!-- css file --&gt; &lt;!--App file --&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"&gt;&lt;/script&gt; &lt;!-- External file --&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="Ctrl"&gt; &lt;form class="Scroller-Container"&gt; &lt;div ng-app&gt; &lt;form class="Scroller-Container" ng-submit="submit()" ng-controller="Ctrl"&gt; &lt;div&gt; What would you like? &lt;div ng-repeat="(key, val) in fruits"&gt; &lt;input type="checkbox" ng-model="formData.selectedFruits[val.id]" name="group[]" id="group[{{val.id}}]" required /&gt;{{val.name}} &lt;/div&gt; &lt;br /&gt; &lt;div ng-repeat="(key, val) in gender"&gt; &lt;input type="radio" ng-model="$parent.formData.selectedGender" name="formData.selectedGender" id="{{val.id}}" value="{{val.id}}" required /&gt;{{val.name}} &lt;/div&gt; &lt;br /&gt; &lt;/div&gt; &lt;pre&gt;{{formData.selectedFruits}}&lt;/pre&gt; &lt;input type="submit" id="submit" value="Submit" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;br&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the code in plunker: <a href="http://plnkr.co/edit/Bz9yhSoPYUNzFDpfASwt?p=preview">http://plnkr.co/edit/Bz9yhSoPYUNzFDpfASwt?p=preview</a> Has anyone done this on AngularJS? Making the checkboxes required, forces me to select all the checkbox values. This problem is also not documented in the AngularJS documentation.</p>
19,633,860
4
0
null
2013-10-28 10:58:47.72 UTC
18
2017-01-17 15:57:23.537 UTC
2016-05-23 07:57:12.66 UTC
null
2,333,214
null
1,113,027
null
1
54
javascript|jquery|angularjs
62,622
<p>If you want to require at least one item in group being selected, it's possible to define dynamic <strong>required</strong> attribute with <strong>ng-required</strong>.</p> <p>For gender radio buttons this would be easy:</p> <pre><code>&lt;input type="radio" ng-model="formData.selectedGender" value="{{val.id}}" ng-required="!formData.selectedGender" &gt; </code></pre> <p>Checkbox group would be easy too, if you used array to store selected fruits (just check array length), but with object it's necessary to check if any of values are set to true with filter or function in controller:</p> <pre><code>$scope.someSelected = function (object) { return Object.keys(object).some(function (key) { return object[key]; }); } </code></pre> <pre><code>&lt;input type="checkbox" value="{{val.id}}" ng-model="formData.selectedFruits[val.id]" ng-required="!someSelected(formData.selectedFruits)" &gt; </code></pre> <p><strong>Update:</strong></p> <pre><code>const someSelected = (object = {}) =&gt; Object.keys(object).some(key =&gt; object[key]) </code></pre> <p>Also keep in mind that it will return false if value is 0.</p>
21,533,158
Remove outliers fully from multiple boxplots made with ggplot2 in R and display the boxplots in expanded format
<p>I have some data <a href="https://www.dropbox.com/s/4wrqfcvr0tngimt/data.txt" rel="noreferrer">here</a> [in a .txt file] which I read into a data frame df,</p> <pre><code>df &lt;- read.table("data.txt", header=T,sep="\t") </code></pre> <p>I remove the negative values in the column <code>x</code> (since I need only positive values) of the <code>df</code> using the following code,</p> <pre><code>yp &lt;- subset(df, x&gt;0) </code></pre> <p>Now I want plot multiple box plots in the same layer. I first melt the data frame <code>df</code>, and the plot which results contains several outliers as shown below.</p> <pre><code># Melting data frame df df_mlt &lt;-melt(df, id=names(df)[1]) # plotting the boxplots plt_wool &lt;- ggplot(subset(df_mlt, value &gt; 0), aes(x=ID1,y=value)) + geom_boxplot(aes(color=factor(ID1))) + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) + theme_bw() + theme(legend.text=element_text(size=14), legend.title=element_text(size=14))+ theme(axis.text=element_text(size=20)) + theme(axis.title=element_text(size=20,face="bold")) + labs(x = "x", y = "y",colour="legend" ) + annotation_logticks(sides = "rl") + theme(panel.grid.minor = element_blank()) + guides(title.hjust=0.5) + theme(plot.margin=unit(c(0,1,0,0),"mm")) plt_wool </code></pre> <p><img src="https://i.stack.imgur.com/xFGeU.png" alt="Boxplot with outliers"></p> <p>Now I need to have a plot without any outliers, so to do this first I compute the lower and upper bound whiskers I use the following code as suggested <a href="https://stackoverflow.com/questions/5677885/ignore-outliers-in-ggplot2-boxplot">here</a>,</p> <pre><code>sts &lt;- boxplot.stats(yp$x)$stats </code></pre> <p>To remove the outlier I add the upper and lower whisker limits as below,</p> <pre><code>p1 = plt_wool + coord_cartesian(ylim = c(sts*1.05,sts/1.05)) </code></pre> <p>The resulting plot is shown below, while the above line of code correctly removes most of the top outliers all the bottom outliers still remain. Could someone please suggest how to remove all the outlier completely from this plot, Thanks.</p> <p><img src="https://i.stack.imgur.com/0RORB.png" alt="enter image description here"></p>
21,548,689
5
0
null
2014-02-03 17:01:32.263 UTC
12
2014-11-11 02:06:58.443 UTC
2017-05-23 12:34:09.103 UTC
null
-1
null
2,834,604
null
1
17
r|ggplot2|boxplot|outliers
51,419
<p>Based on suggestions by @Sven Hohenstein, @Roland and @lukeA I have solved the problem for displaying multiple boxplots in expanded form without outliers.</p> <p>First plot the box plots without outliers by using <code>outlier.colour=NA</code> in <code>geom_boxplot()</code></p> <pre><code>plt_wool &lt;- ggplot(subset(df_mlt, value &gt; 0), aes(x=ID1,y=value)) + geom_boxplot(aes(color=factor(ID1)),outlier.colour = NA) + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) + theme_bw() + theme(legend.text=element_text(size=14), legend.title=element_text(size=14))+ theme(axis.text=element_text(size=20)) + theme(axis.title=element_text(size=20,face="bold")) + labs(x = "x", y = "y",colour="legend" ) + annotation_logticks(sides = "rl") + theme(panel.grid.minor = element_blank()) + guides(title.hjust=0.5) + theme(plot.margin=unit(c(0,1,0,0),"mm")) </code></pre> <p>Then compute the lower, upper whiskers using <code>boxplot.stats()</code> as the code below. Since I only take into account positive values, I choose them using the condition in the <code>subset()</code>.</p> <pre><code>yp &lt;- subset(df, x&gt;0) # Choosing only +ve values in col x sts &lt;- boxplot.stats(yp$x)$stats # Compute lower and upper whisker limits </code></pre> <p>Now to achieve full expanded view of the multiple boxplots, it is useful to modify the y-axis limit of the plot inside <code>coord_cartesian()</code> function as below,</p> <pre><code>p1 = plt_wool + coord_cartesian(ylim = c(sts[2]/2,max(sts)*1.05)) </code></pre> <p><strong>Note:</strong> The limits of y should be adjusted according to the specific case. In this case I have chosen half of lower whisker limit for ymin. </p> <p>The resulting plot is below,</p> <p><img src="https://i.stack.imgur.com/mg2sk.png" alt=""></p>
53,229,221
Terminal error: zsh: permission denied: ./startup.sh
<p>I am running a command</p> <pre><code>./startup.sh nginx:start </code></pre> <p>and I am getting this error message</p> <pre><code>zsh: permission denied: ./startup.sh </code></pre> <p>why could this be happening?</p>
53,229,323
7
1
null
2018-11-09 16:01:15.46 UTC
15
2022-08-22 21:18:02.077 UTC
2022-08-22 21:18:02.077 UTC
null
4,685,471
null
3,424,817
null
1
109
macos|nginx|terminal|sh
291,857
<p>Be sure to give it the execution permission.</p> <pre><code>cd ~/the/script/folder chmod +x ./startup.sh </code></pre> <p>This will give exec permission to user, group and other, so beware of possible security issues. To restrict permission to a single access class, you can use:</p> <pre><code>chmod u+x ./startup.sh </code></pre> <p>This will grant exec permission only to user</p> <p><a href="https://kb.iu.edu/d/abdb" rel="noreferrer">For reference</a></p>
8,675,702
How do you check if an MKAnnotation is available within a MKCoordinateRegion
<p>I've noticed that if I use MKMapView's <code>selectAnnotation:animated:</code>, that it will scroll my map off screen if the MKAnnotation is not displayed in the current MKCoordinateRegion that my map is displaying.</p> <p>Is there a trivial way to check if an annotation is currently on screen within the specified MKCoordinateRegion? I'd like to be able to select an annotation that's only on screen and not something offscreen. </p>
8,675,759
1
0
null
2011-12-30 02:55:22.11 UTC
9
2011-12-30 03:04:33.813 UTC
null
null
null
null
175,836
null
1
8
iphone|ios|mkmapview
5,925
<p>Use the <code>annotationsInMapRect:</code> method in the <a href="http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/doc/uid/TP40008205" rel="noreferrer"><code>MKMapView</code></a> class. It returns a <code>NSSet</code> of all annotation objects that are visible in the given map rect. Use the <code>containsObject:</code> method of <code>NSSet</code> to test if the annotation is present in that set of visible annotations.</p> <pre><code>MKMapRect visibleMapRect = aMapView.visibleMapRect; NSSet *visibleAnnotations = [aMapView annotationsInMapRect:visibleMapRect]; BOOL annotationIsVisible = [visibleAnnotations containsObject:someAnnotation]; </code></pre> <p>Also <code>visibleMapRect</code> is same as the region but just a different form of representation. Take from the docs,</p> <blockquote> <p><code>visibleMapRect</code></p> <p>The area currently displayed by the map view.</p> <p><code>@property(nonatomic) MKMapRect visibleMapRect</code></p> <p>This property represents the same basic information as the region property but specified as a map rectangle instead of a region.</p> </blockquote>
8,850,755
Check if 'this' checkbox is checked
<p>How can I work out if 'this' checkbox has been checked using the this command?</p> <p>I have the following but not sure how to implement this (so it only checks the single checkbox selected rather than all on the page</p> <pre><code>if ($('input[type="checkbox"]').is(':checked') </code></pre>
8,850,795
7
0
null
2012-01-13 12:43:47.487 UTC
2
2012-01-13 12:52:43.387 UTC
null
null
null
null
218,725
null
1
22
jquery|checkbox
51,218
<p>What about this?</p> <pre><code>if($(this).is(':checked')) </code></pre>
8,408,504
How to parse a String containing XML in Java and retrieve the value of the root node?
<p>I have XML in the form of a String that contains </p> <pre><code>&lt;message&gt;HELLO!&lt;/message&gt; </code></pre> <p>How can I get the String "Hello!" from the XML? It should be ridiculously easy but I am lost. The XML isn't in a doc, it is simply a String. </p>
8,408,730
6
0
null
2011-12-06 23:41:16.017 UTC
18
2015-03-10 18:11:09.22 UTC
2011-12-14 19:43:30.437 UTC
null
592,746
null
938,810
null
1
40
java|xml|root
162,289
<p>Using <strong><a href="http://www.jdom.org/">JDOM</a></strong>:</p> <pre><code>String xml = "&lt;message&gt;HELLO!&lt;/message&gt;"; org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder(); try { org.jdom.Document doc = saxBuilder.build(new StringReader(xml)); String message = doc.getRootElement().getText(); System.out.println(message); } catch (JDOMException e) { // handle JDOMException } catch (IOException e) { // handle IOException } </code></pre> <p>Using the <strong><a href="http://xerces.apache.org/">Xerces</a></strong> <code>DOMParser</code>:</p> <pre><code>String xml = "&lt;message&gt;HELLO!&lt;/message&gt;"; DOMParser parser = new DOMParser(); try { parser.parse(new InputSource(new java.io.StringReader(xml))); Document doc = parser.getDocument(); String message = doc.getDocumentElement().getTextContent(); System.out.println(message); } catch (SAXException e) { // handle SAXException } catch (IOException e) { // handle IOException } </code></pre> <p>Using the <strong><a href="http://docs.oracle.com/javase/tutorial/jaxp/index.html">JAXP</a></strong> interfaces:</p> <pre><code>String xml = "&lt;message&gt;HELLO!&lt;/message&gt;"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); try { Document doc = db.parse(is); String message = doc.getDocumentElement().getTextContent(); System.out.println(message); } catch (SAXException e) { // handle SAXException } catch (IOException e) { // handle IOException } } catch (ParserConfigurationException e1) { // handle ParserConfigurationException } </code></pre>
8,726,396
Hibernate Criteria Join with 3 Tables
<p>I am looking for a hibernate criteria to get following:</p> <p>Dokument.class is mapped to Role roleId</p> <p>Role.class has a ContactPerson contactId</p> <p>Contact.class FirstName LastName</p> <p>I want to search for First or LastName on the Contact class and retrieve a list of Dokuments connected.</p> <p>I have tried something like this:</p> <pre><code>session.createCriteria(Dokument.class) .setFetchMode("role",FetchMode.JOIN) .setFetchMode("contact",FetchMode.JOIN) .add(Restrictions.eq("LastName","Test")).list(); </code></pre> <p>I get an error could not resolve property "LastName" for class "Dokument"</p> <p>Can someone explain why the join searches on Dokument and not on all joined tables? Thanks in advance for all the help!</p>
8,726,763
1
0
null
2012-01-04 11:50:44.117 UTC
26
2017-04-20 04:03:10.683 UTC
null
null
null
null
316,408
null
1
64
hibernate|join|criteria
165,690
<p>The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:</p> <pre><code>Criteria c = session.createCriteria(Dokument.class, "dokument"); c.createAlias("dokument.role", "role"); // inner join by default c.createAlias("role.contact", "contact"); c.add(Restrictions.eq("contact.lastName", "Test")); return c.list(); </code></pre> <p>This is of course well explained in the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querycriteria.html#querycriteria-associations" rel="noreferrer">Hibernate reference manual</a>, and the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Criteria.html" rel="noreferrer">javadoc for Criteria</a> even has examples. Read the documentation: it has plenty of useful information.</p>
30,720,354
jQuery .validate() submitHandler not firing
<p>I'm loading a dialog box with a form that's built on-the-fly using <a href="http://bootboxjs.com/" rel="noreferrer">Bootbox.js</a> and I'm validating user input with a jQuery validate plugin.</p> <p>Validation works just fine, but the <code>submitHandler</code> is ignored when the form is filled in successfully.</p> <p>What's going wrong?</p> <pre><code>submitHandler: function(form) { alert("Submitted!"); var $form = $(form); $form.submit(); } </code></pre> <p>See the full example below. I've looked at other posts where a similar issue has been raised. Unfortunately they seem to have the form rendered on the page whereas I'm rendering my via jQuery.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on("click", "[data-toggle=\"contactAdmin\"]", function() { bootbox.dialog({ title: "Contact admin", buttons: { close: { label: 'Close', className: "btn btn-sm btn-danger", callback: function() {} }, success: { label: "Submit", className: "btn btn-sm btn-primary", callback: function() { $("#webteamContactForm").validate({ rules: { requestType: { required: true } }, messages: { requestType: { required: "Please specify what your request is for", } }, highlight: function(a) { $(a).closest(".form-group").addClass("has-error"); }, unhighlight: function(a) { $(a).closest(".form-group").removeClass("has-error"); }, errorElement: "span", errorClass: "help-blocks", errorPlacement: function(error, element) { if (element.is(":radio")) { error.appendTo(element.parents('.requestTypeGroup')); } else { // This is the default behavior error.insertAfter(element); } }, submitHandler: function(form) { alert("Submitted!"); var $form = $(form); $form.submit(); } }).form(); return false; } } }, message: '&lt;div class="row"&gt; ' + '&lt;div class="col-md-12"&gt; ' + '&lt;form id="webteamContactForm" class="form-horizontal" method="post"&gt; ' + '&lt;p&gt;Please get in touch if you wish to delete this content&lt;/p&gt;' + '&lt;div class="form-group"&gt; ' + '&lt;div class="col-md-12"&gt; ' + '&lt;textarea id="message" name="message" class="form-control input-md" rows="3" cols="50"&gt;This email is to notify you the creator is putting a request for the following item\n\n' + this.attributes.getNamedItem("data-url").value + '\n\n' + '&lt;/textarea&gt; ' + '&lt;span class="help-block"&gt;Feel free to change the message and add more information. Please ensure you always provide the link.&lt;/span&gt; &lt;/div&gt; ' + '&lt;/div&gt; ' + '&lt;div class="form-group requestTypeGroup"&gt; ' + '&lt;label class="col-md-4 control-label" for="requestType"&gt;This request is for:&lt;/label&gt; ' + '&lt;div class="col-md-4"&gt; &lt;div class="radio"&gt; &lt;label for="Edit"&gt; ' + '&lt;input type="radio" name="requestType" id="requestType-0" value="Edit"&gt; ' + 'Editing &lt;/label&gt; ' + '&lt;/div&gt;&lt;div class="radio"&gt; &lt;label for="Delete"&gt; ' + '&lt;input type="radio" name="requestType" id="requestType-1" value="Delete"&gt; Deletion&lt;/label&gt; ' + '&lt;/div&gt; ' + '&lt;/div&gt; &lt;/div&gt;' + '&lt;/form&gt; &lt;/div&gt; &lt;/div&gt;' }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"&gt;&lt;/script&gt; &lt;a data-toggle="contactAdmin" data-title="help" data-url="http:/www.mydomain.com/some-url" href="#"&gt;Contact Web team&lt;/a&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/vyaw3ucd/" rel="noreferrer">View on jsFiddle</a></p>
30,720,519
4
0
null
2015-06-08 22:49:39.79 UTC
9
2018-02-06 08:03:34.287 UTC
2015-06-08 23:11:19.88 UTC
null
924,299
null
632,195
null
1
17
jquery|jquery-validate|bootbox
79,069
<p>Inspecting the DOM of the jsFiddle and two problems become apparent.</p> <ol> <li><p>Your "submit" <code>&lt;button&gt;</code> is a <code>type="button"</code>.</p></li> <li><p>Your "submit" button is outside of the <code>&lt;form&gt;&lt;/form&gt;</code> container.</p></li> </ol> <p>If you want the jQuery Validate plugin to automatically capture the <code>click</code> event of the "submit" button...</p> <ul> <li>the button must be a <code>type="submit"</code></li> <li>The button must be within the <code>&lt;form&gt;&lt;/form&gt;</code> container.</li> </ul> <p>These two conditions must be met if you want the plugin to operate as intended. </p> <hr> <p>You've also incorrectly placed the <code>.validate()</code> method within the <code>success</code> callback of your modal dialog box "submit" button.</p> <p>The <code>.validate()</code> method is only used for <strong><em>initializing</em></strong> the plugin and should be called <strong><em>once</em></strong> after the form is created.</p> <hr> <p><strong>EDIT</strong>:</p> <p>After playing around with this, it becomes apparent that the <a href="http://bootboxjs.com" rel="noreferrer">Bootbox modal plugin</a> may have some critical limitations that interfere with the submission of the form. </p> <ol> <li><p>I am initializing the Validate plugin <em>after</em> the dialog is opened.</p></li> <li><p>I am using the <code>.valid()</code> method within the "submit" to trigger the validation test.</p></li> </ol> <p>I can get validation initialized and working as it should, but the dialog is dismissed before the actual form submission takes place. Perhaps there is a solution, but after reviewing the documentation for Bootbox, it's not readily apparent.</p> <p><a href="https://jsfiddle.net/vyaw3ucd/2/" rel="noreferrer">https://jsfiddle.net/vyaw3ucd/2/</a></p> <hr> <p><strong>EDIT 2:</strong></p> <p>As per the OP's solution...</p> <pre><code>bootbox.dialog({ // other options, buttons: { success: { label: "Submit", className: "btn btn-sm btn-primary", callback: function () { if ($("#webteamContactForm").valid()) { var form = $("#webteamContactForm"); form.submit(); // form submits and dialog closes } else { return false; // keeps dialog open } } } } }); </code></pre> <p>However, by simply using the supplied <code>form</code> argument directly, you do not have any errors when using the <code>submitHandler</code> option of the jQuery Validate plugin.</p> <pre><code>submitHandler: function (form) { console.log("Submitted!"); form.submit(); } </code></pre> <p><strong>DEMO: <a href="https://jsfiddle.net/vyaw3ucd/5/" rel="noreferrer">https://jsfiddle.net/vyaw3ucd/5/</a></strong></p>
1,172,171
Composite WPF (Prism) module resource data templates
<p>Given that I have a shell application and a couple of separate module projects using Microsoft CompoisteWPF (Prism v2)...</p> <p>On receiving a command, a module creates a new ViewModel and adds it to a region through the region manager.</p> <pre><code>var viewModel = _container.Resolve&lt;IMyViewModel&gt;(); _regionManager.Regions[RegionNames.ShellMainRegion].Add(viewModel); </code></pre> <p>I thought that I could then create a resource dictionary within the module and set up a data template to display a view for the view model type that was loaded (see below xaml). But when the view model is added to the view, all I get is the view models namespace printed out.</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:Modules.Module1.ViewModels" xmlns:vw="clr-namespace:Modules.Module1.Views" &gt; &lt;DataTemplate DataType="{x:Type vm:MyViewModel}"&gt; &lt;vw:MyView /&gt; &lt;/DataTemplate&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>Edit:</p> <p>I can get it to work by adding to the App.xaml</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="pack://application:,,,/Module1;component/Module1Resources.xaml"/&gt; &lt;ResourceDictionary Source="pack://application:,,,/Module2;component/Module2Resources.xaml"/&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/Application.Resources&gt; </code></pre> <p>Which is fine, but it means that as new modules are created, the App.xaml file needs to be added to. What I'm looking for is a way for modules, as they load to dynamically add to the the Application.Resources. Is this possible?</p>
1,299,000
3
0
null
2009-07-23 14:31:28.617 UTC
12
2012-06-20 12:57:12.53 UTC
2009-07-23 19:23:46.233 UTC
null
99,860
null
99,860
null
1
14
wpf|prism|resourcedictionary
8,551
<p>Within the initialisation of each module, you can add to the application resources:</p> <pre><code>Application.Current.Resources.MergedDictionaries .Add(new ResourceDictionary { Source = new Uri( @"pack://application:,,,/MyApplication.Modules.Module1.Module1Init;component/Resources.xaml") }); </code></pre> <p>Or if you follow a convention of each module has a resource dictionary called "Resources.xmal"...</p> <pre><code>protected override IModuleCatalog GetModuleCatalog() { var catalog = new ModuleCatalog(); AddModules(catalog, typeof (Module1), typeof(Module2), typeof(Module3), typeof(Module4)); return catalog; } private static void AddModules(ModuleCatalog moduleCatalog, params Type[] types) { types.ToList() .ForEach(x =&gt; { moduleCatalog.AddModule(x); Application.Current.Resources.MergedDictionaries .Add(new ResourceDictionary { Source = new Uri(string.Format( @"pack://application:,,,/{0};component/{1}", x.Assembly, "Resources.xaml")) }); }); } </code></pre>
1,036,666
Use of array of zero length
<p>For example we can construct such an array like this:</p> <pre><code> new ElementType[0]; </code></pre> <p>I seen such a construct, but I don't understand why this might be useful.</p>
1,036,699
3
1
null
2009-06-24 06:17:07.08 UTC
9
2016-01-31 22:35:51.7 UTC
2016-01-31 22:35:51.7 UTC
null
452,775
null
124,339
null
1
28
java|arrays
8,733
<p>An example. Say, you have a function</p> <pre><code>public String[] getFileNames(String criteria) { </code></pre> <p>to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - <em>either return null</em>, or <em>0-sized array</em>. </p> <p>The variant with <em>0-sized array</em> is better, because your caller doesn't need to check for <strong>NULL</strong> and can process the array in a consistent way - say, in a loop (which would be empty in this case).</p> <p>There's a chapter on this in <a href="http://books.google.com/books?id=ZZOiqZQIbRMC&amp;lpg=PP1&amp;dq=effective%2Bjava&amp;pg=PA134" rel="noreferrer">Effective Java, Item 27</a></p>
737,009
Temporary function or stored procedure in T-SQL
<p>Is there any chance to create temporary stored procedure or function on MS SQL 2005? I would like to use this stored procedure only in my query so after execution it will be gone.</p> <p>I have a query I would like to EXEC against some data. But for every table I will process this command, I need to change some parts of it. So I thought I would create temporary SP that would return for me a query from arguments I provide (like table name and so on) and than execute this query by EXEC.</p> <p>And this stored procedure will be not useful for me later so I would like to have it temporary so that when I end executing my query - it will disappear.</p>
737,035
3
1
null
2009-04-10 08:01:36.45 UTC
8
2015-07-03 10:51:12.86 UTC
2015-07-03 10:51:12.86 UTC
null
2,630,337
null
38,940
null
1
36
sql-server|tsql|stored-procedures
45,819
<p>Re your edit - it sounds like you should be using sp_ExecuteSQL against a (parameterized) <code>nvarchar</code> that contains TSQL.</p> <p>Search on sp_ExecuteSQL; a simple example:</p> <pre><code>DECLARE @SQL nvarchar(4000), @Table varchar(20) = 'ORDERS', @IDColumn varchar(20) = 'OrderID', @ID int = 10248 SET @SQL = 'SELECT * FROM [' + @Table + '] WHERE [' + @IDColumn + '] = @Key' EXEC sp_executesql @SQL, N'@Key int', @ID </code></pre> <p>Note that table and column names must be concatenated into the query, but values (such as <code>@Key</code>) can be parameterized.</p> <hr> <p>There is a temporary stored procedure - but it is per connection, not per sp.</p> <p>However, you might want to look at Common Table Expressions - they may be what you are after (although you can only read from them once).</p> <p>Maybe if you can clarify what you are trying to <em>do</em>?</p>
1,151,237
JUnit expected tag not working as expected
<p>I have the following test case in eclipse, using JUnit 4 which is refusing to pass. <strong>What could be wrong?</strong></p> <pre><code>@Test(expected = IllegalArgumentException.class) public void testIAE() { throw new IllegalArgumentException(); } </code></pre> <p>This exact testcase came about when trying to test my own code with the expected tag didn't work. I wanted to see if JUnit would pass the most basic test. It didn't.</p> <p>I've also tested with custom exceptions as expected without luck.</p> <p><strong>Screenshot:</strong> <a href="https://i.stack.imgur.com/tVTcA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tVTcA.png" alt="Screenshot"></a> </p>
1,151,384
3
2
null
2009-07-19 23:56:34.827 UTC
10
2019-03-30 14:59:36.73 UTC
2019-03-30 14:59:36.73 UTC
null
4,751,173
null
68,507
null
1
46
java|unit-testing|junit|junit4
22,748
<p>The problem is that your AnnounceThreadTest extends TestCase. Because it extends TestCase, the JUnit Runner is treating it as a JUnit 3.8 test, and the test is running because it starts with the word test, hiding the fact that the @Test annotiation is in fact not being used at all.</p> <p>To fix this, remove the "extends TestCase" from the class definition.</p>
477,892
In jQuery, what's the best way of formatting a number to 2 decimal places?
<p>This is what I have right now: </p> <pre><code>$("#number").val(parseFloat($("#number").val()).toFixed(2)); </code></pre> <p>It looks messy to me. I don't think I'm chaining the functions correctly. Do I have to call it for each textbox, or can I create a separate function?</p>
478,266
3
1
null
2009-01-25 16:28:19.923 UTC
18
2019-12-26 09:14:12.393 UTC
2010-04-21 05:22:39.077 UTC
null
9,314
IainMH
1,122
null
1
72
javascript|jquery|rounding|decimal-point|number-formatting
196,293
<p>If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.<br> Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.<br> It is triggered by the onchange event of the field. You may want something different.</p> <pre><code>&lt;script type="text/javascript"&gt; // mini jQuery plugin that formats to two decimal places (function($) { $.fn.currencyFormat = function() { this.each( function( i ) { $(this).change( function( e ){ if( isNaN( parseFloat( this.value ) ) ) return; this.value = parseFloat(this.value).toFixed(2); }); }); return this; //for chaining } })( jQuery ); // apply the currencyFormat behaviour to elements with 'currency' as their class $( function() { $('.currency').currencyFormat(); }); &lt;/script&gt; &lt;input type="text" name="one" class="currency"&gt;&lt;br&gt; &lt;input type="text" name="two" class="currency"&gt; </code></pre>
36,607,932
"Unterminated template literal" syntax error when literal contains script tag
<p>I'm using ES6 template literals to construct some HTML in strings, and so far it has been working fine. However, as soon as I try to put the literal text <code>&lt;/script&gt;</code> in my string the browser throws up and throws the syntax error:</p> <pre><code>SyntaxError: Unterminated template literal </code></pre> <p>Here is a simple JavaScript sample which throws the error:</p> <pre><code>var str=` &lt;script&gt; &lt;/script&gt; ` var pre = document.createElement('pre') pre.textContent = str document.body.appendChild(pre) </code></pre> <p>See the above code in <a href="https://jsfiddle.net/6quwnhwn/" rel="noreferrer">JS Fiddle</a>.</p> <p>It appears that what is happening is that it gives up looking for the end literal quote and instead starts treating everything at point as literal HTML, so all the JavaScript after that point is incorrectly treated as HTML, which it is not!</p> <p>If I replace <code>script</code> by <em>any</em> other legal HTML tag (and even invalid tags like <code>scripty</code>) then it works just fine, so I can't see how this can possibly be a syntax error or a weird case where I think I have typed one character (e.g. the backtick) but instead have typed another that looks almost like it.</p> <p>I am literally creating a string (to my understand, at compile time), the browser should <em>not</em> be attempting to treat it as HTML or in any way parse it. So what gives?</p>
36,607,971
1
2
null
2016-04-13 19:34:17.647 UTC
5
2017-03-22 18:03:43.043 UTC
2016-04-13 19:46:44.77 UTC
null
3,853,934
null
543,873
null
1
40
javascript|html|ecmascript-6|script-tag|template-literals
34,160
<p>If you insert <code>&lt;/script&gt;</code> inside a script tag, no matter if it's a string in quotes, apostrophes, or even a template literal, it will <em>always</em> close the script tag. You have to escape it, for example like that:</p> <pre><code>var str=` &lt;script&gt; &lt;\/script&gt; ` var pre = document.createElement('pre') pre.textContent = str document.body.appendChild(pre) </code></pre> <p>However, if you use external script <code>&lt;script src="url"&gt;&lt;/script&gt;</code>, it should work fine without escaping.</p>
5,615,206
windows batch files: setting variable in for loop
<p>I have a number of files with the same naming scheme. As a sample, four files are called "num_001_001.txt", "num_002_001.txt", "num_002_002.txt", "num_002_003.txt"</p> <p>The first set of numbers represents which "package" it's from, and the second set of numbers is simply used to distinguish them from one another. So in this example we have one file in package 001, and three files in package 002.</p> <p>I am writing a windows vista batch command to take all of the files and move them into their own directories, where each directory represents a different package. So I want to move all the files for package 001 into directory "001" and all for 002 into directory "002"</p> <p>I have successfully written a script that will iterate over all of the txt files and echo them. I have also written a scrip that will move one file into another location, as well as creating the directory if it doesn't exist.</p> <p>Now I figure that I will need to use substrings, so I used the %var:~start,end% syntax to get them. As a test, I wrote this to verify that I can actually extract the substring and create a directory conditionally</p> <pre> @echo off set temp=num_001_001.txt NOT IF exist %temp:~0,7%\ mkdir %temp:~0,7% </pre> <p>And it works. Great. <br/> So then I added the for loop to it.</p> <pre>@echo off FOR /R %%X IN (*.txt) DO ( set temp=%%~nX echo directory %temp:~0,7% ) </pre> <p>But this is my output:</p> <pre> directory num_002 directory num_002 directory num_002 directory num_002 </pre> <p>What's wrong? Does vista not support re-assigning variables in each iteration? The four files are in my directory, and one of them should create num_001. I put in different files with 003 004 005 and all of it was the last package's name. I'm guessing something's wrong with how I'm setting things.</p> <p>I have different workarounds to get the job done but I'm baffled why such a simple concept wouldn't work.</p>
5,615,355
3
1
null
2011-04-10 22:41:44.503 UTC
11
2013-10-21 16:28:51.037 UTC
2011-04-10 23:40:18.96 UTC
null
536,607
null
536,607
null
1
28
batch-file|windows-vista
89,251
<p>Your problem is that the variable get replaced when the batch processor reads the for command, before it is executed.</p> <p>Try this:</p> <pre><code>SET temp=Hello, world! CALL yourbatchfile.bat </code></pre> <p>And you'll see Hello printed 5 times.</p> <p>The solution is delayed expansion; you need to first enable it, and then use <code>!temp!</code> instead of <code>%temp%</code>:</p> <pre><code>@echo off SETLOCAL ENABLEDELAYEDEXPANSION FOR /R %%X IN (*.txt) DO ( set temp=%%~nX echo directory !temp:~0,7! ) </code></pre> <p>See <a href="http://www.robvanderwoude.com/variableexpansion.php" rel="noreferrer">here</a> for more details.</p>
6,172,364
Can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
<p>I am using javascript to connect websocket:</p> <pre><code>&lt;script&gt; var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"; var socket = new WebSocket(host); &lt;/script&gt; </code></pre> <p>I got the error:</p> <blockquote> <p>Can't establish a connection to the server at </p> </blockquote> <pre><code>var host = "ws://localhost:8000/socket/server/startDaemon.php"; var socket = new WebSocket(host); </code></pre> <p>How can I solve this issue?</p> <p>NOTE : I enabled websocket in mozilla to support web socket application. and when i run in chrome i got error:</p> <pre><code> can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host); </code></pre>
6,277,359
4
2
null
2011-05-30 04:48:22.247 UTC
3
2016-06-21 00:48:57.793 UTC
2011-06-09 04:23:36.3 UTC
null
601,260
null
601,260
null
1
16
php|html|websocket|phpwebsocket
51,582
<p>I solved my error by following code through this link</p> <p><a href="http://www.flynsarmy.com/2010/05/php-web-socket-chat-application/" rel="nofollow">http://www.flynsarmy.com/2010/05/php-web-socket-chat-application/</a> and created socketWebSocketTrigger.class.php file for response message where code as</p> <pre><code>class socketWebSocketTrigger { function responseMessage($param) { $a = 'Unknown parameter'; if($param == 'age'){ $a = "Oh dear, I'm 152"; } if($param == 'hello'){ $a = 'hello, how are you?'; } if($param == 'name'){ $a = 'my name is Mr. websocket'; } if($param == 'today'){ $a = date('Y-m-d'); } if($param == 'hi'){ $a = 'hi there'; } return $a; } } </code></pre> <p>and added code in send function of 'WebSocketServer.php' for calling 'responseMessage' function which response request message</p> <pre><code> public function send($client, $msg){ $this-&gt;say("&gt; ".$msg); $messageRequest = json_decode($msg,true); // $action=$messageRequest[0]; $action = 'responseMessage'; $param = $messageRequest[1]['data']; if( method_exists('socketWebSocketTrigger',$action) ){ $response = socketWebSocketTrigger::$action($param); } $msg = json_encode( array( 'message', array('data' =&gt; $response) ) ); $msg = $this-&gt;wrap($msg); socket_write($client, $msg, strlen($msg)); } </code></pre> <p>it's working great.</p>
1,529,496
Is there a javascript equivalent of python's __getattr__ method?
<p>In python you can define a object having <code>__getattr__(self,key)</code> method to handle all unknown attributes to be solvable in programmatic manner, but in javascript you can only define getters and setters for pre-defined attributes. Is there a generic way of getting the former thing done also in javascript?</p> <p>Sample code would be smth like:</p> <pre><code>function X() {}; X.prototype={ __getattr__:function(attrname) { return "Value for attribute '"+attrname+"'"; } } x=new X() alert(x.lskdjoau); // produces message: "Value of attribute 'lskdjoau'" </code></pre> <p>Key point is getting value of attribute programmatically depending on the name of the attribute. Pre-setting attribute does not help because during init there is no information what attributes might be requested.</p>
1,529,540
2
1
null
2009-10-07 04:36:03.57 UTC
4
2020-04-13 09:25:06.19 UTC
2009-10-20 07:33:42.637 UTC
qweasd
null
qweasd
null
null
1
35
javascript
15,439
<p>Sadly the answer is No. See <a href="https://stackoverflow.com/questions/1441005/pythons-getattr-in-javascript">Python&#39;s __getattr__ in Javascript</a></p> <p>You've got <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/defineGetter" rel="nofollow noreferrer"><code>__defineGetter__</code></a>, but as you noted you need to know the name of the attribute you will be accessing.</p> <p>By the way I think you meant <code>__getattr__</code> (<code>__getitem__</code> is for things you want to access with <code>[]</code>).</p>
29,562,460
Conditional mocking: Call original function if condition does match
<p>How can I conditionally call the original method in a mock?</p> <p>In this example I only want to fake a return value if <code>bar=='x'</code>. Otherwise I want to call the original method.</p> <pre><code>def mocked_some_method(bar): if bar=='x': return 'fake' return some_how_call_original_method(bar) with mock.patch('mylib.foo.some_method', mocked_some_method): do_some_stuff() </code></pre> <p>I know that it is a bit strange. If I want to fake <code>mylib.foo.some_method</code> in side <code>do_some_stuff()</code> it should be condition-less. All (not some) calls to <code>some_method</code> should be mocked.</p> <p>In my case it is an integration test, not a s tiny unittest and <code>mylib.foo.some_method</code> is a kind of dispatcher which gets used very often. And in one case I need to fake the result.</p> <h1>Update</h1> <p>I wrote this question four years ago. Today, it feels very strange to do conditional mocking. Mocks should only get used in tests. Tests (and production code) should be simple and small. Tests should be conditionless. As I wrote this question, we still used huge production methods and long test. Today, I follow these rules (simple methods, conditionless tests ...). I wrote my findings down: <a href="https://github.com/guettli/programming-guidelines/" rel="noreferrer">my programming guidelines</a></p>
29,563,665
3
1
null
2015-04-10 13:17:12.933 UTC
4
2021-07-26 22:21:14.467 UTC
2021-05-25 12:40:14.293 UTC
null
633,961
null
633,961
null
1
31
python|mocking
18,966
<p>If you need just replace behavior without care of mock's calls assert function you can use <code>new</code> argument; otherwise you can use <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect"><code>side_effect</code></a> that take a callable. </p> <p>I guess that <code>some_method</code> is a object method (instead of a <code>staticmethod</code>) so you need a reference its object to call it. Your wrapper should declare as first argument the object and your patch use <code>autospec=True</code> to use the correct signature for <code>side_effect</code> case.</p> <p>Final trick is save the original method reference and use it to make the call.</p> <pre><code>orig = mylib.foo.some_method def mocked_some_method(self, bar): if bar=='x': return 'fake' return orig(self, bar) #Just replace: with mock.patch('mylib.foo.some_method', new=mocked_some_method): do_some_stuff() #Replace by mock with mock.patch('mylib.foo.some_method', side_effect=mocked_some_method, autospec=True) as mock_some_method: do_some_stuff() assert mock_some_method.called </code></pre>
50,367,896
IDEWorkspaceChecks.plist file suddenly appear after updated xcode
<p>I suddenly start having this file in my xcode project after I updated my xcode:</p> <pre><code>myProject.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist </code></pre> <p>What does this file do? Should I exclude it in version control?</p>
50,368,149
1
2
null
2018-05-16 10:02:34.117 UTC
1
2018-05-16 10:14:33.31 UTC
null
null
null
null
740,018
null
1
51
ios|xcode
11,633
<p>You can take a look on the <a href="https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html" rel="noreferrer">Xcode release notes</a></p> <blockquote> <p>Xcode 9.3 adds a new IDEWorkspaceChecks.plist file to a workspace's shared data, to store the state of necessary workspace checks. Committing this file to source control will prevent unnecessary rerunning of those checks for each user opening the workspace. (37293167)</p> </blockquote> <p>It's good to commit it to your repository.</p>
50,304,156
Tensorflow Allocation Memory: Allocation of 38535168 exceeds 10% of system memory
<p>Using ResNet50 pre-trained Weights I am trying to build a classifier. The code base is fully implemented in Keras high-level Tensorflow API. The complete code is posted in the below GitHub Link.</p> <p>Source Code: <a href="https://gist.github.com/Madhivarman/676650f71ec35a5f2802631fcfa0ff73" rel="noreferrer">Classification Using RestNet50 Architecture</a></p> <p>The file size of the pre-trained model is <strong>94.7mb</strong>.</p> <p>I loaded the pre-trained file</p> <pre><code>new_model = Sequential() new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weight_paths)) </code></pre> <p>and fit the model</p> <pre><code>train_generator = data_generator.flow_from_directory( 'path_to_the_training_set', target_size = (IMG_SIZE,IMG_SIZE), batch_size = 12, class_mode = 'categorical' ) validation_generator = data_generator.flow_from_directory( 'path_to_the_validation_set', target_size = (IMG_SIZE,IMG_SIZE), class_mode = 'categorical' ) #compile the model new_model.fit_generator( train_generator, steps_per_epoch = 3, validation_data = validation_generator, validation_steps = 1 ) </code></pre> <p>and in the Training dataset, I have two folders dog and cat, each holder almost 10,000 images. When I compiled the script, I get the following error</p> <blockquote> <p>Epoch 1/1 2018-05-12 13:04:45.847298: W tensorflow/core/framework/allocator.cc:101] Allocation of 38535168 exceeds 10% of system memory. 2018-05-12 13:04:46.845021: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:47.552176: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:48.199240: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:48.918930: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:49.274137: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory. 2018-05-12 13:04:49.647061: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory. 2018-05-12 13:04:50.028839: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory. 2018-05-12 13:04:50.413735: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory.</p> </blockquote> <p>Any ideas to optimize the way to load the pre-trained model (or) get rid of this warning message?</p> <p>Thanks!</p>
51,367,588
9
3
null
2018-05-12 08:09:09.683 UTC
16
2022-07-22 10:14:07.997 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
9,044,016
null
1
56
python|tensorflow|memory|keras-layer|resnet
102,981
<p>Try reducing batch_size attribute to a small number(like 1,2 or 3). Example:</p> <pre><code>train_generator = data_generator.flow_from_directory( 'path_to_the_training_set', target_size = (IMG_SIZE,IMG_SIZE), batch_size = 2, class_mode = 'categorical' ) </code></pre>
32,539,285
Pointer is missing a nullability type specifier
<p>In Xcode 7 GM I started to get this warning:</p> <blockquote> <p>Pointer is missing a nullability type specifier (_Nonnull, _Nullable, or _Null_unspecified)</p> </blockquote> <p>In the following function declaration (NSUserDefaults extension)</p> <pre><code>- (void)setObject:(nullable id)value forKey:(NSString *)defaultName objectChanged:(void(^)(NSUserDefaults *userDefaults, id value))changeHandler objectRamains:(void(^)(NSUserDefaults *userDefaults, id value))remainHandler; </code></pre> <p><a href="https://i.stack.imgur.com/c4TE2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c4TE2.png" alt="Screenshot" /></a></p> <p>Why this warning is showing and how should I fix it?</p>
32,541,409
6
1
null
2015-09-12 13:17:53.297 UTC
12
2021-08-15 20:23:05.67 UTC
2021-01-21 06:45:19.29 UTC
null
1,753,005
null
3,050,403
null
1
75
ios|objective-c|objective-c-nullability
56,990
<p>You need to specify <code>nullable</code> also for the handlers/blocks</p> <pre><code>- (void)setObject:(nullable id)value forKey:(nonnull NSString *)defaultName objectChanged:(nullable void(^)(NSUserDefaults *userDefaults, id value))changeHandler objectRamains:(nullable void(^)(NSUserDefaults *userDefaults, id value))remainHandler; </code></pre> <p>Why? It's due to Swift. Swift allows optional parameters (?), which Objective-C does not. This is done as a bridge between the both of them for the Swift compiler to know those parameters are optional. A 'Nonnull' will tell the Swift compiler that the argument is the required. A nullable that it is optional</p> <p>For more info read: <a href="https://developer.apple.com/swift/blog/?id=25" rel="noreferrer">https://developer.apple.com/swift/blog/?id=25</a></p>
5,840,148
How can I get a file's size in C++?
<p>Let's create a complementary question to <a href="https://stackoverflow.com/questions/238603/how-can-i-get-a-files-size-in-c">this one</a>. What is the most common way to get the file size in C++? Before answering, make sure it is portable (may be executed on Unix, Mac and Windows), reliable, easy to understand and without library dependencies (no boost or qt, but for instance glib is ok since it is portable library).</p>
5,840,160
7
6
null
2011-04-30 06:55:48.853 UTC
48
2021-10-26 18:04:12.043 UTC
2017-05-23 12:02:58.59 UTC
null
-1
null
655,860
null
1
159
c++|filesize
352,283
<pre><code>#include &lt;fstream&gt; std::ifstream::pos_type filesize(const char* filename) { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } </code></pre> <p>See <a href="http://www.cplusplus.com/doc/tutorial/files/" rel="noreferrer">http://www.cplusplus.com/doc/tutorial/files/</a> for more information on files in C++.</p> <p>edit: this answer is not correct since tellg() does not necessarily return the right value. See <a href="http://stackoverflow.com/a/22986486/1835769">http://stackoverflow.com/a/22986486/1835769</a></p>
5,980,042
How to implement the --verbose or -v option into a script?
<p>I know the <code>--verbose</code> or <code>-v</code> from several tools and I'd like to implement this into some of my own scripts and tools.</p> <p>I thought of placing:</p> <pre><code>if verbose: print ... </code></pre> <p>through my source code, so that if a user passes the <code>-v</code> option, the variable <code>verbose</code> will be set to <code>True</code> and the text will be printed.</p> <p>Is this the right approach or is there a more common way?</p> <p>Addition: I am not asking for a way to implement the parsing of arguments. That I know how it is done. I am only interested specially in the verbose option.</p>
5,980,173
9
2
null
2011-05-12 15:01:39.74 UTC
46
2022-06-29 15:26:00.75 UTC
2022-06-29 15:26:00.75 UTC
null
4,294,399
null
641,514
null
1
123
python|command-line-arguments
157,925
<p>My suggestion is to use a function. But rather than putting the <code>if</code> in the function, which you might be tempted to do, do it like this:</p> <pre><code>if verbose: def verboseprint(*args): # Print each argument separately so caller doesn't need to # stuff everything to be printed into a single string for arg in args: print arg, print else: verboseprint = lambda *a: None # do-nothing function </code></pre> <p>(Yes, you can define a function in an <code>if</code> statement, and it'll only get defined if the condition is true!)</p> <p>If you're using Python 3, where <code>print</code> is already a function (or if you're willing to use <code>print</code> as a function in 2.x using <code>from __future__ import print_function</code>) it's even simpler:</p> <pre><code>verboseprint = print if verbose else lambda *a, **k: None </code></pre> <p>This way, the function is defined as a do-nothing if verbose mode is off (using a lambda), instead of constantly testing the <code>verbose</code> flag. </p> <p>If the user could change the verbosity mode <em>during the run</em> of your program, this would be the wrong approach (you'd need the <code>if</code> in the function), but since you're setting it with a command-line flag, you only need to make the decision once.</p> <p>You then use e.g. <code>verboseprint("look at all my verbosity!", object(), 3)</code> whenever you want to print a "verbose" message.</p>
5,717,033
StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First
<p>What is the difference in behavior of <code>[MaxLength]</code> and <code>[StringLength]</code> attributes?</p> <p>As far as I can tell (with the exception that <code>[MaxLength]</code> can validate the maximum length of an array) these are identical and somewhat redundant?</p>
5,717,297
9
3
null
2011-04-19 13:23:23.207 UTC
37
2021-09-24 08:51:53.307 UTC
2015-02-19 13:56:03.887 UTC
null
1,015,495
null
715,267
null
1
171
asp.net-mvc-3|ef-code-first|entity-framework-4.1
143,911
<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.maxlengthattribute%28v=vs.103%29.aspx">MaxLength</a> is used for the Entity Framework to decide how large to make a string value field when it creates the database.</p> <p>From MSDN:</p> <blockquote> <p>Specifies the maximum length of array or string data allowed in a property.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute.aspx">StringLength</a> is a data annotation that will be used for validation of user input.</p> <p>From MSDN:</p> <blockquote> <p>Specifies the minimum and maximum length of characters that are allowed in a data field.</p> </blockquote>
5,917,082
Regular expression to match numbers with or without commas and decimals in text
<p>I'm trying to locate and replace all numbers in a body of text. I've found a few example regex's, which almost solve the problem, but none are perfect yet. The problem I have is that the numbers in my text may or may not have decimals and commas. For example:</p> <blockquote> <p>"The 5000 lb. fox jumped over a 99,999.99998713 foot fence." </p> </blockquote> <p>The regex should return "<code>5000</code>" and "<code>99,999.99998713</code>". Examples I've found break-up the numbers on the comma or are limited to two decimal places. I'm starting to understand regex's enough to see why some examples are limited to two decimal places, but I haven't yet learned how to overcome it and also include the comma to get the entire sequence.</p> <p>Here is my latest version: </p> <pre><code>[0-9]+(\.[0-9][0-9]?)? </code></pre> <p>Which returns, "<code>5000</code>", "<code>99,99</code>", "<code>9.99</code>", and "<code>998713</code>" for the above text.</p>
5,917,250
11
6
null
2011-05-06 21:14:27.68 UTC
62
2022-07-12 12:45:13.56 UTC
2011-05-06 21:16:17.337 UTC
null
121,493
user56512
null
null
1
122
regex
217,998
<h3>EDIT: Since this has gotten a lot of views, let me start by giving everybody what they Googled for:</h3> <pre><code>#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER #For numbers embedded in sentences, see discussion below #### NUMBERS AND DECIMALS ONLY #### #No commas allowed #Pass: (1000.0), (001), (.001) #Fail: (1,000.0) ^\d*\.?\d+$ #No commas allowed #Can't start with &quot;.&quot; #Pass: (0.01) #Fail: (.01) ^(\d+\.)?\d+$ #### CURRENCY #### #No commas allowed #&quot;$&quot; optional #Can't start with &quot;.&quot; #Either 0 or 2 decimal digits #Pass: ($1000), (1.00), ($0.11) #Fail: ($1.0), (1.), ($1.000), ($.11) ^\$?\d+(\.\d{2})?$ #### COMMA-GROUPED #### #Commas required between powers of 1,000 #Can't start with &quot;.&quot; #Pass: (1,000,000), (0.001) #Fail: (1000000), (1,00,00,00), (.001) ^\d{1,3}(,\d{3})*(\.\d+)?$ #Commas required #Cannot be empty #Pass: (1,000.100), (.001) #Fail: (1000), () ^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$ #Commas optional as long as they're consistent #Can't start with &quot;.&quot; #Pass: (1,000,000), (1000000) #Fail: (10000,000), (1,00,00) ^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$ #### LEADING AND TRAILING ZEROES #### #No commas allowed #Can't start with &quot;.&quot; #No leading zeroes in integer part #Pass: (1.00), (0.00) #Fail: (001) ^([1-9]\d*|0)(\.\d+)?$ #No commas allowed #Can't start with &quot;.&quot; #No trailing zeroes in decimal part #Pass: (1), (0.1) #Fail: (1.00), (0.1000) ^\d+(\.\d*[1-9])?$ </code></pre> <p>Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.</p> <hr /> <p>This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as <code>,111</code>, <code>9,9,9</code>, or even <code>.,,.</code>. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234—<strong>and only those numbers</strong>—out of <code>abc22 1,234.56 9.9.9.9 def 1234</code> is a wrong answer.</p> <p>First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.</p> <h3>Basic pattern</h3> <p>Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in <code>0000</code> format and blocks everything else:</p> <pre><code>^\d*\.?\d+$ </code></pre> <p>Here's one that requires <code>0,000</code> format:</p> <pre><code>^\d{1,3}(,\d{3})*(\.\d+)?$ </code></pre> <p>Put them together, and commas become optional as long as they're consistent:</p> <pre><code>^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$ </code></pre> <h3>Embedded numbers</h3> <p>The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see <code>catch22</code> and think it's found the number 22. If you're using something with lookbehind support (like C#, .NET 4.0+), this is pretty easy: replace <code>^</code> with <code>(?&lt;!\S)</code> and <code>$</code> with <code>(?!\S)</code> and you're good to go:</p> <pre><code>(?&lt;!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S) </code></pre> <p>If you're working with JavaScript or Ruby or something, things start looking more complex:</p> <pre><code>(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S) </code></pre> <p>You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).</p> <h3>Validation and more complex rules</h3> <p>I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:</p> <ul> <li>Empty input</li> <li>Leading zeroes (e.g. 000123)</li> <li>Trailing zeroes (e.g. 1.2340000)</li> <li>Decimals starting with the decimal point (e.g. .001 as opposed to 0.001)</li> </ul> <p>Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:</p> <pre><code>(?&lt;!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S) </code></pre> <p>And here's what it means:</p> <pre><code>(?&lt;!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9. (?=.) #The whole thing can't be blank. ( #Rules for the integer part: 0 #1. The integer part could just be 0... | # [1-9] # ...otherwise, it can't have leading zeroes. ( # \d* #2. It could use no commas at all... | # \d{0,2}(,\d{3})* # ...or it could be comma-separated groups of 3 digits each. ) # )? #3. Or there could be no integer part at all. ( #Rules for the decimal part: \. #1. It must start with a decimal point... \d* #2. ...followed by a string of numeric digits only. [1-9] #3. It can't be just the decimal point, and it can't end in 0. )? #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank. </code></pre> <p>Tested here: <a href="http://rextester.com/YPG96786" rel="noreferrer">http://rextester.com/YPG96786</a></p> <p>This will allow things like:</p> <pre><code>100,000 999.999 90.0009 1,000,023.999 0.111 .111 0 </code></pre> <p>It will block things like:</p> <pre><code>1,1,1.111 000,001.111 999. 0. 111.110000 1.1.1.111 9.909,888 </code></pre> <p>There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.</p> <p>Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:</p> <pre><code>(?:^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S) </code></pre> <p>The numbers you're looking for will be in capture group 1.</p> <p>Tested here: <a href="http://rubular.com/r/3HCSkndzhT" rel="noreferrer">http://rubular.com/r/3HCSkndzhT</a></p> <h3>One final note</h3> <p>Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should <em>consider whether you really want to use this in a production environment.</em> Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that <em>might</em> be a number, then another one to weed out whatever <em>isn't</em> a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.</p>
24,479,577
Pandas: Timestamp index rounding to the nearest 5th minute
<p>I have a <code>df</code> with the usual timestamps as an index:</p> <pre><code> 2011-04-01 09:30:00 2011-04-01 09:30:10 ... 2011-04-01 09:36:20 ... 2011-04-01 09:37:30 </code></pre> <p>How can I create a column to this dataframe with the same timestamp but rounded to the nearest 5th minute interval? Like this:</p> <pre><code> index new_col 2011-04-01 09:30:00 2011-04-01 09:35:00 2011-04-01 09:30:10 2011-04-01 09:35:00 2011-04-01 09:36:20 2011-04-01 09:40:00 2011-04-01 09:37:30 2011-04-01 09:40:00 </code></pre>
25,542,523
4
1
null
2014-06-29 19:39:51.023 UTC
11
2019-07-25 09:46:39.72 UTC
null
null
null
null
1,418,224
null
1
18
python|pandas
13,428
<p><a href="https://stackoverflow.com/a/24479736">The <code>round_to_5min(t)</code> solution using <code>timedelta</code> arithmetic</a> is correct but complicated and very slow. Instead make use of the nice <code>Timstamp</code> in pandas:</p> <pre><code>import numpy as np import pandas as pd ns5min=5*60*1000000000 # 5 minutes in nanoseconds pd.to_datetime(((df.index.astype(np.int64) // ns5min + 1 ) * ns5min)) </code></pre> <p>Let's compare the speed:</p> <pre><code>rng = pd.date_range('1/1/2014', '1/2/2014', freq='S') print len(rng) # 86401 # ipython %timeit %timeit pd.to_datetime(((rng.astype(np.int64) // ns5min + 1 ) * ns5min)) # 1000 loops, best of 3: 1.01 ms per loop %timeit rng.map(round_to_5min) # 1 loops, best of 3: 1.03 s per loop </code></pre> <p>Just about 1000 times faster!</p>
42,218,546
Understanding Fragment's lifeCycle methods calls during fragment transaction
<p>I created a demo to understand which all fragment lifecycle's methods are called during different cases of fragment transaction.While most of the calls are as per expectation few things I am still confused which I have written in Bold.</p> <p>Suppose two fragment A and B are there and we are performing transaction between them</p> <p>Case 1</p> <p><strong>When Fragment B is added to Fragment A</strong></p> <pre><code>getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, fragementB).addToBackStack(null).commit(); </code></pre> <p>Fragment B</p> <blockquote> <p>onAttach</p> <p>onCreate</p> <p>onCreateView</p> <p>onActivityCreated</p> <p>onStart</p> <p>onResume</p> </blockquote> <p><strong>No lifecycle methods of Fragment A is being called.</strong></p> <p><strong>What i expected was?</strong></p> <p><strong>onStop method of Fragment A is called since Fragment A is not visible</strong></p> <p>As per documentation-</p> <blockquote> <p>Stopped- The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.</p> </blockquote> <p><strong>Does this mean that no method of current fragment is called when new fragment is added in same activity?</strong></p> <p>Then using <code>popBackStack()</code> in Fragment B</p> <p>Fragment B</p> <blockquote> <p>onPause</p> <p>onStop</p> <p>onDestroyView</p> <p>onDestroy</p> <p>onDetach</p> </blockquote> <p><strong>No lifecycle methods of Fragment A is being called</strong></p> <p><strong>What i expected was?</strong></p> <p><strong>onStart method of Fragment A is called since Fragment A is visible now</strong></p> <p>Case 2</p> <p><strong>When Fragment B replaces Fragment A</strong></p> <pre><code>getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, fragementB).commit(); </code></pre> <p>Fragment B</p> <blockquote> <p>onAttach</p> <p>onCreate</p> <p>onCreateView</p> <p>onActivityCreated</p> <p>onStart</p> <p>onResume</p> </blockquote> <p>Fragment A</p> <blockquote> <p>onPause</p> <p>onStop</p> <p>onDestroyView</p> <p>onDestroy</p> <p>onDetach</p> </blockquote> <p>Everything was as per expectation</p> <p>Case 3</p> <p><strong>When Fragment B replaces Fragment A keeping it in backstack</strong></p> <pre><code> getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, fragementB).addToBackStack("tag").commit(); </code></pre> <p>Fragment B</p> <blockquote> <p>onAttach</p> <p>onCreate</p> <p>onCreateView</p> <p>onActivityCreated</p> <p>onStart</p> <p>onResume</p> </blockquote> <p>Fragment A</p> <blockquote> <p>onPause</p> <p>onStop</p> <p>onDestroyView</p> </blockquote> <p><strong>onDestroy and onDetach method of Fragment A is NOT called.Why its not called?Bcoz as per documentation method <code>replace</code> removes any fragments that are already in the container and add your new one to the same container</strong> </p> <p>Then using <code>popBackStack()</code> in Fragment B</p> <p>Fragment A</p> <blockquote> <p>onCreateView</p> <p>onActivityCreated</p> <p>onStart</p> <p>onResume</p> </blockquote> <p>Fragment B</p> <blockquote> <p>onPause</p> <p>onStop</p> <p>onDestroyView</p> <p>onDestroy</p> <p>onDetach</p> </blockquote>
42,237,744
3
1
null
2017-02-14 05:28:48.41 UTC
23
2020-04-21 06:43:31.11 UTC
2017-02-14 06:08:46.04 UTC
null
3,753,273
null
3,753,273
null
1
25
android|android-fragments|fragment-lifecycle
24,243
<blockquote> <p>Does this mean that no method of current fragment is called when new fragment is added in same activity?</p> </blockquote> <p>Correct, your first fragment A will only be affected if it's removed or replaced (case 2). Simply adding another fragment will just display fragment B over fragment A and no life cycle callbacks should be called.</p> <blockquote> <p>What i expected was?</p> <p>onStart method of Fragment A is called since Fragment A is visible now</p> </blockquote> <p>Again, since fragment B was added on top of A, fragment A is not affected by the removal of B.</p> <blockquote> <p>onDestroy and onDetach method of Fragment A is NOT called.Why its not called?Bcoz as per documentation method replace removes any fragments that are already in the container and add your new one to the same container</p> </blockquote> <p>Unlike a simple replace, when you add your replace transaction to the backstack you're actually keeping the first fragment attached to it's activity, only its view is destroyed.</p> <p>Once you pop the backstack fragment B is removed and fragment A will just recreate its view - starting from onCreateView().</p>
65,306,968
VS Code N: Skipping acquire of configured file 'main/binary-arm64/Packages'
<p>I'm running POP OS 20.04 &amp; have installed / uninstalled VS code. When I run <code>sudo apt-get update</code>, I get:</p> <pre><code>N: Skipping acquire of configured file 'main/binary-arm64/Packages' as repository 'http://packages.microsoft.com/repos/vscode stable InRelease' doesn't support architecture 'arm64' N: Skipping acquire of configured file 'main/binary-armhf/Packages' as repository 'http://packages.microsoft.com/repos/vscode stable InRelease' doesn't support architecture 'armhf' </code></pre>
65,310,278
1
1
null
2020-12-15 13:35:17.253 UTC
2
2020-12-15 16:57:28.477 UTC
2020-12-15 16:38:09.153 UTC
null
4,017,881
null
10,035,965
null
1
28
linux
14,088
<p>For Ubuntu, edit: /etc/apt/sources.list.d/vscode.list. Remove any unwanted architectures from between the brackets and it should end up like this:</p> <p>deb <strong>[arch=amd64]</strong> <a href="http://packages.microsoft.com/repos/vscode" rel="noreferrer">http://packages.microsoft.com/repos/vscode</a> stable main</p>
32,709,655
datagrip Cannot apply changes This table is read only. Cell editor changes cannot be applied
<p>So simply the problem occurs when I want to edit selected rows and then apply it. I'm sure it worked some time ago. Tried redownload postgres driver in preferences(yeah, I use postgres) Anyone faced same issue? Anyone succeed?</p> <p>PS. Running on 142.4861.1.</p> <p>I found read only checkbox in connection preferences, it was not set, toggling didn't help, upgrading, reseting also didn't help.</p>
32,713,494
16
1
null
2015-09-22 06:16:36.02 UTC
1
2022-02-18 10:11:41.013 UTC
2016-12-13 15:19:33.437 UTC
null
4,595,114
null
4,897,652
null
1
28
postgresql|datagrip
22,078
<p>What actually helped was toggling Auto-commit checkbox in console, after that everything runs flawlessly.</p>
9,349,109
How to make horizontal division using html div tag and css
<p>I'm trying to make two horizontal divisons using <code>&lt;div&gt;</code> tag in html, but I couldn't make it. Can anyone help me make horizontal division using html and css with <code>&lt;div&gt;</code> tags?</p> <p><img src="https://i.stack.imgur.com/H5Ulp.png" alt="This is prototype"> </p>
9,349,178
3
0
null
2012-02-19 12:24:06.423 UTC
1
2016-01-28 09:04:03.543 UTC
2012-02-21 22:03:44.027 UTC
null
314,166
null
302,289
null
1
7
html|css|layout|alignment
42,594
<p>Set the <code>float</code> property for each <code>div</code> to be matched, for example <code>left</code> to each, give each of them enough width so that the parent contains them.</p> <h2><a href="http://jsfiddle.net/cwgv4/" rel="nofollow">DEMO</a></h2>
9,591,726
Use different icons with different Android SDK versions
<p>I have icons for my Android menu. On Android 3+ I'm using a black ActionBar so the icons are white. However, on Android 2.x the menu is inherently white which means the icons are nearly invisible. How can I use different menu icons for different versions? I'm assuming I can do it using different drawable directories like res/drawable-mdpi-v11, but I'm wondering if there is another way so I don't have to create a bunch of different directories as I add versions or pixel densities.</p> <p>EDIT: I put dark versions in res/drawable-mdpi and res/drawable-hdpi for use with Android 2.x and I put light versions in res/drawable-mdpi-v11 and res/drawable-hdpi-v11 for use with Android 3.x and higher, but my Android 2.1 (sdk 7) emulator is still showing the light version. </p> <p>Any idea why?</p>
9,592,604
2
0
null
2012-03-06 20:53:52.893 UTC
11
2012-03-06 22:04:50.223 UTC
2012-03-06 21:38:22.89 UTC
null
416,631
null
416,631
null
1
13
android|android-menu|android-actionbar
6,617
<p>You can Select a theme based on platform version, as outlined in the <a href="http://developer.android.com/guide/topics/ui/themes.html#SelectATheme" rel="noreferrer">Styles and Themes</a> dev guide. Define a style in your res/values/styles.xml like this:</p> <pre><code>&lt;style name="ThemeSelector" parent="android:Theme.Light"&gt; ... &lt;/style&gt; </code></pre> <p>Then in a res/values-v11/ folder, select your theme (probably Holo, if you're dark)</p> <pre><code>&lt;style name="ThemeSelector" parent="android:Theme.Holo"&gt; ... &lt;/style&gt; </code></pre> <p>Then add icons to that style. For instance, here's a snippet from the styles.xml file from the <a href="http://developer.android.com/resources/samples/HoneycombGallery/index.html" rel="noreferrer">HoneycombGallery</a> sample application.</p> <pre><code>&lt;style name="AppTheme.Dark" parent="@android:style/Theme.Holo"&gt; ... &lt;item name="menuIconCamera"&gt;@drawable/ic_menu_camera_holo_dark&lt;/item&gt; &lt;item name="menuIconToggle"&gt;@drawable/ic_menu_toggle_holo_dark&lt;/item&gt; &lt;item name="menuIconShare"&gt;@drawable/ic_menu_share_holo_dark&lt;/item&gt; &lt;/style&gt; </code></pre> <p>The bottom 3 elements are all icons in the drawable directories. You'll still need at least one folder per resolution-specific set of icons, but you can combine the light &amp; dark icons into the same folder, but you won't have to have different folders of icons for each platform version. Also, you'll need to list them as references in the values/attrs.xml file, like this:</p> <pre><code>&lt;resources&gt; &lt;declare-styleable name="AppTheme"&gt; &lt;attr name="listDragShadowBackground" format="reference" /&gt; &lt;attr name="menuIconCamera" format="reference" /&gt; &lt;attr name="menuIconToggle" format="reference" /&gt; &lt;attr name="menuIconShare" format="reference" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p>At which point you'll be able to refer to them within your layout XML using the "?attr/NameOfYourDrawable" dereference, like this:</p> <pre><code>&lt;item android:id="@+id/menu_camera" android:title="@string/camera" android:icon="?attr/menuIconCamera" android:showAsAction="ifRoom" /&gt; </code></pre>
9,270,214
html5 canvas - animating an object following a path
<p>I'm a bit new to canvas and such so forgive if it's a trivial question.</p> <p>I'd like to be able to animate an object following a path (defined as bezier path) but I'm not sure how to do it.</p> <p>I've looked at Raphael but I can't work out how to follow the path over time.</p> <p>Cake JS looked promising in the demo, but I'm really struggling the documentation, or lack thereof in this case.</p> <p>Has anyone got some working example of this?</p>
9,271,416
3
0
null
2012-02-14 00:43:03.353 UTC
12
2018-02-05 08:21:42.857 UTC
2013-12-07 20:31:19.37 UTC
null
881,229
null
192,705
null
1
18
html|animation|html5-canvas|raphael
19,791
<p>Use the code <a href="http://phrogz.net/svg/animation_on_a_curve.html" rel="nofollow noreferrer">on my website</a> from <a href="https://stackoverflow.com/questions/8438830/move-a-div-in-a-curved-path-like-tweening-in-flash-old-days">this related question</a>, but instead of changing the <code>.style.left</code> and such in the callback, erase and re-draw your canvas with the item at the new location (and optionally rotation).</p> <p>Note that this uses SVG internally to easily interpolate points along a bézier curve, but you can use the points it gives you for whatever you want (including drawing on a Canvas).</p> <p>In case my site is down, here's a current snapshot of the library:</p> <pre><code>function CurveAnimator(from,to,c1,c2){ this.path = document.createElementNS('http://www.w3.org/2000/svg','path'); if (!c1) c1 = from; if (!c2) c2 = to; this.path.setAttribute('d','M'+from.join(',')+'C'+c1.join(',')+' '+c2.join(',')+' '+to.join(',')); this.updatePath(); CurveAnimator.lastCreated = this; } CurveAnimator.prototype.animate = function(duration,callback,delay){ var curveAnim = this; // TODO: Use requestAnimationFrame if a delay isn't passed if (!delay) delay = 1/40; clearInterval(curveAnim.animTimer); var startTime = new Date; curveAnim.animTimer = setInterval(function(){ var now = new Date; var elapsed = (now-startTime)/1000; var percent = elapsed/duration; if (percent&gt;=1){ percent = 1; clearInterval(curveAnim.animTimer); } var p1 = curveAnim.pointAt(percent-0.01), p2 = curveAnim.pointAt(percent+0.01); callback(curveAnim.pointAt(percent),Math.atan2(p2.y-p1.y,p2.x-p1.x)*180/Math.PI); },delay*1000); }; CurveAnimator.prototype.stop = function(){ clearInterval(this.animTimer); }; CurveAnimator.prototype.pointAt = function(percent){ return this.path.getPointAtLength(this.len*percent); }; CurveAnimator.prototype.updatePath = function(){ this.len = this.path.getTotalLength(); }; CurveAnimator.prototype.setStart = function(x,y){ var M = this.path.pathSegList.getItem(0); M.x = x; M.y = y; this.updatePath(); return this; }; CurveAnimator.prototype.setEnd = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x = x; C.y = y; this.updatePath(); return this; }; CurveAnimator.prototype.setStartDirection = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x1 = x; C.y1 = y; this.updatePath(); return this; }; CurveAnimator.prototype.setEndDirection = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x2 = x; C.y2 = y; this.updatePath(); return this; }; </code></pre> <p>…and here's how you might use it:</p> <pre><code>var ctx = document.querySelector('canvas').getContext('2d'); ctx.fillStyle = 'red'; var curve = new CurveAnimator([50, 300], [350, 300], [445, 39], [1, 106]); curve.animate(5, function(point, angle) { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillRect(point.x-10, point.y-10, 20, 20); });​ </code></pre> <p>In action: <a href="http://jsfiddle.net/Z2YSt/" rel="nofollow noreferrer">http://jsfiddle.net/Z2YSt/</a></p>
30,884,778
How to compile a project with app and library in the same workspace with different configuration names?
<p>I am developing an app and I am using an open source component.</p> <p>I have a workspace containing both <em>MyApp.xcodeproj</em> and <em>Component.xcodeproj</em>. My app has three configurations: <em>Debug</em>, <em>App Store</em> and <em>In House</em> but the component has only two: <em>Debug</em> and <em>Release</em></p> <p>In the <em>Debug</em> configuration, everything works fine, but I can't compile my app in <em>App Store</em> or <em>In House</em> configuration because the configuration names do not match. I get a file not found error when trying to <code>#import &lt;Component/Component.h&gt;</code></p> <p>I need both <em>App Store</em> and <em>In House</em> configurations and I would really like to avoid modifying the component's configurations in order to ease future updates of the component.</p> <p>I know I could use CocoaPods to solve this issue but I would like to know if there is a simple solution in Xcode</p>
30,884,779
3
1
null
2015-06-17 07:19:03.187 UTC
19
2020-08-29 15:23:19.413 UTC
null
null
null
null
21,698
null
1
29
xcode|xcode-workspace
8,435
<p>You can get your project to compile with some tweaks to your app’s settings.</p> <p>I suggest you to modify all settings at the project level so that all your targets can inherit these settings.</p> <ol> <li><p>Add a new <code>DEFAULT_CONFIGURATION</code> user-defined setting and define your configuration mapping. This is how it should look like:</p> <p><img src="https://i.stack.imgur.com/V5KMu.png" alt="Default Configuration Screenshot"></p></li> <li><p>Set <code>FRAMEWORK_SEARCH_PATHS</code> to <code>$(BUILD_DIR)/$(DEFAULT_CONFIGURATION)-$(PLATFORM_NAME)</code> for all configurations, add <strong>Any OS X SDK</strong> variants and set the value to <code>$(BUILD_DIR)/$(DEFAULT_CONFIGURATION)</code>. Set <code>HEADER_SEARCH_PATHS</code> to <code>$(FRAMEWORK_SEARCH_PATHS)/include</code> and <code>LIBRARY_SEARCH_PATHS</code> to <code>$(FRAMEWORK_SEARCH_PATHS)</code>. This is how it should look like:</p> <p><img src="https://i.stack.imgur.com/vSrWu.png" alt="Search Paths Screenshot"></p> <p>This step is quite tedious, it can be automated with the <a href="https://github.com/0xced/xcproj">xcproj</a> tool and by running this script in your project directory. Edit your configurations mapping as needed.</p> <pre><code>#!/bin/bash CONFIGURATIONS=( "App Store:Release" "In House:Release" "Debug:Debug" ) for CONFIGURATION in "${CONFIGURATIONS[@]}"; do xcproj --configuration "${CONFIGURATION%%:*}" write-build-setting DEFAULT_CONFIGURATION "${CONFIGURATION#*:}" done xcproj write-build-setting 'FRAMEWORK_SEARCH_PATHS' '$(BUILD_DIR)/$(DEFAULT_CONFIGURATION)-$(PLATFORM_NAME)' xcproj write-build-setting 'FRAMEWORK_SEARCH_PATHS[sdk=macosx*]' '$(BUILD_DIR)/$(DEFAULT_CONFIGURATION)' xcproj write-build-setting 'HEADER_SEARCH_PATHS' '$(FRAMEWORK_SEARCH_PATHS)/include' xcproj write-build-setting 'LIBRARY_SEARCH_PATHS' '$(FRAMEWORK_SEARCH_PATHS)' </code></pre></li> <li><p>If the component is distributed as a static library, you are done here. If the component comes as a framework you have to update its path reference by editing your project.pbxproj file in a text editor. In the PBXFileReference section (under <code>/* Begin PBXFileReference section */</code>) find <code>Component.framework</code> and update its <code>path</code> like this:</p> <pre><code>name = Component.framework; path = "../$(DEFAULT_CONFIGURATION)/Component.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; </code></pre> <p>Also make sure that the <code>sourceTree</code> is set to <code>BUILT_PRODUCTS_DIR</code>, i.e. relative to built products. Once you edited the project file, this should look like:</p> <p><img src="https://i.stack.imgur.com/Nu39i.png" alt="Location Screenshot"></p></li> </ol> <p>Your project should now build as expected.</p>
10,849,893
How to convert byte array to blob
<p>I want to fetch an image from database. For that I have created a byte array for an image, which is passed by a string, and now I want to convert that string into image format. I am assigning that image to a Jlabel field. The code is as follows:</p> <pre class="lang-java prettyprint-override"><code>try { Blob image_vis = rs1.getBlob(10); InputStream x=image_vis.getBinaryStream(); OutputStream out=new FileOutputStream(string_op); byte[] bytes = string_op.getBytes(); String s=new String(bytes); System.out.println(+s); //prints bytes for the string ImageIcon icon_cap = new ImageIcon(string_op); image_cap.setIcon(icon_cap); //prints nothing to Jlabel //image_cap.setText(s); //prints a path of a image } </code></pre>
10,849,944
1
1
null
2012-06-01 12:02:13.557 UTC
7
2020-04-02 17:40:57.817 UTC
2020-04-02 17:40:57.817 UTC
null
6,028,807
null
1,409,432
null
1
16
java|mysql|swing|netbeans
62,498
<pre><code>Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes); </code></pre>
10,578,249
hosting nodejs application in EC2
<p>I'm interested in hosting nodejs applications in a cloud and I'm looking for a free cloud hosting for my purpose. I've found that Amazon has one but I have the following question: Are there any tutorials around how I can set up and run nodejs application in Amazon EC2?</p> <p><strong>EDIT</strong>: Can you provide any good hostings for nodejs (except heroku)?</p>
10,580,778
8
1
null
2012-05-14 06:15:39.637 UTC
40
2022-01-07 02:58:01.273 UTC
2017-08-19 17:27:36.347 UTC
null
1,006,884
null
1,006,884
null
1
28
node.js|amazon-ec2|hosting
36,589
<p>I've been using Node.js with Amazon EC2 for a while and was quite happy with both of them. For the moment AWS seems to be the cheapest and the most robust cloud provider, so picking up Amazon wouldn't be a mistake. There's nothing special about running Node.js in the cloud - you work with it like if it were your own PC. Below are some general steps to follow for the simplest Node.js application running on EC2 Ubuntu server:</p> <ol> <li><p>Create <a href="http://aws.amazon.com/" rel="noreferrer">Amazon EC2 account</a>.</p></li> <li><p>From AWS console start <code>t1.micro</code> instance with any Ubuntu AMI (<a href="https://whatiscomingtomyhead.wordpress.com/2010/11/24/absolute-first-step-tutorial-for-amazon-web-services/" rel="noreferrer">example</a>).</p></li> <li><p>Login via SSH to your instance.</p></li> <li><p>Install node.js: <code>sudo apt-get install nodejs</code></p></li> <li><p>Create new file <code>test_server.js</code> with the following content:</p> <pre><code>require("http").createServer(function(request, response){ response.writeHeader(200, {"Content-Type": "text/plain"}); response.write("Hello World!"); response.end(); }).listen(8080); </code></pre></li> <li><p>Start the server: <code>node test_server.js</code></p></li> <li><p>Check it's working from another console: <code>curl http://localhost:8080</code></p></li> </ol>
7,135,600
Entity Framework Code First and Connection String Issue
<p>I am getting this error when using Entity Framework 4.1 code first. I can not find any sources of what exactly to use.</p> <pre><code>Unable to load the specified metadata resource. &lt;add name="DataContext" connectionString="metadata=res://*/GrassrootsHoopsDataContext.csdl|res://*/GrassrootsHoopsDataContext.ssdl|res://*/GrassrootsHoopsDataContext.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;Data Source=myserver.com;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=username;Password=password&amp;quot;" providerName="System.Data.EntityClient" /&gt; </code></pre>
7,135,641
2
1
null
2011-08-21 00:34:37.957 UTC
7
2015-07-20 08:31:55.29 UTC
2012-07-15 06:08:09.033 UTC
null
60,108
null
280,602
null
1
33
entity-framework|entity-framework-4.1|ef-code-first|connection-string
30,637
<p>For EF Code First you can use ordinary connection string if you are using <code>SQL Server</code>.</p> <pre><code>&lt;add name="DataContext" connectionString="Data Source=myserver.com;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient" /&gt; </code></pre>
7,477,181
Array-Based vs List-Based Stacks and Queues
<p>I'm trying to compare the growth rates (both run-time and space) for stack and queue operations when implemented as both arrays and as linked lists. So far I've only been able to find average case run-times for queue <code>pop()</code>s, but nothing that comprehensively explores these two data structures and compares their run-times/space behaviors.</p> <p>Specifically, I'm looking to compare <code>push()</code> and <code>pop()</code> for both queues and stacks, implemented as <strong>both</strong> arrays and linked lists (thus 2 operations x 2 structures x 2 implementations, or 8 values).</p> <p>Additionally, I'd appreciate best, average and worst case values for both of these, and anything relating to the amount of space they consume.</p> <p>The closest thing I've been able to find is this "mother of all cs cheat sheets" pdf that is clearly a masters- or doctoral-level cheat sheet of advanced algorithms and discrete functions.</p> <p><strong>I'm just looking for a way to determine when and where I should use an array-based implementation vs. a list-based implementation for both stacks and queues.</strong></p>
7,477,556
2
2
null
2011-09-19 20:55:01.267 UTC
55
2020-12-12 11:52:17.417 UTC
2017-07-17 23:37:03.343 UTC
null
501,557
null
892,029
null
1
64
arrays|data-structures|stack|queue|linked-list
68,961
<p>There are multiple different ways to implement queues and stacks with linked lists and arrays, and I'm not sure which ones you're looking for. Before analyzing any of these structures, though, let's review some important runtime considerations for the above data structures.</p> <p>In a singly-linked list with just a head pointer, the cost to prepend a value is O(1) - we simply create the new element, wire its pointer to point to the old head of the list, then update the head pointer. The cost to delete the first element is also O(1), which is done by updating the head pointer to point to the element after the current head, then freeing the memory for the old head (if explicit memory management is performed). However, the constant factors in these O(1) terms may be high due to the expense of dynamic allocations. The memory overhead of the linked list is usually O(n) total extra memory due to the storage of an extra pointer in each element.</p> <p>In a dynamic array, we can access any element in O(1) time. We can also append an element in <a href="http://en.wikipedia.org/wiki/Amortized_analysis" rel="noreferrer">amortized O(1)</a>, meaning that the total time for n insertions is O(n), though the actual time bounds on any insertion may be much worse. Typically, dynamic arrays are implemented by having most insertions take O(1) by appending into preallocated space, but having a small number of insertions run in &Theta;(n) time by doubling the array capacity and copying elements over. There are techniques to try to reduce this by allocating extra space and lazily copying the elements over (see <a href="https://stackoverflow.com/questions/4834490/what-would-be-an-ideal-data-structure-for-an-add-only-no-removals-collection">this data structure</a>, for example). Typically, the memory usage of a dynamic array is quite good - when the array is completely full, for example, there is only O(1) extra overhead - though right after the array has doubled in size there may be O(n) unused elements allocated in the array. Because allocations are infrequent and accesses are fast, dynamic arrays are usually faster than linked lists.</p> <p>Now, let's think about how to implement a stack and a queue using a linked list or dynamic array. There are many ways to do this, so I will assume that you are using the following implementations:</p> <ul> <li>Stack: <ul> <li>Linked list: As a <a href="http://en.wikipedia.org/wiki/Linked_list#Singly.2C_doubly.2C_and_multiply_linked_lists" rel="noreferrer">singly-linked list</a> with a head pointer.</li> <li>Array: As a <a href="http://en.wikipedia.org/wiki/Dynamic_array" rel="noreferrer">dynamic array</a></li> </ul></li> <li>Queue: <ul> <li>Linked list: As a singly-linked list with a head and tail pointer.</li> <li>Array: As a <a href="http://en.wikipedia.org/wiki/Circular_buffer" rel="noreferrer">circular buffer</a> backed by an array.</li> </ul></li> </ul> <p>Let's consider each in turn.</p> <p><strong>Stack backed by a singly-linked list.</strong> Because a singly-linked list supports O(1) time prepend and delete-first, the cost to push or pop into a linked-list-backed stack is also O(1) worst-case. However, each new element added requires a new allocation, and allocations can be expensive compared to other operations.</p> <p><strong>Stack backed by a dynamic array.</strong> Pushing onto the stack can be implemented by appending a new element to the dynamic array, which takes amortized O(1) time and worst-case O(n) time. Popping from the stack can be implemented by just removing the last element, which runs in worst-case O(1) (or amortized O(1) if you want to try to reclaim unused space). In other words, the most common implementation has best-case O(1) push and pop, worst-case O(n) push and O(1) pop, and amortized O(1) push and O(1) pop.</p> <p><strong>Queue backed by a singly-linked list.</strong> Enqueuing into the linked list can be implemented by appending to the back of the singly-linked list, which takes worst-case time O(1). Dequeuing can be implemented by removing the first element, which also takes worst-case time O(1). This also requires a new allocation per enqueue, which may be slow.</p> <p><strong>Queue backed by a growing circular buffer.</strong> Enqueuing into the circular buffer works by inserting something at the next free position in the circular buffer. This works by growing the array if necessary, then inserting the new element. Using a similar analysis for the dynamic array, this takes best-case time O(1), worst-case time O(n), and amortized time O(1). Dequeuing from the buffer works by removing the first element of the circular buffer, which takes time O(1) in the worst case.</p> <p>To summarize, all of the structures support pushing and popping n elements in O(n) time. The linked list versions have better worst-case behavior, but may have a worse overall runtime because of the number of allocations performed. The array versions are slower in the worst-case, but have better overall performance if the time per operation isn't too important.</p> <p>These aren't the only ways you can implement lists. You could have an <a href="https://en.wikipedia.org/wiki/Unrolled_linked_list" rel="noreferrer">unrolled linked list</a>, where each linked list cell holds multiple values. This slightly increases the locality of reference of the lookups and decreases the number of allocations used. Other options (using a balanced tree keyed by index, for example) represent a different set of tradeoffs.</p> <p>Hope this helps!</p>
19,243,177
How to scroll to top in IOS7 UITableView?
<p>In IOS6 I have the following code to scroll to the top of a UITableView</p> <pre><code>[tableView setContentOffset:CGPointZero animated:YES]; </code></pre> <p>In IOS7 this doesn't work anymore. The table view isn't scrolled completely to the top (but almost).</p>
19,243,807
12
1
null
2013-10-08 08:52:47.47 UTC
15
2017-09-22 09:37:23.857 UTC
null
null
null
null
23,423
null
1
44
ios|uitableview|ios7
43,601
<p>By the help from some other answers here I managed to get it working. To avoid a crash I must first check that there are some sections. NsNotFound can be used as a row index if the first section has no rows. Hopefully this should be a generic function to be placed in a UITableViewController:</p> <pre><code>-(void) scrollToTop { if ([self numberOfSectionsInTableView:self.tableView] &gt; 0) { NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0]; [self.tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES]; } } </code></pre>
36,851,887
recommended way to install mongodb on elastic beanstalk
<p>I have already taken a look at <a href="https://stackoverflow.com/questions/24653625/how-to-install-mongodb-in-elastic-beanstalk">How to install mongodb in Elastic Beanstalk?</a> dated 2014, which no longer works. as well as <a href="https://docs.mongodb.org/ecosystem/platforms/amazon-ec2/#manually-deploy-mongodb-on-ec2" rel="noreferrer">https://docs.mongodb.org/ecosystem/platforms/amazon-ec2/#manually-deploy-mongodb-on-ec2</a></p> <p>I have set up a new elastic beanstalk environment running on node.js with 1 ec2 micro instance '64bit Amazon Linux 2016.03 v2.1.0 running Node.js'</p> <p>I have already tried using ssh to connect into my instance and install the mongodb packages using yum command:</p> <pre><code>$ sudo yum install -y mongodb-org-server mongodb-org-shell mongodb-org-tools </code></pre> <p>and received this call back:</p> <pre><code>Loaded plugins: priorities, update-motd, upgrade-helper No package mongodb-org-server available. No package mongodb-org-shell available. No package mongodb-org-tools available. Error: Nothing to do </code></pre> <p>When I first ssh 'd into my instance, I received this error warning:</p> <pre><code>This EC2 instance is managed by AWS Elastic Beanstalk. Changes made via SSH WILL BE LOST if the instance is replaced by auto-scaling. For more information on customizing your Elastic Beanstalk environment, see our documentation here: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html </code></pre> <p>Currently my environment is set up as a single instance environment, to save on costs. However, in the future I will upgrade to an auto-scaling environment. </p> <p>Because of this, I am asking is it recommendable to make any changes via ssh in ec2, or should I only be using EB CLI?</p> <p>I have both EC2 and EB CLI installed locally, however I have never used EB CLI before. If I should be using EB, does anyone have a recommended way to install mongodb?</p>
36,865,963
2
2
null
2016-04-25 22:01:24.987 UTC
5
2019-07-12 17:50:00.65 UTC
2019-07-12 12:45:38.277 UTC
null
1,233,251
null
4,203,782
null
1
31
node.js|mongodb|ssh|amazon-ec2|amazon-elastic-beanstalk
17,254
<p>In case anyone is looking for an answer, here is the advice I received from aws business support. </p> <p>All code deployed to Elastic Beanstalk needs to be "stateless" I.E. Never make changes directly to a running beanstalk instance using SSH or FTP.... As this will cause inconsistencies and or data lose! - Elastic Beanstalk is not designed for application that are not stateless. The environment is designed to scale up and down pending on your Network / CPU load and build new instances from a base AMI. If an instance has issues or the underlying hardware, Elastic Beanstalk will terminate these running instances and replace with new instances. Hence, why no code modification must be applied or done "directly" to an existing instance as new instances will not be aware of these direct changes. ALL changes / code needs to be either uploaded to Elastic Beanstalk console or the CLI tools and the pushed to all the running instances. More information on Elastic Beanstalk design concepts can be read at the following link <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.concepts.design.html" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.concepts.design.html</a></p> <p>Suggested Solution: With the above in mind, if using MongoDB to store application data our recommendation would be to DE-couple the MongoDB environment from your Node.js application. I.E Create a MongoDB Server outside of Elastic Beanstalk, example launching MongoDB directly on a EC2 instance and have your Elastic Beanstalk Node.js application connect to MongoDB Server using connection settings in your app. </p> <p>-Creating MongoDB Below is some example links that may be of use for your scenario for creating a MongoDB Server. Deploy MongoDB on EC2, <a href="https://docs.mongodb.org/ecosystem/platforms/amazon-ec2/" rel="noreferrer">https://docs.mongodb.org/ecosystem/platforms/amazon-ec2/</a> MongoDB node client <a href="https://docs.mongodb.org/getting-started/node/client/" rel="noreferrer">https://docs.mongodb.org/getting-started/node/client/</a> MongoDB on the AWS Cloud quick start guide <a href="http://docs.aws.amazon.com/quickstart/latest/mongodb/architecture.html" rel="noreferrer">http://docs.aws.amazon.com/quickstart/latest/mongodb/architecture.html</a></p> <p>-Adding environment variables to Elastic Beanstalk to reference your MongoDB server Once you have created your MongoDB Server you can pass the needed connection settings to your Elastic Beanstalk environment using environment variables. Example using .ebextensions .config which you can add Mongo URL / ports / users etc..</p> <p>option_settings: - option_name: MONGO_DB_URL value: "Your MongoDB EC2 internal IP address"</p> <p>Information on how to use environment properties and read them from within your application can be seen below. <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html#create_deploy_nodejs_custom_container-envprop" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html#create_deploy_nodejs_custom_container-envprop</a> And information using .ebextensions .config can be found at the following link <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html</a></p> <p>Alternatively you can also set environment variable using the cli or via the AWS Console eb cli set environment variables can be read per the below link. <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-setenv.html" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-setenv.html</a> Using AWS Console To set system properties (AWS Management Console) Open the Elastic Beanstalk console. Navigate to the management console for your environment. Choose Configuration. In the Software Configuration section, choose Edit. Under Environment Properties, create your name / values ...</p> <p>Accessing Environment Configuration Settings Inside the Node.js environment running in AWS Elastic Beanstalk, you can access the environment variables using process.env.ENV_VARIABLE similar to the following example. process.env.MONGO_DB_URL process.env.PARAM2</p> <p><a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html#create_deploy_nodejs_custom_container-envprop" rel="noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html#create_deploy_nodejs_custom_container-envprop</a></p> <p>Summary: In summary I would recommend the following steps to integrate MongoDB with Elastic Beanstalk environments. Step 1) Create a MongoDB Server outside of Elastic Beanstalk Step 2) Create your Node.js application in Elastic Beanstalk that connect to your MongoDB server</p>
35,728,117
Difference between import http = require('http'); and import * as http from 'http';?
<p>I haven't been able to find a worthwhile NodeJS with Typescript tutorial out there so I'm diving in unguided and sure enough I have a question.</p> <p>I don't understand the difference between these two lines:</p> <pre><code>import * as http from 'http'; // and import http = require('http'); </code></pre> <p>They seem to function the same way but I imagine there's probably some nuance to their behavior or else one of them probably wouldn't exist.</p> <p>I do understand that the first approach could let me selectively import from a module but if I'm importing all of the module then is there a difference between the two? Is there a preferred way? What if I'm importing from my own files, does that change anything?</p>
35,739,633
3
2
null
2016-03-01 16:24:52.517 UTC
7
2020-06-10 18:40:16.86 UTC
null
null
null
null
160,527
null
1
22
node.js|typescript
46,629
<p>In the first form, you create an <strong>http</strong> object in your code (totally clean), then, the interpreter will look for each possible import in <em>http</em> module and append it, one by one, to the <strong>http</strong> object in your code, this is a little slower (not much) than the second form where you are getting the <em>module.exports</em> object defined in the <em>http</em> module, then copying this reference to a new <strong>http</strong> object in your code, this is object in a node special function with a particular context, not only an object created in your code with the contents of the module.</p>
21,033,059
PMA Database ... not OK in phpMyAdmin upgrade
<p>I have just been wrangling with phpMyAdmin and MySQL server on my Win8 PC IIS localhost (there was no connection between these, which I think was due to MySQL service not starting so I reinstalled MySQL and reran the config setup and reestablished a connection between them, which fixed that). </p> <p>However phpMyAdmin advised an update which I did by overwriting the files with the new version and including the previous config file. </p> <p>I now have:<br> <code>The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click here.</code><br> and on clicking I get<br> <code>PMA Database ... not OK [ Documentation ]</code><br> <code>General relation features Disabled</code><br> When I click the link I get a http 404 page which gives this:<br></p> <pre><code>Physical path C:\inetpub\wwwroot\phpMyAdmin\pmadb </code></pre> <p>So what is the pmadb in phpMyAdmin and should I be bothered by this? As it stands I'm a bit fed up at having to have had to spend time tweaking all of this (ie it has not been a smooth trouble free event/install). Is it some DB for the old version or what? I do not think I created it! </p> <p>I do not feel very bothered by this as hopefully I can setup my databases for my localhost IIS websites and press on with my webdeverry(!) but I don't really like having this unknown error and wouldn't mind fixing it/getting rid of it.</p>
21,389,060
7
3
null
2014-01-09 23:05:31.733 UTC
6
2021-11-24 17:12:16.097 UTC
2014-10-03 21:42:51.317 UTC
null
632,951
null
247,135
null
1
27
mysql|phpmyadmin
85,316
<p>There are a few google links on this same issue that I have followed that have helped me fix this (I should have spent more time googling before posting!). So to solve the problem I needed to create a phpmyadmin database and import create_tables.sql and assign a new user with full privileges and then uncomment the config.inc.php file at:</p> <p><code>/* User used to manipulate with storage */ $cfg['Servers'][$i]['controlhost'] = ''; $cfg['Servers'][$i]['controluser'] = 'phpmyadmin';</code></p> <p>and uncomment lines below</p> <p><code>/* Storage database and tables */ $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';</code></p> <p>I also needed to add some lines from the new version <code>config.sample.inc</code> There was a good link describing this I wanted to save but I had to clear my browser cache to reload localhost/phpMyAdmin and in doing so I lost my history &amp; that link! </p> <p>I know this explanation is not exactly described but I hope it may help anyone else who gets a similar issue after updating phpMyAdmin. I'm still not sure what all these features do but it is all fixed now, thanks!</p>
47,761,262
Angular 4/5 HttpClient: Argument of type string is not assignable to 'body'
<p>The Angular docs say:</p> <blockquote> <p>The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions, and inspecting those can be necessary. To do this, you can tell HttpClient you want the full response instead of just the body with the observe option:</p> </blockquote> <pre><code>http .get&lt;MyJsonData&gt;('/data.json', {observe: 'response'}) .subscribe(resp =&gt; { // Here, resp is of type HttpResponse&lt;MyJsonData&gt;. // You can inspect its headers: console.log(resp.headers.get('X-Custom-Header')); // And access the body directly, which is typed as MyJsonData as requested. console.log(resp.body.someField); }); </code></pre> <p>But when I try that, I get a compilation time error (no runtime errors though, works as expected):</p> <blockquote> <p>error TS2345: Argument of type '{ headers: HttpHeaders; observe: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"body"'.</p> </blockquote> <p>Why? I use <code>"@angular/http": "^5.1.0"</code></p> <p>Here is my version of the code:</p> <pre><code> login(credentials: Credentials): Observable&lt;any&gt; { const options = { headers: new HttpHeaders({'Content-Type': 'application/json'}), observe: 'response' }; return this.httpClient.post&lt;any&gt;(`${environment.USER_SERVICE_BASE_URL}`, {'username': credentials.username, 'password': credentials.password}, options) .map((res) =&gt; ... </code></pre>
47,761,516
4
3
null
2017-12-11 20:55:41.823 UTC
8
2020-04-07 06:50:27.28 UTC
2019-12-05 22:54:39.067 UTC
null
431,941
null
4,125,622
null
1
28
angular|typescript|angular-httpclient
53,604
<p>You have to inline the options. See <a href="https://github.com/angular/angular/issues/18586" rel="noreferrer">github ticket #18586</a>, entry by <code>alxhub</code> on August 9 2017.</p> <blockquote> <p>Typescript needs to be able to infer the observe and responseType values statically, in order to choose the correct return type for get(). If you pass in an improperly typed options object, it can't infer the right return type.</p> </blockquote> <pre><code>login(credentials: Credentials): Observable&lt;any&gt; { return this.httpClient.post&lt;any&gt;(`${environment.USER_SERVICE_BASE_URL}`, {'username': credentials.username, 'password': credentials.password}, { headers: new HttpHeaders({'Content-Type': 'application/json'}), observe: 'response' }) .map((res) =&gt; ... </code></pre>
1,463,306
How to get local variables updated, when using the `exec` call?
<p>I thought this would print 3, but it prints 1:</p> <pre class="lang-py prettyprint-override"><code># Python3 def f(): a = 1 exec(&quot;a = 3&quot;) print(a) f() # 1 Expected 3 </code></pre>
1,463,370
3
5
null
2009-09-23 00:18:47.327 UTC
14
2022-06-24 14:50:36.68 UTC
2022-06-24 14:33:58.89 UTC
null
1,896,134
null
177,498
null
1
47
python|python-3.x|exec|local-variables
19,613
<p>This issue is somewhat discussed in the <a href="http://bugs.python.org/issue4831" rel="noreferrer">Python3 bug list</a>. Ultimately, to get this behavior, you need to do:</p> <pre><code>def foo(): ldict = {} exec(&quot;a=3&quot;,globals(),ldict) a = ldict['a'] print(a) </code></pre> <p>And if you check <a href="http://docs.python.org/3/library/functions.html#exec" rel="noreferrer">the Python3 documentation on <code>exec</code></a>, you'll see the following note:</p> <blockquote> <p>The default locals act as described for function <code>locals()</code> below: <strong>modifications to the default locals dictionary should not be attempted</strong>. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.</p> </blockquote> <p>That means that one-argument <code>exec</code> can't safely perform any operations that would bind local variables, including variable assignment, imports, function definitions, class definitions, etc. It can assign to globals if it uses a <code>global</code> declaration, but not locals.</p> <p>Referring back to <a href="http://bugs.python.org/msg79061" rel="noreferrer">a specific message on the bug report</a>, Georg Brandl says:</p> <blockquote> <p>To modify the locals of a function on the fly is not possible without several consequences: <strong>normally, function locals are not stored in a dictionary, but an array</strong>, whose indices are determined at compile time from the known locales. This collides at least with new locals added by exec. The old exec statement circumvented this, because the compiler knew that if an exec without globals/locals args occurred in a function, that namespace would be &quot;unoptimized&quot;, i.e. not using the locals array. Since exec() is now a normal function, <strong>the compiler does not know what &quot;exec&quot; may be bound to, and therefore can not treat is specially</strong>.</p> </blockquote> <p>Emphasis is mine.</p> <p>So the gist of it is that Python3 can better optimize the use of local variables by <em>not</em> allowing this behavior by default.</p> <p>And for the sake of completeness, as mentioned in the comments above, this <em>does</em> work as expected in Python 2.X:</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; def f(): ... a = 1 ... exec &quot;a=3&quot; ... print a ... &gt;&gt;&gt; f() 3 </code></pre>
1,776,496
A simple command line to download a remote maven2 artifact to the local repository?
<p>I have a library that I distribute using maven 2. The typical user of this library doesn't use maven to build their applications, but is likely somewhat familiar with maven and probably has it installed.</p> <p>I'd like to document a "simple" one line command they can use to download my library's artifacts to their local <code>~/.m2/repository</code> without requiring that they set up a pom.xml to do it.</p> <p>I thought there was a way to do this, but I can't seem to find it after looking through the <code>install:install-file</code> and <code>dependency</code> plugin documentation. I tried things like:</p> <pre><code>mvn install:install-file -DrepositoryId=java.net -Durl=http://download.java.net/maven/2/ -Dfile=robo-guice-0.4-20091121.174618-1.jar -DpomFile=robo-guice-0.4-20091121.174618-1.pom -DgroupId=robo-guice -DartifactId=robo-guice -Dversion=0.4-SNAPSHOT -Dpackaging=jar </code></pre> <p>but I think I'm barking up the wrong tree since it appears that the install plugin is used to copy locally built files into the local repository, rather than download remote artifacts into the local repository.</p> <p>This is the artifact I'd like to install: <a href="http://download.java.net/maven/2/robo-guice/robo-guice/0.4-SNAPSHOT/" rel="noreferrer">http://download.java.net/maven/2/robo-guice/robo-guice/0.4-SNAPSHOT/</a></p> <p>Is this possible using maven?</p>
1,776,808
3
2
null
2009-11-21 19:34:43.757 UTC
51
2012-11-28 21:19:41.157 UTC
null
null
null
null
82,156
null
1
133
maven-2
153,144
<p>Since version 2.1 of the <a href="http://maven.apache.org/plugins/maven-dependency-plugin" rel="noreferrer">Maven Dependency Plugin</a>, there is a <a href="http://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html" rel="noreferrer">dependency:get</a> goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":</p> <pre> mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \ -DrepoUrl=http://download.java.net/maven/2/ \ -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT </pre>
8,553,200
How do I install and use a JSON editor in Eclipse?
<p>I wish to install a JSON editor in Eclipse, and I am trying to use <a href="https://sourceforge.net/projects/eclipsejsonedit/" rel="nofollow noreferrer">Eclipse JSON Editor Plugin</a> which is mentioned in <a href="https://stackoverflow.com/a/943720/1743811">an answer</a> to <a href="https://stackoverflow.com/questions/357521/is-there-a-decent-json-editor-around">this SO question</a>.</p> <p>I have copied the zip file from Sourceforge. How do I install the plugin and then how do I configure the editor in Eclipse to recognise and edit JSON files? I do not know how to install plugins manually so please assume ignorance and give detailed descriptions.</p> <p>If there are better/newer solutions please indicate them.</p>
8,553,404
4
1
null
2011-12-18 16:48:32.203 UTC
4
2020-09-11 06:48:27.253 UTC
2017-05-23 12:09:21.117 UTC
null
-1
null
130,964
null
1
31
eclipse|json|eclipse-plugin
52,460
<p>I just went to the site and downloaded the file. You want the zip file that is downloaded. Once you have that, go to Help -&gt; Install New Software. Click the Add.. Button and then the Archive button, and specify the location of the zip file you downloaded, and then proceed through the installation.</p> <p>Make sure you DESELECT group items by Category (see answer below)</p> <p>The zip file provided is set up for this type of installation within Eclipse.</p>
27,124,214
How to Change the status bar color using ios with swift on internet reachability?
<p>i want to change the color of my device status bar if the internet is connected than the status bar color should turn Black and if the internet is not connected the color or status bar should turn Red so that it indicates wether internet is working or not during working with the application using SWIFT...help me out</p>
27,124,446
9
3
null
2014-11-25 10:28:03.247 UTC
9
2020-02-10 12:12:41.9 UTC
null
null
null
null
4,286,978
null
1
13
ios|swift|statusbar
48,614
<p>In your <code>Info.plist</code> you need to set "View controller-based status bar appearance" to a boolean value.</p> <p>If you set it to <code>YES</code> then you should override <code>preferredStatusBarStyle</code> function in each view controller.</p> <p>If you set it to <code>NO</code> then you can set the style in <code>AppDelegate</code> using: </p> <pre><code>UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) </code></pre>
19,700,382
How to show iOS Push Notification Popup?
<p>I'm trying to add push notification to my app. I need to know how to make the push notification popup appear. The popup I'm pertaining to is an alert view that has two choices, "allow" and "don't allow". It asks the user whether to allow the app to receive notifications and stuff or not. </p> <p>I've tried deleting my app over and over again and advancing the time but nothing worked.</p> <p>Also, in case the popup appears, how can I know if the user selected don't allow/ allow? </p>
19,709,441
2
1
null
2013-10-31 07:13:35.827 UTC
10
2016-09-07 13:17:17.74 UTC
2016-09-07 13:17:17.74 UTC
null
3,950,397
null
1,681,701
null
1
15
ios|notifications|push-notification|apple-push-notifications
19,125
<blockquote> <p>Resetting the Push Notifications Permissions Alert on iOS</p> <p>The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.</p> <p>If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:</p> <pre><code>1. Delete your app from the device. 2. Turn the device off completely and turn it back on. 3. Go to Settings &gt; General &gt; Date &amp; Time and set the date ahead a day or more. 4. Turn the device off completely again and turn it back on. </code></pre> </blockquote> <p><a href="https://developer.apple.com/library/ios/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG42">Source</a></p>
924,946
Use of Iframe or Object tag to embed web pages in another
<p>In a web-based system I maintain at work that recently went live, it makes an Object element to embed a second web page within the main web page. (Effectively the main web page contains the menu and header, and the main application pages are in the object)</p> <p>For example</p> <pre><code>&lt;object id="contentarea" standby="loading data, please wait..." title="loading data, please wait..." width="100%" height="53%" type="text/html" data="MainPage.aspx"&gt;&lt;/object&gt; </code></pre> <p>Older versions of this application use an IFRAME to do this though. I have found that by using the object tag the embedded web page behaves differently to when it was previously hosted in an IFRAME. In IE, for example, the tool tips don't seen to work (I will post a separate question about this!), and it looks like the embedded page cannot access the parent page in script, although it can if it was an IFRAME.</p> <p>I am told the reason for favouring the object tag over the IFRAME is that the IFRAME is being deprecated and so cannot be relied on for future versions of browsers. Is this true though? Is it preferable to use the Object tag over the Iframe to embed web pages? Or is it likely that the IFRAME will be well-supported into the future (long after I am old and grey, and past the useful life of the application I maintain)?</p>
925,041
4
0
null
2009-05-29 08:20:50.293 UTC
7
2015-09-29 21:54:12.72 UTC
null
null
null
null
7,585
null
1
36
html|iframe|object
54,365
<p>The <a href="http://www.whatwg.org/specs/web-apps/current-work/#the-iframe-element" rel="noreferrer">IFRAME element</a> is part of the <a href="http://www.whatwg.org/specs/web-apps/current-work/" rel="noreferrer">upcoming HTML5 standard</a>. Also, HTML5 is developed by the major browser vendors out there (Mozilla, Opera, Safari, IE), that basically makes a guarantee that we will have an IFRAME element in the foreseeable future. Some of them have support for some HTML5 elements already, like AUDIO and VIDEO and some new JavaScript APIs.</p> <p>It's also true that <a href="http://www.whatwg.org/specs/web-apps/current-work/#the-object-element" rel="noreferrer">the OBJECT element is in the draft</a>, but that's because IFRAME and OBJECT will have different purposes. IFRAMES are mainly designed for sandboxing web applications.</p> <p>So, my advise is to use IFRAME instead of OBJECT.</p>
1,123,650
How to find the return value of last executed command in UNIX?
<p>How to find the return value of last executed command in UNIX?</p>
1,123,663
1
3
null
2009-07-14 05:50:51.07 UTC
6
2018-02-17 21:48:37.43 UTC
null
null
null
Pradeep
null
null
1
30
unix
32,696
<p>You can use the shell variable <code>$?</code></p> <p>Such as:</p> <pre><code>$ true ; echo $? 0 $ false ; echo $? 1 </code></pre>
41,117,918
How to format pasted JSON in IntelliJ / Android Studio
<p>I often need to use a text editor while writing code to paste random notes but especially JSON responses, where I format them using a plugin (for Sublime). </p> <p>I recently heard about the 'scratch file' feature in IntelliJ / Android Studio which does exactly what I need it to - except I can't make it format JSON I paste in nicely.</p> <p>How can I make Android Studio format JSON in a scratch buffer file?</p>
41,148,344
5
0
null
2016-12-13 09:46:32.797 UTC
10
2021-07-11 01:32:55.48 UTC
null
null
null
null
1,866,373
null
1
75
json|android-studio|intellij-idea|code-formatting
104,715
<p>You are asking about two seperate things: scratch files and scratch buffers.</p> <p>When you create a scratch file in IntelliJ you can choose the type of the file (e.g. JSON) that you want to create. Based on file's type, IntelliJ provides code formatting (use Code->Reformat code).</p> <p>However, scratch buffers are just simple .txt files and the only formatting that can be used is the one associated to .txt format. So, if you put JSON into scratch buffer it won't get formatted with JSON type formatter.</p> <p>I would encourage you to use scratch files instead of scratch buffers if you want JSON formatting.</p> <p>More information can be found at IntelliJ's official page <a href="https://www.jetbrains.com/help/idea/2016.2/scratches.html" rel="noreferrer">https://www.jetbrains.com/help/idea/2016.2/scratches.html</a>.</p>
23,100,836
Android listing BLE devices after device scan
<p>Can u provide me the simple code for scanning the nearby BLE devices and list it by device name and MAC ID. I tried this using sample code provided in <a href="http://developer.android.com/guide/topics/connectivity/bluetooth-le.html" rel="noreferrer">http://developer.android.com/guide/topics/connectivity/bluetooth-le.html</a>. But didn't work, any reference link or ideas since i am new to BLE app.</p>
23,102,124
2
0
null
2014-04-16 05:35:47.053 UTC
6
2020-06-23 13:45:24.533 UTC
2015-02-06 09:24:29.263 UTC
null
927,408
null
676,603
null
1
9
android|bluetooth-lowenergy|device|network-scan
39,502
<p>This example is based on the developers web you posted and works great for me. This is the code:</p> <p><strong>DeviceScanActivity.class</strong></p> <pre><code>package com.example.android.bluetoothlegatt; import android.app.Activity; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class DeviceScanActivity extends ListActivity { private LeDeviceListAdapter mLeDeviceListAdapter; private BluetoothAdapter mBluetoothAdapter; private boolean mScanning; private Handler mHandler; private static final int REQUEST_ENABLE_BT = 1; // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setTitle(R.string.title_devices); mHandler = new Handler(); // Use this check to determine whether BLE is supported on the device. Then you can // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); finish(); return; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if (!mScanning) { menu.findItem(R.id.menu_stop).setVisible(false); menu.findItem(R.id.menu_scan).setVisible(true); menu.findItem(R.id.menu_refresh).setActionView(null); } else { menu.findItem(R.id.menu_stop).setVisible(true); menu.findItem(R.id.menu_scan).setVisible(false); menu.findItem(R.id.menu_refresh).setActionView( R.layout.actionbar_indeterminate_progress); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_scan: mLeDeviceListAdapter.clear(); scanLeDevice(true); break; case R.id.menu_stop: scanLeDevice(false); break; } return true; } @Override protected void onResume() { super.onResume(); // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, // fire an intent to display a dialog asking the user to grant permission to enable it. if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } // Initializes list view adapter. mLeDeviceListAdapter = new LeDeviceListAdapter(); setListAdapter(mLeDeviceListAdapter); scanLeDevice(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // User chose not to enable Bluetooth. if (requestCode == REQUEST_ENABLE_BT &amp;&amp; resultCode == Activity.RESULT_CANCELED) { finish(); return; } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onPause() { super.onPause(); scanLeDevice(false); mLeDeviceListAdapter.clear(); } private void scanLeDevice(final boolean enable) { if (enable) { // Stops scanning after a pre-defined scan period. mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); invalidateOptionsMenu(); } }, SCAN_PERIOD); mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } else { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } invalidateOptionsMenu(); } // Adapter for holding devices found through scanning. private class LeDeviceListAdapter extends BaseAdapter { private ArrayList&lt;BluetoothDevice&gt; mLeDevices; private LayoutInflater mInflator; public LeDeviceListAdapter() { super(); mLeDevices = new ArrayList&lt;BluetoothDevice&gt;(); mInflator = DeviceScanActivity.this.getLayoutInflater(); } public void addDevice(BluetoothDevice device) { if(!mLeDevices.contains(device)) { mLeDevices.add(device); } } public BluetoothDevice getDevice(int position) { return mLeDevices.get(position); } public void clear() { mLeDevices.clear(); } @Override public int getCount() { return mLeDevices.size(); } @Override public Object getItem(int i) { return mLeDevices.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; // General ListView optimization code. if (view == null) { view = mInflator.inflate(R.layout.listitem_device, null); viewHolder = new ViewHolder(); viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address); viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } BluetoothDevice device = mLeDevices.get(i); final String deviceName = device.getName(); if (deviceName != null &amp;&amp; deviceName.length() &gt; 0) viewHolder.deviceName.setText(deviceName); else viewHolder.deviceName.setText(R.string.unknown_device); viewHolder.deviceAddress.setText(device.getAddress()); return view; } } // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { mLeDeviceListAdapter.addDevice(device); mLeDeviceListAdapter.notifyDataSetChanged(); } }); } }; static class ViewHolder { TextView deviceName; TextView deviceAddress; } </code></pre> <p>}</p> <p>The custom layout for the Listview <strong><code>listitem_device.xml</code></strong> :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot;&gt; &lt;TextView android:id=&quot;@+id/device_name&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24dp&quot;/&gt; &lt;TextView android:id=&quot;@+id/device_address&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;12dp&quot;/&gt; &lt;/LinearLayout&gt; </code></pre> <p>The progress bar on scanning <strong><code>actionbar_indeterminate_progress.xml</code></strong> :</p> <pre><code>&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;56dp&quot; android:minWidth=&quot;56dp&quot;&gt; &lt;ProgressBar android:layout_width=&quot;32dp&quot; android:layout_height=&quot;32dp&quot; android:layout_gravity=&quot;center&quot;/&gt; &lt;/FrameLayout&gt; </code></pre> <p>The menu layout <strong><code>main.xml</code></strong> :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;item android:id=&quot;@+id/menu_refresh&quot; android:checkable=&quot;false&quot; android:orderInCategory=&quot;1&quot; android:showAsAction=&quot;ifRoom&quot;/&gt; &lt;item android:id=&quot;@+id/menu_scan&quot; android:title=&quot;@string/menu_scan&quot; android:orderInCategory=&quot;100&quot; android:showAsAction=&quot;ifRoom|withText&quot;/&gt; &lt;item android:id=&quot;@+id/menu_stop&quot; android:title=&quot;@string/menu_stop&quot; android:orderInCategory=&quot;101&quot; android:showAsAction=&quot;ifRoom|withText&quot;/&gt; &lt;/menu&gt; </code></pre> <p>The strings layout <strong><code>strings.xml</code></strong> :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;resources&gt; &lt;string name=&quot;ble_not_supported&quot;&gt;BLE is not supported&lt;/string&gt; &lt;string name=&quot;error_bluetooth_not_supported&quot;&gt;Bluetooth not supported.&lt;/string&gt; &lt;string name=&quot;unknown_device&quot;&gt;Unknown device&lt;/string&gt; &lt;!-- Menu items --&gt; &lt;string name=&quot;menu_connect&quot;&gt;Connect&lt;/string&gt; &lt;string name=&quot;menu_disconnect&quot;&gt;Disconnect&lt;/string&gt; &lt;string name=&quot;menu_scan&quot;&gt;Scan&lt;/string&gt; &lt;string name=&quot;menu_stop&quot;&gt;Stop&lt;/string&gt; &lt;/resources&gt; </code></pre> <p>And the manifest <strong><code>AndroidManifest.xml</code></strong> :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.example.android.bluetoothlegatt&quot; android:versionCode=&quot;1&quot; android:versionName=&quot;1.0&quot;&gt; &lt;uses-sdk android:minSdkVersion=&quot;18&quot; android:targetSdkVersion=&quot;19&quot;/&gt; &lt;uses-feature android:name=&quot;android.hardware.bluetooth_le&quot; android:required=&quot;true&quot;/&gt; &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt; &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_ADMIN&quot;/&gt; &lt;application android:label=&quot;@string/app_name&quot; android:icon=&quot;@drawable/ic_launcher&quot; android:theme=&quot;@android:style/Theme.Holo.Light&quot;&gt; &lt;activity android:name=&quot;.DeviceScanActivity&quot; android:label=&quot;@string/app_name&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>I think this is all. If I missed anything let me now and I fix it. Hope it helps!!</p> <p><em>(Bluetooth LE quite sucks in Android yet :D... needs and update fast!)</em></p> <p><strong>UPDATE:</strong></p> <p>Check the full example of BLE scan and connection in GitHub: <a href="https://github.com/kodartcha/BLEDeviceScanSample" rel="noreferrer">https://github.com/kodartcha/BLEDeviceScanSample</a></p>
44,549,733
How to use Visual Studio Code as the default editor for Git MergeTool including for 3-way merge
<p>Today I was trying to use the <code>git mergetool</code> on the Windows command prompt and realized that it was defaulting to use <em>Vim</em>, which is cool, but I'd prefer <em>VS Code</em>.</p> <p>How can I have <em>Visual Studio Code</em> function as my GUI for handling merge conflicts (or even as a diffing tool) for Git?</p> <p>Is it possible to setup <em>VS Code</em> to get visuals for a <a href="https://en.wikipedia.org/wiki/Merge_(version_control)#Three-way_merge" rel="nofollow noreferrer">three-way merge</a>?</p>
44,549,734
5
0
null
2017-06-14 16:07:39.897 UTC
104
2022-08-19 16:46:43.133 UTC
2022-08-04 20:37:13.29 UTC
null
3,018,212
null
3,018,212
null
1
174
git|visual-studio|visual-studio-code|git-merge|mergetool
88,729
<p><strong>Update:</strong> As of <a href="https://code.visualstudio.com/updates/v1_70#_3way-merge-editor-improvements" rel="noreferrer">Visual Studio Code 1.70</a> <em>Three-way merge</em> with improvements were added. <a href="https://code.visualstudio.com/updates/v1_69#_3-way-merge-editor" rel="noreferrer">Visuals and further explanations</a> are available if that's of interest to you .</p> <p>As of <a href="https://code.visualstudio.com/updates/v1_13#_merge-conflict-coloring-and-actions" rel="noreferrer">Visual Studio Code 1.13</a> <em>Better Merge</em> was integrated into the core of Visual Studio Code.</p> <p>The way to wire them together is to modify your <code>.gitconfig</code> and you have <strong>two options</strong>.</p> <ol> <li><p>To do this with command line entries, enter each of these: <em>(Note: if on Windows Command Prompt replace <code>'</code> with <code>&quot;</code>. Thanks to Iztok Delfin and e4rache for helping clarify this.)</em></p> <ol> <li><code>git config --global merge.tool vscode</code></li> <li><code>git config --global mergetool.vscode.cmd 'code --wait --merge $REMOTE $LOCAL $BASE $MERGED'</code></li> <li><code>git config --global diff.tool vscode</code></li> <li><code>git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'</code></li> </ol> </li> <li><p>To do this by pasting some line in the <code>.gitconfig</code> <a href="https://code.visualstudio.com/Docs/editor/versioncontrol#_git-patchdiff-mode" rel="noreferrer">with Visual Studio Code</a>.</p> <ul> <li><p>Run <code>git config --global core.editor 'code --wait'</code> from the command line.</p> </li> <li><p>From here you can enter the command <code>git config --global -e</code>. You will want to paste in the code in the &quot;Extra Block&quot; below.</p> <pre><code> [user] name = EricDJohnson email = [email protected] [gui] recentrepo = E:/src/gitlab/App-Custom/Some-App # Comment: You just added this via 'git config --global core.editor &quot;code --wait&quot;' [core] editor = code --wait # Comment: Start of &quot;Extra Block&quot; # Comment: This is to unlock Visual Studio Code as your Git diff and Git merge tool [merge] tool = vscode [mergetool &quot;vscode&quot;] # Comment: Original way before three-way merge shown commented out # cmd = code --wait $MERGED # Comment: For &quot;Three-way merge&quot; cmd = code --wait --merge $REMOTE $LOCAL $BASE $MERGED [diff] tool = vscode [difftool &quot;vscode&quot;] cmd = code --wait --diff $LOCAL $REMOTE # Comment: End of &quot;Extra Block&quot; </code></pre> </li> </ul> </li> </ol> <p>Now from within your Git directory with a conflict run <code>git mergetool</code> and, tada, you have Visual Studio Code helping you handle the merge conflict! (Just make sure to <em>save your file</em> before closing Visual Studio Code.)</p> <p><a href="https://i.stack.imgur.com/SjhvD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SjhvD.png" alt="Accept Incoming Change anyone?" /></a></p> <p>For further reading on launching <code>code</code> from the command line, look in <a href="https://code.visualstudio.com/docs/editor/command-line" rel="noreferrer">this documentation</a>.</p> <p>For more information in <code>git mergetool</code> check out <a href="https://git-scm.com/docs/git-mergetool" rel="noreferrer">this documentation</a>.</p>
44,434,199
Access vba Check if file exists
<p>I have a database split in FrontEnd and BackEnd.</p> <p>I have it running: i) in my office ii) updating/testing in my personal computer.</p> <p>My BackEnd file is running in different Folder location according to computer running.</p> <p>I want to place a code and check if file exist.</p> <p>Code:</p> <pre><code>Sub FileExists() Dim strPath As String '&lt;== Office. Dim strApplicationFolder As String Dim strPathAdmin As String '&lt;== Admin. strPath = "\\iMac\Temp\" strApplicationFolder = Application.CurrentProject.Path strPathAdmin = strApplicationFolder &amp; "\Temp\" If Dir(strApplicationFolder &amp; "SerialKey.txt") = "" Then '===&gt; Admin User. If Dir(strPathAdmin &amp; "*.*") = "" Then '===&gt; Empty Folder. Else '===&gt; Files on folder. End If Else '===&gt; Office User. If Dir(strPath &amp; "*.*") = "" Then '===&gt; Empty Folder. Else '===&gt; Files on folder. End If End If End Sub() </code></pre> <p>I have this until now.</p> <p>Any help.</p> <p>Thank you...</p>
44,435,026
1
0
null
2017-06-08 11:16:02.243 UTC
2
2017-06-08 16:25:31.657 UTC
2017-06-08 16:25:31.657 UTC
null
6,535,336
null
7,885,853
null
1
5
vba|file|ms-access|exists
39,844
<p>Create a small function to check if a file exists and call it when needed.</p> <pre><code>Public Function FileExists(ByVal path_ As String) As Boolean FileExists = (Len(Dir(path_)) &gt; 0) End Function </code></pre> <p>Since the backend database paths dont change, why dont you declare two constants and simply check their value?</p> <pre><code>Sub Exist() Const workFolder As String = "C:\Work Folder\backend.accdb" Const personalFolder As String = "D:\Personal Folder\backend.accdb" If FileExists(workFolder) Then 'Work folder exists End If '.... If FileExists(personalFolder) Then 'Personal folder exists End If End Sub </code></pre>
56,419,456
can't find compiler ngcc module after upgrading Angular and project
<p>I've just upgraded Angular cli and one of my project from 7.0.7 to 7.1.0.</p> <p>I've followed <a href="https://stackoverflow.com/questions/43931986/how-to-upgrade-angular-cli-to-the-latest-version">this post</a> and <a href="https://stackoverflow.com/users/3497671/francesco-borzi">@Francesco Borzi's</a> answer.</p> <p>now I've tried running my project using:</p> <pre><code>ng serve --proxy-config proxy.conf.json </code></pre> <p>and got this message</p> <blockquote> <p>Cannot find module '@angular/compiler-cli/ngcc' Error: Cannot find</p> <p>module '@angular/compiler-cli/ngcc'</p> <pre><code>at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15) at Function.Module._load (internal/modules/cjs/loader.js:575:25) at Module.require (internal/modules/cjs/loader.js:705:19) at require (internal/modules/cjs/helpers.js:14:16) at Object.&lt;anonymous&gt; (/Users/path/myproject/node_modules/@ngtools/webpack/src/ngcc_processor.js:10:16) at Module._compile (internal/modules/cjs/loader.js:799:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10) at Module.load (internal/modules/cjs/loader.js:666:32) at tryModuleLoad (internal/modules/cjs/loader.js:606:12) at Function.Module._load (internal/modules/cjs/loader.js:598:3) at Module.require (internal/modules/cjs/loader.js:705:19) at require (internal/modules/cjs/helpers.js:14:16) at Object.&lt;anonymous&gt; (/Users/path/myproject/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:23:26) at Module._compile (internal/modules/cjs/loader.js:799:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10) at Module.load (internal/modules/cjs/loader.js:666:32) </code></pre> </blockquote> <p>here is my <code>package.json</code></p> <pre><code>{ &quot;name&quot;: &quot;myproject&quot;, &quot;version&quot;: &quot;0.0.0&quot;, &quot;scripts&quot;: { &quot;ng&quot;: &quot;ng&quot;, &quot;start&quot;: &quot;ng serve&quot;, &quot;build&quot;: &quot;ng build&quot;, &quot;test&quot;: &quot;ng test&quot;, &quot;lint&quot;: &quot;ng lint&quot;, &quot;e2e&quot;: &quot;ng e2e&quot; }, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@angular/animations&quot;: &quot;~7.0.0&quot;, &quot;@angular/cdk&quot;: &quot;7.3.7&quot;, &quot;@angular/common&quot;: &quot;~7.0.0&quot;, &quot;@angular/compiler&quot;: &quot;~7.0.0&quot;, &quot;@angular/core&quot;: &quot;~7.0.0&quot;, &quot;@angular/forms&quot;: &quot;~7.0.0&quot;, &quot;@angular/http&quot;: &quot;~7.0.0&quot;, &quot;@angular/material&quot;: &quot;^7.3.7&quot;, &quot;@angular/platform-browser&quot;: &quot;~7.0.0&quot;, &quot;@angular/platform-browser-dynamic&quot;: &quot;~7.0.0&quot;, &quot;@angular/router&quot;: &quot;~7.0.0&quot;, &quot;angular&quot;: &quot;^1.7.8&quot;, &quot;bootstrap&quot;: &quot;^4.3.1&quot;, &quot;core-js&quot;: &quot;^2.5.4&quot;, &quot;font-awesome&quot;: &quot;^4.7.0&quot;, &quot;hammerjs&quot;: &quot;^2.0.8&quot;, &quot;jquery&quot;: &quot;1.9.1&quot;, &quot;ngx-gallery&quot;: &quot;^5.9.1&quot;, &quot;popper.js&quot;: &quot;^2.0.0-next.4&quot;, &quot;rxjs&quot;: &quot;~6.3.3&quot;, &quot;zone.js&quot;: &quot;~0.8.26&quot; }, &quot;devDependencies&quot;: { &quot;@angular-devkit/build-angular&quot;: &quot;^0.800.1&quot;, &quot;@angular/cli&quot;: &quot;^8.0.1&quot;, &quot;@angular/compiler-cli&quot;: &quot;~7.0.0&quot;, &quot;@angular/language-service&quot;: &quot;~7.0.0&quot;, &quot;@types/jasmine&quot;: &quot;~2.8.8&quot;, &quot;@types/jasminewd2&quot;: &quot;~2.0.3&quot;, &quot;@types/node&quot;: &quot;~8.9.4&quot;, &quot;codelyzer&quot;: &quot;~4.5.0&quot;, &quot;jasmine-core&quot;: &quot;~2.99.1&quot;, &quot;jasmine-spec-reporter&quot;: &quot;~4.2.1&quot;, &quot;karma&quot;: &quot;~3.0.0&quot;, &quot;karma-chrome-launcher&quot;: &quot;~2.2.0&quot;, &quot;karma-coverage-istanbul-reporter&quot;: &quot;~2.0.1&quot;, &quot;karma-jasmine&quot;: &quot;~1.1.2&quot;, &quot;karma-jasmine-html-reporter&quot;: &quot;^0.2.2&quot;, &quot;protractor&quot;: &quot;~5.4.0&quot;, &quot;ts-node&quot;: &quot;~7.0.0&quot;, &quot;tslint&quot;: &quot;~5.11.0&quot;, &quot;typescript&quot;: &quot;~3.1.1&quot; } } </code></pre>
56,645,853
6
0
null
2019-06-02 22:38:09.643 UTC
7
2021-08-31 00:12:47.63 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,713,208
null
1
34
angular|npm|angular-cli
88,961
<p>In your package.json file, change the @angular/cli version in devDependencies to: </p> <pre><code>"@angular/cli": "7.1.0" </code></pre> <p>There is a version mismatch between your project and the devDependency. You might have probably used <code>npm audit fix --force</code> or a similar auto update command, which might have updated the devDependencies in "package.json" file.</p> <p>You can also use angular cli version 7.3.5 in devDependencies here. Just make sure that the development version and the version mentioned in devDependencies are compatible. Be aware that local anglular/cli version doesn't really matter here.</p> <p>Update: After making the change, delete "package-lock.json" and delete the "node modules" folder. Run <code>npm install</code> to install the modules again.</p>
22,362,634
Correct way to unit test the type of an object
<p>Using the Visual Studio Unit Testing Framework, I'm looking at two options:</p> <pre><code>Assert.AreEqual(myObject.GetType(), typeof(MyObject)); </code></pre> <p>and</p> <pre><code>Assert.IsInstanceOfType(myObject, typeof(MyObject)); </code></pre> <p>Is there a difference between these two options? Is one more "correct" than the other? </p> <p>What is the standard way of doing this?</p>
22,362,708
5
0
null
2014-03-12 20:06:09.167 UTC
1
2020-06-08 12:27:24.41 UTC
2014-03-12 22:33:05.167 UTC
null
889,337
null
889,337
null
1
30
c#|.net|vs-unit-testing-framework
40,431
<p>The first example will fail if the types are not exactly the same while the second will only fail if <code>myObject</code> is not assignable to the given type e.g.</p> <pre><code>public class MySubObject : MyObject { ... } var obj = new MySubObject(); Assert.AreEqual(obj.GetType(), typeof(MyObject)); //fails Assert.IsInstanceOfType(obj, typeof(MyObject)); //passes </code></pre>
43,027,771
Unsupported media type ASP.NET Core Web API
<p>On the front-end i use Angular to collect som data from the form and send it to my server-side controllers. As the image shows below, i get the data ($scope.newData) on my controller and service, but when it reaches the server, i get the following error: "Unsupported media type" and my newData is empty.</p> <p><a href="https://i.stack.imgur.com/1g4nn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1g4nn.png" alt="Website console"></a></p> <p>My controller:</p> <pre><code>// Create new salesman $scope.addSalesman = function (newData) { console.log("Controller"); console.log($scope.newData); myService.addNewSalesman($scope.newData).then(function (data) { console.log(data); }, function (err) { console.log(err); }); }; </code></pre> <p>My service:</p> <pre><code>addNewSalesman: function (newData) { console.log("service"); console.log(newData) var deferred = $q.defer(); $http({ method: 'POST', url: '/api/Salesman', headers: { 'Content-type': 'application/json' } }, newData).then(function (res) { deferred.resolve(res.data); }, function (res) { deferred.reject(res); }); return deferred.promise; } </code></pre> <p>My Salesman model:</p> <pre><code>public class Salesman { public int SalesmanID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string BirthDate { get; set; } public int Phone { get; set; } public string Adress { get; set; } public string City { get; set; } public int Postal { get; set; } public string Role { get; set; } } </code></pre> <p>My server-side controller:</p> <pre><code>[Route("api/[controller]")] public class SalesmanController : Controller { private readonly DataAccess _DataAccess; public SalesmanController() { _DataAccess = new DataAccess(); } [HttpPost] public IActionResult PostSalesman([FromBody] Salesman newData) { return Ok(newData); } </code></pre>
43,028,043
4
4
null
2017-03-26 10:48:40.203 UTC
1
2021-04-30 14:30:45.513 UTC
null
null
null
null
7,714,075
null
1
15
c#|angularjs|json|asp.net-web-api|asp.net-core
42,103
<p>The header you are sending is wrong. You are sending <code>Content-Type: application/json</code>, but you have to send <code>Accept: application/json</code>. </p> <p><code>Content-Type: application/json</code> is what the server must send to the client and the client must send <code>Accept</code> to tell the server which type of response it accepts. </p> <pre><code>addNewSalesman: function (newData) { console.log("service"); console.log(newData) var deferred = $q.defer(); $http({ method: 'POST', url: '/api/Salesman', headers: { 'Accept': 'application/json' } }, newData).then(function (res) { deferred.resolve(res.data); }, function (res) { deferred.reject(res); }); return deferred.promise; } </code></pre> <p>Should do it. Also see "<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation" rel="noreferrer">Content negotiation</a>" on MDN.</p>
25,558,449
DomPDF: Image not readable or empty
<p>For some reason, DomPDF won't render an image included in the html that is being parsed:</p> <p><img src="https://i.stack.imgur.com/fNC36.png" alt="PDF Image missing"></p> <p>However, the image is rendered on the page when it is returned as html:</p> <p><img src="https://i.stack.imgur.com/xvL45.png" alt="HTML Image exists"></p> <p>I've looked at these issues and have make sure that DOMPDF_ENABLE_REMOTE is set to true and verified file permissions:<br/> <a href="https://stackoverflow.com/questions/12543796/dompdf-image-not-real-image-not-readable-or-empty">dompdf image not real image not readable or empty</a><br/> <a href="https://stackoverflow.com/questions/23724442/image-error-in-dompdf-for-zf2/23745381#23745381">Image error in DOMPDF for ZF2</a></p> <p>Are there any other things that I should be checking for?</p>
27,432,489
11
1
null
2014-08-28 21:37:52.577 UTC
6
2022-09-23 07:11:15.367 UTC
2017-05-23 12:34:44.877 UTC
null
-1
user3562712
null
null
1
32
php|html|pdf|laravel|dompdf
99,874
<p>Following helped me like charm, at least localy, and even with</p> <pre><code>define(&quot;DOMPDF_ENABLE_REMOTE&quot;, false); </code></pre> <p>The solution is to change the image SRC to the absolute path on the server, like this:</p> <pre><code>&lt;img src=&quot;/var/www/domain/images/myimage.jpg&quot; /&gt; </code></pre> <p>All of the following worked for me:</p> <pre><code>&lt;img src=&quot;&lt;?php echo $_SERVER[&quot;DOCUMENT_ROOT&quot;].'/placeholder.jpg';?&gt;&quot;/&gt; &lt;img src=&quot;&lt;?php echo $_SERVER[&quot;DOCUMENT_ROOT&quot;].'\placeholder.jpg';?&gt;&quot;/&gt; &lt;img src=&quot;&lt;?php echo $_SERVER[&quot;DOCUMENT_ROOT&quot;].'./placeholder.jpg';?&gt;&quot;/&gt; </code></pre> <p>$_SERVER[&quot;DOCUMENT_ROOT&quot;] is C:/wamp/www/ZendSkeletonApplication/public</p> <p><a href="http://www.lost-in-code.com/programming/php-code/dompdf-images-not-working/" rel="nofollow noreferrer">Thanks to this: lost in code</a></p>
25,597,092
How to load URL in UIWebView in Swift?
<p>I have the following code:</p> <pre><code>UIWebView.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca"))) </code></pre> <p>I am getting the following error:</p> <blockquote> <p>'NSURLRequest' is not convertible to UIWebView.</p> </blockquote> <p>Any idea what the problem is? </p>
25,597,358
19
1
null
2014-08-31 23:11:27.487 UTC
18
2022-07-12 09:40:06.34 UTC
2016-08-11 17:50:54.863 UTC
null
2,291,915
null
2,199,852
null
1
75
swift|ios8
157,550
<p><a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIWebView_Class/#//apple_ref/occ/instm/UIWebView/loadRequest:" rel="noreferrer">loadRequest:</a> is an instance method, not a class method. You should be attempting to call this method with an instance of UIWebview as the receiver, not the class itself.</p> <pre><code>webviewInstance.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")!)) </code></pre> <p>However, as @radex correctly points out below, you can also take advantage of currying to call the function like this: </p> <pre><code>UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.ca")!)) </code></pre> <p>Swift 5</p> <pre><code>webviewInstance.load(NSURLRequest(url: NSURL(string: "google.ca")! as URL) as URLRequest) </code></pre>
51,990,143
400 vs 422 for Client Error Request
<p>I've read a lot of posts and articles regarding proper http status code to return for client request error. Others suggest to use 400 as it has been redefined in <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1" rel="noreferrer">RFC 7231</a> though I'm not sure if the example given covers all the client error in my mind because the examples are syntactic.</p> <blockquote> <p>The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request<br /> message framing, or deceptive request routing).</p> </blockquote> <p>I did find this statement in the Appendix B of the rfc 7231:</p> <blockquote> <p>The 400 (Bad Request) status code has been relaxed so that it isn't<br /> limited to syntax errors. (Section 6.5.1)</p> </blockquote> <p>Does this mean that I can consider any type of client error a bad request? Would it be better to use 400 for client requests and just specify a more specific error in the message?</p> <br> On the other hand, others say that it's better to use 422 (Unprocessable Entity). While this is more focused on semantics, it's only listed in [RFC 4918][2] which is a webDAV extension for http/1.1 <blockquote> <p>The 422 (Unprocessable Entity) status code means the server<br /> understands the content type of the request entity (hence a<br /> 415(Unsupported Media Type) status code is inappropriate), and the<br /> syntax of the request entity is correct (thus a 400 (Bad Request)<br /> status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML<br /> request body contains well-formed (i.e., syntactically correct), but<br /> semantically erroneous, XML instructions.</p> </blockquote> <p>Can I use this webDAV extension codes to handle my http requests? In the case of 422, can I use it even though it's not in the core http codes. <br></p> <p>Should I use 400 or 422 for my client error?</p> <p>Here are the possible client error I have in mind:</p> <pre><code>1.) Invalid parameter. The client provided parameters but are found invalid. Example: I said that the userId is 1, but when I checked there's no userId of 1. Another example of invalid parameter is wrong data type. 2.) Missing required parameters 3.) Let's say I need to hash a value based on given params and it failed 4.) Blocked content is being used. Like, i want to apply for membership and i passed the userId of 1. However, userId of one is blocked / deactivated 5.) When I try to delete an entry but the entry is still being used in another table. 6.) Let's say i require a signature in my payload and the signature does not match when recalculated in the backend 7.) Let's say I have a value that counts a specific attribute like &quot;shares&quot; and it has reached the maximum value like 10. etc... </code></pre> <br> Any informative response will be highly appreciated. Thanks a lot, guys! <p>Update: I checked google api errors and they are not using 422. On the other hand, Twitter uses 422. I'm more confused than ever &gt;.&lt; Though there's a part of me that thinks 400 is the better choice as it is included in the RFC doc and 422 is not. I could be wrong though.</p>
52,098,667
1
2
null
2018-08-23 16:14:03.097 UTC
8
2022-07-19 08:57:43.007 UTC
2021-10-07 07:59:29.08 UTC
null
-1
null
1,681,701
null
1
20
error-handling|http-status-codes|http-error|http-status-code-400|http-status-code-422
11,233
<blockquote> <p>Can I use this WebDAV extension codes to handle my HTTP requests? In the case of <code>422</code>, can I use it even though it's not in the core HTTP codes.</p> </blockquote> <p>HTTP is an extensible protocol and <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> is <a href="https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml" rel="noreferrer">registered in IANA</a>, which makes it a standard status code. So nothing stops you from using <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> in your application.</p> <p>And since June 2022, <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> is defined in the <a href="https://www.rfc-editor.org/rfc/rfc9110.html" rel="noreferrer">RFC 9110</a>, which is the document that currently defines the semantics of the HTTP protocol:</p> <blockquote> <p>Status code <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> (previously defined in Section 11.2 of <a href="https://www.rfc-editor.org/rfc/rfc4918.html" rel="noreferrer">RFC 4918</a>) has been added because of its general applicability.</p> </blockquote> <p>For reference, here's how <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> is defined:</p> <blockquote> <p><strong>15.5.21. 422 Unprocessable Content</strong></p> <p>The <code>422</code> (Unprocessable Content) status code indicates that the server understands the content type of the request content (hence a <code>415</code> (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions. For example, this status code can be sent if an XML request content contains well-formed (i.e., syntactically correct), but semantically erroneous XML instructions.</p> </blockquote> <p>While defined in the <a href="https://www.rfc-editor.org/rfc/rfc4918.html" rel="noreferrer">RFC 4918</a>, the reason phrase of <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> was <em>&quot;Unprocessable Entity&quot;</em>. Since it was added to the <a href="https://www.rfc-editor.org/rfc/rfc9110.html" rel="noreferrer">RFC 9110</a>, it's reason phrase is <em>&quot;Unprocessable Content&quot;</em>.</p> <blockquote> <p>Should I use <code>400</code> or <code>422</code> for my client error?</p> </blockquote> <p>You certainly could use both. In general, use <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.1" rel="noreferrer"><code>400</code></a> to indicate <em>syntax</em> errors in the payload or invalid parameters in the URL. And use <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21" rel="noreferrer"><code>422</code></a> to indicate <em>semantic</em> problems in the payload.</p> <p>As an example, see the <a href="https://docs.github.com/en/rest/overview/resources-in-the-rest-api#client-errors" rel="noreferrer">approach</a> used by the <a href="https://developer.github.com/v3/" rel="noreferrer">GitHub v3 API</a>:</p> <blockquote> <p><a href="https://docs.github.com/en/rest/overview/resources-in-the-rest-api#client-errors" rel="noreferrer"><strong>Client errors</strong></a></p> <p>There are three possible types of client errors on API calls that receive request bodies:</p> <ol> <li><p>Sending invalid JSON will result in a <code>400</code> Bad Request response.</p> <pre><code> HTTP/1.1 400 Bad Request Content-Length: 35 {&quot;message&quot;:&quot;Problems parsing JSON&quot;} </code></pre> </li> <li><p>Sending the wrong type of JSON values will result in a <code>400</code> Bad Request response.</p> <pre><code> HTTP/1.1 400 Bad Request Content-Length: 40 {&quot;message&quot;:&quot;Body should be a JSON object&quot;} </code></pre> </li> <li><p>Sending invalid fields will result in a <code>422</code> Unprocessable Entity response.</p> <pre><code> HTTP/1.1 422 Unprocessable Entity Content-Length: 149 { &quot;message&quot;: &quot;Validation Failed&quot;, &quot;errors&quot;: [ { &quot;resource&quot;: &quot;Issue&quot;, &quot;field&quot;: &quot;title&quot;, &quot;code&quot;: &quot;missing_field&quot; } ] } </code></pre> </li> </ol> </blockquote> <hr /> <h2>Picking the most suitable <code>4xx</code> status code</h2> <p><a href="https://stackoverflow.com/u/27581">Michael Kropat</a> put together a <a href="https://www.codetinkerer.com/2015/12/04/choosing-an-http-status-code.html" rel="noreferrer">set of decision charts</a> that helps determine the best status code for each situation. See the following for <code>4xx</code> status codes:</p> <p><a href="https://i.stack.imgur.com/GgpED.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GgpED.png" alt="HTTP 4xx status codes" /></a></p> <h2>Problem details for HTTP APIs</h2> <p>HTTP status codes are sometimes not sufficient to convey enough information about an error to be helpful. The <a href="https://www.rfc-editor.org/rfc/rfc7807" rel="noreferrer">RFC 7807</a> defines simple JSON and XML document formats to inform the client about a problem in a HTTP API. It's a great start point for reporting errors in your API.</p> <p>It also defines the <code>application/problem+json</code> and <code>application/problem+xml</code> media types.</p>
32,248,882
Complexity of len() with regard to sets and lists
<p>The complexity of <code>len()</code> with regards to sets and lists is equally O(1). How come it takes more time to process sets?</p> <pre><code>~$ python -m timeit "a=[1,2,3,4,5,6,7,8,9,10];len(a)" 10000000 loops, best of 3: 0.168 usec per loop ~$ python -m timeit "a={1,2,3,4,5,6,7,8,9,10};len(a)" 1000000 loops, best of 3: 0.375 usec per loop </code></pre> <p>Is it related to the particular benchmark, as in, it takes more time to build sets than lists and the benchmark takes that into account as well?</p> <p>If the creation of a set object takes more time compared to creating a list, what would be the underlying reason?</p>
32,249,059
7
5
null
2015-08-27 12:03:42.773 UTC
5
2015-09-17 14:37:26.653 UTC
2015-09-01 21:35:13.42 UTC
null
2,476,755
null
2,118,055
null
1
55
python|python-3.x|time-complexity|python-internals
6,962
<p><strong>Firstly,</strong> you have not measured the speed of <code>len()</code>, you have measured the speed of creating a list/set <em>together with</em> the speed of <code>len()</code>.</p> <p>Use the <code>--setup</code> argument of <code>timeit</code>:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)" 10000000 loops, best of 3: 0.0372 usec per loop </code></pre> <p>The statements you pass to <code>--setup</code> are run before measuring the speed of <code>len()</code>.</p> <p><strong>Secondly,</strong> you should note that <code>len(a)</code> is a pretty quick statement. The process of measuring its speed may be subject to "noise". Consider that <a href="https://hg.python.org/cpython/file/3.5/Lib/timeit.py#l70" rel="noreferrer">the code executed (and measured) by timeit</a> is equivalent to the following:</p> <pre><code>for i in itertools.repeat(None, number): len(a) </code></pre> <p>Because both <code>len(a)</code> and <code>itertools.repeat(...).__next__()</code> are fast operations and their speeds may be similar, the speed of <code>itertools.repeat(...).__next__()</code> may influence the timings.</p> <p>For this reason, you'd better measure <code>len(a); len(a); ...; len(a)</code> (repeated 100 times or so) so that the body of the for loop takes a considerably higher amount of time than the iterator:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.2 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.3 usec per loop </code></pre> <p>(The results still says that <code>len()</code> has the same performances on lists and sets, but now you are sure that the result is correct.)</p> <p><strong>Thirdly,</strong> it's true that "complexity" and "speed" are related, but I believe you are making some confusion. The fact that <code>len()</code> has <em>O(1)</em> complexity for lists and sets does not imply that it must run with the same speed on lists and sets.</p> <p>It means that, on average, no matter how long the list <code>a</code> is, <code>len(a)</code> performs the same asymptotic number of steps. And no matter how long the set <code>b</code> is, <code>len(b)</code> performs the same asymptotic number of steps. But the algorithm for computing the size of lists and sets may be different, resulting in different performances (timeit shows that this is not the case, however this may be a possibility).</p> <p><strong>Lastly,</strong></p> <blockquote> <p>If the creation of a set object takes more time compared to creating a list, what would be the underlying reason?</p> </blockquote> <p>A set, as you know, does not allow repeated elements. Sets in CPython are implemented as hash tables (to ensure average <em>O(1)</em> insertion and lookup): constructing and maintaining a hash table is much more complex than adding elements to a list.</p> <p>Specifically, when constructing a set, you have to compute hashes, build the hash table, look it up to avoid inserting duplicated events and so on. By contrast, lists in CPython are implemented as a simple array of pointers that is <code>malloc()</code>ed and <code>realloc()</code>ed as required.</p>
36,433,964
Showing Error :Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
<p>I'm creating an app that display contact list in a listview.The problem is I'm getting the following error when I run my app and I'm struggling to fix it:</p> <pre><code>04-05 13:41:48.868 2488-2488/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.kksworld.jsonparsing, PID: 2488 java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337) at android.widget.ListView.setAdapter(ListView.java:491) at com.kksworld.jsonparsing.MainActivity$JSONTask.onPostExecute(MainActivity.java:120) at com.kksworld.jsonparsing.MainActivity$JSONTask.onPostExecute(MainActivity.java:48) at android.os.AsyncTask.finish(AsyncTask.java:651) at android.os.AsyncTask.-wrap1(AsyncTask.java) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) </code></pre> <p>Here is my code :</p> <p><strong>MainActivity.java</strong></p> <pre><code>package com.kksworld.jsonparsing; import android.content.Context; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.kksworld.jsonparsing.models.ContactModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.lvContacts) } public class JSONTask extends AsyncTask&lt;String,String,List&lt;ContactModel&gt;&gt;{ @Override protected List&lt;ContactModel&gt; doInBackground(String... params) { HttpURLConnection httpURLConnection = null; BufferedReader bufferedReader = null; try { URL url = new URL(params[0]); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.connect(); InputStream inputStream = httpURLConnection.getInputStream(); // Through this we can read the data line by line bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String line = ""; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } String finalJSON = stringBuffer.toString(); JSONArray mainArray = new JSONArray(finalJSON); JSONObject parentObject = mainArray.getJSONObject(0); JSONArray parentArray = parentObject.getJSONArray("contacts"); List&lt;ContactModel&gt; contactModelList = new ArrayList&lt;&gt;(); // For parsing a list of items you have to use for loop for(int i=0;i&lt;11;i++) { JSONObject finalObject = parentArray.getJSONObject(i); ContactModel contactModel = new ContactModel(); contactModel.setName(finalObject.getString("name")); contactModel.setPhone(finalObject.getString("phone")); contactModel.setEmail(finalObject.getString(("email"))); contactModel.setOfficePhone(finalObject.getString(("officePhone"))); contactModel.setLatitude((float) finalObject.getDouble("latitude")); contactModel.setLongitude((float) finalObject.getDouble("longitude")); // Adding the finalObject in the List contactModelList.add(contactModel); } return contactModelList; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); try { if (bufferedReader != null) { bufferedReader.close(); } }catch(IOException e){ e.printStackTrace(); } } } return null; } // Value returned by doInBackGround will be passed here... @Override protected void onPostExecute(List&lt;ContactModel&gt; result) { super.onPostExecute(result); ContactAdapter contactAdapter = new ContactAdapter(getApplicationContext(),R.layout.row,result); listView.setAdapter(contactAdapter); } } public class ContactAdapter extends ArrayAdapter{ private List&lt;ContactModel&gt; contactModelList; private int resource; private LayoutInflater inflater; public ContactAdapter(Context context, int resource, List&lt;ContactModel&gt; objects) { super(context, resource, objects); contactModelList=objects; this.resource=resource; inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = inflater.inflate(resource,null); } TextView textViewName; TextView textViewEmail; TextView textViewPhone; TextView textViewOfficePhone; textViewName = (TextView)convertView.findViewById(R.id.textViewInsertName); textViewEmail= (TextView)convertView.findViewById(R.id.textViewInsertEmail); textViewPhone= (TextView)convertView.findViewById(R.id.textViewInsertPhone); textViewOfficePhone = (TextView)convertView.findViewById(R.id.textViewInsertOfficeNumber); textViewName.setText(contactModelList.get(position).getName()); textViewEmail.setText(contactModelList.get(position).getEmail()); textViewPhone.setText(contactModelList.get(position).getPhone()); textViewOfficePhone.setText(contactModelList.get(position).getOfficePhone()); return convertView; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { new JSONTask().execute("some_url"); return true; } return super.onOptionsItemSelected(item); } </code></pre> <p>}</p> <p>Could someone please help.</p>
36,434,213
3
3
null
2016-04-05 18:13:33.29 UTC
3
2018-11-02 19:57:08.917 UTC
null
null
null
null
5,332,308
null
1
8
android
95,867
<p>Extract this line</p> <pre><code>List&lt;ContactModel&gt; contactModelList = new ArrayList&lt;&gt;(); </code></pre> <p>before the try block and instead of <code>return null;</code> use <code>return contactModelList;</code></p> <p>Looks like your parsing fails and you pass a <code>null</code> object to <code>onPostExecute()</code>. </p>
4,063,682
jqGrid: POST data to server to fetch row data (filtering and searching)
<p>I have a form like this:</p> <pre><code>&lt;form id='myForm'&gt; &lt;input type='text' name='search' /&gt; &lt;input type='text' name='maxPrice' /&gt; &lt;/form&gt; </code></pre> <p>and table for my jqGrid:</p> <pre><code>&lt;table id='myGrid'&gt;&lt;/table&gt; </code></pre> <p>I need to POST (not GET) the data from <code>myForm</code> to my server method in order to fetch the row data and populate the grid. So far, I've not been able to get jqGrid to POST anything. I double-checked my data serialization and it is serializing my form data properly. Here is my jqGrid code:</p> <pre><code>$("#myGrid").jqGrid({ url: '/Products/Search") %&gt;', postData: $("#myForm").serialize(), datatype: "json", mtype: 'POST', colNames: ['Product Name', 'Price', 'Weight'], colModel: [ { name: 'ProductName', index: 'ProductName', width: 100, align: 'left' }, { name: 'Price', index: 'Price', width: 50, align: 'left' }, { name: 'Weight', index: 'Weight', width: 50, align: 'left' } ], rowNum: 20, rowList: [10, 20, 30], imgpath: gridimgpath, height: 'auto', width: '700', //pager: $('#pager'), sortname: 'ProductName', viewrecords: true, sortorder: "desc", caption: "Products", ajaxGridOptions: { contentType: "application/json" }, headertitles: true, sortable: true, jsonReader: { repeatitems: false, root: function(obj) { return obj.Items; }, page: function(obj) { return obj.CurrentPage; }, total: function(obj) { return obj.TotalPages; }, records: function(obj) { return obj.ItemCount; }, id: "ProductId" } }); </code></pre> <p>Can you see what I'm doing wrong or should be doing differently?</p>
4,064,352
1
0
null
2010-10-31 15:19:35.243 UTC
12
2012-01-19 22:01:06.593 UTC
2010-10-31 18:30:24.283 UTC
null
315,935
null
205,753
null
1
21
jquery|jqgrid
62,639
<p>Your main error is the usage of the <code>postData</code> parameter in the form:</p> <pre><code>postData: $("#myForm").serialize() </code></pre> <p>This usage has two problems:</p> <ol> <li>The value <code>$("#myForm").serialize()</code> overwrite all parameters of the POST requests instead of the adding additional parameters.</li> <li>The value <code>$("#myForm").serialize()</code> will be calculated <strong>only once</strong> during the grid initialization time. So you will send always <code>search=""</code> and <code>maxPrice=""</code> to the server.</li> </ol> <p>I suggest you to to replace the form with named edit fields to</p> <pre><code>&lt;fieldset&gt; &lt;input type='text' id='search' /&gt; &lt;input type='text' id='maxPrice' /&gt; &lt;button type='button' id='startSearch'&gt;Search&lt;/button&gt; &lt;/fieldset&gt; </code></pre> <p>define <code>postData</code> parameter as object with methods:</p> <pre><code>postData: { search: function() { return $("#search").val(); }, maxPrice: function() { return $("#maxPrice").val(); }, }, </code></pre> <p>and add <code>onclick</code> event handler to the "Search" button (see above HTML fragment)</p> <pre><code>$("#startSearch").click(function() { $("#myGrid").trigger("reloadGrid"); }); </code></pre> <p>Moreover you write nothing about the server technology which you use. It can be some additional modification is required to be able to read parameters on the server side (for example <code>serializeRowData: function (data) {return JSON.stringify(data);}</code> see <a href="https://stackoverflow.com/questions/3917102/jqgrid-add-row-and-send-data-to-webservice-for-insert/3918615#3918615">this</a> and <a href="https://stackoverflow.com/questions/3912008/jqgrid-does-not-populate-with-data/3914796#3914796">this</a>). I recommend you also to read another old answer: <a href="https://stackoverflow.com/questions/2928371/how-to-filter-the-jqgrid-data-not-using-the-built-in-search-filter-box/2928819#2928819">How to filter the jqGrid data NOT using the built in search/filter box</a>.</p> <p>Some other small errors like <code>'/Products/Search") %&gt;'</code> instead of '/Products/Search' or the usage of deprecated parameter <code>imgpath</code> (see <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:upgrade_from_3.4.x_to_3.5#options" rel="noreferrer">documentation</a>) are less important. The default column options like <code>align: 'left'</code> should be better removed.</p> <p>Consider also to use searching in the grid. For example <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:advanced_searching" rel="noreferrer">advance searching</a></p> <pre><code>$("#myGrid").jqGrid('navGrid','#pager', {add:false,edit:false,del:false,search:true,refresh:true}, {},{},{},{multipleSearch:true}); </code></pre> <p>and also <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching" rel="noreferrer">toolbar searching</a>:</p> <pre><code>$("#myGrid").jqGrid('filterToolbar', {stringResult:true,searchOnEnter:true,defaultSearch:"cn"}); </code></pre> <p>it can probably replace the searching form which you use.</p>
25,200,152
Prevent double clicking asp.net button
<p>I realise this question has been asked but none of the answers worked for my project.</p> <p>I have a button that when clicked calls an API, so there is a 1 second delay.</p> <p>I have tried several things nothing works.</p> <pre><code>btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";"); </code></pre> <p>Even that does nothing.</p>
25,200,336
8
4
null
2014-08-08 09:27:54.3 UTC
8
2019-10-18 20:33:24.617 UTC
2016-02-25 01:51:05.683 UTC
null
5,299,236
null
3,032,493
null
1
23
asp.net|button
53,295
<p>Prevent Double Click .Please add below code in your aspx page.</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler); function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; } &lt;/script&gt; </code></pre>
39,603,447
How can I change the font (family) for the labels in Chart.JS?
<p>I want to change the font to something snazzier in my Chart.JS horizontal bar chart. I've tried the following, but none of it works:</p> <pre><code>var optionsBar = { . . . //fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'" //bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'" //bodyFontFamily: "'Candara'" label: { font: { family: "Georgia" } } }; </code></pre> <p>I also read that this would work:</p> <pre><code>Chart.defaults.global.defaultFont = "Georgia" </code></pre> <p>...but where would this code go, and how exactly should it look? I tried this:</p> <pre><code>priceBarChart.defaults.global.defaultFont = "Georgia"; </code></pre> <p>...but also to no good effet.</p> <p>For the full picture/context, here is all the code that makes up this chart:</p> <p>HTML</p> <pre><code>&lt;div class="chart"&gt; &lt;canvas id="top10ItemsChart" class="pie"&gt;&lt;/canvas&gt; &lt;div id="pie_legend"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>JQUERY</p> <pre><code> var ctxBarChart = $("#priceComplianceBarChart").get(0).getContext("2d"); var barChartData = { labels: ["Bix Produce", "Capitol City", "Charlies Portland", "Costa Fruit and Produce", "Get Fresh Sales", "Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"], datasets: [ { label: "Price Compliant", backgroundColor: "rgba(34,139,34,0.5)", hoverBackgroundColor: "rgba(34,139,34,1)", data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027, 25553] }, { label: "Non-Compliant", backgroundColor: "rgba(255, 0, 0, 0.5)", hoverBackgroundColor: "rgba(255, 0, 0, 1)", data: [170, 10, 180, 140, 30, 10, 50, 100, 10] } ] } var optionsBar = { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] }, //fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'" //bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'" //bodyFontFamily: "'Candara'" //Chart.defaults.global.defaultFont = where does this go? label: { font: { family: "Georgia" } } }; var priceBarChart = new Chart(ctxBarChart, { type: 'horizontalBar', data: barChartData, options: optionsBar }); //priceBarChart.defaults.global.defaultFont = "Georgia"; </code></pre> <p>I even tried this:</p> <p>CSS</p> <pre><code>.candaraFont13 { font-family:"Candara, Georgia, serif"; font-size: 13px; } </code></pre> <p>HTML</p> <pre><code>&lt;div class="graph_container candaraFont13"&gt; &lt;canvas id="priceComplianceBarChart"&gt;&lt;/canvas&gt; &lt;/div&gt; </code></pre> <p>...but I reckon the canvas drawing takes care of the font appearance, as adding this made no difference.</p> <h2>UPDATE</h2> <p>I tried this and it completely broke it:</p> <pre><code>Chart.defaults.global = { defaultFontFamily: "Georgia" } </code></pre> <h2>UPDATE 2</h2> <p>As Matthew intimated, this worked (before any of the chart-specific script):</p> <pre><code>Chart.defaults.global.defaultFontFamily = "Georgia"; </code></pre>
39,603,546
4
2
null
2016-09-20 20:46:46.473 UTC
2
2021-06-22 18:38:06.577 UTC
2016-09-20 21:08:20.41 UTC
null
875,317
null
875,317
null
1
18
javascript|jquery|html|css|chart.js2
40,559
<p>This should be useful: <a href="http://www.chartjs.org/docs/" rel="noreferrer">http://www.chartjs.org/docs/</a>. It says "There are 4 special global settings that can change all of the fonts on the chart. These options are in <code>Chart.defaults.global</code>".</p> <p>You'll need to change <code>defaultFontFamily</code> for the font. And <code>defaultFontColor</code>, <code>defaultFontSize</code>, and <code>defaultFontStyle</code> for color, size, etc.</p>
6,769,654
How to get redirected to a method at login/logout before target-url called in Spring Security?
<p>I am trying to record current time of Login (in a method or object) once the login is successful and assign LastLogin time to current login time at logout. I am using spring security for login, logout. But I don't know how to take control to a method before it goes to the target-url.</p> <p>spring-security.xml </p> <pre><code>&lt;security:form-login login-page="/login" login-processing-url="/home/currentTime" authentication-failure-url="/login?error=true" default-target-url="/home"/&gt; &lt;security:logout invalidate-session="true" logout-success-url="/home/copyLastloginToCurrentLoginTime" logout-url="/logout" /&gt; </code></pre> <p>Controller </p> <pre><code>@RequestMapping(value = "/currentTime", method = RequestMethod.GET) public void recordCurrentLoginTime(Model model) { // code to record current time } @RequestMapping(value = "/copyLastloginToCurrentLoginTime", method = RequestMethod.GET) public void changeLastLoginTime(Model model) { //code to copy current to last time } </code></pre> <p><strong>Problem</strong></p> <p>I get Error 404 for - project-title/j_spring_security_check URL and when I try to debug, it doesn't come into the controller methods at all. </p> <p>Should I use some filters or something else for this purpose?</p> <p>I found <a href="https://stackoverflow.com/questions/229459/springsecurity-always-redirect-logged-in-users-to-a-page">this</a> and <a href="https://stackoverflow.com/questions/4067736/how-to-process-a-form-login-using-spring-security-spring-mvc">that</a> and but that didn't help.</p>
6,770,785
2
0
null
2011-07-20 23:17:44.91 UTC
19
2020-05-13 14:51:55.76 UTC
2020-05-13 14:51:04.153 UTC
null
1,788,806
null
820,362
null
1
18
spring-mvc|spring-security
20,366
<p>Write your own <strong><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/AuthenticationSuccessHandler.html" rel="nofollow noreferrer"><code>AuthenticationSuccessHandler</code></a></strong> and <strong><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html" rel="nofollow noreferrer"><code>LogoutSuccessHandler</code></a></strong>.</p> <p>Example:</p> <p><strong>spring-security.xml</strong> : </p> <pre><code>&lt;security:form-login login-page="/login" login-processing-url="/login_check" authentication-failure-url="/login?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler" /&gt; &lt;security:logout logout-url="/logout" success-handler-ref="myLogoutSuccessHandler" /&gt; </code></pre> <p><p></p> <p><strong>AuthenticationSuccessHandler</strong></p> <pre><code>@Component public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { @Autowired private UserService userService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // changeLastLoginTime(username) userService.changeLastLoginTime(authentication.getName()); setDefaultTargetUrl("/home"); super.onAuthenticationSuccess(request, response, authentication); } } </code></pre> <p><strong>LogoutSuccessHandler</strong></p> <pre><code>@Component public class MyLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { if (authentication != null) { // do something } setDefaultTargetUrl("/login"); super.onLogoutSuccess(request, response, authentication); } } </code></pre>
6,702,125
URL query params or media type params (in Accept header) to configure the response to an HTTP request?
<p>I'm working on designing a REST API that can respond with a variety of formats, one of which is a plain text format which can be configured to show or hide certain aspects from the response (e.g. section headings or footnotes). The traditional way that this is done is via URL query parameters, both to indicate the desired response type and the configuration options, for example:</p> <pre><code>http://api.example.com/foo-book/ch1/?format=text&amp;headings=false&amp;footnotes=true </code></pre> <p>However, a more elegant RESTful way to indicate the desired response type (instead of the <code>format=text</code> URL query param) is to use the <code>Accept</code> header, for example:</p> <pre><code>Accept: text/plain; charset=utf-8 </code></pre> <p>Now, in addition to URLs, media types can take parameters per <a href="https://www.rfc-editor.org/rfc/rfc2046" rel="nofollow noreferrer">RFC 2046</a> and as seen in the ubiquitous <code>text/html; charset=utf-8</code> and in <code>Accept</code> headers like <code>audio/*; q=0.2</code>. It's also <a href="http://www.informit.com/articles/article.aspx?p=1566460" rel="nofollow noreferrer">shown</a> that vendor-crafted MIME types can define their own parameters like:</p> <pre><code>application/vnd.example-com.foo+json; version=1.0 application/vnd.example-info.bar+xml; version=2.0 </code></pre> <p>So for previously-registered MIME types like <code>text/html</code> or <code>application/json</code>, is it acceptable to include custom parameters for an application's needs? For example:</p> <pre><code>Accept: text/plain; charset=utf-8; headings=false; footnotes=true </code></pre> <p>This seems like an elegant RESTful solution, but it also seems like it would be violating something. <a href="https://www.rfc-editor.org/rfc/rfc2046#section-1" rel="nofollow noreferrer">RFC 2046 §1</a> says:</p> <pre><code>Parameters are modifiers of the media subtype, and as such do not fundamentally affect the nature of the content. The set of meaningful parameters depends on the media type and subtype. Most parameters are associated with a single specific subtype. However, a given top-level media type may define parameters which are applicable to any subtype of that type. Parameters may be required by their defining media type or subtype or they may be optional. MIME implementations must also ignore any parameters whose names they do not recognize. </code></pre> <p>Note this last sentence:</p> <pre><code>MIME implementations must also ignore any parameters whose names they do not recognize. </code></pre> <p>Does this mean that a client would be non-conforming if they recognized a <code>footnotes=true</code> parameter of the <code>text/plain</code> media type?</p>
6,709,402
2
0
null
2011-07-15 02:35:10.433 UTC
9
2011-07-15 15:59:43.977 UTC
2021-10-07 05:49:19.053 UTC
null
-1
null
93,579
null
1
20
api|http|rest|mime-types|mime
14,694
<p>It seems to me that the distinction should run as follows:</p> <p><strong>Accept header parameters</strong> pertain to the packaging of the response.</p> <ul> <li>Media type (e.g. <code>application/json</code>)</li> <li>Character encoding (e.g. <code>charset=utf-8</code>)</li> <li>Structure (e.g. vendor extensions that specify the "doctype"; <code>application/vnd.example-com.foo+json; version=1.0</code>)</li> </ul> <p><strong>Query parameters</strong> pertain to resource(s) as addressed.</p> <ul> <li>Components (e.g. headings and footnotes)</li> <li>Optional features (e.g. formatting)</li> <li>Constraints (especially when addressing a range of like resources)</li> </ul>
7,340,019
sort values and return list of keys from dict python
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value">Python: Sort a dictionary by value</a> </p> </blockquote> <p>I have a dictionary like this:</p> <pre><code>A = {'Name1':34, 'Name2': 12, 'Name6': 46,....} </code></pre> <p>I want a list of keys sorted by the values, i.e. <code>[Name2, Name1, Name6....]</code></p> <p>Thanks!!!</p>
7,340,031
4
3
null
2011-09-07 20:16:39.02 UTC
12
2011-09-07 20:22:56.46 UTC
2017-05-23 12:18:01.06 UTC
null
-1
null
804,184
null
1
52
python|dictionary
41,535
<p>Use <a href="http://docs.python.org/library/functions.html#sorted" rel="noreferrer"><code>sorted</code></a> with the <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="noreferrer"><code>get</code></a> method as a key (dictionary keys can be accessed by <a href="http://docs.python.org/library/stdtypes.html#dict" rel="noreferrer">iterating</a>):</p> <pre><code>sorted(A, key=A.get) </code></pre>
24,279,245
How to handle Dynamic JSON in Retrofit?
<p>I am using the retrofit efficient networking library, but I am unable to handle Dynamic JSON which contains single prefix <code>responseMessage</code> which changes to <code>object</code> randomly, the same prefix ( <code>responseMessage</code>) changes to String in some cases (dynamically). </p> <p>Json format Object of responseMessage:</p> <pre><code>{ "applicationType":"1", "responseMessage":{ "surname":"Jhon", "forename":" taylor", "dob":"17081990", "refNo":"3394909238490F", "result":"Received" } } </code></pre> <p><code>responseMessage</code> Json format dynamically changes to type string:</p> <pre><code> { "applicationType":"4", "responseMessage":"Success" } </code></pre> <p>My problem is since retrofit has built-in <code>JSON</code> parsing, I have to assign single POJO per request! but the REST-API unfortunately, is built on dynamic <code>JSON</code> responses. The prefix will change from string to object randomly in both <strong>success(...)</strong> and <strong>failure(...)</strong> methods! </p> <pre><code>void doTrackRef(Map&lt;String, String&gt; paramsref2) { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://192.168.100.44/RestDemo").build(); TrackerRefRequest userref = restAdapter.create(TrackerRefRequest.class); userref.login(paramsref2, new Callback&lt;TrackerRefResponse&gt;() { @Override public void success( TrackerRefResponse trackdetailresponse, Response response) { Toast.makeText(TrackerActivity.this, "Success", Toast.LENGTH_SHORT).show(); } @Override public void failure(RetrofitError retrofitError) { Toast.makeText(TrackerActivity.this, "No internet", Toast.LENGTH_SHORT).show(); } }); } </code></pre> <p>Pojo:</p> <pre><code>public class TrackerRefResponse { private String applicationType; private String responseMessage; //String type //private ResponseMessage responseMessage; //Object of type ResponseMessage //Setters and Getters } </code></pre> <p>In above code POJO TrackerRefResponse.java prefix responseMessage is set to string or object of type responseMessage , so we can create the POJO with ref variable with same name (java basics :) ) so I'm looking for same solution for dynamic <code>JSON</code> in Retrofit. I know this is very easy job in normal http clients with async task, but it's not the best practice in the REST-Api <code>JSON</code> parsing! looking at the performance <a href="https://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-volley/18863395#18863395"><strong>Benchmarks</strong></a> always Volley or Retrofit is the best choice, but I'm failed handle dynamic <code>JSON</code>! </p> <p>Possible solution I Know </p> <ol> <li><p>Use old asyc task with http client parsing. :( </p></li> <li><p>Try to convince the RESTapi backend developer.</p></li> <li><p>Create custom Retrofit client :)</p></li> </ol>
28,576,252
12
1
null
2014-06-18 07:15:24.77 UTC
34
2022-03-16 20:01:49.863 UTC
2019-04-24 21:01:33.24 UTC
null
5,915,318
null
1,254,536
null
1
89
android|json|gson|retrofit
68,078
<p>Late to the party, but you can use a converter.</p> <pre><code>RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://graph.facebook.com") .setConverter(new DynamicJsonConverter()) // set your static class as converter here .build(); api = restAdapter.create(FacebookApi.class); </code></pre> <p>Then you use a static class which implements retrofit's Converter:</p> <pre><code>static class DynamicJsonConverter implements Converter { @Override public Object fromBody(TypedInput typedInput, Type type) throws ConversionException { try { InputStream in = typedInput.in(); // convert the typedInput to String String string = fromStream(in); in.close(); // we are responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // convert to the supplied type, typically Object, JsonObject or Map&lt;String, Object&gt; } } catch (Exception e) { // a lot may happen here, whatever happens throw new ConversionException(e); // wrap it into ConversionException so retrofit can process it } } @Override public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } </code></pre> <p>I have written this sample converter so it returns the Json response either as String, Object, JsonObject or Map&lt; String, Object >. Obviously not all return types will work for every Json, and there is sure room for improvement. But it demonstrates how to use a Converter to convert almost any response to dynamic Json.</p>
24,006,181
Android - How to change fragments in the Navigation Drawer
<p>I'm fairly new to Android programming, but have been doing pretty well until now. I've read a lot of answers to this question but can't seem to make mine work. Basically what I have is a MainActivity with a Navigation Drawer. I have two fragments correctly initialized with corresponding fragment layout xmls. Currently I can get my first fragment to show up when the app starts and when I click on each item in the drawer, the titles change; however, the fragment stays the same. Any suggestions? What I believe to be relevant code is below (not shown is the code for the NavigationDrawerFragment.java with the necessary code automatically built by Eclipse). Thanks in advance!</p> <pre><code>public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, PlaceholderFragment.newInstance(position + 1)) .commit(); } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_home); break; case 2: mTitle = getString(R.string.title_infodirect); break; case 3: mTitle = getString(R.string.title_trailmap); break; case 4: mTitle = getString(R.string.title_poi); break; case 5: mTitle = getString(R.string.title_photomap); break; case 6: mTitle = getString(R.string.title_report); break; case 7: mTitle = getString(R.string.title_rulesreg); } } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.overview, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_home, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } public static class InfoDirectFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static InfoDirectFragment newInstance(int sectionNumber) { InfoDirectFragment fragment = new InfoDirectFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public InfoDirectFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_infodirect, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } } </code></pre>
24,041,015
4
2
null
2014-06-03 02:26:41.45 UTC
10
2017-02-15 15:34:36.077 UTC
null
null
null
null
3,701,403
null
1
18
java|android|android-fragments|fragment|navigation-drawer
67,639
<p>Follow This <a href="http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/">link!!</a> for more details and use </p> <pre><code>private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { selectItem(position); } } </code></pre> <p>and </p> <pre><code>private void selectItem(int position) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); switch (position) { case 0: ft.replace(R.id.content_frame, new Fragment1, Constants.TAG_FRAGMENT).commit(); break; case 1: ft.replace(R.id.content_frame, new Fragment2, Constants.TAG_FRAGMENT); ft.commit(); break; } mDrawerList.setItemChecked(position, true); setTitle(title[position]); // Close drawer mDrawerLayout.closeDrawer(mDrawerList); } </code></pre>
21,797,118
Deprecated: mysql_connect()
<p>I am getting this warning, but the program still runs correctly.</p> <p>The MySQL code is showing me a message in PHP:</p> <blockquote> <p>Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\xampp\htdocs\task\media\new\connect.inc.php on line 2</p> </blockquote> <p>My <code>connect.inc.php</code> page is</p> <pre><code>&lt;?php $connect = mysql_connect('localhost','root',''); mysql_select_db('dbname'); ?&gt; </code></pre> <p>What does this mean and how can I eliminate the message?</p>
21,797,209
12
2
null
2014-02-15 11:49:00.737 UTC
33
2021-09-23 20:08:25.597 UTC
2020-02-22 08:26:41.47 UTC
null
285,587
null
3,215,309
null
1
102
php|mysql|function|deprecated
572,833
<p>There are a few solutions to your problem.</p> <p>The way with MySQLi would be like this:</p> <pre><code>&lt;?php $connection = mysqli_connect('localhost', 'username', 'password', 'database'); </code></pre> <p>To run database queries is also simple and nearly identical with the old way:</p> <pre><code>&lt;?php // Old way mysql_query('CREATE TEMPORARY TABLE `table`', $connection); // New way mysqli_query($connection, 'CREATE TEMPORARY TABLE `table`'); </code></pre> <p>Turn off all deprecated warnings including them from mysql_*:</p> <pre><code>&lt;?php error_reporting(E_ALL ^ E_DEPRECATED); </code></pre> <p>The Exact file and line location which needs to be replaced is "/System/Startup.php > line: 2 " error_reporting(E_All); replace with error_reporting(E_ALL ^ E_DEPRECATED);</p>
1,648,551
Why do all Java Objects have wait() and notify() and does this cause a performance hit?
<p>Every Java <code>Object</code> has the methods <code>wait()</code> and <code>notify()</code> (and additional variants). I have never used these and I suspect many others haven't. Why are these so fundamental that every object has to have them and is there a performance hit in having them (presumably some state is stored in them)? </p> <p><strong>EDIT</strong> to emphasize the question. If I have a <code>List&lt;Double&gt;</code> with 100,000 elements then every <code>Double</code> has these methods as it is extended from <code>Object</code>. But it seems unlikely that all of these have to know about the threads that manage the <code>List</code>.</p> <p><strong>EDIT</strong> excellent and useful answers. @Jon has a very good blog post which crystallised my gut feelings. I also agree completely with @Bob_Cross that you should show a performance problem before worrying about it. (Also as the nth law of successful languages if it had been a performance hit then Sun or someone would have fixed it).</p>
1,648,565
4
1
null
2009-10-30 08:08:12.96 UTC
9
2014-08-18 07:55:26.407 UTC
2009-10-30 09:33:23.753 UTC
null
130,964
null
130,964
null
1
20
java|wait|notify
4,279
<p>Well, it does mean that every object has to <em>potentially</em> have a monitor associated with it. The same monitor is used for <code>synchronized</code>. If you agree with the decision to be able to synchronize on any object, then <code>wait()</code> and <code>notify()</code> don't add any more per-object state. The JVM may allocate the actual monitor lazily (I know .NET does) but there has to be some storage space available to say which monitor is associated with the object. Admittedly it's possible that this is a very small amount (e.g. 3 bytes) which wouldn't actually save any memory anyway due to padding of the rest of the object overhead - you'd have to look at how each individual JVM handled memory to say for sure.</p> <p>Note that just having extra <em>methods</em> doesn't affect performance (other than very slightly due to the code obvious being present <em>somewhere</em>). It's not like each object or even each type has its own copy of the code for <code>wait()</code> and <code>notify()</code>. Depending on how the vtables work, each type <em>may</em> end up with an extra vtable entry for each inherited method - but that's still only on a per type basis, not a per object basis. That's basically going to get lost in the noise compared with the bulk of the storage which is for the actual objects themselves.</p> <p>Personally, I feel that both .NET and Java made a mistake by associating a monitor with every object - I'd rather have explicit synchronization objects instead. I wrote a bit more on this in a <a href="http://codeblog.jonskeet.uk/2008/12/05/redesigning-system-object-java-lang-object" rel="noreferrer">blog post about redesigning java.lang.Object/System.Object</a>.</p>
1,684,904
Getting Current Time in string in Custom format in objective c
<p>I want current time in following format in a string.</p> <p>dd-mm-yyyy HH:MM </p> <p>How?</p>
1,684,915
4
0
null
2009-11-06 01:50:13.663 UTC
19
2017-03-28 11:17:28.023 UTC
2015-04-08 00:08:53.28 UTC
null
893,158
null
140,765
null
1
59
iphone|objective-c|datetime|nstimer
84,765
<p>You want a <a href="http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369" rel="noreferrer">date formatter</a>. Here's an example:</p> <pre><code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy HH:mm"]; NSDate *currentDate = [NSDate date]; NSString *dateString = [formatter stringFromDate:currentDate]; </code></pre>
42,701,019
Problems generating solution for VS 2017 with CMake
<p>So I installed Visual Studio 2017 yesterday. I also installed CMake 3.7.2 which supports VS 2017.</p> <p>My VS installation is with the <code>Game development with C++</code> workflow + a few other components:</p> <p><img src="https://i.imgur.com/QkzfWvv.png" alt="individual_components"></p> <p>I've also added the CMake stuff (but I don't think I even needed it - since I'm using CMake as a standalone tool to just generate the VS solutions) and MSBuild (I had <code>msbuild.exe</code> even before adding that component - so not sure what exactly does that additional component do).</p> <p>With VS 2015 I was able to just run <code>cmake .</code> from a normal command prompt for a solution.</p> <p>With VS 2017 the workflow changes - I've read <a href="https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/" rel="noreferrer">this post from Microsoft</a>.</p> <p>So I tried the following:</p> <ul> <li>I opened the <code>Developer Command Prompt for VS 2017</code> and from it I ran <code>cmake . -G "NMake Makefiles"</code>. Then running <code>cmake --build .</code> compiled everything properly.</li> <li><p>When I tried the following in the prompt: <code>cmake . -G "Visual Studio 15 2017 Win64"</code> to force the creation of a solution I got the following errors:</p> <pre><code>-- The C compiler identification is unknown -- The CXX compiler identification is unknown CMake Error at CMakeLists.txt:3 (project): No CMAKE_C_COMPILER could be found. CMake Error at CMakeLists.txt:3 (project): No CMAKE_CXX_COMPILER could be found. -- Configuring incomplete, errors occurred! </code></pre></li> </ul> <p>I also tried setting up the environment using <a href="https://github.com/Microsoft/vswhere" rel="noreferrer">vswhere.exe</a> and running <code>vcvarsall.bat</code> like this:</p> <blockquote> <p>"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64</p> </blockquote> <p>and again I could only generate NMake files and not a solution.</p> <p>So how can I get a solution?</p> <p>And why does <code>cl.exe</code> report <code>Version 19.10.25017</code> when it's in <code>VC\Tools\MSVC\14.10.25017\bin</code>?</p>
42,738,933
8
13
null
2017-03-09 16:51:20.293 UTC
8
2021-11-27 19:01:25.487 UTC
2017-03-10 11:33:22.833 UTC
null
3,162,383
null
3,162,383
null
1
26
c++|visual-studio|visual-c++|cmake|visual-studio-2017
45,695
<p><em>Turning my comments into an answer</em></p> <p>The error <code>-- The CXX compiler identification is unknown - No CMAKE_CXX_COMPILER could be found.</code> basically means that CMake wasn't able to compile a simple test program (which it always does as part of identifying/validating the compiler).</p> <p>You can take a look into <code>CMakeFiles\CMakeError.log</code> (relative to your binary output directory), the error reason should be in there.</p> <p>Two possible reasons I came across so far:</p> <ol> <li><p>Missing administrator rights. You can try running this again from a shell that has administrative rights to crosscheck if your Visual Studio was setup with the need for administrator rights.</p></li> <li><p>Missing Windows SDK. Verify your SDK installation e.g. check that you have any Resource Compiler installed. It should be in a path similar to:</p> <pre><code>C:\Program Files (x86)\Microsoft SDKs\Windows\v[some version]\bin\RC.Exe </code></pre></li> </ol> <p><strong>Visual Studio 2017 Installation</strong></p> <p>Please note the Visual Studio may <em>not</em> install all necessary C++ packages even when you select one of the C++ pre-defined packages (as I have e.g. used <code>Desktop development with C++</code> and then added more packages under the <code>Individual Components</code> tab).</p> <p>Here is which selection worked for me (VS2017 Community Edition, Windows 10):</p> <p><a href="https://i.stack.imgur.com/8verF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8verF.png" alt="enter image description here"></a></p> <p>If you have projects using MFC/ATL libraries you need to add it under <code>SDKs, libraries, and frameworks</code> subcategory:</p> <p><a href="https://i.stack.imgur.com/dW4HA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dW4HA.png" alt="enter image description here"></a></p> <p><strong>References</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/32801638/cmake-error-at-cmakelists-txt30-project-no-cmake-c-compiler-could-be-found">CMake Error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found</a></li> <li><a href="https://stackoverflow.com/questions/20632860/the-cxx-compiler-identification-is-unknown">The CXX compiler identification is unknown</a></li> <li><a href="https://stackoverflow.com/questions/42190568/vs-2010-and-cmake-rc-is-not-recognized-as-an-internal-or-external-command">VS 2010 and CMake: &#39;rc&#39; is not recognized as an internal or external command</a></li> </ul>
7,261,703
set css border to end in a 90 instead of a 45 degree angle
<p>I have a div with different colors for both the border-bottom and border-right properties. So they are separated via a line leaving the box in a 45 degree angle.</p> <p>How can I make the bottom-border shorter so that the right border goes all the way to the bottom of the element which would yield a 90 degree angle separator-line?</p>
7,261,840
7
2
null
2011-08-31 18:32:39.617 UTC
8
2022-01-12 14:07:21.13 UTC
null
null
null
null
481,512
null
1
35
html|css
28,951
<p>Sad fact: Border corners are mitered. Always. (It's only visible if using different colors.)</p> <p>In order to simulate a butt joint, you can stack two divs to get a simulated result:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { position: absolute; left: 0; top: 0; height: 100px; width: 100px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="border-left: 2px solid #ff0000; border-bottom: 2px solid #ff0000;"&gt; &lt;/div&gt; &lt;div style="border-right: 2px solid #00ff00; border-top: 2px solid #00ff00;"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Stack more or control the top and bottom differently for better control over the appearance of the joint.</p>
7,099,290
How to ignore hidden files using os.listdir()?
<p>My python script executes an <code>os.listdir(path)</code> where the path is a queue containing archives that I need to treat one by one. </p> <p>The problem is that I'm getting the list in an array and then I just do a simple <code>array.pop(0)</code>. It was working fine until I put the project in subversion. Now I get the <code>.svn</code> folder in my array and of course it makes my application crash.</p> <p>So here is my question: is there a function that ignores hidden files when executing an <code>os.listdir()</code> and if not what would be the best way?</p>
7,099,342
8
1
null
2011-08-17 20:48:50.97 UTC
24
2021-12-22 20:38:08.19 UTC
2020-04-11 06:07:04.12 UTC
null
6,862,601
null
715,171
null
1
115
python|hidden-files
118,926
<p>You can write one yourself:</p> <pre><code>import os def listdir_nohidden(path): for f in os.listdir(path): if not f.startswith('.'): yield f </code></pre> <p>Or you can use a <a href="http://docs.python.org/library/glob.html" rel="noreferrer">glob</a>:</p> <pre><code>import glob import os def listdir_nohidden(path): return glob.glob(os.path.join(path, '*')) </code></pre> <p>Either of these will ignore all filenames beginning with <code>'.'</code>.</p>
7,454,990
Why can't we pass arrays to function by value?
<p>Apparently, we can pass complex class instances to functions, but why can't we pass arrays to functions?</p>
7,455,043
9
5
null
2011-09-17 13:08:41.94 UTC
15
2018-10-25 18:48:39.887 UTC
2011-09-17 13:13:17.74 UTC
null
415,784
null
888,051
null
1
56
c++|arrays|function|arguments
55,149
<p>The origin is historical. The problem is that the rule "arrays decay into pointers, when passed to a function" is simple.</p> <p>Copying arrays would be kind of complicated and not very clear, since the behavior would change for different parameters and different function declarations.</p> <p>Note that you can still do an indirect pass by value:</p> <pre><code>struct A { int arr[2]; }; void func(struct A); </code></pre>
29,262,002
Why does this Java 8 lambda fail to compile?
<p>The following Java code fails to compile:</p> <pre><code>@FunctionalInterface private interface BiConsumer&lt;A, B&gt; { void accept(A a, B b); } private static void takeBiConsumer(BiConsumer&lt;String, String&gt; bc) { } public static void main(String[] args) { takeBiConsumer((String s1, String s2) -&gt; new String("hi")); // OK takeBiConsumer((String s1, String s2) -&gt; "hi"); // Error } </code></pre> <p>The compiler reports:</p> <pre><code>Error:(31, 58) java: incompatible types: bad return type in lambda expression java.lang.String cannot be converted to void </code></pre> <p>The weird thing is that the line marked "OK" compiles fine, but the line marked "Error" fails. They seem essentially identical.</p>
29,262,958
4
4
null
2015-03-25 17:05:39.113 UTC
11
2015-04-16 23:38:16.11 UTC
2015-03-26 00:26:25.627 UTC
null
94,687
null
857,012
null
1
86
java|lambda|compiler-errors|java-8|void
29,775
<p>Your lambda needs to be congruent with <code>BiConsumer&lt;String, String&gt;</code>. If you refer to <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.3" rel="noreferrer">JLS #15.27.3 (Type of a Lambda)</a>:</p> <blockquote> <p>A lambda expression is congruent with a function type if all of the following are true:</p> <ul> <li>[...]</li> <li>If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.</li> </ul> </blockquote> <p>So the lambda must either be a statement expression or a void compatible block:</p> <ul> <li>A constructor invocation is <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8" rel="noreferrer">a statement expression</a> so it compiles.</li> <li>A string literal isn't a statement expression and is not void compatible (cf. <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.2-230" rel="noreferrer">the examples in 15.27.2</a>) so it does not compile.</li> </ul>
43,529,931
How to calculate prediction uncertainty using Keras?
<p>I would like to calculate NN model certainty/confidence (see <a href="http://mlg.eng.cam.ac.uk/yarin/blog_3d801aa532c1ce.html" rel="noreferrer">What my deep model doesn't know</a>) - when NN tells me an image represents "8", I would like to know how certain it is. Is my model 99% certain it is "8" or is it 51% it is "8", but it could also be "6"? Some digits are quite ambiguous and I would like to know for which images the model is just "flipping a coin".</p> <p>I have found some theoretical writings about this but I have trouble putting this in code. If I understand correctly, I should evaluate a testing image multiple times while "killing off" different neurons (using dropout) and then...?</p> <p>Working on MNIST dataset, I am running the following model:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense, Activation, Conv2D, Flatten, Dropout model = Sequential() model.add(Conv2D(128, kernel_size=(7, 7), activation='relu', input_shape=(28, 28, 1,))) model.add(Dropout(0.20)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Dropout(0.20)) model.add(Flatten()) model.add(Dense(units=64, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(units=10, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(train_data, train_labels, batch_size=100, epochs=30, validation_data=(test_data, test_labels,)) </code></pre> <p><em>How should I predict with this model so that I get its certainty about predictions too?</em> I would appreciate some practical examples (preferably in Keras, but any will do).</p> <p>To clarify, I am looking for an example of how to get certainty using <a href="http://mlg.eng.cam.ac.uk/yarin/blog_3d801aa532c1ce.html" rel="noreferrer">the method outlined by Yurin Gal</a> (or an explanation of why some other method yields better results). </p>
43,668,304
4
1
null
2017-04-20 21:07:38.627 UTC
18
2019-12-04 11:48:17.847 UTC
2019-11-21 18:02:39.817 UTC
null
3,924,118
null
593,487
null
1
43
machine-learning|neural-network|deep-learning|keras|uncertainty
15,338
<p>If you want to implement <em>dropout</em> approach to measure uncertainty you should do the following:</p> <ol> <li><p>Implement function which applies <em>dropout</em> also during the test time:</p> <pre><code>import keras.backend as K f = K.function([model.layers[0].input, K.learning_phase()], [model.layers[-1].output]) </code></pre></li> <li><p>Use this function as uncertainty predictor e.g. in a following manner:</p> <pre><code>def predict_with_uncertainty(f, x, n_iter=10): result = numpy.zeros((n_iter,) + x.shape) for iter in range(n_iter): result[iter] = f(x, 1) prediction = result.mean(axis=0) uncertainty = result.var(axis=0) return prediction, uncertainty </code></pre></li> </ol> <p>Of course you may use any different function to compute uncertainty. </p>
30,188,499
How to do "go get" on a specific tag of a github repository
<p>I am trying to compile the InfluxDB database (version v0.8.8) using <code>go get github.com/influxdb/influxdb</code></p> <p>But this pulls the master branch, and I need the <code>v0.8.8</code> tag.</p> <p>I have tried to do: <code>go get github.com/influxdb/influxdb/releases/tag/v0.8.8</code> but this fails saying unable to find.</p> <p>I also tried to do a regular <code>go get</code> of the master branch, and then manually checking out the tag using <code>git</code> in <code>GOPATH/src/github...</code> in order to set the corret version.</p> <p>The problem using the last approach is that when I try to pull the dependencies with <code>go get -u -f ./...</code> it tries to find them in the master branch, and some of them do not exist on the master branch...</p> <p><strong>TL;DR</strong>: perform <code>go get</code> on a specific github tag, and pull the correct dependencies.</p>
30,188,904
7
8
null
2015-05-12 10:43:30.293 UTC
16
2021-11-01 07:06:30.477 UTC
2019-06-14 09:26:19.67 UTC
null
2,884,309
null
2,597,143
null
1
108
git|go|github
106,669
<p>It is not possible using the <code>go get</code> tool. Instead you need to use a third party go package management tool or create your own forks for the packages that you wish to manage more fine grained.</p> <p>Spoke to a guy that works at Google and he acknowledged this problem/requirement, he said that vendoring which his team used was bulky and they will probably solve it with the official tools soon.</p> <p><strong>Read more:</strong></p> <ul> <li><a href="https://github.com/golang/go/wiki/PackageManagementTools" rel="noreferrer">Reference of third party package management tools</a></li> <li><a href="https://groups.google.com/forum/#!topic/golang-dev/nMWoEAG55v8%5B1-25%5D" rel="noreferrer">Blog post by golang team discussing the approach for implementing vendoring</a></li> </ul> <p><strong>Vendoring in Go 1.6</strong></p> <p>Vendoring has been <a href="https://blog.golang.org/go1.6" rel="noreferrer">released from experimental in go 1.6</a> (after this post was initially written) that makes the process of using specific tags / versions of packages using third party tools easier. <code>go get</code> does still not have the functionality to fetch specific tags or versions.</p> <p>More about how vendoring works: <a href="https://blog.gopheracademy.com/advent-2015/vendor-folder/" rel="noreferrer">Understanding and using the vendor folder</a></p> <p><strong>Modules in Go 1.11</strong></p> <p>Go 1.11 has released an experimental features called modules to improve dependency management, they hope to release it as stable in Go 1.12: <a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">Information about modules in Go 1.11</a></p>
9,394,840
How can I call a file from the same folder that I am in (in script)
<p>I would like to call script B from script A without specifying the complete path. I've tried with </p> <pre><code>.\scriptb.ps1 </code></pre> <p>but that doesn't work. Do I really have to specify the entire path? </p> <p>(sorry for this quite basic question, but google couldn't help me!)</p>
9,394,938
8
1
null
2012-02-22 12:34:36.187 UTC
2
2020-11-26 17:12:46.253 UTC
null
null
null
null
1,114,155
null
1
28
powershell
43,813
<p>it is possible using <code>$MyInvocation</code> as follows:</p> <pre><code>$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent $scriptPath = Join-Path $executingScriptDirectory "scriptb.ps1" Invoke-Expression ".\$scriptPath" </code></pre>
32,943,593
The name 'nameof' does not exist in the current context
<p>I'm using VS 2013 with .Net Framework 4.6. I want to use new C# 6 features(For example <code>nameof</code>).But I couldn't found it. </p> <p><a href="https://i.stack.imgur.com/HcI5Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HcI5Y.png" alt="enter image description here"></a></p> <p>Should I use VS 2015? Or higher .Net Framework?</p>
32,943,628
9
3
null
2015-10-05 07:47:37.987 UTC
1
2022-02-18 03:09:24.157 UTC
2016-06-03 09:53:13.703 UTC
null
133
null
648,723
null
1
36
c#|visual-studio|visual-studio-2013
46,374
<p>Yes, to use C# 6 features, you need a C# 6 compiler. Visual Studio 2013 doesn't have a C# 6 compiler. Visual Studio 2015 does.</p> <p>There have been Roslyn pre-releases for Visual Studio 2013, but they don't implement the final C# 6: they actually don't implement all the features, and what they do implement is different from the final C# 6 behaviour.</p>
32,830,336
How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?
<h3>Problem</h3> <p>I don't understand how to make LocalDB show up in the SQL Server Object Explorer. On some VMs, it shows up automatically, on some other VMs, it doesn't. Still, after googling for hours, I don't get it.</p> <h3>Current situation</h3> <ol> <li>I have a clean VM</li> <li>I installed Visual Studio 2015 Community (all default settings)</li> <li>I let a console application run (Entity Framework 6, code-first, console application) which worked on another VM and created a database automatically which then showed up in the SQL Server Object Explorer; but not this time</li> </ol> <p>The error says:</p> <pre><code>System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.) ---&gt; System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified </code></pre> <p>So, on this VM, no database gets created and nothing shows up in the SQL Server Object Explorer's <code>SQL Server</code> node.</p> <p><a href="https://i.stack.imgur.com/NsZiq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NsZiq.png" alt="Connecting to LocalDB" /></a></p> <h3>What I think to know</h3> <ul> <li>Visual Studio 2015 Community comes with LocalDB; so everything should just work out of the box, but it doesn't, and I don't know why</li> <li>LocalDB databases are just a pair of files (*.mdf and *.ldf)</li> <li>I've seen the files being created at the default database location at <code>C:\Users\&lt;username&gt;\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB</code>; but on this VM, there is no such folder</li> <li>The <code>App.config</code> looked every time like this (and it was automatically created that way when I installed Entity Framework 6 the NuGet Package Manager in Visual Studio):</li> </ul> <h3>App.config</h3> <pre><code>&lt;configuration&gt; &lt;configSections&gt; &lt;section name=&quot;entityFramework&quot; type=&quot;System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot; requirePermission=&quot;false&quot; /&gt; &lt;/configSections&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type=&quot;System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework&quot;&gt; &lt;parameters&gt; &lt;parameter value=&quot;mssqllocaldb&quot; /&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;providers&gt; &lt;provider invariantName=&quot;System.Data.SqlClient&quot; type=&quot;System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer&quot; /&gt; &lt;/providers&gt; &lt;/entityFramework&gt; &lt;/configuration&gt; </code></pre> <h3>Other random comments</h3> <ul> <li>Earlier, with SQL Server, it was necessary to open up certain ports, but LocalDB runs, as I understand it, as a separate process on demand when started by Visual Studio.</li> <li>I don't know how to debug the <code>SQLException</code></li> <li>Does LocalDB not come packaged with Visual Studio 2015 Community and do I need to install it separately?</li> </ul>
34,348,433
8
4
null
2015-09-28 19:26:23.727 UTC
13
2021-03-19 21:09:56.34 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
33,311
null
1
55
sql-server|visual-studio-2015|localdb
126,209
<p>I had the same issue today recently installing VS2015 Community Edition Update 1. </p> <p>I fixed the problem by just adding the "<strong><em>SQL Server Data Tools</em></strong>" from the <strong>VS2015 setup installer</strong>... When I ran the installer the first time I selected the "Custom" installation type instead of the "Default". I wanted to see what install options were available but not select anything different than what was already ticked. My assumption was that whatever was already ticked was essentially the default install. But its not.</p>