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
5,398,395
How can I insert a tab character with sed on OS X?
<p>I have tried:</p> <pre><code>echo -e "egg\t \t\t salad" | sed -E 's/[[:blank:]]+/\t/g' </code></pre> <p>Which results in:</p> <pre><code>eggtsalad </code></pre> <p>And...</p> <pre><code>echo -e "egg\t \t\t salad" | sed -E 's/[[:blank:]]+/\\t/g' </code></pre> <p>Which results in:</p> <pre><code>egg\tsalad </code></pre> <p>What I would like:</p> <pre><code>egg salad </code></pre>
5,398,430
6
0
null
2011-03-22 22:00:58.3 UTC
18
2020-05-24 19:23:15.997 UTC
2016-03-20 06:36:57.027 UTC
null
3,266,847
null
662,767
null
1
71
regex|macos|sed
49,654
<p>Try: <kbd>Ctrl</kbd>+<kbd>V</kbd> and then press <kbd>Tab</kbd>.</p>
5,553,850
Is there any penalty/cost of virtual inheritance in C++, when calling non-virtual base method?
<p>Does using virtual inheritance in C++ have a runtime penalty in compiled code, when we call a <em>regular function</em> member from its base class? Sample code:</p> <pre><code>class A { public: void foo(void) {} }; class B : virtual public A {}; class C : virtual public A {}; class D : public B, public C {}; // ... D bar; bar.foo (); </code></pre>
5,553,931
8
3
null
2011-04-05 14:50:21.693 UTC
2
2022-09-03 06:17:55.58 UTC
2013-05-03 13:48:41.57 UTC
null
227,536
null
325,519
null
1
31
c++|runtime|overhead|virtual-inheritance
4,839
<p>There may be, yes, if you call the member function via a pointer or reference and the compiler can't determine with absolute certainty what type of object that pointer or reference points or refers to. For example, consider:</p> <pre><code>void f(B* p) { p-&gt;foo(); } void g() { D bar; f(&amp;bar); } </code></pre> <p>Assuming the call to <code>f</code> is not inlined, the compiler needs to generate code to find the location of the <code>A</code> virtual base class subobject in order to call <code>foo</code>. Usually this lookup involves checking the vptr/vtable.</p> <p>If the compiler knows the type of the object on which you are calling the function, though (as is the case in your example), there should be no overhead because the function call can be dispatched statically (at compile time). In your example, the dynamic type of <code>bar</code> is known to be <code>D</code> (it can't be anything else), so the offset of the virtual base class subobject <code>A</code> can be computed at compile time.</p>
5,535,610
Mongoose Unique index not working!
<p>I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:</p> <pre><code>User = new Schema ({ email: {type: String, index: {unique: true, dropDups: true}} }) </code></pre> <p>I can save 2 users with the same email. Darn.</p> <p>The same issue has been expressed here: <a href="https://github.com/LearnBoost/mongoose/issues/56" rel="noreferrer">https://github.com/LearnBoost/mongoose/issues/56</a>, but that thread is old and lead to nowhere.</p> <p>For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.</p> <p>Does anyone have a solution to this?</p>
5,535,629
33
3
null
2011-04-04 07:18:49.177 UTC
26
2022-08-12 16:05:40.883 UTC
null
null
null
null
389,122
null
1
128
mongodb|node.js|mongoose
94,376
<p>Oops! You just have to restart mongo.</p>
12,243,870
Write sent sms to content://sms/sent table
<p>I am working on an android sms application.I can send sms to single contact by using the following code.</p> <pre><code>sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); </code></pre> <p>Now I want to send sms to multicontacts.Some suggest to use loop.SO now I am using loops to send sms to multicontact.</p> <p>After sending each sms I write those values to sent table.</p> <pre><code> ContentValues values = new ContentValues(); values.put("address", mobNo); values.put("body", msg); getContentResolver().insert(Uri.parse("content://sms/sent"), values); </code></pre> <p>Every new address will create a new thread id. For example if my receiver's address is x, then thread id 1, for y thread id 2.And if I want to send sms to both x and y ,then how can I write in to sms/sent table. If I use Loop,then it won't create any new thread id, because send address x already have thread id 1 and y already have thread id 2.So messages will listed under thread id 1 and 2 never creates a new thread id.</p> <p>I tried to manualy insert thread id by</p> <pre><code>values.put("thread_id", 33); </code></pre> <p>But then the messages under new thread id do not listed in default app but in my app.</p> <p>Please help me friends</p> <p>Edit:I tried using 0, and then reading the thread_id that was generated, then place the next sms with this thread_id, still doesn't works. </p>
12,490,617
2
8
null
2012-09-03 07:49:56.877 UTC
9
2013-01-24 20:29:52.13 UTC
2013-01-24 20:29:52.13 UTC
null
1,440,731
null
1,220,296
null
1
11
android|sms|android-contentprovider
7,213
<p>You need to create a new <code>thread_id</code> manually, a normal <code>contentResolver.insert(...)</code> won't do for multiple recipient messages. To create the new <code>thread_id</code> you query the following uri</p> <p><code>content://mms-sms/threadID</code></p> <p>and to it append the necessary recipients so that finally it looks like this</p> <p><code>content://mms-sms/threadID?recipient=9808&amp;recipient=8808</code></p> <p>So the full example would look like this. Say the recipients are <code>9808</code> and <code>8808</code></p> <pre><code>Uri threadIdUri = Uri.parse('content://mms-sms/threadID'); Uri.Builder builder = threadIdUri.buildUpon(); String[] recipients = {"9808","8808"}; for(String recipient : recipients){ builder.appendQueryParameter("recipient", recipient); } Uri uri = builder.build(); </code></pre> <p>Now you can query <code>uri</code> in the normal way and this will give you a <code>thread_id</code> that you can use for the recipients specified, it will create a new id if one doesn't exist or return an existing one.</p> <pre><code>Long threadId = 0; Cursor cursor = getContentResolver().query(uri, new String[]{"_id"}, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { threadId = cursor.getLong(0); } } finally { cursor.close(); } } </code></pre> <p>Now use <code>threadId</code> to insert your SMSs.</p> <p>A few things to note. </p> <p>Do not use this <code>threadId</code> to insert single recipient messages for either <code>9908</code> or <code>8808</code>, create a new thread_id for each or just do an <code>insert</code> without specifying the <code>thread_id</code>.</p> <p>Also, be very careful with the <code>builder.appendQueryParameter(...)</code> part, make sure the key is <code>recipient</code> and not <code>recipients</code>, if you use <code>recipients</code> it will still work but you will always get the same <code>thread_id</code> and all your SMSs will end up in one thread.</p>
19,269,278
cast object to ArrayList<String>
<p>is it possible to cast an <code>Object</code> to e.g. <code>ArrayList&lt;String&gt;</code> </p> <p>the code below gives an example of the problem. The Problem is in the last row</p> <pre><code>setDocs((ArrayList&lt;Document&gt;)obj); </code></pre> <p>where I want to cast an <code>Object obj</code> to <code>ArrayList&lt;String&gt;</code></p> <pre><code>public void setValue(Object obj) { if(obj instanceof TFile) setTFile((TFile)obj); else if(obj instanceof File) setFile((File)obj)); else if(obj instanceof Document) setDoc((Document)obj); else if(obj instanceof ArrayList) setDocs((ArrayList&lt;Document&gt;)obj); } </code></pre>
19,269,417
2
4
null
2013-10-09 10:19:13.197 UTC
1
2014-04-22 11:45:28.62 UTC
null
null
null
null
2,787,530
null
1
7
java|casting|arraylist
52,887
<p>In Java generics are not reified, i.e. their generic type is not used when casting.</p> <p>So this code</p> <pre><code>setDocs((ArrayList&lt;Document&gt;)obj); </code></pre> <p>will be executed as</p> <pre><code>setDocs((ArrayList)obj); </code></pre> <p>As that runtime cast won't check your <code>ArrayList</code> contains <code>Document</code> objects, the compiler raises a warning.</p>
8,748,036
Is there a builtin identity function in python?
<p>I'd like to point to a function that does nothing:</p> <pre><code>def identity(*args) return args </code></pre> <p>my use case is something like this</p> <pre><code>try: gettext.find(...) ... _ = gettext.gettext else: _ = identity </code></pre> <p>Of course, I could use the <code>identity</code> defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).</p> <p>Apparently, <code>map</code> and <code>filter</code> use <code>None</code> for the identity, but this is specific to their implementations.</p> <pre><code>&gt;&gt;&gt; _=None &gt;&gt;&gt; _("hello") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'NoneType' object is not callable </code></pre>
8,748,146
10
11
null
2012-01-05 18:49:27.573 UTC
15
2022-03-26 00:20:26.37 UTC
2022-03-15 19:58:38.933 UTC
null
6,045,800
null
94,363
null
1
172
python
65,126
<p>Doing some more research, there is none, a feature was asked in <a href="http://bugs.python.org/issue1673203" rel="noreferrer">issue 1673203</a> And from <a href="http://mail.python.org/pipermail/python-ideas/2009-March/003647.html" rel="noreferrer">Raymond Hettinger said there won't be</a>:</p> <blockquote> <p>Better to let people write their own trivial pass-throughs and think about the signature and time costs.</p> </blockquote> <p>So a better way to do it is actually (a lambda avoids naming the function):</p> <pre><code>_ = lambda *args: args </code></pre> <ul> <li>advantage: takes any number of parameters</li> <li>disadvantage: the result is a boxed version of the parameters</li> </ul> <p>OR</p> <pre><code>_ = lambda x: x </code></pre> <ul> <li>advantage: doesn't change the type of the parameter</li> <li>disadvantage: takes exactly 1 positional parameter</li> </ul>
22,046,487
Truncate/Clear table variable in SQL Server 2008
<p>Is it possible to truncate or flush out a table variable in SQL Server 2008?</p> <pre><code>declare @tableVariable table ( id int, value varchar(20) ) while @start &lt;= @stop begin insert into @tableVariable(id, value) select id , value from xTable where id = @start --Use @tableVariable --@tableVariable should be flushed out of -- old values before inserting new values set @start = @start + 1 end </code></pre>
22,046,579
7
4
null
2014-02-26 15:52:22.83 UTC
8
2022-02-17 11:07:09.007 UTC
2021-10-05 02:27:23.473 UTC
null
1,127,428
null
1,546,629
null
1
80
sql|sql-server|tsql
112,994
<p>just delete everything</p> <pre><code>DELETE FROM @tableVariable </code></pre>
11,416,069
Compile vim with clipboard and xterm
<p>I want to compile the current version of vim with:</p> <pre><code>+clipboard +xterm_clipboard and ruby support </code></pre> <p>But every time I compile it the <code>clipboard</code> and the <code>xterm_clipboard</code> options aren't enabled.</p> <p>Is there a lib needed or must I add any other options in the configuration step?</p> <pre><code>./configure \ --enable-rubyinterp=dynamic \ --enable-cscope \ --enable-gui=auto \ --enable-gtk2-check \ --enable-gnome-check \ --with-features=huge \ --with-x make &amp;&amp; sudo make install </code></pre>
11,453,463
2
0
null
2012-07-10 14:54:39.23 UTC
12
2020-02-25 02:50:08.857 UTC
2012-07-11 08:51:04.633 UTC
null
1,017,941
null
933,573
null
1
26
vim|clipboard
20,176
<p>You can see if <code>configure</code> manage to find a working X lib by checking the output of (or scroll through the output of <code>configure</code> in your terminal):</p> <pre><code>$ grep X11 src/auto/config.h #define HAVE_X11 </code></pre> <p>If <code>configure</code> failed then you'll see:</p> <pre><code>$ grep X11 src/auto/config.h /* #undef HAVE_X11 */ </code></pre> <p>You'll need to install the appropriate X development library like <code>xlib</code> and <code>xtst</code> for <code>--with-x</code> to work.</p> <p>On ubuntu it should be enough to install <code>libx11-dev</code> and <code>libxtst-dev</code>.</p>
11,437,958
How to debug a basic node.js application (not http) on windows
<p>I know how to debug http applications using node-inspector and iisnode. But can I use node-inspector to debug a <em>non http</em> node application, on windows?</p> <p>I tried:</p> <pre><code> node debug test.js </code></pre> <p>It says:</p> <pre><code>debugger listening on port 5858 </code></pre> <p>But opening <code>http://localhost:5858/</code> in Chrome does not do anything.</p> <hr> <p>BTW: running <code>node debug test.js</code> does start the command-line debugger which works. But it's nothing like node-inspector.</p>
11,463,248
7
1
null
2012-07-11 17:18:02.557 UTC
24
2019-01-21 20:08:53.66 UTC
2012-07-11 18:52:22.743 UTC
null
121,445
null
121,445
null
1
29
node.js|node-inspector
18,386
<p>To use node-inspector, the right switch is <code>node --debug</code> not <code>node debug</code></p> <p>Here are the detailed steps:</p> <ol> <li>install node-inspector globally (<code>npm install -g node-inspector</code>)</li> <li>from a command-line window, run: <code>node-inspector</code></li> <li>open Chrome and go to <code>http://localhost:8080/debug?port=5858</code>. You'll get the node-inspector UI but without any running app.</li> <li>from another command-line window, run your app with the <code>--debug</code> switch like this: <code>node --debug test.js</code></li> <li>refresh the Chrome tab and <em>voila!</em></li> </ol> <p>A few interesting points:</p> <ul> <li>If you kill your app and start it again, just refresh the node-inspector tab. It will keep all your breakpoints.</li> <li>To break automatically on the first line start your app with <code>node --debug-brk test.js</code></li> </ul>
11,142,109
How to use Utilities.sleep() function
<p>What is the exact use of <code>Utilities.sleep()</code> function? Should we use it between function calls or API calls? </p> <p>I use the <code>Utilities.sleep(1000)</code> in-between function calls, is it right? Will it slow down the execution time?</p>
11,142,322
4
0
null
2012-06-21 16:00:11.717 UTC
13
2021-10-06 08:29:53.607 UTC
2012-06-22 15:35:03.847 UTC
null
3,340
null
1,446,249
null
1
46
google-apps-script
141,784
<p>Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.</p> <p>Here is an example :</p> <pre><code>function delsheets(){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet for (pa=numbofsheet-1;pa&gt;0;--pa){ ss.setActiveSheet(ss.getSheets()[pa]); var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one Utilities.sleep(200);// pause in the loop for 200 milliseconds } ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function) } </code></pre>
11,260,155
How to use float filter to show just two digits after decimal point?
<p>I am using Flask/Jinja2 template to show a number using <code>|float</code> filter.</p> <p>Here is my code</p> <pre><code>{% set proc_err = nb_err|length / sum * 100 %} ({{proc_err|float}}%) </code></pre> <p>Output is a bit awkward:</p> <pre><code>17/189 (8.99470899471%) </code></pre> <p>I am looking for a way to make the places after dot limited to a number e.g. 2.</p> <p>Desired output:</p> <pre><code>17/189 (8.99%) </code></pre>
11,260,267
4
0
null
2012-06-29 10:28:33.703 UTC
7
2022-06-05 18:37:48.217 UTC
2022-06-05 18:37:48.217 UTC
null
515,189
null
201,644
null
1
80
flask|jinja2|number-formatting
78,704
<p>It turns to be quite simple:</p> <p>My code:</p> <pre><code>{% set proc_err = nb_err|length / sum * 100 %} ({{proc_err|float}}%) </code></pre> <p>Can be changed a bit with:</p> <pre><code>{% set proc_err = nb_err|length / sum * 100 %} ({{'%0.2f' % proc_err|float}}%) </code></pre> <p>or using <strong><em>format</em></strong>:</p> <pre><code>({{'%0.2f'| format(proc_err|float)}}%) </code></pre> <p>Reference can be found here on <a href="https://github.com/mitsuhiko/jinja2/issues/70" rel="noreferrer">jinja2 github issue 70</a></p>
10,934,683
How do I configure Qt for cross-compilation from Linux to Windows target?
<p>I want to cross compile the Qt libraries (and eventually my application) for a Windows x86_64 target using a Linux x86_64 host machine. I feel like I am close, but I may have a fundamental misunderstanding of some parts of this process.</p> <p>I began by installing all the mingw packages on my Fedora machine and then modifying the <code>win32-g++</code> qmake.conf file to fit my environment. However, I seem to be getting stuck with some seemingly obvious configure options for Qt: <code>-platform</code> and <code>-xplatform</code>. Qt documentation says that <code>-platform</code> should be the host machine architecture (where you are compiling) and <code>-xplatform</code> should be the target platform for which you wish to deploy. In my case, I set <code>-platform linux-g++-64</code> and <code>-xplatform linux-win32-g++</code> where linux-win32-g++ is my modified win32-g++ configuration.</p> <p>My problem is that, after executing configure with these options, I see that it invokes my system's compiler instead of the cross compiler (x86_64-w64-mingw32-gcc). If I omit the <code>-xplatform</code> option and set <code>-platform</code> to my target spec (linux-win32-g++), it invokes the cross compiler but then errors when it finds some Unix related functions aren't defined.</p> <p>Here is some output from my latest attempt: <a href="http://pastebin.com/QCpKSNev" rel="noreferrer">http://pastebin.com/QCpKSNev</a>.</p> <p>Questions:</p> <ol> <li><p>When cross-compiling something like Qt for Windows from a Linux host, should the native compiler <em>ever</em> be invoked? That is, during a cross compilation process, shouldn't we use <em>only</em> the cross compiler? I don't see why Qt's configure script tries to invoke my system's native compiler when I specify the <code>-xplatform</code> option.</p></li> <li><p>If I'm using a mingw cross-compiler, when will I have to deal with a specs file? Spec files for GCC are still sort of a mystery to me, so I am wondering if some background here will help me.</p></li> <li><p>In general, beyond specifying a cross compiler in my qmake.conf, what else might I need to consider?</p></li> </ol>
13,211,922
5
3
null
2012-06-07 15:14:23.527 UTC
50
2021-09-11 16:58:30.983 UTC
2013-10-02 09:54:50.423 UTC
null
321,731
null
65,928
null
1
88
linux|qt|mingw|cross-compiling
91,733
<p>Just use <a href="http://mxe.cc/" rel="noreferrer">M cross environment (MXE)</a>. It takes the pain out of the whole process:</p> <ul> <li><p>Get it:</p> <pre><code>$ git clone https://github.com/mxe/mxe.git </code></pre></li> <li><p>Install <a href="http://mxe.cc/#requirements" rel="noreferrer">build dependencies</a></p></li> <li><p>Build Qt for Windows, its dependencies, and the cross-build tools; this will take about an hour on a fast machine with decent internet access; the download is about 500MB:</p> <pre><code>$ cd mxe &amp;&amp; make qt </code></pre></li> <li><p>Go to the directory of your app and add the cross-build tools to the <strong>PATH</strong> environment variable:</p> <pre><code>$ export PATH=&lt;mxe root&gt;/usr/bin:$PATH </code></pre></li> <li><p>Run the Qt Makefile generator tool then build:</p> <pre><code>$ &lt;mxe root&gt;/usr/i686-pc-mingw32/qt/bin/qmake &amp;&amp; make </code></pre></li> <li><p>You should find the binary in the ./release directory:</p> <pre><code>$ wine release/foo.exe </code></pre></li> </ul> <p><strong>Some notes</strong>:</p> <ul> <li><p>Use the master branch of the MXE repository; it appears to get a lot more love from the development team.</p></li> <li><p>The output is a 32-bit static binary, which will work well on 64-bit Windows.</p></li> </ul>
10,906,411
ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8
<p>I recently upgraded from Visual Studio 2010 to the Visual Studio 2012 RC. The installer also installs IIS 8 Express which Visual Studio now uses as the default web server.</p> <p>IIS 8 is blocking my WEB API requests that use PUT AND DELETE verbs. IIS returns a 405 error, <code>The requested resource does not support http method 'PUT'</code>.</p> <p>I know people have issues with this in the past and there are several messages about it on Stack Overflow. With IIS 7 Express the solution was to uninstall WebDav. Unfortunately I don't see any way to do that with IIS 8. </p> <p>I've tried editing out the WebDav sections from applicationhost.config but that hasn't helped. For example I removed <code>&lt;add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /&gt;</code> from the config file.</p> <p>I've spent far too long on this. There must be a simple way to enable PUT and DELETE? </p>
10,907,343
22
4
null
2012-06-05 23:34:09.167 UTC
51
2022-06-04 08:28:05.06 UTC
2012-11-14 10:10:19.833 UTC
null
724,310
null
724,310
null
1
160
asp.net|iis|asp.net-web-api|iis-8
217,140
<p>Okay. I finally got to the bottom of this. You need to jump through some hoops to get the PUT and DELETE verbs working correctly with IIS8. In fact if you install the release candidate of VS 2012 and create a new WEB API project you'll find that the sample PUT and DELETE methods return 404 errors out of the box.</p> <p>To use the PUT and DELETE verbs with the Web API you need to edit %userprofile%\documents\iisexpress\config\applicationhost.config and add the verbs to the ExtensionlessUrl handler as follows:</p> <p>Change this line:</p> <pre><code>&lt;add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; </code></pre> <p>to:</p> <pre><code>&lt;add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; </code></pre> <p>In addition to the above you should ensure WebDAV is not interfering with your requests. This can be done by commenting out the following lines from applicationhost.config.</p> <pre><code>&lt;add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /&gt; &lt;add name="WebDAVModule" /&gt; &lt;add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" /&gt; </code></pre> <p>Also be aware that the default Web API convention is that your method name should be the same as the invoked HTTP verb. For example if you're sending an HTTP delete request your method, by default, should be named Delete. </p>
12,994,298
properly join two files based on 2 columns in common
<p>I have two files I'm trying to join/merge based on columns <code>1</code> and <code>2</code>. They look something like this, with <code>file1</code> (<code>58210</code> lines) being much shorter than <code>file2</code> (<code>815530</code> lines) and I'd like to find the intersection of these two files based on fields <code>1</code> and <code>2</code> as an index:</p> <p><code>file1</code>:</p> <pre><code>2L 25753 33158 2L 28813 33158 2L 31003 33158 2L 31077 33161 2L 31279 33161 3L 32124 45339 3L 33256 45339 ... </code></pre> <p><code>file2</code>:</p> <pre><code>2L 20242 0.5 0.307692307692308 2L 22141 0.32258064516129 0.692307692307692 2L 24439 0.413793103448276 0.625 2L 24710 0.371428571428571 0.631578947368421 2L 25753 0.967741935483871 0.869565217391304 2L 28813 0.181818181818182 0.692307692307692 2L 31003 0.36 0.666666666666667 2L 31077 0.611111111111111 0.931034482758621 2L 31279 0.75 1 3L 32124 0.558823529411765 0.857142857142857 3L 33256 0.769230769230769 0.90625 ... </code></pre> <p>I've been using the following couple of commands but end up with different numbers of lines:</p> <pre><code>awk 'FNR==NR{a[$1$2]=$3;next} {if($1$2 in a) print}' file1 file2 | wc -l awk 'FNR==NR{a[$1$2]=$3;next} {if($1$2 in a) print}' file2 file1 | wc -l </code></pre> <p>I'm not sure why this happens, and I've tried sorting prior to comparison, just in case I have duplicate lines (based on columns <code>1</code> and <code>2</code>) in either of the files, but it doesn't seem to help. (Any insights on why this is so are also appreciated)</p> <p>How can I just merge the files so that just the lines of <code>file2</code> that have the corresponding columns <code>1</code> and <code>2</code> in <code>file1</code> get printed, with column <code>3</code> of <code>file1</code> added on, to look something like this:</p> <pre><code>2L 25753 0.967741935483871 0.869565217391304 33158 2L 28813 0.181818181818182 0.692307692307692 33158 2L 31003 0.36 0.666666666666667 33158 2L 31077 0.611111111111111 0.931034482758621 33161 2L 31279 0.75 1 33161 3L 32124 0.558823529411765 0.857142857142857 45339 3L 33256 0.769230769230769 0.90625 45339 </code></pre>
12,994,872
3
7
null
2012-10-21 02:01:02.11 UTC
15
2019-01-06 20:39:39.58 UTC
2018-07-23 00:25:26.44 UTC
null
8,852,408
null
1,322,656
null
1
10
unix|join|awk
23,160
<pre><code>awk 'NR==FNR{a[$1,$2]=$3;next} ($1,$2) in a{print $0, a[$1,$2]}' file1 file2 </code></pre> <p>Look:</p> <pre><code>$ cat file1 2L 5753 33158 2L 8813 33158 2L 7885 33159 2L 1279 33159 2L 5095 33158 $ $ cat file2 2L 8813 0.6 1.2 2L 5762 0.4 0.5 2L 1279 0.5 0.9 $ $ awk 'NR==FNR{a[$1,$2]=$3;next} ($1,$2) in a{print $0, a[$1,$2]}' file1 file2 2L 8813 0.6 1.2 33158 2L 1279 0.5 0.9 33159 $ </code></pre> <p>If that's not what you want, please clarify and perhaps post some more representative sample input/output.</p> <p>Commented version of the above code to provide requested explanation:</p> <pre><code>awk ' # START SCRIPT # IF the number of records read so far across all files is equal # to the number of records read so far in the current file, a # condition which can only be true for the first file read, THEN NR==FNR { # populate array "a" such that the value indexed by the first # 2 fields from this record in file1 is the value of the third # field from the first file. a[$1,$2]=$3 # Move on to the next record so we don't do any processing intended # for records from the second file. This is like an "else" for the # NR==FNR condition. next } # END THEN # We only reach this part of the code if the above condition is false, # i.e. if the current record is from file2, not from file1. # IF the array index constructed from the first 2 fields of the current # record exist in array a, as would occur if these same values existed # in file1, THEN ($1,$2) in a { # print the current record from file2 followed by the value from file1 # that occurred at field 3 of the record that had the same values for # field 1 and field 2 in file1 as the current record from file2. print $0, a[$1,$2] } # END THEN ' file1 file2 # END SCRIPT </code></pre> <p>Hope that helps.</p>
13,042,278
Launch android application from a browser link
<p>I have a problem trying to launch my application from the browser using my own scheme.<br> Code is as follow:<br> Manifest file:</p> <pre><code> &lt;activity android:name=".MainActivity" android:label="@string/title_activity_main" android:exported="false"&gt; &lt;intent-filter&gt; &lt;data android:scheme="allplayer" /&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>Html file:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="allplayer://site.com"&gt;Test link&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If I click on the link, my application wont start. I did a lot of researches, but couldn't find an answer.<br> If I change <strong>allplayer</strong> with <strong>http</strong> everything works fine.<br> From <a href="https://stackoverflow.com/a/6139783/1503155">this link</a>, I learnt that it is not recommended to use your own schemes.<br> Does that mean your own schemes wont work?<br> The person <a href="https://stackoverflow.com/q/3469908/1503155">here</a> is using his own scheme, and from his feedback it seems that it is working.<br> Am I missing something?<br></p>
13,044,911
1
4
null
2012-10-24 02:43:30.827 UTC
9
2018-07-04 10:00:59.773 UTC
2018-07-04 10:00:59.773 UTC
null
1,503,155
null
1,503,155
null
1
17
android|android-intent
20,037
<p>It took me 6 hours to figure out the problem. Somehow setting the exported to false caused all the problem: <code>android:exported="false"</code>. When I set it to true, it worked like a charm.</p> <p>Funny because I put it there in the first place to avoid the <code>Exported activity does not require permission</code> warning. Setting it back to true, brought back the warning, but it is working now.</p> <p>Solution is below. Hope it will help others save time.</p> <pre><code>&lt;activity android:name=".MainActivity" android:label="@string/title_activity_main" android:exported="true"&gt; &lt;intent-filter&gt; &lt;data android:scheme="allplayer" /&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre>
13,215,716
IOError: [Errno 13] Permission denied when trying to open hidden file in "w" mode
<p>I want to replace the contents of a hidden file, so I attempted to open it in <code>w</code> mode so it would be erased/truncated:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ini_path = '.picasa.ini' &gt;&gt;&gt; os.path.exists(ini_path) True &gt;&gt;&gt; os.access(ini_path, os.W_OK) True &gt;&gt;&gt; ini_handle = open(ini_path, 'w') </code></pre> <p>But this resulted in a traceback:</p> <pre><code>IOError: [Errno 13] Permission denied: '.picasa.ini' </code></pre> <p>However, I was able to achieve the intended result with <code>r+</code> mode:</p> <pre><code>&gt;&gt;&gt; ini_handle = open(ini_path, 'r+') &gt;&gt;&gt; ini_handle.truncate() &gt;&gt;&gt; ini_handle.write(ini_new) &gt;&gt;&gt; ini_handle.close() </code></pre> <p><strong>Q.</strong> What is the difference between the <code>w</code> and <code>r+</code> modes, such that one has "permission denied" but the other works fine?</p> <p><strong>UPDATE:</strong> I am on win7 x64 using Python 2.6.6, and the target file has its hidden attribute set. When I tried turning off the hidden attribute, <code>w</code> mode succeeds. But when I turn it back on, it fails again.</p> <p><strong>Q.</strong> Why does <code>w</code> mode fail on hidden files? Is this known behaviour?</p>
13,215,998
3
0
null
2012-11-04 03:08:58.643 UTC
8
2020-09-02 02:33:14.527 UTC
2012-11-04 05:21:26.607 UTC
null
1,796,587
null
1,796,587
null
1
30
python|windows|winapi|file-io|hidden-files
86,334
<p>It's just how the Win32 API works. Under the hood, Python's <code>open</code> function is calling the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx"><code>CreateFile</code></a> function, and if that fails, it translates the Windows error code into a Python <code>IOError</code>.</p> <p>The <code>r+</code> open mode corresponds to a <code>dwAccessMode</code> of <code>GENERIC_READ|GENERIC_WRITE</code> and a <code>dwCreationDisposition</code> of <code>OPEN_EXISTING</code>. The <code>w</code> open mode corresponds to a <code>dwAccessMode</code> of <code>GENERIC_WRITE</code> and a <code>dwCreationDisposition</code> of <code>CREATE_ALWAYS</code>.</p> <p>If you carefully read the remarks in the <code>CreateFile</code> documentation, it says this:</p> <blockquote> <p>If <code>CREATE_ALWAYS</code> and <code>FILE_ATTRIBUTE_NORMAL</code> are specified, <code>CreateFile</code> fails and sets the last error to <code>ERROR_ACCESS_DENIED</code> if the file exists and has the <code>FILE_ATTRIBUTE_HIDDEN</code> or <code>FILE_ATTRIBUTE_SYSTEM</code> attribute. To avoid the error, specify the same attributes as the existing file.</p> </blockquote> <p>So if you were calling <code>CreateFile</code> directly from C code, the solution would be to add in <code>FILE_ATTRIBUTE_HIDDEN</code> to the <code>dwFlagsAndAttributes</code> parameter (instead of just <code>FILE_ATTRIBUTE_NORMAL</code>). However, since there's no option in the Python API to tell it to pass in that flag, you'll just have to work around it by either using a different open mode or making the file non-hidden.</p>
13,085,024
Reset a model with angular.js
<p>I'm simply try to reset values like this :</p> <pre><code>$scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } </code></pre> <p>But it doesn't produce anything, any idea to fix it ? </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('app', []).controller('MyCtrl', function($scope) { $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app" ng-controller="MyCtrl"&gt; &lt;div ng-repeat="data in datas"&gt; &lt;input type="text" ng-model="data.data1" /&gt; &lt;input type="text" ng-model="data.data2" /&gt; &lt;/div&gt; &lt;a ng-click="reset()"&gt;Reset to initial value&lt;/a&gt; or &lt;button ng-click="name = initial"&gt;Reset to initial value&lt;/button&gt; &lt;hr /&gt; &lt;p ng-repeat="data in datas"&gt;{{data.data1}}, {{data.data2}}&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>There is a working example on <a href="http://jsfiddle.net/fmzzs/4/" rel="noreferrer">jsfiddle</a></p>
13,093,219
7
0
null
2012-10-26 10:18:14.387 UTC
12
2016-01-18 07:13:16.003 UTC
2016-01-18 07:13:16.003 UTC
null
863,110
null
616,095
null
1
35
javascript|angularjs
76,304
<p>This is really a question about JavaScript (so I added the "javascript" tag). When a JavaScript object (such as array $scope.initial) is assigned to a variable, it is assigned by reference, not by copy. So, this statement</p> <pre><code>$scope.datas= $scope.initial; </code></pre> <p>results in $scope.datas pointing to the $scope.initial object. Any changes that are made to $scope.datas or $scope.initial both affect the same (single) object. Since ng-model is used to data-bind object elements data1 and data2, any changes to the text inputs will change the data1 and data2 elements of the object that $scope.datas references -- i.e., $scope.initial. To see this in action, add the following to your fiddle's HTML:</p> <pre><code>&lt;p&gt;{{initial}}&lt;/p&gt; </code></pre> <p>When you change the values in the text boxes, you'll see that $scope.initial is also changing.</p> <p>@Max provided a partial answer: use angular.copy() in the reset function. However, you'll also have to use angular.copy() in the initial assignment too:</p> <pre><code> $scope.datas = angular.copy($scope.initial); </code></pre> <hr> <p>Update:</p> <p>As @EpokK shows in his answer, an alternate solution is</p> <pre><code>angular.copy($scope.initial, $scope.datas); </code></pre> <p>As @bekite mentions in his answer, @EpokK's solution does not create another object.</p> <p><strong>The full code</strong> <div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('app', []).controller('MyCtrl', function($scope) { $scope.initial = [{ data1: 10, data2: 20 }]; $scope.datas = angular.copy($scope.initial); $scope.reset = function () { $scope.datas = angular.copy($scope.initial); // or // angular.copy($scope.initial, $scope.datas); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app" ng-controller="MyCtrl"&gt; &lt;div ng-repeat="data in datas"&gt; &lt;input type="text" ng-model="data.data1" /&gt; &lt;input type="text" ng-model="data.data2" /&gt; &lt;/div&gt; &lt;a ng-click="reset()"&gt;Reset to initial value&lt;/a&gt; or &lt;hr /&gt; &lt;p ng-repeat="data in datas"&gt;{{data.data1}}, {{data.data2}}&lt;/p&gt;{{initial}} &lt;/div&gt;</code></pre> </div> </div> </p> <p><kbd><a href="http://jsfiddle.net/wgR5c/1" rel="noreferrer">fiddle</a></kbd></p>
30,511,864
IHttpActionResult and helper methods in ASP.NET Core
<p>I'm trying to move my web api 2 project to ASP.NET 5. But I have many elements that are not present anymore.</p> <p>For example <code>IHttpActionResult</code> or <code>Ok(), NotFound()</code> methods. Or <code>RoutePrefix</code>[]</p> <p>Should I change every <code>IHttpActionResult</code> with <code>IActionResult</code> ? Change <code>Ok</code>() with <code>new ObjectResult</code> ? (is it the same ?)</p> <p>What about <code>HttpConfiguration</code> that seems no more present in startup.cs ?</p>
31,973,951
3
6
null
2015-05-28 16:10:08.877 UTC
7
2020-01-17 00:25:52.323 UTC
2016-06-20 22:05:17.397 UTC
null
990,356
null
491,723
null
1
49
asp.net-web-api|owin|asp.net-core
33,132
<p><code>IHttpActionResult</code> is now effectively <code>IActionResult</code>, and to return an <code>Ok</code> with a return object, you'd use <code>return new ObjectResult(...);</code></p> <p>So effectively something like this:</p> <pre><code>public IActionResult Get(int id) { if (id == 1) return HttpNotFound("not found!"); return new ObjectResult("value: " + id); } </code></pre> <p>Here's a good article with more detail:</p> <p><a href="http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6">http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6</a></p>
10,865,957
printf with std::string?
<p>My understanding is that <code>string</code> is a member of the <code>std</code> namespace, so why does the following occur?</p> <pre><code>#include &lt;iostream&gt; int main() { using namespace std; string myString = "Press ENTER to quit program!"; cout &lt;&lt; "Come up and C++ me some time." &lt;&lt; endl; printf("Follow this command: %s", myString); cin.get(); return 0; } </code></pre> <p><img src="https://i.stack.imgur.com/W1w68.png" alt="enter image description here"></p> <p>Each time the program runs, <code>myString</code> prints a seemingly random string of 3 characters, such as in the output above.</p>
10,865,967
8
3
null
2012-06-02 21:07:06.06 UTC
52
2022-02-03 15:59:17.287 UTC
2019-03-14 16:20:54.773 UTC
null
1,671,066
null
336,929
null
1
195
c++|string|namespaces|printf|std
461,745
<p>It's compiling because <code>printf</code> isn't type safe, since it uses variable arguments in the C sense<sup>1</sup>. <code>printf</code> has no option for <code>std::string</code>, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.</p> <p>The easiest way to fix this, since you're using C++, is printing it normally with <code>std::cout</code>, since <code>std::string</code> supports that through operator overloading:</p> <pre><code>std::cout &lt;&lt; "Follow this command: " &lt;&lt; myString; </code></pre> <p>If, for some reason, you need to extract the C-style string, you can use the <code>c_str()</code> method of <code>std::string</code> to get a <code>const char *</code> that is null-terminated. Using your example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdio.h&gt; int main() { using namespace std; string myString = "Press ENTER to quit program!"; cout &lt;&lt; "Come up and C++ me some time." &lt;&lt; endl; printf("Follow this command: %s", myString.c_str()); //note the use of c_str cin.get(); return 0; } </code></pre> <p>If you want a function that is like <code>printf</code>, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one <a href="https://web.archive.org/web/20131018185034/http://www.generic-programming.org/~dgregor/cpp/variadic-templates.html" rel="noreferrer">here</a>. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically <a href="http://www.boost.org/doc/libs/1_49_0/libs/format/" rel="noreferrer"><code>boost::format</code></a>.</p> <hr> <p>[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of <code>printf</code>, that means a string with encoded type information like <code>%d</code> meaning <code>int</code>. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.</p>
16,949,248
UITableViewCell bad performance with AutoLayout
<p>I'm somewhat stuck with this one… any help is very appreciated. I've already spent lots of time debugging this.</p> <p>I've got <code>UITableView</code> with data source provided by <code>NSFetchedResultsController</code>. In a separate view controller I insert new records to the CoreData using <code>[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]</code>, save the managed object context and dismiss that controller. Very standard stuff.</p> <p>The changes in managed object context are then received by <code>NSFetchedResultsController</code>:</p> <pre><code>- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.tableView beginUpdates]; } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { switch (type) { case NSFetchedResultsChangeInsert: [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; break; case NSFetchedResultsChangeUpdate: [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; break; case NSFetchedResultsChangeMove: [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone]; break; } } </code></pre> <p>And this is where the problem appears — it takes too long(about 3-4 seconds on an iPhone 4) to do that. And it seems like the time is spent calculating layout for the cells.</p> <p>I've stripped everything from the cell(including custom subclass) and left it with just <code>UILabel</code>, but nothing changed. Then I've changed the style of the cell to Basic(or anything except Custom) and the problem disappeared — new cells are added instantaneously.</p> <p>I've doubled checked and <code>NSFetchedResultsControllerDelegate</code> callbacks are called only once. If I ignore them and do <code>[UITableView reloadSections:withRowAnimation:]</code>, nothing changes — it is still very slow.</p> <p>It seems to me like Auto Layout is disabled for the default cell styles, which makes them very fast. But if that is the case — why does everything loads quickly when I push the <code>UITableViewController</code>?</p> <p>Here's the call trace for that problem: <img src="https://i.stack.imgur.com/z2hCd.png" alt="stack trace"></p> <p>So the question is — what is going on here? Why are cells being rendered so slowly?</p> <p><strong>UPDATE 1</strong></p> <p>I've built a very simple demo app that illustrates the problem I'm having. here's the source — <a href="https://github.com/antstorm/UITableViewCellPerformanceProblem" rel="noreferrer">https://github.com/antstorm/UITableViewCellPerformanceProblem</a></p> <p>Try adding at least a screenful of cells to feel the performance problems.</p> <p>Also note that adding a row directly ("Insert now!" button) is not causing any slowness.</p>
17,067,676
5
6
null
2013-06-05 20:29:37.173 UTC
16
2015-01-01 01:57:10.123 UTC
2013-06-09 09:08:23.817 UTC
null
883,019
null
883,019
null
1
19
iphone|ios|performance|uitableview|autolayout
9,382
<p>Ok, I finally got around this problem without sacrificing animation. My solution is to implement <code>UITableViewCell</code>'s interface in a separate Nib file with AutoLayout disabled. It takes a little bit longer to load and you need to positions subviews yourself.</p> <p>Here's the code to make it possible:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; ... UINib *rowCellNib = [UINib nibWithNibName:@"RowCell" bundle:nil]; [self.tableView registerNib:rowCellNib forCellReuseIdentifier:@"ROW_CELL"]; } </code></pre> <p>Of course you'll need a RowCell.nib file with your cell's view.</p> <p>While there's no solution to the original problem(which clearly seems a bug to me), I'm using this one.</p>
16,782,990
Rails -- how to populate parent object id using nested attributes for child object and strong parameters?
<p>I've got a situation much like is presented in <a href="http://railscasts.com/episodes/196-nested-model-form-part-1" rel="noreferrer">Railscast 196-197: Nested Model Form</a>. However, I've encountered a conflict between this approach and strong parameters. I can't figure out a good way to populate the parent record id field on the child object, since I don't want that to be assignable through the form (to prevent users from associating child records to parent records they don't own). I have a solution (see code below) but this seems like the kind of thing Rails might have a clever, easy way to do for me.</p> <p>Here's the code...</p> <p>There's a parent object (call it Survey) that has_many child objects (call them Questions):</p> <pre><code># app/models/survey.rb class Survey belongs_to :user has_many :questions accepts_nested_attributes_for :questions end # app/models/question.rb class Question validates :survey_id, :presence =&gt; true belongs_to :survey end </code></pre> <p>There's a form that allows users to create a survey and the questions on that survey at the same time (for simplicity, the code below treats surveys as though they have only question):</p> <pre><code># app/views/surveys/edit.html.erb &lt;%= form_for @survey do |f| %&gt; &lt;%= f.label :name %&gt; &lt;%= f.text_field :name %&gt;&lt;br /&gt; &lt;%= f.fields_for :questions do |builder| %&gt; &lt;%= builder.label :content, "Question" %&gt; &lt;%= builder.text_area :content, :rows =&gt; 3 %&gt;&lt;br /&gt; &lt;% end %&gt; &lt;%= f.submit "Submit" %&gt; &lt;% end %&gt; </code></pre> <p>The problem is the controller. I want to protect the survey_id field on the question record via strong parameters, but in doing so the questions don't pass validation, since the survey_id is a required field.</p> <pre><code># app/controllers/surveys_controller.rb class SurveysController def edit @survey = Survey.new Survey.questions.build end def create @survey = current_user.surveys.build(survey_params) if @survey.save redirect_to @survey else render :new end end private def survey_params params.require(:survey).permit(:name, :questions_attributes =&gt; [:content]) end end </code></pre> <p>The only way I can think to solve this problem is to build the questions separately from the survey like this:</p> <pre><code>def create @survey = current_user.surveys.build(survey_params) if @survey.save if params[:survey][:questions_attributes] params[:survey][:questions_attributes].each_value do |q| question_params = ActionController::Parameters.new(q) @survey.questions.build(question_params.permit(:content)) end end redirect_to @survey else render :new end end private def survey_params params.require(:survey).permit(:name) end </code></pre> <p>(Rails 4 beta 1, Ruby 2)</p> <p><strong>UPDATE</strong></p> <p>Perhaps the best way to handle this problem is to factor out a "Form object" as suggested in <a href="http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/" rel="noreferrer">this Code Climate blog post</a>. I'm leaving the question open, though, as I'm curious to other points of view</p>
17,255,991
1
1
null
2013-05-28 02:31:04.163 UTC
13
2013-06-22 22:39:28.677 UTC
2013-06-04 18:09:54.467 UTC
null
1,700,875
null
1,700,875
null
1
36
ruby-on-rails|strong-parameters
12,339
<p>So the problem you are running into is that the child objects don't pass validation, right? When the child objects are created at the same time as the parent, the child objects could not possibly know the id of their parent in order to pass validation, it's true.</p> <p>Here is how you can solve that problem. Change your models as follows:</p> <pre><code># app/models/survey.rb class Survey belongs_to :user has_many :questions, :inverse_of =&gt; :survey accepts_nested_attributes_for :questions end # app/models/question.rb class Question validates :survey, :presence =&gt; true belongs_to :survey end </code></pre> <p>The differences here are the <code>:inverse_of</code> passed to the <code>has_many</code> association, and that the Question now validates on just <code>:survey</code> instead of <code>:survey_id</code>.</p> <p><code>:inverse_of</code> makes it so that when a child object is created or built using the association, it also receives a back-reference to the parent who created it. This seems like something that should happen automagically, but it unfortunately does not unless you specify this option.</p> <p>Validating on <code>:survey</code> instead of on <code>:survey_id</code> is kind of a compromise. The validation is no longer simply checking for the existence of something non-blank in the survey_id field; it now actually checks the association for the existence of a parent object. In this case it is helpfully known due to <code>:inverse_of</code>, but in other cases it will actually have to load the association from the database using the id in order to validate. This also means that ids not matching anything in the database will not pass validation.</p> <p>Hope that helps.</p>
16,910,057
How to paste columns from separate files using bash?
<p>Using the following data:</p> <pre><code>$cat date1.csv Bob,2013-06-03T17:18:07 James,2013-06-03T17:18:07 Kevin,2013-06-03T17:18:07 $cat date2.csv 2012-12-02T18:30:31 2012-12-02T18:28:37 2013-06-01T12:16:05 </code></pre> <p>How can date1.csv and date2.csv files be merged? Output desired:</p> <pre><code>$cat merge-date1-date2.csv Bob,2013-06-03T17:18:07,2012-12-02T18:30:31 James,2013-06-03T17:18:07,2012-12-02T18:28:37 Kevin,2013-06-03T17:18:07,2013-06-01T12:16:05 </code></pre> <p>Please note: the best solution will be able to quickly manage a massive number of lines. </p>
16,910,076
4
3
null
2013-06-04 04:54:54.603 UTC
10
2019-07-30 10:05:33.247 UTC
null
null
null
null
2,322,417
null
1
46
bash|paste|multiple-columns
92,458
<p>You were on track with <a href="http://www.manpagez.com/man/1/paste/" rel="noreferrer"><code>paste(1)</code></a>:</p> <pre><code>$ paste -d , date1.csv date2.csv Bob,2013-06-03T17:18:07,2012-12-02T18:30:31 James,2013-06-03T17:18:07,2012-12-02T18:28:37 Kevin,2013-06-03T17:18:07,2013-06-01T12:16:05 </code></pre> <p>It's a bit unclear from your question if there are leading spaces on those lines. If you want to get rid of that in the final output, you can use <a href="http://www.manpagez.com/man/1/cut/" rel="noreferrer"><code>cut(1)</code></a> to snip it off before pasting:</p> <pre><code> $ cut -c 2- date2.csv | paste -d , date1.csv - Bob,2013-06-03T17:18:07,2012-12-02T18:30:31 James,2013-06-03T17:18:07,2012-12-02T18:28:37 Kevin,2013-06-03T17:18:07,2013-06-01T12:16:05 </code></pre>
17,114,904
python pandas replacing strings in dataframe with numbers
<p>Is there any way to use the mapping function or something better to replace values in an entire dataframe?</p> <p>I only know how to perform the mapping on series.</p> <p>I would like to replace the strings in the 'tesst' and 'set' column with a number for example set = 1, test =2</p> <p>Here is a example of my dataset: (Original dataset is very large)</p> <pre><code>ds_r respondent brand engine country aware aware_2 aware_3 age tesst set 0 a volvo p swe 1 0 1 23 set set 1 b volvo None swe 0 0 1 45 set set 2 c bmw p us 0 0 1 56 test test 3 d bmw p us 0 1 1 43 test test 4 e bmw d germany 1 0 1 34 set set 5 f audi d germany 1 0 1 59 set set 6 g volvo d swe 1 0 0 65 test set 7 h audi d swe 1 0 0 78 test set 8 i volvo d us 1 1 1 32 set set </code></pre> <p>Final result should be</p> <pre><code> ds_r respondent brand engine country aware aware_2 aware_3 age tesst set 0 a volvo p swe 1 0 1 23 1 1 1 b volvo None swe 0 0 1 45 1 1 2 c bmw p us 0 0 1 56 2 2 3 d bmw p us 0 1 1 43 2 2 4 e bmw d germany 1 0 1 34 1 1 5 f audi d germany 1 0 1 59 1 1 6 g volvo d swe 1 0 0 65 2 1 7 h audi d swe 1 0 0 78 2 1 8 i volvo d us 1 1 1 32 1 1 </code></pre>
17,115,229
9
0
null
2013-06-14 18:20:02.803 UTC
13
2021-12-02 05:17:25.83 UTC
2021-12-02 05:17:25.83 UTC
null
7,508,700
null
2,219,369
null
1
56
python|replace|dataframe|pandas
129,970
<p>What about <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>DataFrame.replace</code></a>?</p> <pre><code>In [9]: mapping = {'set': 1, 'test': 2} In [10]: df.replace({'set': mapping, 'tesst': mapping}) Out[10]: Unnamed: 0 respondent brand engine country aware aware_2 aware_3 age \ 0 0 a volvo p swe 1 0 1 23 1 1 b volvo None swe 0 0 1 45 2 2 c bmw p us 0 0 1 56 3 3 d bmw p us 0 1 1 43 4 4 e bmw d germany 1 0 1 34 5 5 f audi d germany 1 0 1 59 6 6 g volvo d swe 1 0 0 65 7 7 h audi d swe 1 0 0 78 8 8 i volvo d us 1 1 1 32 tesst set 0 2 1 1 1 2 2 2 1 3 1 2 4 2 1 5 1 2 6 2 1 7 1 2 8 2 1 </code></pre> <p>As @Jeff pointed out in the comments, in pandas versions &lt; 0.11.1, manually tack <code>.convert_objects()</code> onto the end to properly convert tesst and set to <code>int64</code> columns, in case that matters in subsequent operations.</p>
16,944,894
C++ Lambdas: Difference between "mutable" and capture-by-reference
<p>In C++ you can declare lambdas for example like this:</p> <pre><code>int x = 5; auto a = [=]() mutable { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; }; auto b = [&amp;]() { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; }; </code></pre> <p>Both let me modify <code>x</code>, so what is the difference?</p>
16,944,895
1
0
null
2013-06-05 16:15:08.847 UTC
18
2018-11-08 22:15:52.53 UTC
2013-06-05 18:36:18.68 UTC
null
1,149,664
null
76,722
null
1
72
c++|c++11|lambda
9,661
<h2>What is happening</h2> <p>The first will only modify its own copy of <code>x</code> and leave the outside <code>x</code> unchanged. The second will modify the <em>outside <code>x</code></em>.</p> <p>Add a print statement after trying each:</p> <pre><code>a(); std::cout &lt;&lt; x &lt;&lt; "----\n"; b(); std::cout &lt;&lt; x &lt;&lt; '\n'; </code></pre> <p>This is expected to print:</p> <pre><code>6 5 ---- 6 6 </code></pre> <h2>Why</h2> <p>It may help to consider that lambda </p> <blockquote> <p>[...] expressions provide a concise way to create simple function objects </p> </blockquote> <p><sup>(see [expr.prim.lambda] of the Standard)</sup></p> <p>They have </p> <blockquote> <p>[...] a public inline function call operator [...]</p> </blockquote> <p>which is declared as a <code>const</code> member function, but only </p> <blockquote> <p>[...] if and only if the lambda expression’s <em>parameter-declaration-clause</em> is not followed by <code>mutable</code></p> </blockquote> <p>You can think of as if </p> <pre><code> int x = 5; auto a = [=]() mutable { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; }; ==&gt; int x = 5; class __lambda_a { int x; public: __lambda_a () : x($lookup-one-outer$::x) {} inline void operator() { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; } } a; </code></pre> <p>and</p> <pre><code> auto b = [&amp;]() { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; }; ==&gt; int x = 5; class __lambda_b { int &amp;x; public: __lambda_b() : x($lookup-one-outer$::x) {} inline void operator() const { ++x; std::cout &lt;&lt; x &lt;&lt; '\n'; } // ^^^^^ } b; </code></pre> <p><strong>Q:</strong> But if it is a <code>const</code> function, why can I still change <code>x</code>?</p> <p><strong>A:</strong> You are only changing <em>the outside <code>x</code></em>. The lambda's own <code>x</code> is a reference, and the operation <code>++x</code> does not modify <em>the reference</em>, but <em>the refered value</em>. </p> <p>This works because in C++, the constness of a pointer/reference does not change the constness of the pointee/referencee seen through it.</p>
16,589,519
Use css gradient over background image
<p>I've been trying to use a linear gradient on top of my background image in order to get a fading effect on the bottom of my background from black to transparent but can't seem to be able to make it show.</p> <p>I've read other cases here and examples but none of them are working for me. I can only see the gradient or the image but not both of them. Here's the <a href="http://nazer.urucas.com/">link</a></p> <p>Just click on the first logo, ignore that effect, what I'm trying is in the body in the whole site after that.</p> <p>This is my css code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: url('http://www.skrenta.com/images/stackoverflow.jpg') no-repeat, -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 1))); }</code></pre> </div> </div> </p>
16,590,040
4
4
null
2013-05-16 14:00:01.41 UTC
17
2022-08-19 19:52:11.963 UTC
2015-05-28 20:26:20.087 UTC
null
6,999,690
null
510,106
null
1
74
html|css|gradient
193,565
<p>Ok, I solved it by adding the url for the background image <strong>at the end of the line</strong>.</p> <p>Here's my working code:</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>.css { background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="css"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
16,670,931
Hide scroll bar, but while still being able to scroll
<p>I want to be able to scroll through the whole page, but without the scrollbar being shown.</p> <p>In Google Chrome it's:</p> <pre><code>::-webkit-scrollbar { display: none; } </code></pre> <p>But Mozilla Firefox and Internet Explorer don't seem to work like that.</p> <p>I also tried this in CSS:</p> <pre><code>overflow: hidden; </code></pre> <p>That does hide the scrollbar, but I can't scroll any more.</p> <p>Is there a way I can remove the scrollbar while still being able to scroll the whole page?</p> <p>With just CSS or HTML, please.</p>
16,671,476
41
2
null
2013-05-21 13:11:37.403 UTC
507
2022-08-02 05:53:08.743 UTC
2019-11-10 11:47:50.093 UTC
null
63,550
null
2,215,528
null
1
1,669
html|css|google-chrome|internet-explorer|firefox
2,378,998
<p>Just a test which is working fine.</p> <pre class="lang-css prettyprint-override"><code>#parent{ width: 100%; height: 100%; overflow: hidden; } #child{ width: 100%; height: 100%; overflow-y: scroll; padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */ box-sizing: content-box; /* So the width will be 100% + 17px */ } </code></pre> <p><strong><a href="http://jsfiddle.net/5GCsJ/954/" rel="noreferrer">Working Fiddle</a></strong></p> <h3>JavaScript:</h3> <p>Since the scrollbar width differs in different browsers, it is better to handle it with JavaScript. If you do <code>Element.offsetWidth - Element.clientWidth</code>, the exact scrollbar width will show up.</p> <p><strong><a href="http://jsfiddle.net/5GCsJ/4713/" rel="noreferrer">JavaScript Working Fiddle</a></strong></p> <h2>Or</h2> <p>Using <code>Position: absolute</code>,</p> <pre class="lang-css prettyprint-override"><code>#parent{ width: 100%; height: 100%; overflow: hidden; position: relative; } #child{ position: absolute; top: 0; bottom: 0; left: 0; right: -17px; /* Increase/Decrease this value for cross-browser compatibility */ overflow-y: scroll; } </code></pre> <p><strong><a href="http://jsfiddle.net/5GCsJ/2125/" rel="noreferrer">Working Fiddle</a></strong></p> <p><a href="http://jsfiddle.net/5GCsJ/4714/" rel="noreferrer"><strong>JavaScript Working Fiddle</strong></a></p> <h3>Information:</h3> <p>Based on this answer, I created a <a href="https://github.com/kamlekar/slim-scroll" rel="noreferrer">simple scroll plugin</a>.</p>
25,707,441
Why does std::declval add a reference?
<p><a href="http://en.cppreference.com/w/cpp/utility/declval"><code>std::declval</code></a> is a compile-time utility used to construct an expression for the purpose of determining its type. It is defined like this:</p> <pre><code>template&lt; class T &gt; typename std::add_rvalue_reference&lt;T&gt;::type declval() noexcept; </code></pre> <p>Would this not be simpler instead?</p> <pre><code>template&lt; class T &gt; T declval() noexcept; </code></pre> <p>What is the advantage of a reference return type? And shouldn't it be called <code>declref</code>?</p> <p>The earliest historical example I find is <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2958.html#Value">n2958</a>, which calls the function <code>value()</code> but already always returns a reference.</p> <p>Note, the operand of <code>decltype</code> does not need to have an accessible destructor, i.e. it is not semantically checked as a full-expression.</p> <pre><code>template&lt; typename t &gt; t declprval() noexcept; class c { ~ c (); }; decltype ( declprval&lt; c &gt;() ) * p = nullptr; // OK </code></pre>
25,707,702
3
7
null
2014-09-07 05:44:57.13 UTC
12
2022-09-16 19:26:38.193 UTC
2022-09-16 19:26:38.193 UTC
null
5,825,294
null
153,285
null
1
49
c++|c++11|templates|decltype|declval
4,921
<p>The "no temporary is introduced for function returning prvalue of object type in <code>decltype</code>" rule applies only if the function call itself is either the operand of <code>decltype</code> or the right operand of a comma operator that's the operand of <code>decltype</code> (§5.2.2 [expr.call]/p11), which means that given <code>declprval</code> in the OP,</p> <pre><code>template&lt; typename t &gt; t declprval() noexcept; class c { ~ c (); }; int f(c &amp;&amp;); decltype(f(declprval&lt;c&gt;())) i; // error: inaccessible destructor </code></pre> <p>doesn't compile. More generally, returning <code>T</code> would prevent most non-trivial uses of <code>declval</code> with incomplete types, type with private destructors, and the like:</p> <pre><code>class D; int f(D &amp;&amp;); decltype(f(declprval&lt;D&gt;())) i2; // doesn't compile. D must be a complete type </code></pre> <p>and doing so has little benefit since xvalues are pretty much indistinguishable from prvalues except when you use <code>decltype</code> on them, and you don't usually use <code>decltype</code> directly on the return value of <code>declval</code> - you know the type already.</p>
4,490,454
How to take a screenshot in Java?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/58305/is-there-a-way-to-take-a-screenshot-using-java-and-save-it-to-some-sort-of-image">Is there a way to take a screenshot using Java and save it to some sort of image?</a> </p> </blockquote> <p>How to take a screenshot in Java?</p>
4,490,471
2
1
null
2010-12-20 14:19:27.547 UTC
19
2021-05-06 16:49:27.31 UTC
2017-05-23 12:02:14.733 UTC
null
-1
null
548,730
null
1
50
java
100,638
<p>Use <a href="http://download.oracle.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture%28java.awt.Rectangle%29" rel="noreferrer"><code>Robot#createScreenCapture()</code></a>.</p> <pre><code>BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "png", new File("/screenshot.png")); </code></pre>
26,802,581
Can anyone identify this encoding?
<p>Im working on a program to interface with some hardware that is sending data that has been encoded and wrapped to send within a CDATA block in an XML document.</p> <p>the software in the device as far as I know is written in Python and i'm writing the interface in Delphi.</p> <p>the data the device sends is this</p> <blockquote> <p>\x00E\x18\x10\x14}*UF!A\x81\xac\x08&amp;\x02\x01\n\x15\x1a\xc2PP\x92\x17\xc2\xc1\xa0\x0e\x1a\xc2\xd0K\x94\'\x830\x11\x8b \x84a_\xa0+\x04\x81\x17\x89\x15D\x91B\x05.\x84\xf1\x1b\x89%E\x00\x04\x9c\x0e\xc5\xc1=\x87\x0bE\xf18\x07\x1f\xc8a\xa5\x95\x08H\x80?\x84\x18\tPK\x8a$\t\xf1\xb2\x8e(J\xb0\x08\x91\x1eJ\xf0W\x0c-\x0b\xf0\x0e\x88\x07\x0c\x00\x9b\n \x910Z\x06!\x92\xf0W\x073S \x08\x87\xff\xff\xff\xf0\x0e\xff\xff\xff\xff\xff\xf3\x10\x0e\xba\xff\xff\xff\xf4C \xed\xbb\xb9_\xffDD1\r\xcb\xbaw\xf5TD2\xed\xbb\xba\x88EUDB\x0c\xba\xaa\x99UUDB\x0c\xba\xaa\xa9UUD2\r\xbb\xaa\xaaUTD2\r\xcb\xbb\xaaUTC!\r\xcb\xbb\xbbUD3!\x0e\xdc\xbb\xbbDD3!\x0e\xdc\xcc\xbbDC2!\x0e\xdc\xcc\xcc33"\x11\x0e\xdd\xcc\xccC3"\x11\x0e\xed\xdc\xcc\xf33!\x10\x0e\xee\xdd\xcc\xf32!\x10\x0e\xee\xdd\xdc\xff2!\x10\x00\xee\xee\xdd\xff\xf2!\x11\x00\x0e\xee\xdd\xff\xf2!\x11\x10\x0e\xee\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00</p> </blockquote> <p>I need to be able to send similar data back to the device but the format i have it in is this </p> <blockquote> <p>0x451C0E148A4A65781B0291080E1644B0680B340580A28615C9001E8F1EC9F0559D260A4147901A0AF16D93304BC09A8523CC513E25218CA00CD42C0CE137891FCDB02397054DD07C04124E112408158E5124841E0ED17F8E28CEE12C96284F511B231C8FB07C1228D09079BD31D090960B2050B075871CD1217B8D171131830B3552509A8E295271621D2E9271AD972ED371AB93FFFCDFFFFFFFFFFFFCDDFFFFFFFFFFBCCDE0122FFFFFBCCDE01123FFFBBBCDE011234FFAABCDE001233FFAABCCE001234FFAAABCDE01234FFAAABCDE01234FFAAAABCE01344FAAA99ABE12344FAAA99ABE124555FAA99AAC044555FAA9999A96655FFAA9989998765FFAA98899BB855FFAA9999ABBD45FFAA9999ABCD34FAAA999AABCD345FAAA999BBCD33F000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</p> </blockquote> <p>I know that \x is usually used to represent ascii chars using their hex values in 2 digit pairs but looking at the data this not the case. i'm struggling to identify the encoding used and the manufacturer is not providing much help.</p> <p>what I want to know is how do I convert the hex I have to the format they are using in Delphi xe4?</p> <p><strong>BTW the two block do not contain the same data but it is the same type of data ie the format is the same just different encoding</strong></p> <p>example of the data being sent</p> <pre><code>POST ******** HTTP/1.1 Host: 172.16.1.136:8080 Accept-Encoding: identity Content-Length: 1552 Content-Type: text/xml Authorization: 1344354:PASS User-Agent: ********* &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Biometrics&gt; &lt;Templates&gt; &lt;Template badge="1075" readerType="6" index="6" ts="2014-11-06T17:28:40.000+01:00" chk="3a6a4924ec04e668186b15e244e6fe73"&gt; &lt;![CDATA[ ['1075_6', 1415294920.3754971, [0, 0], [['3\x04\x00\x00\x00P\x00\x00E\x18\x10\x14}*UF!A\x81\xac\x08&amp;\x02\x01\n\x15\x1a\xc2PP\x92\x17\xc2\xc1\xa0\x0e\x1a\xc2\xd0K\x94\'\x830\x11\x8b \x84a_\xa0+\x04\x81\x17\x89\x15D\x91B\x05.\x84\xf1\x1b\x89%E\x00\x04\x9c\x0e\xc5\xc1=\x87\x0bE\xf18\x07\x1f\xc8a\xa5\x95\x08H\x80?\x84\x18\tPK\x8a$\t\xf1\xb2\x8e(J\xb0\x08\x91\x1eJ\xf0W\x0c-\x0b\xf0\x0e\x88\x07\x0c\x00\x9b\n \x910Z\x06!\x92\xf0W\x073S \x08\x87\xff\xff\xff\xf0\x0e\xff\xff\xff\xff\xff\xf3\x10\x0e\xba\xff\xff\xff\xf4C \xed\xbb\xb9_\xffDD1\r\xcb\xbaw\xf5TD2\xed\xbb\xba\x88EUDB\x0c\xba\xaa\x99UUDB\x0c\xba\xaa\xa9UUD2\r\xbb\xaa\xaaUTD2\r\xcb\xbb\xaaUTC!\r\xcb\xbb\xbbUD3!\x0e\xdc\xbb\xbbDD3!\x0e\xdc\xcc\xbbDC2!\x0e\xdc\xcc\xcc33"\x11\x0e\xdd\xcc\xccC3"\x11\x0e\xed\xdc\xcc\xf33!\x10\x0e\xee\xdd\xcc\xf32!\x10\x0e\xee\xdd\xdc\xff2!\x10\x00\xee\xee\xdd\xff\xf2!\x11\x00\x0e\xee\xdd\xff\xf2!\x11\x10\x0e\xee\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']]] ]]&gt; &lt;/Template&gt; &lt;/Templates&gt; &lt;/Biometrics&gt; HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/xml;charset=ISO-8859-1 Transfer-Encoding: chunked Date: Thu, 06 Nov 2014 17:28:41 GMT 52 &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;OperationStatus uid=""&gt;OK&lt;/OperationStatus&gt; 0 </code></pre> <p>These are biometric templates used by the Suprema Reader if that helps.</p> <p><strong>Solution</strong></p> <p>I have successfully deciphered what is going on with this now. to turn my original hex string into the required format I'm using this code, hope this helps someone else in the future. Please feel free to comment and make suggestions to improve the code.</p> <pre><code>class function TConvert.HexToPythonEscAscii(const aHexString: string): string; var i: Integer; ByteArray: array of Byte; begin Result := ''; SetLength(ByteArray, (length(aHexString) div 2) ); TConvert.HexToBytes(aHexString, ByteArray, length(ByteArray)); for i := Low(ByteArray) to High(ByteArray) do begin if ByteArray[i] in [$20..$7E] then begin case ByteArray[i] of $5c : Result := Result +'\\'; $27 : Result := Result +'\'''; else Result := Result + char(ByteArray[i]) end; end else begin case ansichar(ByteArray[i]) of TAB : Result := Result + '\t'; LF : Result := Result + '\n'; CR : Result := Result + '\r'; else Result := Result + '\x' + LowerCase(IntToHex(ByteArray[i], 2)); end; end; end; end; </code></pre>
26,802,784
1
7
null
2014-11-07 13:40:49.22 UTC
5
2020-10-20 16:39:54.933 UTC
2014-11-13 14:44:10.82 UTC
null
407,361
null
407,361
null
1
15
python|delphi|character-encoding|escaping
75,890
<p>This looks like binary data held in a Python <code>bytes</code> object. Loosely, bytes that map to printable ASCII characters are presented as those ASCII characters. All other bytes are encoded <code>\x**</code> where <code>**</code> is the hex representation of the byte.</p> <pre> >>> b = b'\x00E\x18\x10\x14}*UF!A\x81\xac\x08&\x02\x01\n\x15\x1a\xc2PP\x92' >>> str(b) '\x00E\x18\x10\x14}*UF!A\x81\xac\x08&\x02\x01\n\x15\x1a\xc2PP\x92' >>> ord(b[0]) 0 >>> ord(b[1]) 69 >>> ord(b[2]) 24 >>> ord(b[3]) 16 >>> ord(b[4]) 20 >>> ord(b[5]) 125 >>> ord(b[6]) 42 >>> bytes(bytearray((0, 69, 24, 16, 20, 125, 42))) '\x00E\x18\x10\x14}*' >>> bytes(bytearray(range(256))) '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15 \x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;?@ABCDEFGHIJKL MNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86 \x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b \x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0 \xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5 \xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda \xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef \xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' </pre> <p>The Python documentation describes bytes literals here: <a href="https://docs.python.org/3.4/reference/lexical_analysis.html#strings" rel="noreferrer">https://docs.python.org/3.4/reference/lexical_analysis.html#strings</a></p> <p>As to what the binary means, I presume that you know that.</p>
9,959,563
Why do I get a multiple definition error while linking?
<p>I use these two files <a href="https://raw.github.com/elanthis/easylogger/master/easylogger.h" rel="nofollow noreferrer">here</a> and <a href="https://raw.github.com/elanthis/easylogger/master/easylogger-impl.h" rel="nofollow noreferrer">here</a>.</p> <p>I created a class in two separate files:</p> <p>modul1.h</p> <pre><code>#ifndef MODUL1_H #define MODUL1_H #include &lt;iostream&gt; #include &lt;fstream&gt; #include &quot;easylogger.h&quot; class Modul1 { public: Modul1(std::string name); protected: private: easylogger::Logger *log; }; #endif // MODUL1_H </code></pre> <p>and modul1.cpp</p> <pre><code>#include &quot;modul1.h&quot; Modul1::Modul1(std::string name):log(new easylogger::Logger(name)) { //ctor //std::ofstream *f = new std::ofstream(name.c_str(), std::ios_base::app); //log-&gt;Stream(*f); //log-&gt;Level(easylogger::LEVEL_DEBUG); //LOG_DEBUG(*log, &quot;ctor ende!&quot;); } </code></pre> <p>Now I want to use this class in another file (main.cpp):</p> <pre><code>#include &quot;modul1.h&quot; int main() { std::cout &lt;&lt; &quot;Hello world!&quot; &lt;&lt; std::endl; Modul1 mod1(&quot;test.log&quot;); return 0; } </code></pre> <p>When I compile it with the following Makefile, I get a &quot;multiple definition of...&quot; error:</p> <blockquote> <p>g++ main.o modul1.o -o main<br /> modul1.o: In function <code>easylogger::Logger::Format(std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;)</code>:<br /> modul1.cpp:(.text+0x0): multiple definition of <code>easylogger::Logger::Format(std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;)</code><br /> main.o:main.cpp:(.text+0x0): first defined here<br /> modul1.o: In function <code>easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*)</code>: modul1.cpp:(.text+0x2a): multiple definition of <code>easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*)</code><br /> main.o:main.cpp:(.text+0x2a): first defined here<br /> collect2: ld returned 1 exit status</p> </blockquote> <p>(At first I compiled it with code::blocks and got the same error)</p> <p>How can I modify my Modul1 in order not to get this linking error? I don't think it is important, but I am using some Ubuntu 64bit with g++ 4.4.3</p> <p>Makefile:</p> <pre><code>CC=g++ CFLAGS=-c -Wall all: log_test log_test: main.o easylogger.h modul1.o $(CC) main.o modul1.o -o main main.o: main.cpp modul1.h $(CC) $(CFLAGS) main.cpp modul1.o: modul1.cpp modul1.h $(CC) $(CFLAGS) modul1.cpp </code></pre>
9,960,210
3
4
null
2012-03-31 20:46:11.19 UTC
2
2022-02-13 09:08:58.177 UTC
2021-12-16 15:11:56.357 UTC
null
3,789,665
null
12,860
null
1
5
c++|ubuntu|linker|gcc4.4
40,765
<p>The way you are building this, easylogger.h (and consequently easylogger-inl.h) gets included twice, once for modul1.h and once for main.cpp </p> <p>Your usage of it is wrong. But you can do this to make it work: </p> <p>In modul1.h (remove #include "easylogger.h") and make it look like this</p> <pre><code>#ifndef MODUL1_H #define MODUL1_H #include &lt;iostream&gt; #include &lt;fstream&gt; //#include "easylogger.h" namespace easylogger { class Logger; }; class Modul1 { public: Modul1(std::string name); protected: private: easylogger::Logger *log; }; #endif // MODUL1_H </code></pre> <p>and for modul1.cpp, include the real thing</p> <pre><code>#include "modul1.h" #include "easylogger.h" Modul1::Modul1(std::string name):log(new easylogger::Logger(name)) { //ctor //std::ofstream *f = new std::ofstream(name.c_str(), std::ios_base::app); //log-&gt;Stream(*f); //log-&gt;Level(easylogger::LEVEL_DEBUG); //LOG_DEBUG(*log, "ctor ende!"); } </code></pre> <p>Good luck!</p>
9,663,562
What is the difference between __init__ and __call__?
<p>I want to know the difference between <code>__init__</code> and <code>__call__</code> methods. </p> <p>For example:</p> <pre><code>class test: def __init__(self): self.a = 10 def __call__(self): b = 20 </code></pre>
9,663,601
16
1
null
2012-03-12 08:09:45.493 UTC
257
2022-07-30 17:30:57.38 UTC
2019-05-31 22:00:39.46 UTC
null
2,956,066
null
778,942
null
1
730
python|class|oop|object|callable-object
329,115
<p>The first is used to initialise newly created object, and receives arguments used to do that:</p> <pre><code>class Foo: def __init__(self, a, b, c): # ... x = Foo(1, 2, 3) # __init__ </code></pre> <p>The second implements function call operator.</p> <pre><code>class Foo: def __call__(self, a, b, c): # ... x = Foo() x(1, 2, 3) # __call__ </code></pre>
7,764,887
MySQL Stored Procedure Error Handling
<p>I believe there is nothing currently available in MySQL that allows access to the <code>SQLSTATE</code> of the last executed statement within a MySQL stored procedure. This means that when a generic <code>SQLException</code> is raised within a stored procedure it is hard/impossible to derive the exact nature of the error.</p> <p>Does anybody have a workaround for deriving the <code>SQLSTATE</code> of an error in a MySQL stored procedure that does not involve declaring a handler for every possible SQLSTATE?</p> <p>For example - imagine that I am trying to return an error_status that goes beyond the generic "SQLException happened somewhere in this <code>BEGIN....END</code> block" in the following:</p> <pre><code>DELIMITER $$ CREATE PROCEDURE `myProcedure`(OUT o_error_status varchar(50)) MY_BLOCK: BEGIN DECLARE EXIT handler for 1062 set o_error_status := "Duplicate entry in table"; DECLARE EXIT handler for 1048 set o_error_status := "Trying to populate a non-null column with null value"; -- declare handlers ad nauseum here.... DECLARE EXIT handler for sqlexception set o_error_status:= "Generic SQLException. You'll just have to figure out the SQLSTATE yourself...." ; -- Procedure logic that might error to follow here... END MY_BLOCK$$ </code></pre> <p>Any tips?</p> <p>PS I am running MySQL 5.1.49</p>
8,923,471
3
0
null
2011-10-14 08:19:21.91 UTC
5
2018-05-05 17:27:55.337 UTC
2018-05-05 17:27:55.337 UTC
null
8,464,442
null
966,491
null
1
13
mysql|stored-procedures|error-handling
68,330
<p>GET DIAGNOSTICS is available in 5.6.4</p> <p>See <a href="http://dev.mysql.com/doc/refman/5.6/en/get-diagnostics.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.6/en/get-diagnostics.html</a></p>
11,944,915
Getting an ElasticSearch Cluster to Green (Cluster Setup on OS X)
<p>I have <a href="https://github.com/mxcl/homebrew/blob/master/Library/Formula/elasticsearch.rb">installed ElasticSearch on Mac OS X using Homebrew</a>. It works. The cluster started off with "green" <a href="http://www.elasticsearch.org/guide/reference/api/admin-cluster-health.html">health</a>. However, right after adding data, it has gone to "yellow".</p> <blockquote> <p>The cluster health is status is: green, yellow or red. On the shard level, a red status indicates that the specific shard is not allocated in the cluster, yellow means that the primary shard is allocated but replicas are not, and green means that all shards are allocated. The index level status is controlled by the worst shard status. The cluster status is controlled by the worst index status.</p> </blockquote> <p>So, my replica shards are not allocated. How do I allocate them? (I'm thinking out loud.)</p> <p>According to Shay on <a href="http://elasticsearch-users.115913.n3.nabble.com/I-keep-getting-cluster-health-status-of-Yellow-td929520.html">"I keep getting cluster health status of Yellow"</a>: "the shard allocation mechanism does not allocate a shard and its replica on the same node, though it does allocate different shards on the same node. So, you will need two nodes to get cluster state of green."</p> <p>So, I need to start up a second node. I did this by:</p> <pre> cd ~/Library/LaunchAgents/ cp homebrew.mxcl.elasticsearch.plist homebrew.mxcl.elasticsearch-2.plist # change line 8 to: homebrew.mxcl.elasticsearch-2 launchctl load -wF ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch-2.plist </pre> <p>Now I have "Korvus" on <code>http://localhost:9200/</code> and "Iron Monger" on <code>http://localhost:9201/</code>. Woot. But, I don't see any indications that they know about each other. How do I connect / introduce them to each other?</p> <p>Note: I read <a href="http://www.elasticsearch.org/guide/reference/modules/discovery/zen.html">Zen Discovery</a>, but do not feel enlightened yet.</p> <h3>Update 2012-08-13 11:30 PM EST:</h3> <p>Here are my two nodes:</p> <pre><code>curl "http://localhost:9200/_cluster/health?pretty=true" { "cluster_name" : "elasticsearch_david", "status" : "green", "timed_out" : false, "number_of_nodes" : 1, "number_of_data_nodes" : 1, "active_primary_shards" : 0, "active_shards" : 0, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 } curl "http://localhost:9201/_cluster/health?pretty=true" { "cluster_name" : "elasticsearch_david", "status" : "green", "timed_out" : false, "number_of_nodes" : 1, "number_of_data_nodes" : 1, "active_primary_shards" : 0, "active_shards" : 0, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 } </code></pre> <h3>Update 2012-08-13 11:35 PM EST:</h3> <p>To clarify, my question is <strong>not</strong> how to "ignore" the problem by setting <code>index.number_of_replicas: 0</code>. I want multiple nodes, connected.</p> <h3>Update 2012-08-13 11:48 PM EST:</h3> <p>I just posted a <a href="https://gist.github.com/3346123">double gist that includes elasticsearch.yml and elasticsearch_david.log</a>. It looks to me like both nodes are calling themselves 'master'. Is that what I should expect?</p> <h3>Update 2012-08-14 12:36 AM EST:</h3> <p>And the novel continues! :) If I disconnect my Mac from all external networks, and then restart the nodes, <em>then</em> they find each other. Double Woot. This makes me think that the problem is with my network/multicast configuration. Currently I have this in my config: <code>network.host: 127.0.0.1</code>. Perhaps this is not correct?</p>
11,945,968
3
0
null
2012-08-14 02:19:26.097 UTC
11
2015-02-06 19:56:58.12 UTC
2012-08-14 06:15:05.97 UTC
null
109,618
null
109,618
null
1
12
macos|elasticsearch
17,674
<p>Solved. Do not use <code>network.host: 127.0.0.1</code>. Leave that line commented out to let it be automatically derived.</p> <p>The default <code>elasticsearch.yml</code> was correct. A <a href="https://github.com/Homebrew/homebrew/commit/c6518a2d01f349af0558a57af8b3fad5e05d8307" rel="noreferrer">configuration tweak by the Homebrew installer</a> specifies the <code>127.0.0.1</code> loopback interface:</p> <pre><code># Set up ElasticSearch for local development: inreplace "#{prefix}/config/elasticsearch.yml" do |s| # ... # 3. Bind to loopback IP for laptops roaming different networks s.gsub! /#\s*network\.host\: [^\n]+/, "network.host: 127.0.0.1" end </code></pre> <p>I filed <a href="https://github.com/mxcl/homebrew/issues/14167" rel="noreferrer">an issue on the Homebrew issue tracker</a>.</p>
11,585,954
Varying axis labels formatter per facet in ggplot/R
<p>I have a dataframe capturing several measures over time that I would like to visualize a 3x1 facet. However, each measure contains different units/scales that would benefit from custom transformations and labeling schemes.</p> <p>So, my question is: <strong>If the units and scales are different across different facets, how can I specify a custom formatter or transformation (i.e., log10) to a particular axis within a facet?</strong></p> <p>For example, let's say I have the data:</p> <pre><code>df = data.frame(dollars=10^rlnorm(50,0,1), counts=rpois(50, 100)) melted.df = melt(df, measure.var=c("dollars", "counts")) </code></pre> <p>How would one go upon setting up a 2x1 facet showing dollars and counts over the index with <code>labels=dollars</code> and <code>scale_y_continuous(trans = "log10", ...)</code> for the <code>df$dollars</code> data?</p> <p>Thank you!</p>
11,586,430
1
2
null
2012-07-20 19:40:19.693 UTC
10
2012-07-20 20:20:33.167 UTC
null
null
null
null
194,264
null
1
26
r|facet|ggplot2
10,058
<p>As you discovered, there isn't an easy solution to this, but it comes up a lot. Since this sort of thing is asked so often, I find it helpful to explain <em>why</em> this is hard, and suggest a potential solution.</p> <p>My experience has been that people coming to <strong>ggplot2</strong> or <strong>lattice</strong> graphics fundamentally misunderstand the purpose of faceting (or trellising, in <strong>lattice</strong>). This feature was developed with a very specific idea in mind: the visualization of data across multiple groups that <em>share a common scale</em>. It comes from something called the principle of small multiples, espoused by Tufte and others.</p> <p>Placing panels next to each other with very different scales is something that visual design experts will tend to avoid, because it can be at best misleading. (I'm not scolding you here, just explaining the rationale...)</p> <p>But of course, once you have this great tool out in the open, you never know how folks are going to use it. So it gets stretched: the requests come in for the ability to allows the scales to vary by panel, and to set various aspects of the plot separately for each panel. And so faceting in <strong>ggplot2</strong> has been expanded well beyond its original intent.</p> <p>One consequence of this is that some things are difficult to implement simply due to the original design intent of the feature. This is likely one such instance.</p> <p>Ok, enough explanation. Here's my solution.</p> <p>The trick here is to recognize that you <em>aren't plotting graphs that share a scale</em>. To me, that means you shouldn't even be thinking of using faceting at all. Instead, make each plot separately, and arrange them together in one plot:</p> <pre><code>library(gridExtra) p1 &lt;- ggplot(subset(melted.df,variable == 'dollars'), aes(x = value)) + facet_wrap(~variable) + geom_density() + scale_x_log10(labels = dollar_format()) p2 &lt;- ggplot(subset(melted.df,variable == 'counts'), aes(x = value)) + facet_wrap(~variable) + geom_density() grid.arrange(p1,p2) </code></pre> <p><img src="https://i.stack.imgur.com/kTejg.png" alt="enter image description here"></p> <p>I've just guessed at what <code>geom_*</code> you wanted to use, and I'm sure this isn't really what you wanted to plot, but at least it illustrates the principle.</p>
11,927,968
Document Root PHP
<p>Just to confirm, is using:</p> <pre><code>$_SERVER["DOCUMENT_ROOT"] </code></pre> <p>the same as using: /</p> <p>in HTML.</p> <p>Eg. If current document is:</p> <pre><code>folder/folder/folder/index.php </code></pre> <p>I could use (in HTML) to start at the roort:</p> <pre><code>/somedoc.html </code></pre> <p>and to do the same in PHP I would have to use:</p> <pre><code>$_SERVER["DOCUMENT_ROOT"] . "/somedoc.html"; </code></pre> <p>Is that correct? Is there an easier way to do it?</p>
11,928,042
4
0
null
2012-08-13 03:45:57.893 UTC
7
2021-07-28 08:11:24.24 UTC
null
null
null
null
1,511,184
null
1
32
php|html|root
147,123
<pre><code>&lt;a href=&quot;&lt;?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?&gt;&quot;&gt;go with php&lt;/a&gt; &lt;br /&gt; &lt;a href=&quot;/hello.html&quot;&gt;go to with html&lt;/a&gt; </code></pre> <p>Try this yourself and find that they are not exactly the same.</p> <p><code>$_SERVER['DOCUMENT_ROOT']</code> renders an actual file path (on my computer running as it's own server, <code>C:/wamp/www/</code></p> <p>HTML's <code>/</code> renders the root of the server url, in my case, <code>localhost/</code></p> <p>But <code>C:/wamp/www/hello.html</code> and <code>localhost/hello.html</code> are in fact the same file</p>
11,979,154
SELECT .. INTO to create a table in PL/pgSQL
<p>I want to use <code>SELECT INTO</code> to make a temporary table in one of my functions. <code>SELECT INTO</code> works in SQL but not PL/pgSQL.</p> <p>This statement creates a table called mytable (If <code>orig_table</code> exists as a relation):</p> <pre><code>SELECT * INTO TEMP TABLE mytable FROM orig_table; </code></pre> <p>But put this function into PostgreSQL, and you get the error: <code>ERROR: "temp" is not a known variable</code></p> <pre><code>CREATE OR REPLACE FUNCTION whatever() RETURNS void AS $$ BEGIN SELECT * INTO TEMP TABLE mytable FROM orig_table; END; $$ LANGUAGE plpgsql; </code></pre> <p>I can <code>SELECT INTO</code> a variable of type <code>record</code> within PL/pgSQL, but then I have to define the structure when getting data out of that record. <code>SELECT INTO</code> is really simple - automatically creating a table of the same structure of the <code>SELECT</code> query. Does anyone have any explanation for why this doesn't work inside a function?</p> <p>It seems like <code>SELECT INTO</code> works differently in PL/pgSQL, because you can select into the variables you've declared. I don't want to declare my temporary table structure, though. I wish it would just create the structure automatically like it does in SQL.</p>
11,979,191
1
0
null
2012-08-16 00:32:12.747 UTC
5
2017-03-08 13:42:57.36 UTC
2017-03-08 12:37:37.097 UTC
null
674,064
null
173,630
null
1
36
postgresql|plpgsql|postgresql-9.1
45,536
<p>Try </p> <pre><code>CREATE TEMP TABLE mytable AS SELECT * FROM orig_table; </code></pre> <p>Per <a href="http://www.postgresql.org/docs/current/static/sql-selectinto.html" rel="noreferrer">http://www.postgresql.org/docs/current/static/sql-selectinto.html</a></p> <blockquote> <p>CREATE TABLE AS is functionally similar to SELECT INTO. CREATE TABLE AS is the recommended syntax, since this form of SELECT INTO is not available in ECPG or PL/pgSQL, because they interpret the INTO clause differently. Furthermore, CREATE TABLE AS offers a superset of the functionality provided by SELECT INTO.</p> </blockquote>
11,636,790
Why do we need mktemp?
<p>I do not understand the function of <code>mktemp</code> and what a temporary file means. </p> <p>Whats the difference between say <code>touch xyz</code> and <code>mktemp xyz</code> (apart from the fact that <code>mktemp</code> will create some file with xxx appended to it and will have 600 permissions?)</p> <p>Please clarify.</p>
11,636,850
5
5
null
2012-07-24 18:09:19.24 UTC
17
2021-01-19 15:12:45.273 UTC
2019-04-04 08:55:09.19 UTC
null
387,076
null
1,190,922
null
1
64
linux|shell|filesystems
57,567
<p><code>mktemp</code> randomizes the name. It is very important from the security point of view.</p> <p>Just imagine that you do something like:</p> <pre><code>echo something &gt; /tmp/temporary-file </code></pre> <p>in your root-running script.</p> <p>And someone (who has read your script) does</p> <pre><code>ln -s /etc/passwd /tmp/temporary-file </code></pre> <p>before.</p> <p>This results in <code>/etc/passwd</code> being overwritten, and potentially it can mean different unpleasant things starting from the system becomes broken, and ending with the system becomes hacked (when the input <code>something</code> could be carefully crafted).</p> <p>The <code>mktemp</code> command could help you in this situation:</p> <pre><code>TEMP=$(mktemp /tmp/temporary-file.XXXXXXXX) echo something &gt; ${TEMP} </code></pre> <p>Now this <code>ln /etc/passwd</code> attack will not work.</p> <p><em>A brief insight into the history of mktemp</em>: The <code>mktemp</code> command was invented by the OpenBSD folks, and first appeared in OpenBSD 2.1 back in 1997. Their goal was to improve the security of shell scripts. Previously the norm had been to add <code>$$</code> to temporary file names, which was absolutely insecure. Now all UNIX/Linux systems have either <code>mktemp</code> or its alternatives, and it became standard de-facto. Funny enough, the <code>mktemp</code> C function was deprecated for being unsecure.</p>
19,991,665
My scipy.misc module appears to be missing imsave
<p>I open the python3 interpreter and type</p> <pre><code>import scipy.misc scipy.misc.imsave </code></pre> <p>with the result</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'imsave' </code></pre> <p>Has the name changed? It works fine in python2 but I would rather not migrate backwards so to speak.</p> <p>I have python 3.3.1 on Lubuntu 13.04 with all the modules downloaded from the default repositories. Scipy is installed and <code>print(scipy.misc.__doc__)</code> shows that <code>imsave</code> should be there.</p> <p>EDIT:</p> <p><code>scipy.__version__</code> gives 0.11.0</p> <p><code>from scipy.misc import imsave</code> gives</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name imsave </code></pre>
56,446,053
4
4
null
2013-11-15 01:08:33.143 UTC
3
2019-06-12 14:09:30.643 UTC
2013-11-15 01:54:34.317 UTC
null
1,227,915
null
1,227,915
null
1
38
python-3.x|scipy|python-3.3
48,617
<p><code>scipy.misc.imsave</code> has been deprecated in newer Scipy versions.</p> <p>Change your code to:</p> <pre><code>import imageio imageio.imwrite('filename.jpg', array) </code></pre>
4,014,935
Why doesn't focus() select my container div?
<p>I have an index.html which has JavaScript:</p> <pre><code>byId("p").value = page; byId("nav_container").focus(); document.forms["nav_form_main"].submit(); </code></pre> <p>The focus part doesn't work here.</p> <p>I want the browser to focus on a specific part of the page (almost at top).</p> <p>I have tried putting the focus after the submit(), same issue there.</p>
4,014,940
5
1
null
2010-10-25 13:22:16.073 UTC
2
2020-04-16 22:50:05.847 UTC
2019-08-15 18:56:51.24 UTC
null
2,756,409
user188962
null
null
1
23
javascript|html|forms
41,402
<p>make sure the element you want to focus has an attribute <code>tabindex="-1"</code>, otherwise that element is not focusable.</p> <p>For example</p> <pre><code>&lt;div id="myfocusablediv" tabindex="-1"&gt;&lt;/div&gt; </code></pre> <p>When you set the tabindex=-1 for an element it allows it to get focus() through javascript. If instead you want it to get focus through tabbing through elements, then you would set the tabindex attribute to 0.</p>
3,234,205
HTML form input tag name element array with JavaScript
<p>This is a two part question. Someone answered a similar question the other day (which also contained info about this type of array in PHP), but I cannot find it.</p> <p>1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?</p> <pre><code>&lt;form&gt; &lt;input name="p_id[]" value="0"/&gt; &lt;input name="p_id[]" value="1"/&gt; &lt;input name="p_id[]" value="2"/&gt; &lt;/form&gt; </code></pre> <p>2.) How do I get the information from that array with JavaScript? Specifically, I am right now just wanting to count the elements of the array. Here is what I did but it isn't working.</p> <pre><code>function form_check(){ for(var i = 0; i &lt; count(document.form.p_id[]); i++){ //Error on this line if (document.form.p_name[i].value == ''){ window.alert('Name Message'); document.form.p_name[i].focus(); break; } else{ if (document.form.p_price[i].value == ''){ window.alert('Price Message'); document.form.p_price[i].focus(); break; } else{ update_confirmation(); } } } } </code></pre>
3,234,383
5
0
null
2010-07-13 04:31:43.503 UTC
11
2017-08-09 08:19:43.263 UTC
2012-05-05 18:40:37.307 UTC
null
181,337
null
288,341
null
1
25
javascript|html|forms|input
178,636
<blockquote> <p>1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?</p> </blockquote> <p>"Oftimes Confusing PHPism"</p> <p>As far as JavaScript is concerned a bunch of form controls with the same name are just a bunch of form controls with the same name, and form controls with names that include square brackets are just form controls with names that include square brackets.</p> <p>The PHP naming convention for form controls with the same name is sometimes useful (when you have a number of groups of controls so you can do things like this:</p> <pre><code>&lt;input name="name[1]"&gt; &lt;input name="email[1]"&gt; &lt;input name="sex[1]" type="radio" value="m"&gt; &lt;input name="sex[1]" type="radio" value="f"&gt; &lt;input name="name[2]"&gt; &lt;input name="email[2]"&gt; &lt;input name="sex[2]" type="radio" value="m"&gt; &lt;input name="sex[2]" type="radio" value="f"&gt; </code></pre> <p>) but does confuse some people. Some other languages have adopted the convention since this was originally written, but generally only as an optional feature. For example, via <a href="https://www.npmjs.com/package/qs#readme" rel="noreferrer">this module for JavaScript</a>. </p> <blockquote> <p>2.) How do I get the information from that array with JavaScript? </p> </blockquote> <p>It is still just a matter of getting the property with the same name as the form control from <code>elements</code>. The trick is that since the name of the form controls includes square brackets, you can't use <a href="http://www.dev-archive.net/articles/js-dot-notation/" rel="noreferrer">dot notation and have to use square bracket notation</a> just like any other <a href="https://stackoverflow.com/questions/12953704/how-to-access-object-properties-containing-special-characters">JavaScript property name that includes special characters</a>.</p> <p>Since you have multiple elements with that name, it will be a collection rather then a single control, so you can loop over it with a standard for loop that makes use of its length property.</p> <pre><code>var myForm = document.forms.id_of_form; var myControls = myForm.elements['p_id[]']; for (var i = 0; i &lt; myControls.length; i++) { var aControl = myControls[i]; } </code></pre>
3,705,425
Java: reference escape
<p>Read that the following code is an example of "unsafe construction" as it allows this reference to escape. I couldn't quite get how 'this' escapes. I am pretty new to the java world. Can any one help me understand this. </p> <pre><code>public class ThisEscape { public ThisEscape(EventSource source) { source.registerListener( new EventListener() { public void onEvent(Event e) { doSomething(e); } }); } } </code></pre>
3,705,628
5
0
null
2010-09-14 00:49:57.09 UTC
26
2022-07-02 20:44:44.69 UTC
null
null
null
null
94,169
null
1
36
java|concurrent-programming
8,025
<p>The example you have posted in your question comes from <a href="https://rads.stackoverflow.com/amzn/click/com/0321349601" rel="noreferrer" rel="nofollow noreferrer">"Java Concurrency In Practice"</a> by Brian Goetz et al. It is in section 3.2 "Publication and escape". I won't attempt to reproduce the details of that section here. (Go buy a copy for your bookshelf, or borrow a copy from your co-workers!) </p> <p>The problem illustrated by the example code is that the constructor allows the reference to the object being constructed to "escape" before the constructor finishes creating the object. This is a problem for two reasons:</p> <ol> <li><p>If the reference escapes, something can use the object before its constructor has completed the initialization and see it in an inconsistent (partly initialized) state. Even if the object escapes after initialization has completed, declaring a subclass can cause this to be violated. </p></li> <li><p>According to <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/memory.html#65124/memory.html#17.5" rel="noreferrer">JLS 17.5</a>, final attributes of an object can be used safely without synchronization. However, this is only true if the object reference is not published (does not escape) before its constructor finished. If you break this rule, the result is an insidious concurrency bug that <em>might</em> bite you when the code is executed on a multi-core / multi-processor machines.</p></li> </ol> <p>The <code>ThisEscape</code> example is sneaky because the reference is escaping via the <code>this</code> reference passed implicitly to the anonymous <code>EventListener</code> class constructor. However, the same problems will arise if the reference is explicitly published too soon.</p> <p>Here's an example to illustrate the problem of incompletely initialized objects:</p> <pre><code>public class Thing { public Thing (Leaker leaker) { leaker.leak(this); } } public class NamedThing extends Thing { private String name; public NamedThing (Leaker leaker, String name) { super(leaker); } public String getName() { return name; } } </code></pre> <p>If the <code>Leaker.leak(...)</code> method calls <code>getName()</code> on the leaked object, it will get <code>null</code> ... because at that point in time the object's constructor chain has not completed.</p> <p>Here's an example to illustrate the unsafe publication problem for <code>final</code> attributes.</p> <pre><code>public class Unsafe { public final int foo = 42; public Unsafe(Unsafe[] leak) { leak[0] = this; // Unsafe publication // Make the "window of vulnerability" large for (long l = 0; l &lt; /* very large */ ; l++) { ... } } } public class Main { public static void main(String[] args) { final Unsafe[] leak = new Unsafe[1]; new Thread(new Runnable() { public void run() { Thread.yield(); // (or sleep for a bit) new Unsafe(leak); } }).start(); while (true) { if (leak[0] != null) { if (leak[0].foo == 42) { System.err.println("OK"); } else { System.err.println("OUCH!"); } System.exit(0); } } } } </code></pre> <p>Some runs of this application <em>may</em> print "OUCH!" instead of "OK", indicating that the main thread has observed the <code>Unsafe</code> object in an "impossible" state due to unsafe publication via the <code>leak</code> array. Whether this happens or not will depend on your JVM and your hardware platform.</p> <p>Now this example is clearly artificial, but it is not difficult to imagine how this kind of thing can happen in real multi-threaded applications. </p> <hr> <p><sup>The current Java Memory Model was specified in Java 5 (the 3rd edition of the JLS) as a result of JSR 133. Prior to then, memory-related aspects of Java were under-specified. Sources that refer to earlier versions / editions are out of date, but the information on the memory model in Goetz edition 1 is up to date.</sup></p> <p><sup>There are some technical aspects of the memory model that are apparently in need of revision; see <a href="https://openjdk.java.net/jeps/188" rel="noreferrer">https://openjdk.java.net/jeps/188</a> and <a href="https://www.infoq.com/articles/The-OpenJDK9-Revised-Java-Memory-Model/" rel="noreferrer">https://www.infoq.com/articles/The-OpenJDK9-Revised-Java-Memory-Model/</a>. However, this work has yet to appear in a JLS revision.</sup></p>
3,379,220
How to limit a table cell to one line of text using CSS?
<p>I have a table of users where each row contains their names, e-mail address, and such. For some users this row is one text line high, for some others two, etc. But I would like that each row of the table be one text line high, truncating the rest.</p> <p>I saw these two questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/2779779/a-column-of-a-table-needs-to-stay-in-one-line-html-css-javascript">A column of a table needs to stay in one line (HTML/CSS/Javascript)</a></li> <li><a href="https://stackoverflow.com/questions/1318108/css-limit-element-to-1-line">CSS: limit element to 1 line</a></li> </ul> <p>In fact my question is exactly similar to the first one, but since the link is dead I can't study it. Both answers say to use <code>white-space: nowrap</code>. However this doesn't work, maybe I'm missing something.</p> <p>Since I can't show you the code, I reproduced the problem:</p> <pre><code>&lt;style type="text/css"&gt; td { white-space: nowrap; overflow: hidden; width: 125px; height: 25px; } &lt;/style&gt; &lt;div style="width:500px"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;lorem ipsum here... blablablablablablablablablabla&lt;/td&gt; &lt;td&gt;lorem ipsum here... blablablablablablablablablabla&lt;/td&gt; &lt;td&gt;lorem ipsum here... blablablablablablablablablabla&lt;/td&gt; &lt;td&gt;lorem ipsum here... blablablablablablablablablabla&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>Without <code>white-space</code> the table is 500px wide, and the text takes more than one line.</p> <p>But <code>white-space: nowrap</code> makes the browser simply ignore the <code>width</code> directive and increase the width of the table until all data fits in one line.</p> <p>What am I doing wrong? </p>
3,379,241
5
1
null
2010-07-31 17:55:51.137 UTC
6
2022-04-12 16:51:36.877 UTC
2017-06-07 19:03:41.027 UTC
null
4,370,109
null
392,546
null
1
50
css|html-table|overflow
90,541
<p>overflow will only work if it knows where to start considering it overflown. You need to set the width and height attribute of the <code>&lt;td&gt;</code></p> <p><strong>TAKE 2</strong></p> <p>Try adding <code>table-layout: fixed; width:500px;</code> to the table's style.</p> <p><strong>UPDATE 3</strong></p> <p>confirmed this worked: <a href="http://jsfiddle.net/e3Eqn/" rel="noreferrer">http://jsfiddle.net/e3Eqn/</a></p>
3,538,774
Is it possible to override git command by git alias?
<p>my ~/.gitconfig is:</p> <pre><code>[alias] commit = "!sh commit.sh" </code></pre> <p>However, when I type <em>git commit</em>, script is not called.</p> <p>Is it possible, or I have to use another alias name?</p>
3,538,791
5
2
null
2010-08-21 20:10:56.697 UTC
7
2019-09-11 19:22:21.98 UTC
null
null
null
null
338,581
null
1
62
git|alias
12,460
<p><strong>It is NOT POSSIBLE</strong></p> <p>This is from my clone of git.git:</p> <pre><code>static int run_argv(int *argcp, const char ***argv) { int done_alias = 0; while (1) { /* See if it's an internal command */ handle_internal_command(*argcp, *argv); /* .. then try the external ones */ execv_dashed_external(*argv); /* It could be an alias -- this works around the insanity * of overriding "git log" with "git show" by having * alias.log = show */ if (done_alias || !handle_alias(argcp, argv)) break; done_alias = 1; } return done_alias; } </code></pre> <p>So its not possible. (<code>handle_internal_command</code> calls <code>exit</code> if it finds the command).</p> <p>You could fix this in your sources by changing the order of the lines and making <code>handle_alias</code> call <code>exit</code> if it finds the alias.</p>
3,639,415
Variables in crontab?
<p>How can I store variables in my crontab? I realize it's not shell but say I want to have some constants like a path to my app or something?</p>
51,866,717
5
0
null
2010-09-03 20:36:01.167 UTC
9
2022-05-06 03:14:59.973 UTC
2021-01-09 17:15:13.713 UTC
null
103,739
null
103,739
null
1
67
cron
65,180
<p>To keep my crontab clean, I would just call a shell script and do the fun stuff in the script.</p>
3,659,782
How to write the code for the back button?
<p>I have a php code here and I would like to create a &quot;back&quot; href to get me back to where I was before. Here's what I have:</p> <pre><code>&lt;input type=&quot;submit&quot; &lt;a href=&quot;#&quot; onclick=&quot;history.back();&quot;&gt;&quot;Back&quot;&lt;/a&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;?php // get form selection $day = $_GET['day']; // check value and select appropriate item if ($day == 1) { $special = 'Chicken in oyster sauce'; } elseif ($day == 2) { $special = 'French onion soup'; } elseif ($day == 3) { $special = 'Pork chops with mashed potatoes and green salad'; } else { $special = 'Fish and chips'; } ?&gt; &lt;h2&gt;Today's special is:&lt;/h2&gt; &lt;?php echo $special; ?&gt; &lt;input type=&quot;submit&quot; &lt;a href=&quot;#&quot; onclick=&quot;history.back();&quot;&gt;&quot;Back&quot;&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3,659,805
7
2
null
2010-09-07 14:52:30.44 UTC
14
2021-09-24 23:30:35.45 UTC
2020-07-05 15:17:54.587 UTC
null
472,495
null
68,348
null
1
23
php|button|href
141,032
<pre><code>&lt;button onclick="history.go(-1);"&gt;Back &lt;/button&gt; </code></pre>
8,137,225
read txt file via client javascript
<p>I'm new to javascript and trying to open a txt file into var and then inject it to html div... I tried to use fopen but I didn't succeed.</p> <pre><code>&lt;script type="text/javascript"&gt; file = fopen(getScriptPath("info.txt"), 0); file_length = flength(file); var content = fread(file,file_length); var div = document.getElementById("myDiv"); //alert(div); div.innerHTML = ""; div.innerHTML = content; &lt;/script&gt; </code></pre>
8,137,318
4
6
null
2011-11-15 13:42:03.797 UTC
5
2012-12-07 11:29:59.853 UTC
2011-11-15 13:42:43.32 UTC
null
19,068
null
998,853
null
1
9
javascript
40,985
<p>abandoned question:</p> <pre><code>if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","YOUR_FILE.txt",false); xmlhttp.send(); xmlDoc=xmlhttp.responseText; </code></pre> <p>by Freek8</p>
7,859,611
Could not load file or assembly, PublicKeyToken=null
<blockquote> <p>Could not load file or assembly 'NCrawler.GeckoProcessor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.</p> </blockquote> <p>When I call <code>CrawlUsingGeckoProcessor.Run();</code></p> <p>What does this mean? I can click "go to definition" and I can see the <code>Run()</code> method.</p>
7,859,650
4
0
null
2011-10-22 12:44:22.267 UTC
2
2019-04-09 09:06:22.063 UTC
2018-01-05 21:32:48.283 UTC
null
2,093,880
null
267,679
null
1
12
c#|visual-studio|.net-assembly
101,767
<p>This error usually means that the assembly was not found. Try verifying that the file exists in the directory where your application is running.</p> <p>If you still can't figure out which file fails loading, try using a tool such as Fusion Log Viewer (run <code>fuslogvw.exe</code> from the Visual Studio command prompt), to determine which files the CLR was trying to load and from where, so that you can see exactly what failed.</p>
8,321,874
How to get all childNodes in JS including all the 'grandchildren'?
<p>I want to scan a div for all childNodes including the ones that are nestled within other elements. Right now I have this:</p> <pre><code>var t = document.getElementById('DivId').childNodes; for(i=0; i&lt;t.length; i++) alert(t[i].id); </code></pre> <p>But it only gets the children of the Div and not the grandchildren. Thanks!</p> <p>Edit: This question was too vague. Sorry about that. Here's a fiddle:</p> <p><a href="http://jsfiddle.net/F6L2B/" rel="noreferrer">http://jsfiddle.net/F6L2B/</a></p> <p>The body.onload script doesn't run at JSFiddle, but it works, except that the 'Me Second' and 'Me Third' input fields are not being assigned a tabIndex and are therefore being skipped over.</p>
29,901,297
4
0
null
2011-11-30 06:15:14.967 UTC
12
2022-09-13 16:23:15.483 UTC
2011-12-02 06:59:31.223 UTC
null
137,629
null
137,629
null
1
76
javascript
74,118
<p>This is the fastest and simplest way, and it works on all browsers:</p> <pre><code>myDiv.getElementsByTagName("*") </code></pre>
7,872,589
Call specific client from SignalR
<p>I want to call specific client from server, and not broadcast to all of them. Problem is that I'm in scope of some AJAX request (in .aspx codebehind let say), and not in Hub or PersistentConnection, so don't have Clients property - and client who made that ajax (jquery) call is not the client I want to send signalr message! </p> <p>Now, I have one hub that it's called on JS page load, which registers new client into server static list, so I have client Guids. But don't know how to use that to send message from server to specific client. </p>
7,872,685
5
0
null
2011-10-24 07:47:30.17 UTC
25
2016-10-27 05:02:24.947 UTC
2016-02-01 14:33:44.88 UTC
null
1,407
null
1,407
null
1
75
asp.net|signalr
94,697
<p>See the docs for the latest:</p> <p>Persistent connections - <a href="https://github.com/SignalR/SignalR/wiki/PersistentConnection" rel="noreferrer">https://github.com/SignalR/SignalR/wiki/PersistentConnection</a></p> <p>Hubs - <a href="http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server" rel="noreferrer">http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server</a></p>
7,803,771
Call getLayoutInflater() in places not in activity
<p>What does need to be imported or how can I call the Layout inflater in places other than activity?</p> <pre><code>public static void method(Context context){ //this doesn't work the getLayoutInflater method could not be found LayoutInflater inflater = getLayoutInflater(); // this also doesn't work LayoutInflater inflater = context.getLayoutInflater(); } </code></pre> <p>I am able to call <code>getLayoutInflater</code> only in activity, is that an restriction? What if I want to create custom dialog and I want to inflate view for it, or what if I want to have Toast message with custom view that is shown from a service, I only have the context from the service I do not have any activity but I want to show custom message.</p> <p>I need the inflater in places in the code that isn't in the activity class.</p> <p>How can I do this ?</p>
7,803,853
6
0
null
2011-10-18 07:23:51.603 UTC
46
2022-05-05 07:11:57.307 UTC
2022-05-05 07:11:57.307 UTC
null
17,133,283
null
706,780
null
1
205
android|service|android-context|toast|layout-inflater
162,571
<p>You can use this outside activities - all you need is to provide a <code>Context</code>:</p> <pre><code>LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); </code></pre> <p>Then to retrieve your different widgets, you inflate a layout:</p> <pre><code>View view = inflater.inflate( R.layout.myNewInflatedLayout, null ); Button myButton = (Button) view.findViewById( R.id.myButton ); </code></pre> <hr> <p><strong>EDIT as of July 2014</strong></p> <p>Davide's <a href="https://stackoverflow.com/a/18942760/157274">answer</a> on how to get the <code>LayoutInflater</code> is actually more correct than mine (which is still valid though).</p>
7,999,503
Rx: How can I respond immediately, and throttle subsequent requests
<p>I would like to set up an Rx subscription that can respond to an event right away, and then ignore subsequent events that happen within a specified &quot;cooldown&quot; period.</p> <p>The out of the box Throttle/Buffer methods respond only once the timeout has elapsed, which is not quite what I need.</p> <p>Here is some code that sets up the scenario, and uses a Throttle (which isn't the solution I want):</p> <pre><code>class Program { static Stopwatch sw = new Stopwatch(); static void Main(string[] args) { var subject = new Subject&lt;int&gt;(); var timeout = TimeSpan.FromMilliseconds(500); subject .Throttle(timeout) .Subscribe(DoStuff); var factory = new TaskFactory(); sw.Start(); factory.StartNew(() =&gt; { Console.WriteLine(&quot;Batch 1 (no delay)&quot;); subject.OnNext(1); }); factory.StartNewDelayed(1000, () =&gt; { Console.WriteLine(&quot;Batch 2 (1s delay)&quot;); subject.OnNext(2); }); factory.StartNewDelayed(1300, () =&gt; { Console.WriteLine(&quot;Batch 3 (1.3s delay)&quot;); subject.OnNext(3); }); factory.StartNewDelayed(1600, () =&gt; { Console.WriteLine(&quot;Batch 4 (1.6s delay)&quot;); subject.OnNext(4); }); Console.ReadKey(); sw.Stop(); } private static void DoStuff(int i) { Console.WriteLine(&quot;Handling {0} at {1}ms&quot;, i, sw.ElapsedMilliseconds); } } </code></pre> <p>The output of running this right now is:</p> <blockquote> <p>Batch 1 (no delay)</p> <p><strong>Handling 1 at 508ms</strong></p> <p>Batch 2 (1s delay)</p> <p>Batch 3 (1.3s delay)</p> <p>Batch 4 (1.6s delay)</p> <p><strong>Handling 4 at 2114ms</strong></p> </blockquote> <p>Note that batch 2 isn't handled (which is fine!) because we wait for 500ms to elapse between requests due to the nature of throttle. Batch 3 is also not handled, (which is less alright because it happened more than 500ms from batch 2) due to its proximity to Batch 4.</p> <p>What I'm looking for is something more like this:</p> <blockquote> <p>Batch 1 (no delay)</p> <p><strong>Handling 1 at ~0ms</strong></p> <p>Batch 2 (1s delay)</p> <p><strong>Handling 2 at ~1000s</strong></p> <p>Batch 3 (1.3s delay)</p> <p>Batch 4 (1.6s delay)</p> <p><strong>Handling 4 at ~1600s</strong></p> </blockquote> <p>Note that batch 3 wouldn't be handled in this scenario (which is fine!) because it occurs within 500ms of Batch 2.</p> <p><strong>EDIT</strong>:</p> <p>Here is the implementation for the &quot;StartNewDelayed&quot; extension method that I use:</p> <pre><code>/// &lt;summary&gt;Creates a Task that will complete after the specified delay.&lt;/summary&gt; /// &lt;param name=&quot;factory&quot;&gt;The TaskFactory.&lt;/param&gt; /// &lt;param name=&quot;millisecondsDelay&quot;&gt;The delay after which the Task should transition to RanToCompletion.&lt;/param&gt; /// &lt;returns&gt;A Task that will be completed after the specified duration.&lt;/returns&gt; public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay) { return StartNewDelayed(factory, millisecondsDelay, CancellationToken.None); } /// &lt;summary&gt;Creates a Task that will complete after the specified delay.&lt;/summary&gt; /// &lt;param name=&quot;factory&quot;&gt;The TaskFactory.&lt;/param&gt; /// &lt;param name=&quot;millisecondsDelay&quot;&gt;The delay after which the Task should transition to RanToCompletion.&lt;/param&gt; /// &lt;param name=&quot;cancellationToken&quot;&gt;The cancellation token that can be used to cancel the timed task.&lt;/param&gt; /// &lt;returns&gt;A Task that will be completed after the specified duration and that's cancelable with the specified token.&lt;/returns&gt; public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken) { // Validate arguments if (factory == null) throw new ArgumentNullException(&quot;factory&quot;); if (millisecondsDelay &lt; 0) throw new ArgumentOutOfRangeException(&quot;millisecondsDelay&quot;); // Create the timed task var tcs = new TaskCompletionSource&lt;object&gt;(factory.CreationOptions); var ctr = default(CancellationTokenRegistration); // Create the timer but don't start it yet. If we start it now, // it might fire before ctr has been set to the right registration. var timer = new Timer(self =&gt; { // Clean up both the cancellation token and the timer, and try to transition to completed ctr.Dispose(); ((Timer)self).Dispose(); tcs.TrySetResult(null); }); // Register with the cancellation token. if (cancellationToken.CanBeCanceled) { // When cancellation occurs, cancel the timer and try to transition to cancelled. // There could be a race, but it's benign. ctr = cancellationToken.Register(() =&gt; { timer.Dispose(); tcs.TrySetCanceled(); }); } if (millisecondsDelay &gt; 0) { // Start the timer and hand back the task... timer.Change(millisecondsDelay, Timeout.Infinite); } else { // Just complete the task, and keep execution on the current thread. ctr.Dispose(); tcs.TrySetResult(null); timer.Dispose(); } return tcs.Task; } </code></pre>
8,013,785
9
1
null
2011-11-03 17:45:28.44 UTC
15
2019-07-09 08:54:49.62 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
354,718
null
1
38
c#|system.reactive
7,514
<p>The initial answer I posted has a flaw: namely that the <code>Window</code> method, when used with an <code>Observable.Interval</code> to denote the end of the window, sets up an infinite series of 500ms windows. What I really need is a window that starts when the first result is pumped into the subject, and ends after the 500ms.</p> <p>My sample data masked this problem because the data broke down nicely into the windows that were already going to be created. (i.e. 0-500ms, 501-1000ms, 1001-1500ms, etc.) </p> <p>Consider instead this timing:</p> <pre><code>factory.StartNewDelayed(300,() =&gt; { Console.WriteLine("Batch 1 (300ms delay)"); subject.OnNext(1); }); factory.StartNewDelayed(700, () =&gt; { Console.WriteLine("Batch 2 (700ms delay)"); subject.OnNext(2); }); factory.StartNewDelayed(1300, () =&gt; { Console.WriteLine("Batch 3 (1.3s delay)"); subject.OnNext(3); }); factory.StartNewDelayed(1600, () =&gt; { Console.WriteLine("Batch 4 (1.6s delay)"); subject.OnNext(4); }); </code></pre> <p>What I get is:</p> <blockquote> <p>Batch 1 (300ms delay)</p> <p><strong>Handling 1 at 356ms</strong> </p> <p>Batch 2 (700ms delay)</p> <p><strong>Handling 2 at 750ms</strong> </p> <p>Batch 3 (1.3s delay)</p> <p><strong>Handling 3 at 1346ms</strong> </p> <p>Batch 4 (1.6s delay)</p> <p><strong>Handling 4 at 1644ms</strong></p> </blockquote> <p>This is because the windows begin at 0ms, 500ms, 1000ms, and 1500ms and so each <code>Subject.OnNext</code> fits nicely into its own window.</p> <p>What I want is:</p> <blockquote> <p>Batch 1 (300ms delay)</p> <p><strong>Handling 1 at ~300ms</strong></p> <p>Batch 2 (700ms delay)</p> <p>Batch 3 (1.3s delay)</p> <p><strong>Handling 3 at ~1300ms</strong></p> <p>Batch 4 (1.6s delay)</p> </blockquote> <p>After a lot of struggling and an hour banging on it with a co-worker, we arrived at a better solution using pure Rx and a single local variable:</p> <pre><code>bool isCoolingDown = false; subject .Where(_ =&gt; !isCoolingDown) .Subscribe( i =&gt; { DoStuff(i); isCoolingDown = true; Observable .Interval(cooldownInterval) .Take(1) .Subscribe(_ =&gt; isCoolingDown = false); }); </code></pre> <p>Our assumption is that calls to the subscription method are synchronized. If they are not, then a simple lock could be introduced.</p>
8,243,742
Chrome JavaScript Debugging - how to save break points between page refresh or break via code?
<p>When using Chrome and it's JavaScript debugger, every time I reload my page / scripts, my breakpoints are lost and I have to go find the script file in the pop-up, find the line of code for my break point, click to add it, etc.</p> <p>Is there a way to save these breakpoints so it breaks even after a page refresh (other debuggers I have used do this)?</p> <p>Alternatively, is there a clean way in my JavaScript code I can type something to tell chrome to start tracing (to pause on a line)?</p>
8,243,809
9
3
null
2011-11-23 14:22:30.147 UTC
11
2021-11-10 11:45:30.63 UTC
null
null
null
null
158,438
null
1
85
javascript|debugging|google-chrome|breakpoints
39,945
<p>You can put a</p> <pre><code>debugger; </code></pre> <p>to break in most of the JavaScript environments. They will persist for sure. It's good to have a minifier that rids the debugger and console.log calls for the production environment, if you are using these.</p> <p>In the recent versions of Chrome browser, there is a "Preserve Log" option on the top of the console panel, next to the filters. In the older versions, right clicking on the empty console window will bring that option ("Preserve log upon navigation"). It's handy when you don't have console.log statements or hard-coded debugger calls.</p> <p>update: I found a tool on github, called <a href="https://github.com/mikaa123/chimney" rel="noreferrer">chimney</a>, which takes a file and removes all the console.log calls. it gives a good idea about how to remove debugger calls. </p>
4,178,437
Java send and receive SMS. Free SMS gateway?
<p>On some questions here on SOverflow I found <a href="https://labs.ericsson.com/apis/sms-send-and-receive/" rel="noreferrer">THIS</a>. But it says that it is not avaiable at the moment and probably it will never get avaiable.</p> <p>Based on <a href="https://stackoverflow.com/questions/84282/what-can-you-use-to-get-an-application-to-be-able-to-receive-sms-message">THIS</a> I realised that there is no need on building my own SMS service.</p> <p>So the question:</p> <p><strong>My java application has to send SMS messages to users and receive SMS messages from users. Do I really need to pay some SMS gateway or is there some free SMS GATEWAY (with some limitations ofcourse) that I could use to test my application?</strong></p> <p><a href="http://www.tucows.com/preview/221572" rel="noreferrer">Simplewire Kit</a> looks really simple but the demo examples are failing because I don' have <a href="http://www.simplewire.com/index.html" rel="noreferrer">Simplewire account</a>. Simplewire documentation says that there is a 30-day trial for sending SMS. But this is for two way: </p> <p><em>"For 2-Way, demo credits are not available because you will need your own mobile number hosted on Simplewire’s Network. Simplewire supports 2-Way numbers for many different countries and area codes. Please contact Simplewire for more information."</em></p>
4,268,040
3
1
null
2010-11-14 16:32:19.087 UTC
11
2020-08-06 10:18:30.363 UTC
2017-05-23 12:32:58.553 UTC
null
-1
null
365,011
null
1
18
java|sms|gateway
57,933
<p>FYI Simplewire is now OpenMarket.com/MXTelecom.com</p> <p>There are a couple of free SMS gateways but they all attach a SMS ad in your message to pay for the cost. ZeepMobile is the one I hear about the most. As for paying there are a couple of solution but this all depends on your needs.</p> <p>Two way communication would require the end user to subscribe to your service. There are a few ways to approach this:</p> <p>Short Code: you could get your own (www.openmarket.com) or share with others (www.clickatell.com) You could use a new service www.twilio.com looks to be good but haven't tested it yet.</p> <p>If one way communication is all you need you could so something like <a href="http://en.wikipedia.org/wiki/List_of_SMS_gateways" rel="nofollow">email to gateway sms</a> but then you would need to know the carrier the end user is on.</p>
4,382,801
How can I make a SQL temp table with primary key and auto-incrementing field?
<p>What am I missing here? I'm trying to get the <code>ID</code> field to be the primary key and auto increment so that I don't need to insert it explicitly.</p> <pre><code>CREATE TABLE #tmp ( ID INT IDENTITY(1, 1) , AssignedTo NVARCHAR(100), AltBusinessSeverity NVARCHAR(100), DefectCount int ); insert into #tmp select 'user','high',5 union all select 'user','med',4 select * from #tmp </code></pre> <p>I get an error with this saying: </p> <blockquote> <p>Insert Error: Column name or number of supplied values does not match table definition.</p> </blockquote>
4,382,816
3
1
null
2010-12-07 23:36:56.073 UTC
3
2020-05-02 15:29:49.347 UTC
2020-05-02 15:29:49.347 UTC
null
4,925,121
null
352,157
null
1
35
sql-server|sql-server-2005|temp-tables
122,314
<p>You are just missing the words "primary key" as far as I can see to meet your specified objective. </p> <p>For your other columns it's best to explicitly define whether they should be <code>NULL</code> or <code>NOT NULL</code> though so you are not relying on the <code>ANSI_NULL_DFLT_ON</code> setting.</p> <pre><code>CREATE TABLE #tmp ( ID INT IDENTITY(1, 1) primary key , AssignedTo NVARCHAR(100), AltBusinessSeverity NVARCHAR(100), DefectCount int ); insert into #tmp select 'user','high',5 union all select 'user','med',4 select * from #tmp </code></pre>
4,581,733
Show message after submit
<p>How can I display an alert after a user clicks a submit button in a form? </p> <p>I want the alert to show when the page has loaded after the submit button has been clicked. </p> <p>Is there any way to do this?</p> <p><em><strong>EDIT:</em></strong> </p> <p>I need the message to be HTML text that is displayed on the page--not a javascript alert. </p>
4,581,746
4
8
null
2011-01-03 02:35:22.617 UTC
0
2016-07-21 10:15:15.707 UTC
null
null
null
null
142,237
null
1
4
php|forms
62,664
<p>pagewithform.php</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;form action="myformsubmit.php" method="POST"&gt; &lt;label&gt;Name: &lt;input type="text" name="name" /&gt;&lt;label&gt; &lt;input type="Submit" value="Submit" /&gt; &lt;/form&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <p>myformsubmit.php</p> <pre><code>&lt;html&gt; &lt;head&gt; .... &lt;/head&gt; &lt;body&gt; &lt;?php if (count($_POST)&gt;0) echo '&lt;div id="form-submit-alert"&gt;Form Submitted!&lt;/div&gt;'; ?&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>EDITED</strong> Fits new critieria of OP on last edit.</p> <p><strong>EDITv2</strong> Try it at home!</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Notify on Submit&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;" method="POST"&gt; &lt;label&gt;Name: &lt;input type="text" name="name" /&gt;&lt;/label&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; &lt;?php if (count($_POST)&gt;0) echo "Form Submitted!"; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Try that on for size.</p>
4,201,441
Is there any practical reason to use quoted strings for JSON keys?
<p>According to Crockford's <a href="http://www.json.org/" rel="noreferrer">json.org</a>, a JSON <em>object</em> is made up of <em>members</em>, which is made up of <em>pairs</em>.</p> <p>Every pair is made of a <em>string</em> and a <em>value</em>, with a <em>string</em> being defined as:</p> <blockquote> <p>A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.</p> </blockquote> <p>But in practice most programmers don't even know that a JSON key should be surrounded by double quotes, because most browsers don't require the use of double quotes.</p> <p>Does it make any sense to bother surrounding your JSON in double quotes?</p> <p>Valid Example:</p> <pre><code>{ "keyName" : 34 } </code></pre> <p>As opposed to the invalid:</p> <pre><code>{ keyName : 34 } </code></pre>
4,201,631
4
9
null
2010-11-17 04:17:06.593 UTC
20
2021-10-25 20:02:00.463 UTC
2015-02-20 02:08:29.31 UTC
null
359,284
null
25,847
null
1
96
javascript|json|browser|double-quotes
33,525
<p>The real reason about why JSON keys should be in quotes, relies in the semantics of Identifiers of ECMAScript 3.</p> <p><a href="http://bclary.com/2004/11/07/#a-7.5.1" rel="noreferrer">Reserved words</a> cannot be used as <em>property names</em> in Object Literals without quotes, for example:</p> <pre><code>({function: 0}) // SyntaxError ({if: 0}) // SyntaxError ({true: 0}) // SyntaxError // etc... </code></pre> <p>While if you use quotes the property names are valid:</p> <pre><code>({"function": 0}) // Ok ({"if": 0}) // Ok ({"true": 0}) // Ok </code></pre> <p>The own Crockford explains it in <a href="http://developer.yahoo.com/yui/theater/video.php?v=crockford-json" rel="noreferrer">this talk</a>, they wanted to keep the JSON standard simple, and they wouldn't like to have all those semantic restrictions on it:</p> <blockquote> <p>....</p> <p>That was when we discovered the unquoted name problem. It turns out ECMA Script 3 has a whack reserved word policy. Reserved words must be quoted in the key position, which is really a nuisance. When I got around to formulizing this into a standard, I didn't want to have to put all of the reserved words in the standard, because it would look really stupid.</p> <p>At the time, I was trying to convince people: yeah, you can write applications in JavaScript, it's actually going to work and it's a good language. I didn't want to say, then, at the same time: and look at this really stupid thing they did! So I decided, instead, let's just quote the keys.<br> That way, we don't have to tell anybody about how whack it is.</p> <p>That's why, to this day, keys are quoted in JSON.</p> <p>...</p> </blockquote> <p>The ECMAScript 5th Edition Standard fixes this, now in an ES5 implementation, even reserved words can be used without quotes, in both, Object literals and member access (<code>obj.function</code> Ok in ES5).</p> <p>Just for the record, this standard is being implemented these days by software vendors, you can see what browsers include this feature on this <a href="http://kangax.github.com/es5-compat-table/" rel="noreferrer">compatibility table</a> (see <em>Reserved words as property names</em>)</p>
4,357,101
promise already under evaluation: recursive default argument reference or earlier problems?
<p>Here is my R code. The functions are defined as:</p> <pre><code>f &lt;- function(x, T) { 10 * sin(0.3 * x) * sin(1.3 * x ^ 2) + 0.001 * x ^ 3 + 0.2 * x + 80 } g &lt;- function(x, T, f=f) { exp(-f(x) / T) } test &lt;- function(g=g, T=1) { g(1, T) } </code></pre> <p>The running error is:</p> <blockquote> <p>> test()<br> Error in test() :<br> promise already under evaluation: recursive default argument reference or earlier problems?</p> </blockquote> <p>If I substitute the definition of <code>f</code> in that of <code>g</code>, then the error goes away.</p> <p>I was wondering what the error was? How to correct it if don't substitute the definition of <code>f</code> in that of <code>g</code>? Thanks!</p> <hr> <p>Update:</p> <p>Thanks! Two questions:</p> <p>(1) if function <code>test</code> further takes an argument for <code>f</code>, will you add something like <code>test &lt;- function(g.=g, T=1, f..=f){ g.(1,T, f.=f..) }</code> ? In cases with more recursions, is it a good and safe practice adding more <em>.</em>? </p> <p>(2) if <code>f</code> is a non-function argument, for example <code>g &lt;- function(x, T, f=f){ exp(-f*x/T) }</code> and <code>test &lt;- function(g.=g, T=1, f=f){ g.(1,T, f=f.) }</code>, will using the same name for both formal and actual non-functional arguments a good and safe practice or it may cause some potential trouble? </p>
4,357,159
4
0
null
2010-12-05 02:53:51.05 UTC
35
2022-03-06 21:18:07.16 UTC
2017-01-06 01:42:26.527 UTC
null
1,840,471
null
156,458
null
1
179
r
66,893
<p>Formal arguments of the form <code>x=x</code> cause this. Eliminating the two instances where they occur we get the following. (The reason you can't use <code>x=x</code> in the formal arguments of a function definition is that it first looks up the default argument within the function itself so using that form is telling it to use itself as the default but it has not been defined so that makes no sense and we get an error.)</p> <pre><code>f &lt;- function(x, T) { 10 * sin(0.3 * x) * sin(1.3 * x^2) + 0.001 * x^3 + 0.2 * x + 80 } g &lt;- function(x, T, f. = f) { ## 1. note f. exp(-f.(x)/T) } test&lt;- function(g. = g, T = 1) { ## 2. note g. g.(1,T) } test() ## [1] 8.560335e-37 </code></pre>
4,727,287
How do you Tar an svn directory and filter out all the .svn files?
<p>I'm trying to create a tar file for deployment of some code but I dont want all the .svn files being deployed. </p> <p>How can I filter these out? They're in multiple directories...</p>
9,438,826
5
0
null
2011-01-18 17:50:43.583 UTC
10
2019-11-06 16:56:10.287 UTC
null
null
null
null
177,389
null
1
35
svn|filter|tar
26,730
<pre><code>tar --exclude=.svn -z -c -v -f mytarball.tar.gz mydir/ </code></pre>
4,141,555
How to use getSystemService in a non-activity class?
<p>I am building an application which triggers an alarm via AlarmManager.</p> <p>I would like to be able to call the Alarm via it's own non-activity class, but since I am not extending Activity, I don't appear to have any 'context'. This concept confuses me, and I've read the sdk docs. </p> <p>How would I go about using:</p> <pre><code>alarmTest = (AlarmManager)getSystemService(Context.ALARM_SERVICE); </code></pre> <p>in my non-activty class?</p> <p>Also, I'm assuming getting context will allow me to use SharedPrefs and Intents in my non-activity class as well?</p>
4,141,627
5
0
null
2010-11-10 05:40:58.93 UTC
8
2020-12-05 13:44:38.363 UTC
2013-06-07 05:55:22.67 UTC
null
2,683
null
502,630
null
1
57
android|android-context
95,188
<p>You can pass the context to the non-activity class which is the preferred way or you could encapsulate the base context of the application to a singleton which would allow you to access the context anywhere within the application. At some cases this might be a good solution but in others its certainly not a good one. </p> <p>Anyway, if you want to trigger an alarm via the <code>AlarmManager</code> I'm pretty sure the alarm should inherit from a <code>Service</code> or better yet from <code>IntentService</code> and in such cases you have access to the context via <code>this.getBaseContext()</code> or <code>this.getApplicationContext()</code></p>
4,201,455
SQLAlchemy: What's the difference between flush() and commit()?
<p>What the difference is between <code>flush()</code> and <code>commit()</code> in SQLAlchemy?</p> <p>I've read the docs, but am none the wiser - they seem to assume a pre-understanding that I don't have.</p> <p>I'm particularly interested in their impact on memory usage. I'm loading some data into a database from a series of files (around 5 million rows in total) and my session is occasionally falling over - it's a large database and a machine with not much memory. </p> <p>I'm wondering if I'm using too many <code>commit()</code> and not enough <code>flush()</code> calls - but without really understanding what the difference is, it's hard to tell!</p>
4,202,016
6
1
null
2010-11-17 04:20:20.037 UTC
178
2022-02-01 16:38:04.433 UTC
2018-04-29 05:00:25.637 UTC
null
110,488
null
267,831
null
1
597
python|sqlalchemy
194,954
<p>A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).</p> <p>The session object registers transaction operations with <code>session.add()</code>, but doesn't yet communicate them to the database until <code>session.flush()</code> is called. </p> <p><code>session.flush()</code> communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what <code>session.commit()</code> does).</p> <p><code>session.commit()</code> commits (persists) those changes to the database.</p> <p><code>flush()</code> is <em>always</em> called as part of a call to <code>commit()</code> (<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#committing" rel="noreferrer">1</a>).</p> <p>When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects <code>autoflush</code> their operations, but this can be disabled.</p> <p>Hopefully this example will make this clearer:</p> <pre><code>#--- s = Session() s.add(Foo('A')) # The Foo('A') object has been added to the session. # It has not been committed to the database yet, # but is returned as part of a query. print 1, s.query(Foo).all() s.commit() #--- s2 = Session() s2.autoflush = False s2.add(Foo('B')) print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned # as part of this query because it hasn't # been flushed yet. s2.flush() # Now, Foo('B') is in the same state as # Foo('A') was above. print 3, s2.query(Foo).all() s2.rollback() # Foo('B') has not been committed, and rolling # back the session's transaction removes it # from the session. print 4, s2.query(Foo).all() #--- Output: 1 [&lt;Foo('A')&gt;] 2 [&lt;Foo('A')&gt;] 3 [&lt;Foo('A')&gt;, &lt;Foo('B')&gt;] 4 [&lt;Foo('A')&gt;] </code></pre>
4,407,553
android RadioButton button drawable gravity
<p>I am generating RadioButtons dynamically with </p> <pre><code>RadioButton radioButton=new RadioButton(context); LayoutParams layoutParams=new LayoutParams(radioWidth,radioHeight); layoutParams.gravity=Gravity.CENTER; radioButton.setLayoutParams(layoutParams); radioButton.setGravity(Gravity.CENTER); BitmapDrawable bitmap = ((BitmapDrawable)drawableResource); bitmap.setGravity(Gravity.CENTER); radioButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.itabs_radio)); radioButton.setButtonDrawable(bitmap); </code></pre> <p>as you can see I am desperately trying to set gravity of button drawable to center, but without a reason its always center and left aligned, heres the reason- the default style of android radio button:</p> <pre><code>&lt;style name="Widget.CompoundButton"&gt; &lt;item name="android:focusable"&gt;true&lt;/item&gt; &lt;item name="android:clickable"&gt;true&lt;/item&gt; &lt;item name="android:textAppearance"&gt;?android:attr/textAppearance&lt;/item&gt; &lt;item name="android:textColor"&gt;?android:attr/textColorPrimaryDisableOnly&lt;/item&gt; &lt;item name="android:gravity"&gt;center_vertical|left&lt;/item&gt; &lt;/style&gt; &lt;style name="Widget.CompoundButton.RadioButton"&gt; &lt;item name="android:background"&gt;@android:drawable/btn_radio_label_background&lt;/item&gt; &lt;item name="android:button"&gt;@android:drawable/btn_radio&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>Is there any way I can align button drawable to center?</strong></p>
4,407,803
7
0
null
2010-12-10 09:53:01.21 UTC
16
2022-06-20 16:12:35.377 UTC
2010-12-10 10:12:49.96 UTC
null
447,238
null
447,238
null
1
28
android|radio-button|center|drawable
23,928
<p>According to <a href="http://google.com/codesearch/p?hl=en#uX1GffpyOZk/core/java/android/widget/CompoundButton.java&amp;q=android%20RadioButton&amp;d=4&amp;l=229"><code>CompoundButton.onDraw()</code> source code</a> it's always left-aligned.</p> <p>(Note the line <code>buttonDrawable.setBounds(0, y, buttonDrawable.getIntrinsicWidth(), y + height);</code>)</p> <p>You will have to derive a new class from <code>RadioButton</code> and override <code>onDraw()</code>.</p> <p><strong>EXAMPLE ADDED LATER:</strong></p> <p>Ok, so here's what you do. Firstly, here's a layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;org.test.TestProj.RadioButtonCenter android:id="@+id/myview" android:layout_width="fill_parent" android:layout_height="100dp" android:layout_centerInParent="true" android:text="Button test" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Secondly here's the custom-drawing RadioButtonCenter:</p> <pre><code>package org.test.TestProj; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.Gravity; import android.widget.RadioButton; import android.graphics.Canvas; import android.graphics.drawable.Drawable; public class RadioButtonCenter extends RadioButton { public RadioButtonCenter(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, 0, 0); buttonDrawable = a.getDrawable(1); setButtonDrawable(android.R.color.transparent); } Drawable buttonDrawable; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (buttonDrawable != null) { buttonDrawable.setState(getDrawableState()); final int verticalGravity = getGravity() &amp; Gravity.VERTICAL_GRAVITY_MASK; final int height = buttonDrawable.getIntrinsicHeight(); int y = 0; switch (verticalGravity) { case Gravity.BOTTOM: y = getHeight() - height; break; case Gravity.CENTER_VERTICAL: y = (getHeight() - height) / 2; break; } int buttonWidth = buttonDrawable.getIntrinsicWidth(); int buttonLeft = (getWidth() - buttonWidth) / 2; buttonDrawable.setBounds(buttonLeft, y, buttonLeft+buttonWidth, y + height); buttonDrawable.draw(canvas); } } } </code></pre> <p>Finally, here's an <strong>attrs.xml</strong> file you need to put in <strong>res/values</strong> so the code can get at platform-defined attributes.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="CompoundButton"&gt; &lt;attr name="android:button" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre>
4,156,011
How to select rows for a specific date, ignoring time in SQL Server
<p>Given a table with a datetime column, how do I query for rows where the date matches the value I specify but ignores the time portion?</p> <p>For example, <code>select * from sales where salesDate = '11/11/2010'</code></p> <p>For this query we don't care about the time. Other queries require the time component so we can't store only the date component.</p> <p>Thanks!</p>
4,156,090
8
0
null
2010-11-11 15:24:34.753 UTC
13
2022-01-08 19:15:16.337 UTC
2014-04-08 22:53:01.35 UTC
null
3,133,871
null
98,215
null
1
58
sql|sql-server-2005
225,468
<p>You can remove the time component when comparing:</p> <pre><code>SELECT * FROM sales WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, salesDate))) = '11/11/2010' </code></pre> <p>Another approach is to change the select to cover all the time between the start and end of the date:</p> <pre><code>SELECT * FROM sales -- WHERE salesDate BETWEEN '11/11/2010 00:00:00.00' AND '11/11/2010 23:59:59.999' WHERE salesDate BETWEEN '2020-05-18T00:00:00.00' AND '2020-05-18T23:59:59.999' </code></pre>
4,820,816
How to get URI from an asset File?
<p>I have been trying to get the URI path for an asset file. </p> <pre><code>uri = Uri.fromFile(new File("//assets/mydemo.txt")); </code></pre> <p>When I check if the file exists I see that file doesn't exist</p> <pre><code>File f = new File(filepath); if (f.exists() == true) { Log.e(TAG, "Valid :" + filepath); } else { Log.e(TAG, "InValid :" + filepath); } </code></pre> <p>Can some one tell me how I can mention the absolute path for a file existing in the asset folder</p>
4,820,905
12
0
null
2011-01-27 19:22:45.907 UTC
24
2022-05-07 11:41:18.353 UTC
2015-09-03 13:25:05.403 UTC
null
553,488
null
592,773
null
1
155
android|uri|filepath|assets
278,832
<p>There is no "absolute path for a file existing in the asset folder". The content of your project's <code>assets/</code> folder are packaged in the APK file. Use an <a href="http://developer.android.com/reference/android/content/res/AssetManager.html" rel="noreferrer"><code>AssetManager</code></a> object to get an <code>InputStream</code> on an asset.</p> <p>For <code>WebView</code>, you can use the <code>file</code> <code>Uri</code> scheme in much the same way you would use a URL. The syntax for assets is <code>file:///android_asset/...</code> (note: three slashes) where the ellipsis is the path of the file from within the <code>assets/</code> folder.</p>
4,216,745
Java string to date conversion
<p>What is the best way to convert a <code>String</code> in the format 'January 2, 2010' to a <code>Date</code> in Java?</p> <p>Ultimately, I want to break out the month, the day, and the year as integers so that I can use</p> <pre><code>Date date = new Date(); date.setMonth().. date.setYear().. date.setDay().. date.setlong currentTime = date.getTime(); </code></pre> <p>to convert the date into time.</p>
4,216,767
17
7
null
2010-11-18 15:53:01.24 UTC
364
2021-11-21 08:15:31.043 UTC
2018-06-25 13:53:42.593 UTC
null
8,583,692
null
123,891
null
1
984
java|string|date|time|data-conversion
2,291,755
<p>That's the hard way, and those <code>java.util.Date</code> setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole <code>java.util.Date</code> class was de-facto deprecated (discommended) since introduction of <code>java.time</code> API in Java 8 (2014).</p> <p>Simply format the date using <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer"><code>DateTimeFormatter</code></a> with a pattern matching the input string (<a href="https://docs.oracle.com/javase/tutorial/datetime/iso/format.html" rel="noreferrer">the tutorial is available here</a>).</p> <p>In your specific case of &quot;January 2, 2010&quot; as the input string:</p> <ol> <li>&quot;January&quot; is the full text month, so use the <code>MMMM</code> pattern for it</li> <li>&quot;2&quot; is the short day-of-month, so use the <code>d</code> pattern for it.</li> <li>&quot;2010&quot; is the 4-digit year, so use the <code>yyyy</code> pattern for it.</li> </ol> <pre><code>String string = &quot;January 2, 2010&quot;; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;MMMM d, yyyy&quot;, Locale.ENGLISH); LocalDate date = LocalDate.parse(string, formatter); System.out.println(date); // 2010-01-02 </code></pre> <p>Note: if your format pattern happens to contain the time part as well, then use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>LocalDateTime#parse(text, formatter)</code></a> instead of <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>LocalDate#parse(text, formatter)</code></a>. And, if your format pattern happens to contain the time zone as well, then use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>ZonedDateTime#parse(text, formatter)</code></a> instead.</p> <p>Here's an extract of relevance from <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer">the javadoc</a>, listing all available format patterns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Symbol</th> <th>Meaning</th> <th>Presentation</th> <th>Examples</th> </tr> </thead> <tbody> <tr> <td><code>G</code></td> <td>era</td> <td>text</td> <td>AD; Anno Domini; A</td> </tr> <tr> <td><code>u</code></td> <td>year</td> <td>year</td> <td>2004; 04</td> </tr> <tr> <td><code>y</code></td> <td>year-of-era</td> <td>year</td> <td>2004; 04</td> </tr> <tr> <td><code>D</code></td> <td>day-of-year</td> <td>number</td> <td>189</td> </tr> <tr> <td><code>M</code>/<code>L</code></td> <td>month-of-year</td> <td>number/text</td> <td>7; 07; Jul; July; J</td> </tr> <tr> <td><code>d</code></td> <td>day-of-month</td> <td>number</td> <td>10</td> </tr> <tr> <td><code>Q</code>/<code>q</code></td> <td>quarter-of-year</td> <td>number/text</td> <td>3; 03; Q3; 3rd quarter</td> </tr> <tr> <td><code>Y</code></td> <td>week-based-year</td> <td>year</td> <td>1996; 96</td> </tr> <tr> <td><code>w</code></td> <td>week-of-week-based-year</td> <td>number</td> <td>27</td> </tr> <tr> <td><code>W</code></td> <td>week-of-month</td> <td>number</td> <td>4</td> </tr> <tr> <td><code>E</code></td> <td>day-of-week</td> <td>text</td> <td>Tue; Tuesday; T</td> </tr> <tr> <td><code>e</code>/<code>c</code></td> <td>localized day-of-week</td> <td>number/text</td> <td>2; 02; Tue; Tuesday; T</td> </tr> <tr> <td><code>F</code></td> <td>week-of-month</td> <td>number</td> <td>3</td> </tr> <tr> <td><code>a</code></td> <td>am-pm-of-day</td> <td>text</td> <td>PM</td> </tr> <tr> <td><code>h</code></td> <td>clock-hour-of-am-pm (1-12)</td> <td>number</td> <td>12</td> </tr> <tr> <td><code>K</code></td> <td>hour-of-am-pm (0-11)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>k</code></td> <td>clock-hour-of-am-pm (1-24)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>H</code></td> <td>hour-of-day (0-23)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>m</code></td> <td>minute-of-hour</td> <td>number</td> <td>30</td> </tr> <tr> <td><code>s</code></td> <td>second-of-minute</td> <td>number</td> <td>55</td> </tr> <tr> <td><code>S</code></td> <td>fraction-of-second</td> <td>fraction</td> <td>978</td> </tr> <tr> <td><code>A</code></td> <td>milli-of-day</td> <td>number</td> <td>1234</td> </tr> <tr> <td><code>n</code></td> <td>nano-of-second</td> <td>number</td> <td>987654321</td> </tr> <tr> <td><code>N</code></td> <td>nano-of-day</td> <td>number</td> <td>1234000000</td> </tr> <tr> <td><code>V</code></td> <td>time-zone ID</td> <td>zone-id</td> <td>America/Los_Angeles; Z; -08:30</td> </tr> <tr> <td><code>z</code></td> <td>time-zone name</td> <td>zone-name</td> <td>Pacific Standard Time; PST</td> </tr> <tr> <td><code>O</code></td> <td>localized zone-offset</td> <td>offset-O</td> <td>GMT+8; GMT+08:00; UTC-08:00;</td> </tr> <tr> <td><code>X</code></td> <td>zone-offset 'Z' for zero</td> <td>offset-X</td> <td>Z; -08; -0830; -08:30; -083015; -08:30:15;</td> </tr> <tr> <td><code>x</code></td> <td>zone-offset</td> <td>offset-x</td> <td>+0000; -08; -0830; -08:30; -083015; -08:30:15;</td> </tr> <tr> <td><code>Z</code></td> <td>zone-offset</td> <td>offset-Z</td> <td>+0000; -0800; -08:00;</td> </tr> </tbody> </table> </div> <p>Do note that it has several <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined" rel="noreferrer">predefined formatters</a> for the more popular patterns. So instead of e.g. <code>DateTimeFormatter.ofPattern(&quot;EEE, d MMM yyyy HH:mm:ss Z&quot;, Locale.ENGLISH);</code>, you could use <code>DateTimeFormatter.RFC_1123_DATE_TIME</code>. This is possible because they are, on the contrary to <code>SimpleDateFormat</code>, thread safe. You could thus also define your own, if necessary.</p> <p>For a particular input string format, you don't need to use an explicit <code>DateTimeFormatter</code>: a standard <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> date, like 2016-09-26T17:44:57Z, can be parsed directly with <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>LocalDateTime#parse(text)</code></a> as it already uses the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME" rel="noreferrer"><code>ISO_LOCAL_DATE_TIME</code></a> formatter. Similarly, <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>LocalDate#parse(text)</code></a> parses an ISO date without the time component (see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE" rel="noreferrer"><code>ISO_LOCAL_DATE</code></a>), and <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>ZonedDateTime#parse(text)</code></a> parses an ISO date with an offset and time zone added (see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_ZONED_DATE_TIME" rel="noreferrer"><code>ISO_ZONED_DATE_TIME</code></a>).</p> <hr /> <h2>Pre-Java 8</h2> <p>In case you're not on Java 8 yet, or are forced to use <code>java.util.Date</code>, then format the date using <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a> using a format pattern matching the input string.</p> <pre><code>String string = &quot;January 2, 2010&quot;; DateFormat format = new SimpleDateFormat(&quot;MMMM d, yyyy&quot;, Locale.ENGLISH); Date date = format.parse(string); System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010 </code></pre> <p>Note the importance of the explicit <code>Locale</code> argument. If you omit it, then it will use the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#getDefault--" rel="noreferrer">default locale</a> which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a <code>java.text.ParseException</code> even though when the format pattern seems valid.</p> <p>Here's an extract of relevance from <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">the javadoc</a>, listing all available format patterns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Letter</th> <th>Date or Time Component</th> <th>Presentation</th> <th>Examples</th> </tr> </thead> <tbody> <tr> <td><code>G</code></td> <td>Era designator</td> <td>Text</td> <td>AD</td> </tr> <tr> <td><code>y</code></td> <td>Year</td> <td>Year</td> <td>1996; 96</td> </tr> <tr> <td><code>Y</code></td> <td>Week year</td> <td>Year</td> <td>2009; 09</td> </tr> <tr> <td><code>M</code>/<code>L</code></td> <td>Month in year</td> <td>Month</td> <td>July; Jul; 07</td> </tr> <tr> <td><code>w</code></td> <td>Week in year</td> <td>Number</td> <td>27</td> </tr> <tr> <td><code>W</code></td> <td>Week in month</td> <td>Number</td> <td>2</td> </tr> <tr> <td><code>D</code></td> <td>Day in year</td> <td>Number</td> <td>189</td> </tr> <tr> <td><code>d</code></td> <td>Day in month</td> <td>Number</td> <td>10</td> </tr> <tr> <td><code>F</code></td> <td>Day of week in month</td> <td>Number</td> <td>2</td> </tr> <tr> <td><code>E</code></td> <td>Day in week</td> <td>Text</td> <td>Tuesday; Tue</td> </tr> <tr> <td><code>u</code></td> <td>Day number of week</td> <td>Number</td> <td>1</td> </tr> <tr> <td><code>a</code></td> <td>Am/pm marker</td> <td>Text</td> <td>PM</td> </tr> <tr> <td><code>H</code></td> <td>Hour in day (0-23)</td> <td>Number</td> <td>0</td> </tr> <tr> <td><code>k</code></td> <td>Hour in day (1-24)</td> <td>Number</td> <td>24</td> </tr> <tr> <td><code>K</code></td> <td>Hour in am/pm (0-11)</td> <td>Number</td> <td>0</td> </tr> <tr> <td><code>h</code></td> <td>Hour in am/pm (1-12)</td> <td>Number</td> <td>12</td> </tr> <tr> <td><code>m</code></td> <td>Minute in hour</td> <td>Number</td> <td>30</td> </tr> <tr> <td><code>s</code></td> <td>Second in minute</td> <td>Number</td> <td>55</td> </tr> <tr> <td><code>S</code></td> <td>Millisecond</td> <td>Number</td> <td>978</td> </tr> <tr> <td><code>z</code></td> <td>Time zone</td> <td>General time zone</td> <td>Pacific Standard Time; PST; GMT-08:00</td> </tr> <tr> <td><code>Z</code></td> <td>Time zone</td> <td>RFC 822 time zone</td> <td>-0800</td> </tr> <tr> <td><code>X</code></td> <td>Time zone</td> <td>ISO 8601 time zone</td> <td>-08; -0800; -08:00</td> </tr> </tbody> </table> </div> <p>Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. <code>MMMMM</code> or more is unnecessary.</p> <p>Here are some examples of valid <code>SimpleDateFormat</code> patterns to parse a given string to date:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Input string</th> <th>Pattern</th> </tr> </thead> <tbody> <tr> <td>2001.07.04 AD at 12:08:56 PDT</td> <td><code>yyyy.MM.dd G 'at' HH:mm:ss z</code></td> </tr> <tr> <td>Wed, Jul 4, '01</td> <td><code>EEE, MMM d, ''yy</code></td> </tr> <tr> <td>12:08 PM</td> <td><code>h:mm a</code></td> </tr> <tr> <td>12 o'clock PM, Pacific Daylight Time</td> <td><code>hh 'o''clock' a, zzzz</code></td> </tr> <tr> <td>0:08 PM, PDT</td> <td><code>K:mm a, z</code></td> </tr> <tr> <td>02001.July.04 AD 12:08 PM</td> <td><code>yyyyy.MMMM.dd GGG hh:mm aaa</code></td> </tr> <tr> <td>Wed, 4 Jul 2001 12:08:56 -0700</td> <td><code>EEE, d MMM yyyy HH:mm:ss Z</code></td> </tr> <tr> <td>010704120856-0700</td> <td><code>yyMMddHHmmssZ</code></td> </tr> <tr> <td>2001-07-04T12:08:56.235-0700</td> <td><code>yyyy-MM-dd'T'HH:mm:ss.SSSZ</code></td> </tr> <tr> <td>2001-07-04T12:08:56.235-07:00</td> <td><code>yyyy-MM-dd'T'HH:mm:ss.SSSXXX</code></td> </tr> <tr> <td>2001-W27-3</td> <td><code>YYYY-'W'ww-u</code></td> </tr> </tbody> </table> </div> <p>An important note is that <code>SimpleDateFormat</code> is <strong>not</strong> thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope.</p>
4,654,636
How to determine if a string is a number with C++?
<p>I've had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way). I wrote the below function which I believe was working smoothly (or I accidentally edited to stop it or I'm schizophrenic or Windows is schizophrenic):</p> <pre><code>bool isParam (string line) { if (isdigit(atoi(line.c_str()))) return true; return false; } </code></pre>
4,654,718
35
8
null
2011-01-11 05:51:31.32 UTC
49
2022-09-03 17:17:45.243 UTC
2018-11-08 00:20:46.863 UTC
null
1,666,510
null
546,901
null
1
168
c++|visual-c++
450,355
<p>The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.</p> <pre><code>bool is_number(const std::string&amp; s) { std::string::const_iterator it = s.begin(); while (it != s.end() &amp;&amp; std::isdigit(*it)) ++it; return !s.empty() &amp;&amp; it == s.end(); } </code></pre> <p>Or if you want to do it the C++11 way:</p> <pre><code>bool is_number(const std::string&amp; s) { return !s.empty() &amp;&amp; std::find_if(s.begin(), s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end(); } </code></pre> <p>As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.</p>
14,524,751
Cast Object to Generic Type for returning
<p>Is there a way to cast an object to return value of a method? I tried this way but it gave a compile time exception in "instanceof" part:</p> <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o) { if (o instanceof T) { return (T) o; } else { return null; } } </code></pre> <p>I also tried this one but it gave a runtime exception, ClassCastException:</p> <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o) { try { T rv = (T)o; return rv; } catch(java.lang.ClassCastException e) { return null; } } </code></pre> <p>Is there a possible way of doing this easily:</p> <pre><code>String s = convertInstanceOfObject("string"); System.out.println(s); // should print "string" Integer i = convertInstanceOfObject(4); System.out.println(i); // should print "4" String k = convertInstanceOfObject(345435.34); System.out.println(k); // should print "null" </code></pre> <p>EDIT: I wrote a working copy of the correct answer:</p> <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o, Class&lt;T&gt; clazz) { try { return clazz.cast(o); } catch(ClassCastException e) { return null; } } public static void main(String args[]) { String s = convertInstanceOfObject("string", String.class); System.out.println(s); Integer i = convertInstanceOfObject(4, Integer.class); System.out.println(i); String k = convertInstanceOfObject(345435.34, String.class); System.out.println(k); } </code></pre>
14,524,815
3
2
null
2013-01-25 15:16:54.22 UTC
56
2018-06-28 09:01:47.467 UTC
2013-01-25 15:34:27.77 UTC
null
618,279
null
618,279
null
1
167
java|generics|casting
262,062
<p>You have to use a <code>Class</code> instance because of the generic type erasure during compilation.</p> <pre><code>public static &lt;T&gt; T convertInstanceOfObject(Object o, Class&lt;T&gt; clazz) { try { return clazz.cast(o); } catch(ClassCastException e) { return null; } } </code></pre> <p>The declaration of <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#cast%28java.lang.Object%29" rel="noreferrer">that method</a> is:</p> <pre><code>public T cast(Object o) </code></pre> <p>This can also be used for array types. It would look like this:</p> <pre><code>final Class&lt;int[]&gt; intArrayType = int[].class; final Object someObject = new int[]{1,2,3}; final int[] instance = convertInstanceOfObject(someObject, intArrayType); </code></pre> <p>Note that when <code>someObject</code> is passed to <code>convertToInstanceOfObject</code> it has the compile time type <code>Object</code>.</p>
14,901,245
How to style a JSON block in Github Wiki?
<p>Is there a way to nicely format/style <code>JSON</code> code in <code>Github Wiki</code> (i.e Markdown preferred)?</p> <p>Something like this with few colors (or bold) and correct indentation:</p> <p><a href="http://www.freeformatter.com/json-formatter.html#ad-output" rel="noreferrer">http://www.freeformatter.com/json-formatter.html#ad-output</a></p>
14,901,880
4
2
null
2013-02-15 18:39:42.267 UTC
22
2022-04-28 00:16:46.897 UTC
2020-09-04 06:24:56.297 UTC
null
5,953,610
null
149,367
null
1
251
json|github|markdown|wiki
251,891
<p>Some color-syntaxing enrichment can be applied with the following blockcode syntax</p> <pre><code>```json Here goes your json object definition ``` </code></pre> <p><strong>Note:</strong> This won't prettify the json representation. To do so, one can previously rely on an external service such as <strong><a href="http://jsbeautifier.org/">jsbeautifier.org</a></strong> and paste the prettified result in the wiki.</p>
3,013,382
MATLAB - read files from directory?
<p>I wish to read files from a directory and iteratively perform an operation on each file. This operation does not require altering the file.</p> <p>I understand that I should use a for loop for this. Thus far I have tried:</p> <pre><code>FILES = ls('path\to\folder'); for i = 1:size(FILES, 1); STRU = pdbread(FILES{i}); end </code></pre> <p>The error returned here suggests to me, a novice, that listing a directory with ls() does not assign the contents to a data structure.</p> <p>Secondly I tried creating a file containing on each line a path to a file, e.g.,</p> <pre><code>C:\Documents and Settings\My Documents\MATLAB\asd.pdb C:\Documents and Settings\My Documents\MATLAB\asd.pdb </code></pre> <p>I then read this file using the following code:</p> <pre><code>fid = fopen('paths_to_files.txt'); FILES = textscan(fid, '%s'); FILES = FILES{1}; fclose(fid); </code></pre> <p>This code reads the file but creates a newline where a space exists in the pathway, i.e.</p> <pre><code>'C:\Documents' 'and' 'Setting\My' 'Documents\MATLAB\asd.pdb' </code></pre> <p>Ultimately, I then intended to use the for loop</p> <pre><code>for i = 1:size(FILES, 1) PDB = pdbread(char(FILES{i})); </code></pre> <p>to read each file but pdbread() throws an error proclaiming that the file is of incorrect format or does not exist.</p> <p>Is this due to the newline separation of paths when the pathway file is read in?</p> <p>Any help or suggestions greatly apppreciated.</p> <p>Thanks, S :-)</p>
3,013,516
2
0
null
2010-06-10 10:04:16.657 UTC
1
2016-02-06 20:17:54.323 UTC
null
null
null
null
233,816
null
1
13
matlab|file|directory
56,934
<p>First Get a list of all files matching your criteria:<br> ( in this case <strong>pdb</strong> files in <strong>C:\My Documents\MATLAB</strong> )</p> <pre><code>matfiles = dir(fullfile('C:', 'My Documents', 'MATLAB', '*.pdb')) </code></pre> <p>Then read in a file as follows:<br> ( Here <strong><code>i</code></strong> can vary from 1 to the number of files )</p> <pre><code>data = load(matfiles(i).name) </code></pre> <p>Repeat this until you have read all your files.</p> <hr> <p>A <strong>simpler alternative</strong> if you can <strong>rename your files</strong> is as follows:-</p> <p>First save the reqd. files as 1.pdb, 2.pdb, 3.pdb,... etc.</p> <p>Then the code to read them iteratively in Matlab is as follows:</p> <pre><code>for i = 1:n str = strcat('C:\My Documents\MATLAB', int2str(i),'.pdb'); data = load(matfiles(i).name); % use our logic here % before proceeding to the next file end </code></pre>
2,349,339
How do I replace an item in a string array?
<p>Using C# how do I replace an item text in a string array if I don't know the position? </p> <p>My array is [berlin, london, paris] how do I replace paris with new york?</p>
2,349,348
2
0
null
2010-02-27 23:13:08.857 UTC
3
2015-07-08 11:15:53.19 UTC
2012-02-07 19:00:32.697 UTC
null
76,337
null
132,801
null
1
21
c#|arrays
73,037
<p>You need to address it by index:</p> <pre><code>arr[2] = "new york"; </code></pre> <p>Since you say you don't know the position, you can use Array.IndexOf to find it:</p> <pre><code>arr[Array.IndexOf(arr, "paris")] = "new york"; // ignoring error handling </code></pre>
50,145,627
Is it possible to decompile a C++ executable file
<p>I lost the source code to an executable file but still have the actual file. Is there any way to retrieve the original C++ code?</p>
50,145,647
3
3
null
2018-05-03 01:17:01.89 UTC
2
2018-05-03 01:23:40.7 UTC
null
null
null
null
7,669,003
null
1
11
c++|executable|decompiling
83,200
<p><strong>Duplicate of <a href="https://stackoverflow.com/questions/273145/is-it-possible-to-decompile-a-windows-exe-or-at-least-view-the-assembly">this question here.</a></strong></p> <p>Yes, it is possible, however when it comes to peeking function bodies and the like, you might have a little less luck. Operating systems like Kali Linux specialize in de-compilation and reverse engineering, so maybe look into a VM of that. And of course, windows has a lot of applications you can use as well to check the application code.</p> <p>Look over the other question for specific app suggestions. :)</p> <ul> <li>Edit : You will most likely have lost all your logic and function bodies, but you might be able to recover the overall structure. It's your EXE so you might be more familiar with how it was all connected up.</li> </ul>
20,583,339
Autofac and Func factories
<p>I'm working on an application using Caliburn.Micro and Autofac.</p> <p>In my composition root I'm now facing a problem with Autofac: I have to inject the globally used IEventAggregator into my FirstViewModel, and a second IEventAggregator that has to be used only by this FirstViewModel and it's children.</p> <p>My idea was to make the second one be injected as <code>Owned&lt;IEA&gt;</code>, and it works, the container provides a different instance of IEA.</p> <pre class="lang-cs prettyprint-override"><code>public FirstViewModel( IEventAggregator globalEA, IEventAggregator localEA, Func&lt;IEventAggregator, SecondViewModel&gt; secVMFactory) {} </code></pre> <p>The problem comes when I have to provide the event aggregators to the SecondViewModel.</p> <p>To create the SecondViewModel I use a factory method as <code>Func&lt;IEA, SecondVM&gt;</code>. The SecondViewModel's constructor is the following:</p> <p><code>public SecondViewModel(IEventAggregator globalEA, IEventAggregator localEA) {}</code></p> <p>I want the container to inject the first as the registered one, and the second will be the IEA parameter of the <code>Func&lt;IEA, SecVM&gt;</code>.</p> <p>this is the function I registered in the container:</p> <pre class="lang-cs prettyprint-override"><code>builder.Register&lt;Func&lt;IEventAggregator, SecondViewModel&gt;&gt;( c =&gt; (ea) =&gt; { return new SecondViewModel( c.Resolve&lt;IEventAggregator&gt;(), ea); } ); </code></pre> <p>but when it gets called by the <code>FirstViewModel</code> I get the following error:</p> <blockquote> <p>An exception of type 'System.ObjectDisposedException' occurred in Autofac.dll but was not handled in user code</p> <p>Additional information: This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c', or resolve a Func&lt;&gt; based factory to create subsequent components from.</p> </blockquote> <p>I can't understand where the problem is, can you help me please, what am I missing?</p> <p>Thank you.</p>
20,583,876
1
0
null
2013-12-14 12:33:07.89 UTC
11
2014-08-04 01:21:11.74 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,790,497
null
1
32
.net|mvvm|dependency-injection|autofac|caliburn.micro
18,540
<p>You are calling <code>secVMFactory</code> outside of your <code>FirstViewModel</code> constructor so by that time the ResolveOperation is disposed and in your factory method the <code>c.Resolve</code> will throw the exception.</p> <p>Luckily the exception message is very descriptive and telling you what to do:</p> <blockquote> <p>When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c'</p> </blockquote> <p>So instead of calling <code>c.Resolve</code> you need to resolve the <code>IComponentContext</code> from <code>c</code> and use that in your factory func:</p> <pre class="lang-cs prettyprint-override"><code>builder.Register&lt;Func&lt;IEventAggregator, SecondViewModel&gt;&gt;(c =&gt; { var context = c.Resolve&lt;IComponentContext&gt;(); return ea =&gt; { return new SecondViewModel(context.Resolve&lt;IEventAggregator&gt;(), ea); }; }); </code></pre>
53,550,321
Keycloak-gatekeeper: 'aud' claim and 'client_id' do not match
<p>What is the correct way to set the <code>aud</code> claim to avoid the error below?</p> <pre><code>unable to verify the id token {"error": "oidc: JWT claims invalid: invalid claims, 'aud' claim and 'client_id' do not match, aud=account, client_id=webapp"} </code></pre> <p>I kinda worked around this error message by hardcoding <code>aud</code> claim to be the same as my <code>client_id</code>. Is there any better way?</p> <p>Here is my <code>docker-compose.yml</code>:</p> <pre><code>version: '3' services: keycloak-proxy: image: "keycloak/keycloak-gatekeeper" environment: - PROXY_LISTEN=0.0.0.0:3000 - PROXY_DISCOVERY_URL=http://keycloak.example.com:8181/auth/realms/realmcom - PROXY_CLIENT_ID=webapp - PROXY_CLIENT_SECRET=0b57186c-e939-48ff-aa17-cfd3e361f65e - PROXY_UPSTREAM_URL=http://test-server:8000 ports: - "8282:3000" command: - "--verbose" - "--enable-refresh-tokens=true" - "--enable-default-deny=true" - "--resources=uri=/*" - "--enable-session-cookies=true" - "--encryption-key=AgXa7xRcoClDEU0ZDSH4X0XhL5Qy2Z2j" test-server: image: "test-server" </code></pre>
53,627,747
4
0
null
2018-11-30 02:20:54.977 UTC
26
2022-08-11 14:16:54.15 UTC
null
null
null
null
255,633
null
1
46
keycloak|keycloak-gatekeeper
42,987
<p>With recent keycloak version 4.6.0 the client id is apparently no longer automatically added to the audience field 'aud' of the access token. Therefore even though the login succeeds the client rejects the user. To fix this you need to configure the audience for your clients (compare doc [2]). </p> <h2>Configure audience in Keycloak</h2> <ul> <li>Add realm or configure existing</li> <li>Add client my-app or use existing</li> <li>Goto to the newly added "Client Scopes" menu [1] <ul> <li>Add Client scope 'good-service' </li> <li>Within the settings of the 'good-service' goto Mappers tab <ul> <li>Create Protocol Mapper 'my-app-audience' <ul> <li>Name: my-app-audience</li> <li>Choose Mapper type: Audience</li> <li>Included Client Audience: my-app</li> <li>Add to access token: on</li> </ul></li> </ul></li> </ul></li> <li>Configure client my-app in the "Clients" menu <ul> <li>Client Scopes tab in my-app settings</li> <li>Add available client scopes "good-service" to assigned default client scopes</li> </ul></li> </ul> <p>If you have more than one client repeat the steps for the other clients as well and add the good-service scope. The intention behind this is to isolate client access. The issued access token will only be valid for the intended audience. This is thoroughly described in Keycloak's documentation [1,2].</p> <h3>Links to recent master version of keycloak documentation:</h3> <ul> <li>[1] <a href="https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/client-scopes.adoc" rel="noreferrer">https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/client-scopes.adoc</a></li> <li>[2] <a href="https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/oidc/audience.adoc" rel="noreferrer">https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/oidc/audience.adoc</a></li> </ul> <h3>Links with git tag:</h3> <ul> <li>[1] <a href="https://github.com/keycloak/keycloak-documentation/blob/f490e1fba7445542c2db0b4202647330ddcdae53/server_admin/topics/clients/oidc/audience.adoc" rel="noreferrer">https://github.com/keycloak/keycloak-documentation/blob/f490e1fba7445542c2db0b4202647330ddcdae53/server_admin/topics/clients/oidc/audience.adoc</a></li> <li>[2] <a href="https://github.com/keycloak/keycloak-documentation/blob/5e340356e76a8ef917ef3bfc2e548915f527d093/server_admin/topics/clients/client-scopes.adoc" rel="noreferrer">https://github.com/keycloak/keycloak-documentation/blob/5e340356e76a8ef917ef3bfc2e548915f527d093/server_admin/topics/clients/client-scopes.adoc</a></li> </ul>
44,513,738
Pandas create empty DataFrame with only column names
<p>I have a dynamic DataFrame which works fine, but when there are no data to be added into the DataFrame I get an error. And therefore I need a solution to create an empty DataFrame with only the column names.</p> <p>For now I have something like this:</p> <pre><code>df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there are now row data inserted. </code></pre> <p>PS: It is important that the column names would still appear in a DataFrame.</p> <p>But when I use it like this I get something like that as a result:</p> <pre><code>Index([], dtype='object') Empty DataFrame </code></pre> <p>The "Empty DataFrame" part is good! But instead of the Index thing I need to still display the columns.</p> <p>Edit:</p> <p>An important thing that I found out: I am converting this DataFrame to a PDF using Jinja2, so therefore I'm calling out a method to first output it to HTML like that:</p> <pre><code>df.to_html() </code></pre> <p>This is where the columns get lost I think.</p> <p>Edit2: In general, I followed this example: <a href="http://pbpython.com/pdf-reports.html" rel="noreferrer">http://pbpython.com/pdf-reports.html</a>. The css is also from the link. That's what I do to send the dataframe to the PDF:</p> <pre><code>env = Environment(loader=FileSystemLoader('.')) template = env.get_template("pdf_report_template.html") template_vars = {"my_dataframe": df.to_html()} html_out = template.render(template_vars) HTML(string=html_out).write_pdf("my_pdf.pdf", stylesheets=["pdf_report_style.css"]) </code></pre> <p>Edit3:</p> <p>If I print out the dataframe right after creation I get the followin:</p> <pre><code>[0 rows x 9 columns] Empty DataFrame Columns: [column_a, column_b, column_c, column_d, column_e, column_f, column_g, column_h, column_i] Index: [] </code></pre> <p>That seems reasonable, but if I print out the template_vars:</p> <pre><code>'my_dataframe': '&lt;table border="1" class="dataframe"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt;Index([], dtype=\'object\')&lt;/td&gt;\n &lt;td&gt;Empty DataFrame&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;' </code></pre> <p>And it seems that the columns are missing already.</p> <p>E4: If I print out the following:</p> <pre><code>print(df.to_html()) </code></pre> <p>I get the following result already:</p> <pre><code>&lt;table border="1" class="dataframe"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Index([], dtype='object')&lt;/td&gt; &lt;td&gt;Empty DataFrame&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
44,514,187
4
0
null
2017-06-13 06:22:57.92 UTC
57
2021-01-19 02:23:37.263 UTC
2017-06-13 10:40:35.02 UTC
null
1,772,193
null
1,772,193
null
1
279
python|pandas|dataframe
556,792
<p>You can create an empty DataFrame with either column names or an Index:</p> <pre><code>In [4]: import pandas as pd In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G']) In [6]: df Out[6]: Empty DataFrame Columns: [A, B, C, D, E, F, G] Index: [] </code></pre> <p>Or</p> <pre><code>In [7]: df = pd.DataFrame(index=range(1,10)) In [8]: df Out[8]: Empty DataFrame Columns: [] Index: [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>Edit: Even after your amendment with the .to_html, I can't reproduce. This:</p> <pre><code>df = pd.DataFrame(columns=['A','B','C','D','E','F','G']) df.to_html('test.html') </code></pre> <p>Produces:</p> <pre><code>&lt;table border="1" class="dataframe"&gt; &lt;thead&gt; &lt;tr style="text-align: right;"&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;A&lt;/th&gt; &lt;th&gt;B&lt;/th&gt; &lt;th&gt;C&lt;/th&gt; &lt;th&gt;D&lt;/th&gt; &lt;th&gt;E&lt;/th&gt; &lt;th&gt;F&lt;/th&gt; &lt;th&gt;G&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
2,954,022
MySQL/PHP Search Efficiency
<p>I'm trying to create a small search for my site. I've tried using full-text index search, but I could never get it to work. Here is what I've come up with:</p> <pre><code>if(isset($_GET['search'])) { $search = str_replace('-', ' ', $_GET['search']); $result = array(); $titles = mysql_query("SELECT title FROM Entries WHERE title LIKE '%$search%'"); while($row = mysql_fetch_assoc($titles)) { $result[] = $row['title']; } $tags = mysql_query("SELECT title FROM Entries WHERE tags LIKE '%$search%'"); while($row = mysql_fetch_assoc($tags)) { $result[] = $row['title']; } $text = mysql_query("SELECT title FROM Entries WHERE entry LIKE '%$search%'"); while($row = mysql_fetch_assoc($text)) { $result[] = $row['title']; } $result = array_unique($result); } </code></pre> <p>So basically, it searches through all the titles, body-text, and tags of all the entries in the DB. This works decently well, but I'm just wondering how efficient would it be? This would only be for a small blog, too. Either way I'm just wondering if this could be made any more efficient.</p>
2,954,062
3
0
null
2010-06-01 23:21:45.41 UTC
9
2012-11-01 16:04:56.54 UTC
2010-06-01 23:45:08.08 UTC
null
65,732
null
218,913
null
1
8
php|mysql|search|performance
6,569
<p>There's no way to make <code>LIKE '%pattern%'</code> queries efficient. Once you get a nontrivial amount of data, using those wildcard queries performs hundreds or thousands of times slower than using a fulltext indexing solution.</p> <p>You should look at the presentation I did for MySQL University: <a href="http://www.slideshare.net/billkarwin/practical-full-text-search-with-my-sql" rel="noreferrer">http://www.slideshare.net/billkarwin/practical-full-text-search-with-my-sql</a></p> <p>Here's how to get it to work:</p> <ol> <li><p>First make sure your table uses the MyISAM storage engine. MySQL FULLTEXT indexes support only MyISAM tables. (<strong>edit 11/1/2012:</strong> MySQL 5.6 is introducing a FULLTEXT index type for InnoDB tables.)</p> <pre><code>ALTER TABLE Entries ENGINE=MyISAM; </code></pre></li> <li><p>Create a fulltext index.</p> <pre><code>CREATE FULLTEXT INDEX searchindex ON Entries(title, tags, entry); </code></pre></li> <li><p>Search it!</p> <pre><code>$search = mysql_real_escape_string($search); $titles = mysql_query("SELECT title FROM Entries WHERE MATCH(title, tags, entry) AGAINST('$search')"); while($row = mysql_fetch_assoc($titles)) { $result[] = $row['title']; } </code></pre> <p>Note that the columns you name in the <code>MATCH</code> clause <em>must</em> be the same columns in the same order as those you declared in the fulltext index definition. Otherwise it won't work.</p></li> </ol> <hr> <blockquote> <p>I've tried using full-text index search, but I could never get it to work... I'm just wondering if this could be made any more efficient.</p> </blockquote> <p>This is exactly like saying, "I couldn't figure out how to use this chainsaw, so I decided to cut down this redwood tree with a pocketknife. How can I make that work as well as the chainsaw?"</p> <hr> <p>Regarding your comment about searching for words that match more than 50% of the rows.</p> <p>The MySQL manual says <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-natural-language.html" rel="noreferrer">this</a>:</p> <blockquote> <p>Users who need to bypass the 50% limitation can use the boolean search mode; see <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html" rel="noreferrer">Section 11.8.2, “Boolean Full-Text Searches”</a>. </p> </blockquote> <p>And <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-fine-tuning.html" rel="noreferrer">this</a>:</p> <blockquote> <p>The 50% threshold for natural language searches is determined by the particular weighting scheme chosen. To disable it, look for the following line in storage/myisam/ftdefs.h:</p> <p>#define GWS_IN_USE GWS_PROB</p> <p>Change that line to this:</p> <p>#define GWS_IN_USE GWS_FREQ</p> <p>Then recompile MySQL. There is no need to rebuild the indexes in this case.</p> </blockquote> <p>Also, you might be searching for <em>stopwords</em>. These are words that are ignored by the fulltext search because they're too common. Words like "the" and so on. See <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-stopwords.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/fulltext-stopwords.html</a></p>
38,858,977
"grep -rnw": search for a string in all files
<p>Related question: <a href="https://stackoverflow.com/questions/16956810/finding-all-files-containing-a-text-string-on-linux">How do I find all files containing specific text on Linux?</a></p> <p>I have been using the command mentioned in the answer of above question to search for string occurences in all files:</p> <pre><code>grep -rnw '/path/to/somewhere/' -e "pattern" </code></pre> <p>However lately I encountered a problem, shown in the following picture: <a href="https://i.stack.imgur.com/ckOL9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ckOL9.png" alt="enter image description here"></a></p> <p>Looks like this command only recognizes strings that stand out as a word or something. How should I modify the command to improve my search result?</p>
38,859,459
1
0
null
2016-08-09 19:31:24.087 UTC
3
2016-08-09 20:02:18.01 UTC
2017-05-23 12:10:11.31 UTC
null
-1
null
2,302,661
null
1
31
linux|grep|find|full-text-search
100,856
<p><a href="http://www.explainshell.com" rel="noreferrer">explainshell</a> helpfully explains your command, and gives an excerpt from <code>man grep</code>:</p> <pre><code> -w, --word-regexp Select only those lines containing matches that form whole words. </code></pre> <p>So just remove <code>-w</code> since that explicitly does what you don't want:</p> <pre><code>grep -rn '/path/to/somewhere/' -e "pattern" </code></pre>
35,327,016
Using "preLaunchTasks" and Naming a Task in Visual Studio Code
<p>According to <a href="https://code.visualstudio.com/Docs/editor/debugging" rel="noreferrer">the documentation</a>, it is possible to launch a program before debugging:</p> <blockquote> <p>To launch a task before the start of each debug session, set the <code>preLaunchTask</code> to the <em>name</em> of one of the tasks specified in tasks.json.</p> </blockquote> <p>I've not seen example syntax of a "named" task, but the <a href="https://code.visualstudio.com/docs/editor/tasks_appendix" rel="noreferrer">schema documentation</a> reveals a property called <code>taskName</code>. I tried using that to link my launch.json <code>preLaunchTasks</code> to the task, but it didn't work. When I launched my program, Visual Studio Code reported this error:</p> <blockquote> <p>Could not find a unique task 'launch-core'. Make sure the task exists and that it has a unique name.</p> </blockquote> <p>My custom "named" task looked something like this:</p> <pre><code>{ "taskName": "launch-core", "version": "0.1.0", "command": "C:\\utils\\mystuff.exe", // The command is a shell script "isShellCommand": true, // Show the output window only if unrecognized errors occur. "showOutput": "silent", } </code></pre> <p>I then tried changing the property name from <code>taskName</code> to just <code>name</code>, <a href="https://stackoverflow.com/questions/30046411/define-multiple-tasks-in-vscode">based on this link</a>. That also didn't work.</p> <p>Intellisense gives no suggestions of how to name a task.</p> <p>Does anybody know how to uniquely name a task in the tasks.json file? What is the syntax? What is the property name?</p> <p>Ultimately I'd like to execute two or three node.js processes before my own node.js app is launched. For example, I'd like to have the following three apps launched before my app is launched into the debugger:</p> <pre><code>sh -c 'cd ./manager/ &amp;&amp; node manager.js' sh -c 'cd ./adapter/ &amp;&amp; node adapter.js' sh -c 'cd ./core/ &amp;&amp; node core.js' </code></pre> <p>If I'm working on a Windows box, my task might look something like this:</p> <pre><code>{ "taskName": "core-launch", "version": "0.1.0", // The command is tsc. Assumes that tsc has been installed using npm install -g typescript "command": "start", // The command is a shell script "isShellCommand": true, // Show the output window only if unrecognized errors occur. "showOutput": "silent", // args is the HelloWorld program to compile. "args": [ "ACD-Manager", "/B", "/D", "./manager/", "node", "manager.js" ] } </code></pre> <p>The above task using using the <a href="https://stackoverflow.com/questions/17201507/how-to-use-the-start-command-in-a-batch-file">cmd <code>start</code> capability</a>. I'm not sure yet how to make several node tasks launch instead of one, but I can't even get one task to launch because of this task-naming issue. </p> <p>How do I name a task in the tasks.json file?</p>
38,746,951
6
0
null
2016-02-10 22:14:56.037 UTC
15
2019-08-05 10:48:37.227 UTC
2017-05-23 10:31:15.87 UTC
null
-1
null
284,758
null
1
61
node.js|visual-studio-code
69,996
<p>So, if it's still relevant, or if someone finds this thread with the same problem, I've just figured it out how it works:</p> <p>In the <strong>tasks.json</strong>, you need to create a <strong>'tasks' array</strong> - code hint will help you with that - which holds an array of objects. Inside an object, you can have the <strong>'taskName'</strong> key-value pair.</p> <p>Example:</p> <pre><code>{ "version": "0.1.0", "command": "npm", "isShellCommand": true, "args": ["run-script", "webpack"], "showOutput": "always", "tasks": [ { "taskName": "runwebpack", "suppressTaskName": true } ] } </code></pre> <p>In my case, I had to run the <code>npm run-script webpack</code> command before running my project. In the <strong>launch.json</strong> file, the <code>"preLaunchTask": "runwebpack"</code> will work now.</p> <p>Note: the <code>suppressTaskName</code> is true in my example. Omitting it, or setting it to false will result in VS Code appending the <code>taskName</code> after the command.</p> <p>A more general approach would be something like this:</p> <pre><code>{ "version": "0.1.0", "command": "npm", "isShellCommand": true, "args": ["run-script"], "showOutput": "always", "tasks": [ { "taskName": "webpack" } ] } </code></pre> <p>With the latter example, you can extend the <code>tasks</code> array with other scripts to be run also.</p> <p><em>Hint for my usage</em>: npm run-script fetches what to do from the <strong>package.json</strong> file's <code>scripts</code> object.</p> <p>Edit: this works with <strong>VS Code 1.3.1</strong></p>
28,969,543
fatal error: sqlite3.h: No such file or directory
<p>I'm trying to build a C application through cross compiling for a Zynq board (ARM architecture). When I type make without mentioning the ARM arch, it works fine on my laptop. But as soon as I modify the Makefile, I get an error saying:</p> <pre><code>main.c:20:43: fatal error: sqlite3.h: No such file or directory #include "sqlite3.h" //library for sqlite3 ^ compilation terminated. make: *** [ws_temp_server] Error 1 </code></pre> <p>The Makefile looks like this:</p> <pre><code>SOURCE=lib/base64_enc.c lib/websocket.c lib/sha1.c lib/sqlite/sqlite3.c main.c CC = arm-xilinx-linux-gnueabi-gcc LDFLAGS=-lpthread -ldl INCLUDES=lib/ PROGRAM=ws_temp_server all: $(PROGRAM) $(PROGRAM): $(SOURCE) $(CC) $(SOURCE) -I$(INCLUDES) -o$(PROGRAM) $(LDFLAGS) clean: rm $(PROGRAM) </code></pre> <p>What am I doing wrong? Thanks for any help I can get.</p>
28,970,269
2
0
null
2015-03-10 16:52:16.37 UTC
8
2019-11-19 14:52:57.363 UTC
null
null
null
null
2,263,752
null
1
36
sqlite|compilation|makefile|arm|zynq
64,079
<p>You don't provide enough information to say for sure: in particular, you don't say where the <code>sqlite3.h</code> file actually is on your filesystem. However, based on what you do show I suspect you need to change the <code>INCLUDES</code> variable, to this:</p> <pre><code>INCLUDES = lib/sqlite </code></pre> <p>(or else change the <code>#include</code> in your code to be <code>#include "sqlite/sqlite3.h"</code>). This is assuming that the header file is in the same directory as the <code>sqlite3.c</code> source file.</p> <p>Note that this is a bad/confusing implementation. You should be putting the <code>-I</code> flag in the <code>INCLUDES</code> variable:</p> <pre><code>INCLUDES = -Ilib/sqlite ... $(PROGRAM): $(SOURCE) $(CC) $(SOURCE) $(INCLUDES) -o$(PROGRAM) $(LDFLAGS) </code></pre> <p><code>INCLUDES</code> is plural which may lead someone to believe they could add multiple directories in that variable, but if you leave it the way you have it, this will cause strange compiler errors:</p> <pre><code>INCLUDES = lib/sqlite another/dir ... $(PROGRAM): $(SOURCE) $(CC) $(SOURCE) -I$(INCLUDES) -o$(PROGRAM) $(LDFLAGS) </code></pre> <p>will add the flags <code>-Ilib/sqlite another/dir</code>... note how the second directory doesn't have a <code>-I</code> option.</p> <p>Of course, by convention you should be using <code>CPPFLAGS</code> (for C preprocessor flags), not <code>INCLUDES</code>, but... :)</p>
40,729,335
Ionic2 ion-toggle get value on ionChange
<p>I have this toggle here:</p> <pre><code>&lt;ion-toggle (ionChange)="notify(value)"&gt;&lt;/ion-toggle&gt; </code></pre> <p>When I click this I want to call the method notify passing the toggle value by parameter. How I can get the toggle value?</p> <p>Thank you!</p>
40,739,821
5
2
null
2016-11-21 21:02:38.503 UTC
3
2022-08-11 07:54:18.867 UTC
2018-08-23 15:54:46.62 UTC
null
3,915,438
null
2,639,187
null
1
16
angular|typescript|ionic-framework|ionic2|ionic3
44,383
<p>Just like you can see in <a href="http://ionicframework.com/docs/v2/api/components/toggle/Toggle/" rel="noreferrer">Ionic2 Docs - Toggle</a>, a better way to do that would be to <strong>bind the toggle to a property</strong> from your component by using <strong>ngModel</strong>.</p> <p>Component code:</p> <pre><code>public isToggled: boolean; // ... constructor(...) { this.isToggled = false; } public notify() { console.log(&quot;Toggled: &quot;+ this.isToggled); } </code></pre> <p>View:</p> <pre><code>&lt;ion-toggle [(ngModel)]=&quot;isToggled&quot; (ionChange)=&quot;notify()&quot;&gt;&lt;/ion-toggle&gt; </code></pre> <p>This way, you don't need to send the value because it's already a property from your component and you can always get the value by using <code>this.isToggled</code>.</p> <p><strong>UPDATE</strong></p> <p>Just like <strong><a href="https://stackoverflow.com/users/654708/gfoley83">@GFoley83</a></strong> mentioned on his comment:</p> <blockquote> <p>Be very careful with ionChange when it's bound directly to <code>ngModel</code>. The notify method will get called when the value bound to <code>ngModel</code> changes, either from the view via someone clicking the toggle or in your component via code e.g. when you do a fresh GET call. I had an issue recently whereby clicking the toggle triggered a <code>PATCH</code>, this meant that every other client would automatically trigger a <code>PATCH</code> when the data bound to the toggle changed.</p> <p>We used: <code>&lt;ion-toggle [ngModel]=&quot;isToggled&quot; (ngModelChange)=&quot;notifyAndUpdateIsToggled()&quot;&gt;&lt;/ion-toggle&gt;</code> to get around this</p> </blockquote>
21,092,885
How to replace the element with ng-transclude
<p>Is it possible to replace the element with <code>ng-transclude</code> on it rather than the entire template element?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;div my-transcluded-directive&gt; &lt;div&gt;{{someData}}&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Directive:</strong></p> <pre><code>return { restrict:'A', templateUrl:'templates/my-transcluded-directive.html', transclude:true, link:function(scope,element,attrs) { } }; </code></pre> <p><strong>my-transcluded-directive.html:</strong></p> <pre><code>&lt;div&gt; &lt;div ng-transclude&gt;&lt;/div&gt; &lt;div&gt;I will not be touched.&lt;/div&gt; &lt;/div&gt; </code></pre> <p>What I am looking for is a way to have <code>&lt;div&gt;{{someData}}&lt;/div&gt;</code> replace <code>&lt;div ng-transclude&gt;&lt;/div&gt;</code>. What currently happens is the transcluded HTML is placed <em>inside</em> the <code>ng-transclude</code> div element.</p> <p>Is that possible?</p>
22,995,121
4
0
null
2014-01-13 13:49:49.603 UTC
14
2018-06-06 09:18:57.643 UTC
null
null
null
null
383,148
null
1
36
angularjs|angularjs-directive
27,712
<p>I think the best solution would probably be to create your own transclude-replace directive that would handle this. But for a quick and dirty solution to your example you could essentially manually place the result of the transclusion where you want:</p> <p><strong>my-transcluded-directive.html:</strong></p> <pre><code>&lt;div&gt; &lt;span&gt;I WILL BE REPLACED&lt;/span&gt; &lt;div&gt;I will not be touched.&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Directive:</strong></p> <pre><code>return { restrict:'A', templateUrl:'templates/my-transcluded-directive.html', transclude:true, link:function(scope,element,attrs,ctrl, transclude) { element.find('span').replaceWith(transclude()); } }; </code></pre>
38,667,445
Is ApiController deprecated in .NET Core
<p>Is it true that "<code>ApiController</code> will get deprecated in .NET Core"? Asking since I'm planning to use it in new projects.</p>
38,672,681
4
2
null
2016-07-29 21:02:19.403 UTC
13
2021-11-11 17:32:55.823 UTC
2019-08-16 08:35:28.313 UTC
null
492,336
null
2,779,615
null
1
78
c#|asp.net-mvc|asp.net-web-api|asp.net-core|.net-core
66,946
<p><strong>Update ASP.NET Core 2.1</strong></p> <p>Since ASP.NET Core 2.1 a new set of types is available to create Web API controllers. You can annotate your controllers with the <code>[ApiController]</code> attribute which enables a few new features such as automatic model state validation and binding source parameter inference. See the docs for more information: <a href="https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#annotate-class-with-apicontrollerattribute" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#annotate-class-with-apicontrollerattribute</a>.</p> <hr> <p>There is indeed no particular <code>ApiController</code> class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the <code>Controller</code> class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding.</p> <p>You've got two options if you want something different:</p> <p>Use the <code>ControllerBase</code> class in the <a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/ControllerBase.cs" rel="noreferrer">Microsoft.AspNetCore.Mvc.Core</a> package.</p> <p><strong>Or</strong> </p> <p>Create your <code>ApiController</code> base class. The key here is to add the <code>[ActionContext]</code> attribute which injects the current <code>ActionContext</code> instance into the property:</p> <pre><code>[Controller] public abstract class ApiController { [ActionContext] public ActionContext ActionContext { get; set; } } </code></pre> <p>Also, add the <code>[Controller]</code> attribute to the class to mark it as a controller for the MVC controller discovery.</p> <p>See more details in my <a href="http://henkmollema.github.io/web-api-in-mvc-6/" rel="noreferrer">“Web API in MVC 6” blogpost</a>.</p>
21,101,250
Sending GET request with Authentication headers using restTemplate
<p>I need to retrieve resources from my server by sending a GET request with some Authorization headers using <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html" rel="noreferrer">RestTemplate</a>.</p> <p>After going over the <a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/client/RestTemplate.html" rel="noreferrer">docs</a> I noticed that none of the GET methods accepts headers as a parameter, and the only way to send Headers such as accept and Authorization is by using the <a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/client/RestTemplate.html#exchange%28java.lang.String,%20org.springframework.http.HttpMethod,%20org.springframework.http.HttpEntity,%20java.lang.Class,%20java.lang.Object...%29" rel="noreferrer">exchange</a> method.</p> <p>Since it is a very basic action I am wondering if I am missing something and there another, easier way to do it?</p>
21,101,295
6
0
null
2014-01-13 21:00:26.163 UTC
15
2021-02-18 09:47:34.117 UTC
2021-02-18 09:47:34.117 UTC
null
1,029,822
null
162,345
null
1
100
java|spring|spring-mvc|resttemplate
239,841
<p>You're not missing anything. <code>RestTemplate#exchange(..)</code> is the appropriate method to use to set request headers.</p> <p><a href="https://stackoverflow.com/questions/19238715/set-accept-header-for-spring-rest-template">Here's an example</a> (with POST, but just change that to GET and use the entity you want). </p> <p><a href="https://stackoverflow.com/questions/10358345/making-authenticated-post-requests-with-spring-resttemplate-for-android">Here's another example.</a></p> <p>Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.</p>
26,326,296
Changing text of UIButton programmatically swift
<p>Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here's what I have:</p> <pre><code>currencySelector.text = "foobar" </code></pre> <p>Xcode gives me the error "Expected Declaration". What am I doing wrong, and how can I make the button's text change?</p>
26,326,362
12
0
null
2014-10-12 14:42:01.16 UTC
43
2021-12-13 01:45:56.567 UTC
2017-03-23 15:34:47.253 UTC
null
1,033,581
null
3,892,545
null
1
263
ios|xcode|swift|uibutton
314,776
<p>In Swift 3, 4, 5:</p> <pre><code>button.setTitle("Button Title", for: .normal) </code></pre> <p>Otherwise:</p> <pre><code>button.setTitle("Button Title", forState: UIControlState.Normal) </code></pre> <p>Also an <code>@IBOutlet</code> has to declared for the <code>button</code>.</p>
45,185,555
SceneKit – Get direction of camera
<p>I need to find out which direction a camera is looking at, e.g. if it is looking towards <code>Z+</code>, <code>Z-</code>, <code>X+</code>, or <code>X-</code>.</p> <p>I've tried using <code>eulerAngles</code>, but the range for yaw goes <code>0</code> -> <code>90</code> -> <code>0</code> -> <code>-90</code> -> <code>0</code> which means I can only detect if the camera is looking towards <code>Z</code> or <code>X</code>, not if it's looking towards the positive or negative directions of those axes.</p>
45,197,017
1
0
null
2017-07-19 08:53:12.18 UTC
8
2018-09-02 13:53:47.953 UTC
2018-09-02 13:53:47.953 UTC
null
6,599,590
null
7,362,882
null
1
5
swift|camera|scenekit|direction|arkit
3,831
<p>You can create an SCNNode that place it in worldFront property to get a vector with the x, y, and z direction.</p> <p>Another way you could do it is like how this project did it:</p> <pre><code>// Credit to https://github.com/farice/ARShooter func getUserVector() -&gt; (SCNVector3, SCNVector3) { // (direction, position) if let frame = self.sceneView.session.currentFrame { let mat = SCNMatrix4(frame.camera.transform) // 4x4 transform matrix describing camera in world space let dir = SCNVector3(-1 * mat.m31, -1 * mat.m32, -1 * mat.m33) // orientation of camera in world space let pos = SCNVector3(mat.m41, mat.m42, mat.m43) // location of camera in world space return (dir, pos) } return (SCNVector3(0, 0, -1), SCNVector3(0, 0, -0.2)) } </code></pre>
41,904,975
Refresh page and run function after - JavaScript
<p>I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?</p> <p><strong>My code</strong></p> <pre><code>function reloadP(){ document.location.reload(); myFunction(); } &lt;button onclick: &quot;reloadP()&quot;&gt;Click&lt;/button&gt; </code></pre>
41,905,026
5
1
null
2017-01-28 00:06:45.657 UTC
5
2022-08-18 15:14:57.477 UTC
2022-01-10 09:20:17.493 UTC
null
14,895,985
null
6,135,775
null
1
22
javascript|reload
88,862
<p>You need to call <code>myFunction()</code> when the page is loaded.</p> <pre><code>window.onload = myFunction; </code></pre> <p>If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use <code>sessionStorage</code> to pass this information.</p> <pre><code>window.onload = function() { var reloading = sessionStorage.getItem("reloading"); if (reloading) { sessionStorage.removeItem("reloading"); myFunction(); } } function reloadP() { sessionStorage.setItem("reloading", "true"); document.location.reload(); } </code></pre> <p><a href="https://jsfiddle.net/barmar/5sL3hd74/" rel="noreferrer">DEMO</a></p>
39,178,169
When using JavaScript's reduce, how do I skip an iteration?
<p>I am trying to figure out a way to conditionally break out of an iteration when using JavaScript's <code>reduce</code> function. </p> <p>Given the following code sums an array of integers and will return the number <code>10</code>: </p> <pre><code>[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue; }); </code></pre> <p>How can I do something like this: </p> <pre><code>[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { if(currentValue === "WHATEVER") { // SKIP or NEXT -- don't include it in the sum } return previousValue + currentValue; }); </code></pre>
39,178,200
3
1
null
2016-08-27 06:27:26.383 UTC
4
2020-08-06 19:29:04.53 UTC
null
null
null
null
5,482,113
null
1
39
javascript
21,561
<p>You can just return previousValue</p> <pre><code>[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { if(currentValue === "WHATEVER") { return previousValue; } return previousValue + currentValue; }); </code></pre>
2,850,205
Cannot bulk load. The file "c:\data.txt" does not exist
<p>I'm having a problem reading data from a text file into ms sql. I created a text file in my c:\ called data.txt, but for some reason ms sql server cannot find the file. I get the error "Cannot bulk load. The file "c:\data.txt" does not exist." Any ideas?</p> <p>The data file (yes I know the data looks crappy, but in the real world thats how it comes from clients):</p> <pre><code>01-04 10.338,18 0,00 597.877,06- 5 0,7500 62,278- 06-04 91.773,00 9.949,83 679.700,23- 1 0,7500 14,160- 07-04 60.648,40 149.239,36 591.109,27- 1 0,7500 12,314- 08-04 220.173,70 213.804,37 597.478,60- 1 0,7500 12,447- 09-04 986.071,39 0,00 1.583.549,99- 3 0,7500 98,971- 12-04 836.049,00 1.325.234,79 1.094.364,20- 1 0,7500 22,799- 13-04 38.000,00 503.010,49 629.353,71- 1 0,7500 13,111- 14-04 286.400,00 840.126,50 75.627,21- 1 0,7500 1,575- </code></pre> <p>The Sql:</p> <pre><code>CREATE TABLE #temp ( vchCol1 VARCHAR (50), vchCol2 VARCHAR (50), vchCol3 VARCHAR (50), vchCol4 VARCHAR (50), vchCol5 VARCHAR (50), vchCol6 VARCHAR (50), vchCol7 VARCHAR (50) ) BULK insert #temp FROM 'c:\data.txt' WITH ( FIELDTERMINATOR = ' ', ROWTERMINATOR = '\n' ) select * from #temp drop table #temp </code></pre>
2,850,221
3
1
null
2010-05-17 15:08:51.697 UTC
null
2017-01-13 21:51:11.927 UTC
2010-05-17 15:24:51.89 UTC
null
141,443
null
141,443
null
1
26
sql|bulkinsert
88,395
<p>That's run on the server, so its looking for <code>C:\data.txt</code> on the server's <code>C:</code> drive.</p> <p>Also ensure the logon your using has read permissions on C:.</p>
2,465,425
How do I determine if a terminal is color-capable?
<p>I would like to change a program to automatically detect whether a terminal is color-capable or not, so when I run said program from within a non-color capable terminal (say M-x shell in (X)Emacs), color is automatically turned off.</p> <p>I don't want to hardcode the program to detect TERM={emacs,dumb}.</p> <p>I am thinking that termcap/terminfo should be able to help with this, but so far I've only managed to cobble together this (n)curses-using snippet of code, which fails badly when it can't find the terminal:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;curses.h&gt; int main(void) { int colors=0; initscr(); start_color(); colors=has_colors() ? 1 : 0; endwin(); printf(colors ? "YES\n" : "NO\n"); exit(0); } </code></pre> <p>I.e. I get this:</p> <pre><code>$ gcc -Wall -lncurses -o hep hep.c $ echo $TERM xterm $ ./hep YES $ export TERM=dumb $ ./hep NO $ export TERM=emacs $ ./hep Error opening terminal: emacs. $ </code></pre> <p>which is... suboptimal.</p>
2,465,638
3
2
null
2010-03-17 19:59:01.673 UTC
10
2011-09-15 05:43:48.18 UTC
null
null
null
null
2,905
null
1
32
unix|terminal|termcap|terminfo
9,195
<p>A friend pointed me towards tput(1), and I cooked up this solution:</p> <pre><code>#!/bin/sh # ack-wrapper - use tput to try and detect whether the terminal is # color-capable, and call ack-grep accordingly. OPTION='--nocolor' COLORS=$(tput colors 2&gt; /dev/null) if [ $? = 0 ] &amp;&amp; [ $COLORS -gt 2 ]; then OPTION='' fi exec ack-grep $OPTION "$@" </code></pre> <p>which works for me. It would be great if I had a way to integrate it into <a href="http://betterthangrep.com/" rel="noreferrer">ack</a>, though.</p>
2,530,663
printf anomaly after "fork()"
<p>OS: Linux, Language: pure C</p> <p>I'm moving forward in learning C programming in general, and C programming under UNIX in a special case.</p> <p>I detected a strange (for me) behaviour of the <code>printf()</code> function after using a <code>fork()</code> call. </p> <p><strong>Code</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;system.h&gt; int main() { int pid; printf( "Hello, my pid is %d", getpid() ); pid = fork(); if( pid == 0 ) { printf( "\nI was forked! :D" ); sleep( 3 ); } else { waitpid( pid, NULL, 0 ); printf( "\n%d was forked!", pid ); } return 0; } </code></pre> <p><strong>Output</strong></p> <pre><code>Hello, my pid is 1111 I was forked! :DHello, my pid is 1111 2222 was forked! </code></pre> <p>Why did the second "Hello" string occur in the child's output?</p> <p>Yes, it is exactly what the parent printed when it started, with the parent's <code>pid</code>.</p> <p>But! If we place a <code>\n</code> character at the end of each string we get the expected output:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;system.h&gt; int main() { int pid; printf( "Hello, my pid is %d\n", getpid() ); // SIC!! pid = fork(); if( pid == 0 ) { printf( "I was forked! :D" ); // removed the '\n', no matter sleep( 3 ); } else { waitpid( pid, NULL, 0 ); printf( "\n%d was forked!", pid ); } return 0; } </code></pre> <p><strong>Output</strong>:</p> <pre><code>Hello, my pid is 1111 I was forked! :D 2222 was forked! </code></pre> <p>Why does it happen? Is it correct behaviour, or is it a bug?</p>
2,530,870
3
0
null
2010-03-27 19:37:14.947 UTC
47
2018-12-12 22:16:37.41 UTC
2017-08-29 02:21:43.333 UTC
null
952,648
null
298,326
null
1
92
c|linux|unix|printf|fork
33,674
<p>I note that <code>&lt;system.h&gt;</code> is a non-standard header; I replaced it with <code>&lt;unistd.h&gt;</code> and the code compiled cleanly.</p> <p>When the output of your program is going to a terminal (screen), it is line buffered. When the output of your program goes to a pipe, it is fully buffered. You can control the buffering mode by the Standard C function <code>setvbuf()</code> and the <code>_IOFBF</code> (full buffering), <code>_IOLBF</code> (line buffering) and <code>_IONBF</code> (no buffering) modes.</p> <p>You could demonstrate this in your revised program by piping the output of your program to, say, <code>cat</code>. Even with the newlines at the end of the <code>printf()</code> strings, you would see the double information. If you send it direct to the terminal, then you will see just the one lot of information.</p> <p>The moral of the story is to be careful to call <code>fflush(0);</code> to empty all I/O buffers before forking.</p> <hr> <p>Line-by-line analysis, as requested (braces etc removed - and leading spaces removed by markup editor):</p> <ol> <li><code>printf( "Hello, my pid is %d", getpid() );</code></li> <li><code>pid = fork();</code></li> <li><code>if( pid == 0 )</code></li> <li><code>printf( "\nI was forked! :D" );</code></li> <li><code>sleep( 3 );</code></li> <li><code>else</code></li> <li><code>waitpid( pid, NULL, 0 );</code></li> <li><code>printf( "\n%d was forked!", pid );</code></li> </ol> <p>The analysis:</p> <ol> <li>Copies "Hello, my pid is 1234" into the buffer for standard output. Because there is no newline at the end and the output is running in line-buffered mode (or full-buffered mode), nothing appears on the terminal.</li> <li>Gives us two separate processes, with exactly the same material in the stdout buffer.</li> <li>The child has <code>pid == 0</code> and executes lines 4 and 5; the parent has a non-zero value for <code>pid</code> (one of the few differences between the two processes - return values from <code>getpid()</code> and <code>getppid()</code> are two more).</li> <li>Adds a newline and "I was forked! :D" to the output buffer of the child. The first line of output appears on the terminal; the rest is held in the buffer since the output is line buffered.</li> <li>Everything halts for 3 seconds. After this, the child exits normally through the return at the end of main. At that point, the residual data in the stdout buffer is flushed. This leaves the output position at the end of a line since there is no newline.</li> <li>The parent comes here.</li> <li>The parent waits for the child to finish dying.</li> <li>The parent adds a newline and "1345 was forked!" to the output buffer. The newline flushes the 'Hello' message to the output, after the incomplete line generated by the child.</li> </ol> <p>The parent now exits normally through the return at the end of main, and the residual data is flushed; since there still isn't a newline at the end, the cursor position is after the exclamation mark, and the shell prompt appears on the same line.</p> <p>What I see is:</p> <pre><code>Osiris-2 JL: ./xx Hello, my pid is 37290 I was forked! :DHello, my pid is 37290 37291 was forked!Osiris-2 JL: Osiris-2 JL: </code></pre> <p>The PID numbers are different - but the overall appearance is clear. Adding newlines to the end of the <code>printf()</code> statements (which becomes standard practice very quickly) alters the output a lot:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int main() { int pid; printf( "Hello, my pid is %d\n", getpid() ); pid = fork(); if( pid == 0 ) printf( "I was forked! :D %d\n", getpid() ); else { waitpid( pid, NULL, 0 ); printf( "%d was forked!\n", pid ); } return 0; } </code></pre> <p>I now get:</p> <pre><code>Osiris-2 JL: ./xx Hello, my pid is 37589 I was forked! :D 37590 37590 was forked! Osiris-2 JL: ./xx | cat Hello, my pid is 37594 I was forked! :D 37596 Hello, my pid is 37594 37596 was forked! Osiris-2 JL: </code></pre> <p>Notice that when the output goes to the terminal, it is line-buffered, so the 'Hello' line appears before the <code>fork()</code> and there was just the one copy. When the output is piped to <code>cat</code>, it is fully-buffered, so nothing appears before the <code>fork()</code> and both processes have the 'Hello' line in the buffer to be flushed.</p>
2,482,100
NSFetchedResultsController: changing predicate not working?
<p>I'm writing an app with two tables on one screen. The left table is a list of folders and the right table shows a list of files. When tapped on a row on the left, the right table will display the files belonging to that folder.</p> <p>I'm using Core Data for storage. When the selection of folder changes, the fetch predicate of the right table's NSFetchedResultsController will change and perform a new fetch, then reload the table data. I used the following code snippet:</p> <pre><code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"list = %@",self.list]; [fetchedResultsController.fetchRequest setPredicate:predicate]; NSError *error = nil; if (![[self fetchedResultsController] performFetch:&amp;error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } [table reloadData]; </code></pre> <p><strong>However the fetch results are still the same</strong>. I've NSLog'ed "predicate" before and after the fetch, and they were correct with updated information. The fetch results stay the same as initial fetch (when view is loaded).</p> <p>I'm not very familiar with the way Core Data fetches objects (is there a caching system?), but I've done similar things before(changing predicates, re-fetching data, and refreshing table) with single table views and everything went well.</p> <p>If someone could gave me a hint I would be very appreciated.</p> <p>Thanks in advance.</p>
2,491,732
4
0
null
2010-03-20 05:46:42.983 UTC
10
2018-09-28 18:52:31.527 UTC
2010-03-24 14:20:52.53 UTC
null
30,461
null
164,397
null
1
39
iphone|uitableview|core-data|nspredicate|nsfetchedresultscontroller
20,201
<p>I had almost exactly this problem, until I found the hint in a very recent blog post at <a href="http://iphoneincubator.com/blog/data-management/delete-the-nsfetchedresultscontroller-cache-before-changing-the-nspredicate" rel="noreferrer">iphone incubator</a></p> <p>NSFetchedResultsController is caching the first results. (You probably have something set at initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName)</p> <p>I'm guessing your code (like mine) is a derivation of the CoreData sample, so assuming it's @"Root", before you change the predicate, do a</p> <pre><code>[NSFetchedResultsController deleteCacheWithName:@"Root"]; </code></pre>
29,179,149
Ubunutu - .ssh folder exists but I cannot see it? only through terminal
<p>When I go to my terminals and use $ cd ~/.ssh I am able to enter the directory, which proves it exists. However, when I use any other file browser, I cannot find the .ssh folder!</p> <p>Why is this happening?? I desperately need to access the .ssh perhaps it is invisible? Can anyone help me</p> <p>(Ubuntu 14.04)</p>
29,180,877
2
0
null
2015-03-21 04:10:05 UTC
null
2016-09-25 19:03:53.837 UTC
null
null
null
null
4,509,751
null
1
13
linux|ssh|ubuntu-14.04|invisible
47,848
<p>Any files or directories which start with dot are hidden. They cannot be seen from file browser. Open you terminal and </p> <pre><code>ls -a </code></pre> <p>now you will see your .ssh directory listed. make sure you are using ls -a command in the right home directory. If you able to cd ~ssh from one user then use ls -a command in the that user's home directory.</p> <p>If you really want to see the files in the file browser then create a directory without starting with a dot and copy all the contents from the .ssh directory to the new directory which you have created.</p> <pre><code>sudo mkdir /home/user_name/sshfolder sudo cp /home/user_name/.ssh/* /home/user_name/sshfolder/ </code></pre> <p>Now open you file system browser and verify the contents. I hope this is helpful.</p>
46,280,014
Is GraphQL an ORM?
<p>Is GraphQL an ORM? It seems like it is. At the end of the day it needs to query the database for information. You need to give it a schema (just like an ORM). From my understanding, on the front end you pass it the specifics that you want and GraphQL on the back end will give you <em>just</em> the info you requested.</p> <p>The only difference I see from traditional ORMs, such as Sequelize or ActiveRecord, is that GraphQL will give you only what you want, making it very attractive and flexible. I suspect though that whatever's going on under the hood may leave you with some inefficient queries (common to ORMs). So is GraphQL simply an ORM that gives you 100% flexibility in what you ask for and receive?</p>
49,698,671
3
0
null
2017-09-18 13:03:53.533 UTC
3
2021-12-31 03:02:44.933 UTC
null
null
null
null
2,525,633
null
1
29
orm|graphql
6,625
<p>GraphQL is not an ORM, because it doesn't understand the concept of DBs. It just gets the data from a "data source", which could be static, from a file, etc. Nor can it figure out how to get data once you point the source at it. You have to write resolver functions that tell the DB how to find the value of each field.</p> <p>Some gems/packages will simplify some of this. Some of those may be or may become ORMs, but GraphQL itself is completely platform/data source agnostic.</p>
685,995
TCPClient vs Socket in C#
<p>I don't see much use of <code>TCPClient</code>, yet there is a lot of <code>Socket</code>? What is the major difference between them and when would you use each?</p> <p>I understand that .NET <code>Socket</code> is written on top of WINSOCK, and <code>TCPClient</code> is a wrapper over <code>Socket</code> class. Thus <code>TCPClient</code> is way up the chain, and possibly inefficient. Correct me if I am wrong. </p>
686,003
2
0
null
2009-03-26 14:19:51.233 UTC
11
2019-10-22 13:54:39.27 UTC
2017-05-26 14:51:56.217 UTC
Sasha
133
Sasha
null
null
1
61
c#|.net|sockets|network-programming
31,861
<p>The use of TcpClient and TcpListener just means a few less lines of code. As you say it's just a wrapper over the Socket class so there is no performance difference between them it's purely a style choice.</p> <p><strong>Update:</strong> Since this answer was posted the .Net source code has become available. It does indeed show that <a href="https://referencesource.microsoft.com/#System/net/System/Net/Sockets/TCPClient.cs" rel="noreferrer">TcpClient</a> is a very light wrapper over the <a href="https://referencesource.microsoft.com/#System/net/System/Net/Sockets/Socket.cs" rel="noreferrer">Socket</a> class which is itself a wrapper on top of the native <a href="https://docs.microsoft.com/en-us/windows/win32/api/_winsock/" rel="noreferrer">WinSock2 API</a>*.</p> <ul> <li>On Windows. Will be different for .Net Standard/Core etc. on other platforms. </li> </ul>
3,033,633
How to check null element if it is integer array in Java?
<p>I'm quite new to Java and having an issue checking null element in integer array. I'm using Eclipse for editor and the line that checks null element is showing error:</p> <p>Line that complains:</p> <pre><code>if(a[i] != null) { </code></pre> <p>Error msg from Eclipse:</p> <pre><code>The operator != is undefined for the argument type(s) int, null </code></pre> <p>In PHP, this works without any problem but in Java it seems like I have to change the array type from integer to Object to make the line not complain (like below)</p> <pre><code>Object[] a = new Object[3]; </code></pre> <p>So my question is if I still want to declare as integer array and still want to check null, what is the syntax for it?</p> <p>Code:</p> <pre><code>public void test() { int[] a = new int[3]; for(int i=0; i&lt;a.length; i++) { if(a[i] != null) { //this line complains... System.out.println('null!'); } } } </code></pre>
3,033,635
5
0
null
2010-06-13 19:39:21.503 UTC
2
2016-03-02 23:58:27.51 UTC
2013-12-29 03:38:38.187 UTC
null
1,054,245
null
355,044
null
1
15
java|arrays|null|int
55,605
<p>In Java, an <code>int</code> is a primitive type and cannot be <code>null</code>. Objects, however, are stored as references, so if you declare an object reference but do not make a <code>new</code> object, the reference will be <code>null</code>.</p> <p><code>Integers</code> are object wrappers around <code>ints</code>, meaning they can be <code>null</code>.</p> <pre><code>public void test() { Integer[] a = new Integer[3]; for(int i=0; i&lt;a.length; i++) { if(a[i] != null) { //should now compile System.out.println('null!'); } } } </code></pre>
3,152,424
How do I comment SQL code out in Microsoft Access?
<p>Is it possible to comment code out in the SQL window in Microsoft Access?</p>
68,977,544
5
0
null
2010-06-30 18:55:20.313 UTC
1
2021-08-30 00:22:24.237 UTC
2019-07-01 00:16:22.76 UTC
null
63,550
null
117,700
null
1
27
sql|ms-access
65,474
<p>Depending on your needs you can use the &quot;Description&quot; field on the query &quot;Properties&quot; dialog box:</p> <p><img src="https://i.stack.imgur.com/WQQzB.png" alt="1" />.</p>
3,015,803
How to disable autocomplete in MVC Html Helper
<p>I have a typical ADO.NET EF-driven form that allows the user to input a date. I have put a jQuery datepicker on it but when the user goes to select a date the browser shows some other entries in a dropdown. How do I turn off that dropdown? In traditional ASP.NET I would put autocomplete="off". Not sure of the MVC equivalent.</p> <pre><code>&lt;div class="editor-field"&gt; &lt;%= Html.TextBoxFor(model =&gt; model.date, new { @class = "aDatePicker" })%&gt; &lt;%= Html.ValidationMessageFor(model =&gt; model.date) %&gt; &lt;/div&gt; </code></pre>
3,015,847
5
0
null
2010-06-10 15:22:36.883 UTC
8
2021-04-13 18:00:00.33 UTC
2014-06-04 11:38:34.03 UTC
null
306,028
null
278,768
null
1
64
asp.net-mvc
85,166
<p>Try this:</p> <pre><code>&lt;%= Html.TextBoxFor( model =&gt; model.date, new { @class = "aDatePicker", autocomplete = "off" } )%&gt; </code></pre> <p>It will generate markup that is close to the following:</p> <pre><code>&lt;input type="text" id="date" name="date" class="aDatePicker" autocomplete="off" /&gt; </code></pre>
2,857,989
Using pg_dump to only get insert statements from one table within database
<p>I'm looking for a way to get all rows as <code>INSERT</code> statements from one specific table within a database using <code>pg_dump</code> in PostgreSQL.</p> <p>E.g., I have table A and all rows in table A I need as <code>INSERT</code> statements, it should also dump those statements to a file.</p> <p>Is this possible? </p>
2,858,039
5
0
null
2010-05-18 14:08:10.07 UTC
38
2021-11-12 04:16:11.403 UTC
2012-12-17 13:43:51.023 UTC
null
96,588
null
131,637
null
1
162
postgresql
173,093
<p>if version &lt; 8.4.0 </p> <pre><code>pg_dump -D -t &lt;table&gt; &lt;database&gt; </code></pre> <p>Add <code>-a</code> before the <code>-t</code> if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.</p> <p>version >= 8.4.0</p> <pre><code>pg_dump --column-inserts --data-only --table=&lt;table&gt; &lt;database&gt; </code></pre>
2,567,498
Objective-C categories in static library
<p>Can you guide me how to properly link static library to iPhone project. I use static library project added to app project as direct dependency (target -> general -> direct dependencies) and all works OK, but categories. A category defined in static library is not working in app. </p> <p>So my question is how to add static library with some categories into other project? </p> <p>And in general, what is best practice to use in app project code from other projects?</p>
2,615,407
6
1
null
2010-04-02 15:30:55.98 UTC
135
2019-11-13 10:15:05.43 UTC
2016-02-10 01:13:21.16 UTC
null
211,292
null
286,361
null
1
158
iphone|objective-c|static-libraries|categories
54,128
<p><strong>Solution:</strong> As of Xcode 4.2, you only need to go to the application that is linking against the library (not the library itself) and click the project in the Project Navigator, click your app's target, then build settings, then search for &quot;Other Linker Flags&quot;, click the + button, and add '-ObjC'. '-all_load' and '-force_load' are no longer needed.</p> <p><strong>Details:</strong> I found some answers on various forums, blogs and apple docs. Now I try make short summary of my searches and experiments.</p> <p>Problem was caused by (citation from apple Technical Q&amp;A QA1490 <a href="https://developer.apple.com/library/content/qa/qa1490/_index.html" rel="noreferrer">https://developer.apple.com/library/content/qa/qa1490/_index.html</a>):</p> <blockquote> <p>Objective-C does not define linker symbols for each function (or method, in Objective-C) - instead, linker symbols are only generated for each class. If you extend a pre-existing class with categories, the linker does not know to associate the object code of the core class implementation and the category implementation. This prevents objects created in the resulting application from responding to a selector that is defined in the category.</p> </blockquote> <p>And their solution:</p> <blockquote> <p>To resolve this issue, the static library should pass the -ObjC option to the linker. This flag causes the linker to load every object file in the library that defines an Objective-C class or category. While this option will typically result in a larger executable (due to additional object code loaded into the application), it will allow the successful creation of effective Objective-C static libraries that contain categories on existing classes.</p> </blockquote> <p>and there is also recommendation in iPhone Development FAQ:</p> <blockquote> <p>How do I link all the Objective-C classes in a static library? Set the Other Linker Flags build setting to -ObjC.</p> </blockquote> <p>and flags descriptions:</p> <blockquote> <p>-<strong>all_load</strong> Loads all members of static archive libraries.</p> <p>-<strong>ObjC</strong> Loads all members of static archive libraries that implement an Objective-C class or category.</p> <p>-<strong>force_load (path_to_archive)</strong> Loads all members of the specified static archive library. Note: -all_load forces all members of all archives to be loaded. This option allows you to target a specific archive.</p> </blockquote> <p>*we can use force_load to reduce app binary size and to avoid conflicts which all_load can cause in some cases.</p> <p>Yes, it works with *.a files added to the project. Yet I had troubles with lib project added as direct dependency. But later I found that it was my fault - direct dependency project possibly was not added properly. When I remove it and add again with steps:</p> <ol> <li>Drag&amp;drop lib project file in app project (or add it with Project-&gt;Add to project…).</li> <li>Click on arrow at lib project icon - mylib.a file name shown, drag this mylib.a file and drop it into Target -&gt; Link Binary With Library group.</li> <li>Open target info in fist page (General) and add my lib to dependencies list</li> </ol> <p>after that all works OK. &quot;-ObjC&quot; flag was enough in my case.</p> <p>I also was interested with idea from <a href="http://iphonedevelopmentexperiences.blogspot.com/2010/03/categories-in-static-library.html" rel="noreferrer">http://iphonedevelopmentexperiences.blogspot.com/2010/03/categories-in-static-library.html</a> blog. Author say he can use category from lib without setting -all_load or -ObjC flag. He just add to category h/m files empty dummy class interface/implementation to force linker use this file. And yes, this trick do the job.</p> <p>But author also said he even not instantiated dummy object. Mm… As I've found we should explicitly call some &quot;real&quot; code from category file. So at least class function should be called. And we even need not dummy class. Single c function do the same.</p> <p>So if we write lib files as:</p> <pre><code>// mylib.h void useMyLib(); @interface NSObject (Logger) -(void)logSelf; @end // mylib.m void useMyLib(){ NSLog(@&quot;do nothing, just for make mylib linked&quot;); } @implementation NSObject (Logger) -(void)logSelf{ NSLog(@&quot;self is:%@&quot;, [self description]); } @end </code></pre> <p>and if we call useMyLib(); anywhere in App project then in any class we can use logSelf category method;</p> <pre><code>[self logSelf]; </code></pre> <p>And more blogs on theme:</p> <p><a href="http://t-machine.org/index.php/2009/10/13/how-to-make-an-iphone-static-library-part-1/" rel="noreferrer">http://t-machine.org/index.php/2009/10/13/how-to-make-an-iphone-static-library-part-1/</a></p> <p><a href="http://blog.costan.us/2009/12/fat-iphone-static-libraries-device-and.html" rel="noreferrer">http://blog.costan.us/2009/12/fat-iphone-static-libraries-device-and.html</a></p>
2,503,923
HTML button calling an MVC Controller and Action method
<p>I know this isn't right, but for the sake of illustration I'd like to do something like this:</p> <pre><code>&lt;%= Html.Button("Action", "Controller") %&gt; </code></pre> <p>My goal is to make an HTML button that will call my MVC controller's action method.</p>
2,510,668
19
2
null
2010-03-23 21:56:58.307 UTC
49
2022-01-05 06:17:56.737 UTC
2016-01-18 17:21:26.407 UTC
null
2,756,409
null
269,855
null
1
234
html|asp.net-mvc
912,382
<p>No need to use a form at all unless you want to post to the action. An input button (not submit) will do the trick.</p> <pre><code> &lt;input type="button" value="Go Somewhere Else" onclick="location.href='&lt;%: Url.Action("Action", "Controller") %&gt;'" /&gt; </code></pre>
10,825,443
Django heroku static dir
<p>I'm new to heroku and I tried a simple django app without css.</p> <p>But I just added a css file in my app and when i do this: </p> <pre><code>git push heroku master </code></pre> <p>The static file collection fails :</p> <pre><code>[...] -----&gt; Collecting static files Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle return self.handle_noargs(**options) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 163, in handle_noargs collected = self.collect() File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 105, in list for path in utils.get_files(storage, ignore_patterns): File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 25, in get_files directories, files = storage.listdir(location) File "/tmp/build_2unndirli15s7/.heroku/venv/lib/python2.7/site-packages/django/core/files/storage.py", line 235, in listdir for entry in os.listdir(path): OSError: [Errno 2] No such file or directory: '/home/kevin/web/django/appheroku/blogapp/static' ! Heroku push rejected, failed to compile Python/django app To [email protected]:[...] ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to '[email protected]:[...]' </code></pre> <p>Here is my settings.py:</p> <pre><code>[...] STATIC_ROOT = '/home/kevin/web/django/appheroku/staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( '/home/kevin/web/django/appheroku/blogapp/static', ) [...] </code></pre> <p>The urls.py:</p> <pre><code> [...] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() </code></pre> <p>Procfile :</p> <pre><code>web: python appheroku/manage.py collectstatic --noinput; bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT appheroku/monblog/settings.py </code></pre> <p>It seems even the '/home/kevin/web/django/appheroku/blogapp/static' directory exists, it is not detected and I can't figure out why. :(</p> <p>Please help me ^^</p> <p>EDIT:</p> <p>Now my settings.py looks like this : </p> <pre><code>import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_DIR = os.path.join(PROJECT_ROOT,'../blogapp') [...] STATIC_ROOT = os.path.join(PROJECT_ROOT,'staticfiles/') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static/'), ) [...] </code></pre> <p>And now the static file collection step seems to work well:</p> <pre><code> -----&gt; Collecting static files 74 static files copied. </code></pre> <p>There was another problem : in my procfile, 'appheroku/manage.py' , 'bin/gunicorn_django' and 'appheroku/monblog/settings.py' were not found. I fixed it and now my procfile looks like this :</p> <pre><code>web: python manage.py collectstatic --noinput; gunicorn_django --workers=4 --bind=0.0.0.0:$PORT monblog.settings </code></pre> <p>The app doesn't crash anymore but there is still no css. Here is the log:</p> <pre><code>'2012-05-31T17:35:16+00:00 heroku[router]: GET xxxx-xxxx-number.herokuapp.com/ dyno=web.1 queue=0 wait=0ms service=85ms status=200 bytes=1054 2012-05-31T17:35:17+00:00 heroku[router]: GET xxxx-xxxx-number.herokuapp.com/static/css/style.css dyno=web.1 queue=0 wait=0ms service=5ms status=404 bytes=2088 2012-05-31T17:35:17+00:00 heroku[router]: GET xxxx-xxxx-number.herokuapp.com/static/js/jquery-1.7.2.min.js dyno=web.1 queue=0 wait=0ms service=5ms status=404 bytes=2115' </code></pre> <p>EDIT3 :</p> <p>Yes ! it works ^^ The problem was in my urls.py. I wrote :</p> <pre><code>[...] if not settings.DEBUG: urlpatterns += staticfiles_urlpatterns() </code></pre> <p>instead of</p> <pre><code> [...] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() </code></pre> <p>The error was not in my message.. Yes, it was really difficult to help me. (Sorry) I feel so stupid ^^'</p>
10,826,316
3
0
null
2012-05-30 22:58:19.847 UTC
12
2016-06-22 16:39:18.533 UTC
2012-05-31 18:04:32.523 UTC
null
1,322,358
null
1,322,358
null
1
17
django|heroku
8,657
<p>The problem is the absolute path you are using for <code>STATIC_ROOT</code> isn't found in Heroku server. </p> <p>To resolve it, consider the following approach.</p> <p>In your settings.py:</p> <pre><code>PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATIC_ROOT= os.path.join(PROJECT_DIR,'staticfiles/') STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT,'static/'), ) </code></pre>
10,339,338
<T extends Object & E> vs <T extends E>
<p>The signature of <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max%28java.util.Collection%29" rel="noreferrer">java.util.Collections.max</a> looks like this:</p> <blockquote> <p>public static &lt;T extends Object &amp; Comparable&lt;? super T>> T max(Collection collection);</p> </blockquote> <p>From what I understand, it basically means that T must be both a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max%28java.util.Collection%29" rel="noreferrer">java.lang.Object</a> and a <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html" rel="noreferrer">java.lang.Comparable&lt;? super T>></a>,</p> <p>However, since every <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html" rel="noreferrer">java.lang.Comparable</a> is also an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html" rel="noreferrer">java.lang.Object</a>, what is the difference between the signature above and this below? :</p> <blockquote> <p>public static &lt;T extends Comparable&lt;? super T>> T max(Collection collection);</p> </blockquote>
10,339,472
1
0
null
2012-04-26 18:33:01.69 UTC
5
2012-05-02 20:48:36.64 UTC
2012-05-02 20:48:36.64 UTC
null
869,458
null
632,951
null
1
29
java|generics
4,959
<p><strong>To preserve binary compatibility</strong>: It's completely described <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ104">here</a>. The second signature actually changes the return type of the method to <code>Comparable</code> and it loses the generality of returning an <code>Object</code>. The original signature preserves both.</p>