id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
1,584,425
Return value while using cProfile
<p>I'm trying to profile an instance method, so I've done something like:</p> <pre><code>import cProfile class Test(): def __init__(self): pass def method(self): cProfile.runctx("self.method_actual()", globals(), locals()) def method_actual(self): print "Run" if __name__ == "__main__": Test().method() </code></pre> <p>But now problems arise when I want "method" to return a value that is computed by "method_actual". I don't really want to call "method_actual" twice.</p> <p>Is there another way, something that can be thread safe? (In my application, the cProfile data are saved to datafiles named by one of the args, so they don't get clobbered and I can combine them later.)</p>
1,584,468
5
0
null
2009-10-18 09:04:26.217 UTC
13
2017-01-05 21:01:11.71 UTC
null
null
null
null
188,535
null
1
26
python
10,329
<p>I discovered that you can do this:</p> <pre><code>prof = cProfile.Profile() retval = prof.runcall(self.method_actual, *args, **kwargs) prof.dump_stats(datafn) </code></pre> <p>The downside is that it's undocumented.</p>
1,912,029
"Warning: Cannot modify header information - headers already sent by" error
<p>I keep receiving this error each time I try to submit a deletion form.</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\speedycms\deleteclient.php:47) in C:\xampp\htdocs\speedycms\deleteclient.php on line 106</p> </blockquote> <p>Is there something wrong with my code? What do I need to change to make it work?</p> <pre><code>&lt;?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = &quot;&quot;; $MM_donotCheckaccess = &quot;true&quot;; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(&quot;,&quot;, $strUsers); $arrGroups = Explode(&quot;,&quot;, $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == &quot;&quot;) &amp;&amp; true) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = &quot;login.php&quot;; if (!((isset($_SESSION['MM_Username'])) &amp;&amp; (isAuthorized(&quot;&quot;,$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = &quot;?&quot;; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, &quot;?&quot;)) $MM_qsChar = &quot;&amp;&quot;; if (isset($QUERY_STRING) &amp;&amp; strlen($QUERY_STRING) &gt; 0) $MM_referrer .= &quot;?&quot; . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . &quot;accesscheck=&quot; . urlencode($MM_referrer); header(&quot;Location: &quot;. $MM_restrictGoTo); exit; } ?&gt; &lt;?php require_once('Connections/speedycms.php'); $client_id = mysql_real_escape_string($_GET['id']); $con = mysql_connect($hostname_speedycms, $username_speedycms, $password_speedycms); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db(&quot;speedycms&quot;) or die(mysql_error()); ?&gt; &lt;?php if (!function_exists(&quot;GetSQLValueString&quot;)) { function GetSQLValueString($theValue, $theType, $theDefinedValue = &quot;&quot;, $theNotDefinedValue = &quot;&quot;) { if (PHP_VERSION &lt; 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists(&quot;mysql_real_escape_string&quot;) ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case &quot;text&quot;: $theValue = ($theValue != &quot;&quot;) ? &quot;'&quot; . $theValue . &quot;'&quot; : &quot;NULL&quot;; break; case &quot;long&quot;: case &quot;int&quot;: $theValue = ($theValue != &quot;&quot;) ? intval($theValue) : &quot;NULL&quot;; break; case &quot;double&quot;: $theValue = ($theValue != &quot;&quot;) ? doubleval($theValue) : &quot;NULL&quot;; break; case &quot;date&quot;: $theValue = ($theValue != &quot;&quot;) ? &quot;'&quot; . $theValue . &quot;'&quot; : &quot;NULL&quot;; break; case &quot;defined&quot;: $theValue = ($theValue != &quot;&quot;) ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } if ((isset($_GET['id'])) &amp;&amp; ($_GET['id'] != &quot;&quot;) &amp;&amp; (isset($_POST['deleteForm']))) { $deleteSQL = sprintf(&quot;DELETE FROM tbl_accident WHERE id=%s&quot;, GetSQLValueString($_GET['id'], &quot;int&quot;)); mysql_select_db($database_speedycms, $speedycms); $Result1 = mysql_query($deleteSQL, $speedycms) or die(mysql_error()); $deleteGoTo = &quot;progress.php&quot;; if (isset($_SERVER['QUERY_STRING'])) { $deleteGoTo .= (strpos($deleteGoTo, '?')) ? &quot;&amp;&quot; : &quot;?&quot;; $deleteGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf(&quot;Location: %s&quot;, $deleteGoTo)); } mysql_select_db($database_speedycms, $speedycms); $query_delete = &quot;SELECT * FROM tbl_accident WHERE id=$client_id&quot;; $delete = mysql_query($query_delete, $speedycms) or die(mysql_error()); $row_delete = mysql_fetch_assoc($delete); $totalRows_delete = mysql_num_rows($delete); ?&gt; &lt;p class=&quot;form2&quot;&gt;Are you sure you wish to &lt;b&gt;delete&lt;/b&gt; the record for &lt;?php echo $row_delete['clientName']; ?&gt;?&lt;/p&gt; &lt;form name=&quot;form&quot; method=&quot;POST&quot; action=&quot;&lt;?php echo $deleteAction; ?&gt;&quot;&gt; &lt;p class=&quot;form2&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Yes&quot; /&gt; &lt;input name=&quot;no&quot; type=&quot;button&quot; id=&quot;no&quot; value=&quot;No&quot; /&gt; &lt;/p&gt; &lt;input type=&quot;hidden&quot; name=&quot;deleteForm&quot; value=&quot;form&quot; /&gt; &lt;/form&gt; </code></pre>
1,912,050
5
3
null
2009-12-16 03:15:18.897 UTC
11
2020-08-12 21:11:50.84 UTC
2020-08-12 21:09:44.083 UTC
null
1,839,439
null
436,493
null
1
26
php|mysql
236,864
<p>Lines 45-47:</p> <pre><code>?&gt; &lt;?php </code></pre> <p>That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.</p> <p>Notice that the error message you got actually gives you a lot of information to help you find this yourself:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (<strong>output started at C:\xampp\htdocs\speedycms\deleteclient.php:47</strong>) in <strong>C:\xampp\htdocs\speedycms\deleteclient.php on line 106</strong></p> </blockquote> <p>The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).</p>
1,871,331
PHP MYSQL - Insert into without using column names but with autoincrement field
<p>I need to insert a long row with 32 fields into a MySQL table.</p> <p>I'd like to do something like this:</p> <pre><code>$sql=&quot;insert into tblname values (... 32 fields ...)&quot;; </code></pre> <p>Obviously, it works fine if the fields are in the same order as the MySQL table fields. But, my table has an auto-increment id as it's first field.</p> <p>What I want is to fill in all table names but the first (id) one.</p> <p>Suggestions?</p>
1,871,343
5
0
null
2009-12-09 02:57:41.993 UTC
9
2022-09-09 17:54:47.803 UTC
2022-09-09 17:54:47.803 UTC
null
8,172,439
null
208,713
null
1
53
php|mysql|sql|database|auto-increment
44,755
<p>Just use <code>NULL</code> as your first value, the <code>autoincrement</code> field will still work as expected:</p> <pre><code>INSERT INTO tblname VALUES (NULL, ... 32 Fields ... ) </code></pre>
1,528,152
Is it possible to build a Console app that does not display a console Window when double-clicked?
<blockquote> <p>Related:<br> <a href="https://stackoverflow.com/questions/1117275/should-i-include-a-command-line-mode-in-my-applications">Should I include a command line mode in my applications?</a><br> <a href="https://stackoverflow.com/questions/377911/how-to-grab-parent-process-standard-output">How to grab parent process standard output?</a><br> <a href="https://stackoverflow.com/questions/510805">Can a console application detect if it has been run from Explorer?</a></p> </blockquote> <p>I want to build a console app, that is normally run from the command line. </p> <p>But, when it is double clicked from within Explorer (as opposed to being run from a cmd.exe prompt) then I'd like the program to NOT display a console window. </p> <p>I want to avoid this: </p> <p><a href="https://i.stack.imgur.com/vPkpr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vPkpr.png" alt="alt text"></a> </p> <p>Is it possible? </p> <p><strong>EDIT</strong> I guess another way to ask it is, <em>is it possible for a program to know how it was invoked - whether by double-click or by command line</em> ? </p> <p>I'm working in .NET, on Windows. </p> <p><strong>EDIT 2:</strong> From <a href="http://blogs.msdn.com/oldnewthing/archive/2009/01/01/9259142.aspx" rel="nofollow noreferrer">this <em>Old New Thing</em> blog post</a> I learned some good stuff. Here's what I know now...</p> <p>In Windows, EXE files are marked as either GUI or non-GUI. With csc.exe, this is selected with <code>/target:winexe</code> or <code>/target:exe</code>. Before the first instruction in the process executes, the Windows kernel sets up the execution environment. At that moment, if the EXE is marked GUI, the kernel sets the stdin/stdout for the process to NULL, and if non-GUI (command-line) the kernel creates a console and sets the stdin/stdout for the process to that console. </p> <p>When launching the process, if there is no stdin/stdout (== <code>/target:winexe</code>), then the call immediately returns. So, launching a gui app from a cmd.exe, you will immediately get your cmd prompt back. If there is a stdin/stdout, and if run from cmd.exe, then the parent cmd.exe waits for process exit. </p> <p>The "immediate return" is important because if you code a GUI app to attach to its parent's console, you will be able to do console.writeline, etc. But the cmd.exe prompt is active. The user can type new commands, start a new process, and so on. In other words, from a winexe, simply attaching to the parent console with <code>AttachConsole(-1)</code> will not "turn it into" a console app. </p> <hr> <p>At this point I think the only way to allow an app to use the console if it is invoked from cmd.exe, and NOT use it if it is double-clicked, is to define the exe as a regular console exe (<code>/target:exe</code>), and <em>hide the window</em> on startup if appropriate. You still get a console window appearing briefly. </p> <p>I still haven't figured how to know whether it was launched from explorer or cmd.exe, but I'm getting closer.. </p> <hr> <p><strong>ANSWERS</strong></p> <p>It is not possible to build a console app that does not display a console window. </p> <p>It <em>is possible</em> to build a console app that hides its window very quickly, but not so quickly that it is as if the window never appears. </p> <p>Now, to determine whether a console app was launched from explorer, some have suggested to look at the console it is running in<br> (from <a href="https://stackoverflow.com/questions/1528152/is-it-possible-to-build-a-console-app-that-does-not-display-a-console-window-when/1528271#1528271">mgb's answer</a>, and <a href="http://support.microsoft.com/kb/99115" rel="nofollow noreferrer">KB article 99115</a>) :</p> <pre><code> int left = Console.CursorLeft; int top = Console.CursorTop; bool ProcessWasRunFromExplorer = (left==0 &amp;&amp; top==0); </code></pre> <p>This tells you if the process was launched in its own console, but not whether it was explorer. A double click in explorer would do this, but also a Start.Process() from within an app would do the same thing. </p> <p>If you want to treat those situations differently, use this to learn the name of the parent process:</p> <pre><code> System.Console.WriteLine("Process id: {0}", Process.GetCurrentProcess().Id); string name = Process.GetCurrentProcess().ProcessName ; System.Console.WriteLine("Process name: {0}", name); PerformanceCounter pc = new PerformanceCounter("Process", "Creating Process Id", name); Process p = Process.GetProcessById((int)pc.RawValue); System.Console.WriteLine("Parent Process id: {0}", p.Id); System.Console.WriteLine("Parent Process name: {0}", p.ProcessName); // p.ProcessName == "cmd" or "Explorer" etc </code></pre> <p>To hide the window quickly after the process is launched, use this: </p> <pre><code> private static readonly int SW_HIDE= 0; [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow); .... { IntPtr myHandle = Process.GetCurrentProcess().MainWindowHandle; ShowWindow(myHandle, SW_HIDE); } </code></pre> <p>If you produce a <code>winexe</code> (a WinForms app), and optionally attach to the parent console when appropriate with <code>AttachConsole(-1)</code>, you do not get the equivalent of a regular console app. For a winexe, the parent process (like cmd.exe) will return to the command prompt immediately after starting a GUI application. In other words, the command prompt is active and ready for input while the just-launched process may be emitting output. This is confusing and is probably useful only for debugging winforms apps. </p> <p>This worked for me. </p>
1,528,271
6
2
2009-10-07 02:42:05.373 UTC
2009-10-06 21:18:46.273 UTC
9
2021-03-12 21:45:35.14 UTC
2019-04-29 04:05:44.853 UTC
null
4,751,173
null
48,082
null
1
23
.net|windows|console|console-application
8,883
<p>See <a href="https://stackoverflow.com/questions/510805/can-a-win32-console-application-detect-if-it-has-been-run-from-the-explorer-or-no">Can a Win32 console application detect if it has been run from the explorer or not?</a></p> <p>Or I think the official way is to check the parent process is cmd.exe or explorer.exe</p>
2,073,481
Headless, scriptable Firefox/Webkit on linux?
<p>I'm looking to automate some web interactions, namely periodic download of files from a secure website. This basically involves entering my username/password and navigating to the appropriate URL.</p> <p>I tried simple scripting in Python, followed by more sophisticated scripting, only to discover this particular website is using some obnoxious javascript and flash based mechanism for login, rendering my methods useless. </p> <p>I then tried HTMLUnit, but that doesn't seem to want to work either. I suspect use of Flash is the issue.</p> <p>I don't really want to think about it any more, so I'm leaning towards scripting an actual browser to log in and grab the file I need. </p> <p>Requirements are:</p> <ul> <li>Run on linux server (ie. no X running). If I really need to have X I can make that happen, but I won't be happy.</li> <li>Be reliable. I want to start this thing and never think about it again.</li> <li>Be scriptable. Nothing too sophisticated, but I should be able to tell the browser the various steps to take and pages to visit.</li> </ul> <p>Are there any good toolkits for a headless, X-less scriptable browser? Have you tried something like this and if so do you have any words of wisdom?</p>
2,944,492
6
0
null
2010-01-15 17:20:26.04 UTC
25
2018-09-04 06:26:03.303 UTC
2012-08-17 05:18:27.97 UTC
null
527,702
null
13,055
null
1
46
firefox|webkit|screen-scraping|headless-browser
22,074
<p>I did related task with IE embedded browser (although it was gui application with hidden browser component panel). Actually you can take any <a href="http://en.wikipedia.org/wiki/List_of_web_browser_engines" rel="nofollow noreferrer">layout engine</a> and cut output logic. Navigation is should be done via firing script-like events.</p> <p>You can use <a href="https://github.com/sawantuday/crowbar" rel="nofollow noreferrer">Crowbar</a>. It is headless version of firefox (Gecko engine). It turns browser into RESTful server that can accept requests ("fetch url"). So it parse html, represent it as DOM, wait defined delay for all script performed. </p> <p>It works on linux. I suppose you can easily extend it for your goal using JS and rich XULrunner abilities.</p>
1,383,516
Date Difference in MySQL to calculate age
<p>I have a problem regarding the <code>datediff</code> MYSQL function, I can use it and it is simple. But I don't understand how to use it to collect differences within the table field. E.g.</p> <p>I have a column <code>dob</code> and I want to write a query that will do something like</p> <pre><code>select dateDiff(current_timeStamp,dob) from sometable 'here dob is the table column </code></pre> <p>I mean I want the difference from the current date time to the table field <code>dob</code>, each query result is the difference, the age of the user.</p>
1,383,576
7
1
null
2009-09-05 14:54:45.503 UTC
3
2016-05-17 20:46:27.49 UTC
2015-03-19 17:39:03.073 UTC
null
2,686,013
null
132,263
null
1
8
mysql|sql|date|datediff
38,381
<p>You mean like this?</p> <pre><code>SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), dob)), "%Y")+0 AS age from sometable </code></pre> <p>(<a href="http://goharsahi.wordpress.com/2007/08/18/calculating-age-from-date-of-birth-in-mysql/" rel="noreferrer">Source</a>)</p>
2,325,926
how to align all my li on one line?
<p>my CSS</p> <pre><code>ul{ overflow:hidden; } li{ display:inline-block; } </code></pre> <p>my HTML</p> <pre><code>&lt;ul&gt; &lt;li&gt;a&lt;/li&gt; &lt;li&gt;b&lt;/li&gt; &lt;li&gt;c&lt;/li&gt; &lt;li&gt;d&lt;/li&gt; &lt;li&gt;e&lt;/li&gt; &lt;li&gt;f&lt;/li&gt; &lt;li&gt;g&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>i want to align all my li items in one line, if i did that everything works fine except that when 3 or 4 li's fills the first line on my body they go the the second line, i want them to be on 1 line and everything after the 1 line is filled will be "hidden"</p> <p>FOR EXAMPLE :: </p> <p>// NOTE li holds sentences not just 1 letter</p> <p>OUTPUT NOW ::</p> <pre><code>a b c d e f g </code></pre> <p>DESIRED OUTPUT ::</p> <pre><code>a b c d e f //all of them in 1 line and the rest of them are hidden 'overflow:hidden' </code></pre>
2,325,958
7
0
null
2010-02-24 12:31:24.497 UTC
5
2022-01-14 14:18:46.09 UTC
2010-02-24 12:37:54.17 UTC
null
223,130
null
223,130
null
1
22
html|css
146,879
<p>Try putting <code>white-space:nowrap;</code> in your <code>&lt;ul&gt;</code> style</p> <p>edit: and use 'inline' rather than 'inline-block' as other have pointed out (and I forgot)</p>
1,438,083
Getting the first sheet from an Excel document regardless of sheet name with OleDb
<p>I have users that name their sheets all sorts of crazy things, but I want to be able to get the first sheet of the Excel document regardless of what it is named. </p> <p>I currently use:</p> <pre><code>OleDbDataAdapter adapter = new OleDbDataAdapter( "SELECT * FROM [sheetName$]", connString); </code></pre> <p>How would I go about getting the first sheet no matter what it is named?</p> <p>Thank you.</p>
1,438,221
9
1
null
2009-09-17 10:51:29.267 UTC
6
2019-10-24 14:31:07.373 UTC
2009-09-17 11:29:36.927 UTC
null
25,544
null
14,777
null
1
40
.net|oledb
73,420
<p>ended up using this:</p> <pre><code>using (OleDbConnection conn = new OleDbConnection(connString)) { conn.Open(); dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); Sheet1= dtSchema.Rows[0].Field&lt;string&gt;("TABLE_NAME"); } </code></pre>
1,599,219
C# catch a stack overflow exception
<p>I have a recursive call to a method that throws a stack overflow exception. The first call is surrounded by a try catch block but the exception is not caught. </p> <p>Does the stack overflow exception behave in a special way? Can I catch/handle the exception properly?</p> <p>Not sure if relevant, but additional information: </p> <ul> <li><p>the exception is not thrown in the main thread </p></li> <li><p>the object where the code is throwing the exception is manually loaded by Assembly.LoadFrom(...).CreateInstance(...)</p></li> </ul>
1,599,238
9
4
null
2009-10-21 07:15:40.163 UTC
19
2020-10-16 21:16:10.7 UTC
2019-10-28 17:38:15.937 UTC
null
4,479,165
null
111,992
null
1
134
c#|try-catch|stack-overflow
123,001
<p>Starting with 2.0 a StackOverflow Exception can only be caught in the following circumstances.</p> <ol> <li>The CLR is being run in a hosted environment<sup>*</sup> where the host specifically allows for StackOverflow exceptions to be handled</li> <li>The stackoverflow exception is thrown by user code and not due to an actual stack overflow situation (<a href="https://docs.microsoft.com/en-us/archive/blogs/jaredpar/when-can-you-catch-a-stackoverflowexception" rel="noreferrer">Reference</a>)</li> </ol> <p><sub><sup>*</sup>&quot;hosted environment&quot; as in &quot;my code hosts CLR and I configure CLR's options&quot; and not &quot;my code runs on shared hosting&quot;</sub></p>
1,953,048
Java project structure explained for newbies?
<p>I come from a .NET background and am completely new to Java and am trying to get my head around the Java project structure. </p> <p>My typical .NET solution structure contains projects that denote logically distinct components, usually named using the format: </p> <p><code>MyCompany.SomeApplication.ProjectName</code></p> <p>The project name usually equals the root namespace for the project. I might break the namespace down further if it's a large project, but more often than not I see no need to namespace any further. </p> <p>Now in Java, you have applications consisting of projects, and then you have a new logical level - the package. What is a package? What should it contain? How do you namespace within this <code>App.Project.Package</code> structure? Where do JARs fit into all this? Basically, can someone provide a newbies intro to Java application structure?</p> <p>Thanks!</p> <p><strong>Edit:</strong> Some really cracking answers thanks guys. A couple of followup questions then:</p> <ul> <li>Do .JAR files contain compiled code? Or just compressed source code files?</li> <li>Is there a good reason why package names are all lower case?</li> <li>Can Packages have 'circular dependencies'? In other words, can Package.A use Package.B and vice versa? </li> <li>Can anyone just show the typical syntax for declaring a class as being in a package and declaring that you wish to reference another package in a class (a using statement maybe?)</li> </ul>
1,953,893
10
4
null
2009-12-23 14:16:34.79 UTC
23
2015-06-26 11:36:12.403 UTC
2009-12-24 11:30:30.027 UTC
null
146,588
null
146,588
null
1
57
java|development-environment
65,968
<h2>"Simple" J2SE projects</h2> <p>As cletus explained, source directory structure is directly equivalent to package structure, and that's essentially built into Java. Everything else is a bit less clear-cut.</p> <p>A lot of simple projects are organized by hand, so people get to pick a structure they feel OK with. What's often done (and this is also reflected by the structure of projects in Eclipse, a very dominant Java tool) is to have your source tree begin in a directory called <code>src</code>. Your package-less source files would sit directly in src, and your package hierarchy, typically starting with a <code>com</code> directory, would likewise be contained in <code>src</code>. If you <code>CD</code> to the <code>src</code> directory before firing up the <code>javac</code> compiler, your compiled <code>.class</code> files will end up in the same directory structure, with each .class file sitting in the same directory and next to its <code>.java</code> file.</p> <p>If you have a lot of source and class files, you'll want to separate them out from each other to reduce clutter. Manual and Eclipse organization often place a <code>bin</code> or <code>classes</code> directory parallel to <code>src</code> so the .class files end up in a hierarchy that mirrors that of <code>src</code>.</p> <p>If your project has a set of <code>.jar</code> files to deliver capability from third-party libraries, then a third directory, typically <code>lib</code>, is placed parallel to <code>src</code> and <code>bin</code>. Everything in <code>lib</code> needs to be put on the classpath for compilation and execution.</p> <p>Finally, there's a bunch of this and that which is more or less optional:</p> <ul> <li>docs in <code>doc</code></li> <li>resources in <code>resources</code></li> <li>data in <code>data</code> </li> <li>configuration in <code>conf</code>...</li> </ul> <p>You get the idea. The compiler doesn't care about these directories, they're just ways for you to organize (or confuse) yourself.</p> <h2>J2EE projects</h2> <p>J2EE is roughly equivalent to ASP.NET, it's a massive (standard) framework for organizing Web applications. While you can develop your code for J2EE projects any way you like, there is a firm standard for the structure that a Web container will expect your application delivered in. And that structure tends to reflect back a bit to the source layout as well. Here is a page that details project structures for Java projects in general (they don't agree very much with what I wrote above) and for J2EE projects in particular:</p> <p><a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="noreferrer">http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html</a></p> <h2>Maven projects</h2> <p><code>Maven</code> is a very versatile project build tool. Personally, my build needs are nicely met by <code>ant</code>, which roughly compares with <code>nmake</code>. Maven, on the other hand, is complete-lifecyle build management with dependency management bolted on. The libs and source for most of the code in the Java world is freely available in the 'net, and maven, if asked nicely, will go crawling it for you and bring home everything your project needs without you needing to even tell it to. It manages a little repository for you, too.</p> <p>The downside to this highly industrious critter is the fact that it's highly fascist about project structure. You do it the Maven way or not at all. By forcing its standard down your throat, Maven manages to make projects worldwide a bit more similar in structure, easier to manage and easier to build automatically with a minimum of input.</p> <p>Should you ever opt for Maven, you can stop worrying about project structure, because there can only be one. This is it: <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="noreferrer">http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html</a></p>
2,060,561
optional local variables in rails partial templates: how do I get out of the (defined? foo) mess?
<p>I've been a bad kid and used the following syntax in my partial templates to set default values for local variables if a value wasn't explicitly defined in the :locals hash when rendering the partial -- </p> <pre><code>&lt;% foo = default_value unless (defined? foo) %&gt; </code></pre> <p>This seemed to work fine until recently, when (for no reason I could discern) non-passed variables started behaving as if they had been defined to nil (rather than undefined).</p> <p>As has been pointed by various helpful people on SO, <a href="http://api.rubyonrails.org/classes/ActionView/Base.html" rel="noreferrer">http://api.rubyonrails.org/classes/ActionView/Base.html</a> says <em>not</em> to use</p> <pre><code>defined? foo </code></pre> <p>and instead to use</p> <pre><code>local_assigns.has_key? :foo </code></pre> <p>I'm trying to amend my ways, but that means changing a lot of templates. </p> <p>Can/should I just charge ahead and make this change in all the templates? Is there any trickiness I need to watch for? How diligently do I need to test each one?</p>
2,061,027
12
1
null
2010-01-13 21:55:16.443 UTC
70
2018-08-12 15:52:24.797 UTC
null
null
null
null
239,712
null
1
246
ruby-on-rails|partials
88,396
<p>I do this:</p> <pre><code>&lt;% some_local = default_value if local_assigns[:some_local].nil? %&gt; </code></pre>
8,603,788
Hadoop JobConf class is deprecated , need updated example
<p>I am writing hadoop programs , and i really dont want to play with deprecated classes . Anywhere online i am not able to find programs with updated </p> <blockquote> <p>org.apache.hadoop.conf.Configuration</p> </blockquote> <p>class insted of </p> <blockquote> <p>org.apache.hadoop.mapred.JobConf</p> </blockquote> <p>class.</p> <pre><code> public static void main(String[] args) throws Exception { JobConf conf = new JobConf(Test.class); conf.setJobName("TESST"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(Map.class); conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); JobClient.runJob(conf); } </code></pre> <p>This is how my main() looks like. Can please anyone will provide me with updated function.</p>
8,607,564
2
2
null
2011-12-22 12:21:37.343 UTC
11
2015-03-31 09:29:12.98 UTC
null
null
null
null
1,095,275
null
1
12
hadoop|mapreduce|cloudera
19,705
<p>Here it's the classic WordCount example. You'll notice a tone of other imports that may not be necessary, reading the code you'll figure out which is which. </p> <p>What's different? I'm using the Tool interface and the GenericOptionParser to parse the job command a.k.a : hadoop jar ....</p> <p>In the mapper you'll notice a run thing. You can get rid of that, it's usually called by default when you supply the code for the Map method. I put it there to give you the info that you can further control the mapping stage. This is all using the new API. I hope you find it useful. Any other questions, let me know!</p> <pre><code>import java.io.IOException; import java.util.*; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.util.GenericOptionsParser; public class Inception extends Configured implements Tool{ public static class Map extends Mapper&lt;LongWritable, Text, Text, IntWritable&gt; { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, one); } } public void run (Context context) throws IOException, InterruptedException { setup(context); while (context.nextKeyValue()) { map(context.getCurrentKey(), context.getCurrentValue(), context); } cleanup(context); } } public static class Reduce extends Reducer&lt;Text, IntWritable, Text, IntWritable&gt; { public void reduce(Text key, Iterable&lt;IntWritable&gt; values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } } public int run(String[] args) throws Exception { Job job = Job.getInstance(new Configuration()); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setJarByClass(WordCount.class); job.submit(); return 0; } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); ToolRunner.run(new WordCount(), otherArgs); } } </code></pre>
17,830,372
How to apply border radius in IE8 and below IE8 browsers?
<p>I would like to know how to apply border-radius to IE8 and below IE8 browsers.</p> <p>I know that border-radius is a HTML5 feature and IE8 doesn't support it.</p> <p>I found that by using .htc we can achieve this but by using htc I am encountering the problem of black background.</p> <p>I am unable to overcome this problem.</p> <p>Is there any other way of applying border-radius to IE8? If so can anyone explain me how?</p>
17,830,451
6
1
null
2013-07-24 09:41:24.087 UTC
14
2014-01-31 10:49:00.603 UTC
2014-01-31 10:49:00.603 UTC
null
107,625
null
2,594,152
null
1
19
css
113,165
<p><strong>Option 1</strong></p> <p><a href="http://jquery.malsup.com/corner/" rel="nofollow noreferrer">http://jquery.malsup.com/corner/</a></p> <p><strong>Option 2</strong></p> <p><a href="http://code.google.com/p/curved-corner/downloads/detail?name=border-radius-demo.zip" rel="nofollow noreferrer">http://code.google.com/p/curved-corner/downloads/detail?name=border-radius-demo.zip</a></p> <p><strong>Option 3</strong></p> <p><a href="http://css3pie.com/" rel="nofollow noreferrer">http://css3pie.com/</a></p> <p><strong>Option 4</strong></p> <p><a href="http://www.netzgesta.de/corner/" rel="nofollow noreferrer">http://www.netzgesta.de/corner/</a></p> <p><strong>Option 5</strong></p> <p><a href="https://stackoverflow.com/questions/9426979/border-radius-for-ie8">See this question</a></p> <p>EDIT: <strong>Option 6</strong></p> <p><a href="https://code.google.com/p/jquerycurvycorners/" rel="nofollow noreferrer">https://code.google.com/p/jquerycurvycorners/</a></p>
41,750,026
AWS Lambda Error: "Cannot find module '/var/task/index'"
<p><strong>Node.js Alexa Task Issue</strong></p> <p>I'm currently coding a Node.js Alexa Task via AWS Lambda, and I have been trying to code a function that receives information from the OpenWeather API and parses it into a variable called <code>weather</code>. The relevant code is as follows:</p> <pre><code>var request = require('request'); var weather = &quot;&quot;; function isBadWeather(location) { var endpoint = &quot;http://api.openweathermap.org/data/2.5/weather?q=&quot; + location + &quot;&amp;APPID=205283d9c9211b776d3580d5de5d6338&quot;; var body = &quot;&quot;; request(endpoint, function (error, response, body) { if (!error &amp;&amp; response.statusCode == 200) { body = JSON.parse(body); weather = body.weather[0].id; } }); } function testWeather() { setTimeout(function() { if (weather &gt;= 200 &amp;&amp; weather &lt; 800) weather = true; else weather = false; console.log(weather); generateResponse(buildSpeechletResponse(weather, true), {}); }, 500); } </code></pre> <p>I ran this snippet countless times in Cloud9 and other IDEs, and it seems to be working flawlessly. However, when I zip it into a package and upload it to AWS Lambda, I get the following error:</p> <pre><code>{ &quot;errorMessage&quot;: &quot;Cannot find module '/var/task/index'&quot;, &quot;errorType&quot;: &quot;Error&quot;, &quot;stackTrace&quot;: [ &quot;Function.Module._load (module.js:276:25)&quot;, &quot;Module.require (module.js:353:17)&quot;, &quot;require (internal/module.js:12:17)&quot; ] } </code></pre> <p>I installed module-js, request, and many other Node modules that should make this code run, but nothing seems to fix this issue. Here is my directory, just in case:</p> <pre><code>- planyr.zip - index.js - node_modules - package.json </code></pre> <p>Does anyone know what the issue could be?</p>
41,887,552
9
3
null
2017-01-19 19:23:12.053 UTC
19
2021-06-14 15:45:41.137 UTC
2021-06-14 15:45:41.137 UTC
null
1,536,976
null
7,432,026
null
1
94
javascript|node.js|amazon-web-services|request|aws-lambda
65,857
<p>Fixed it! My issue was that I tried to zip the file using my Mac's built-in compression function in Finder. </p> <p>If you're a Mac user, like me, you should run the following script in terminal when you are in the root directory of your project (folder containing your <code>index.js</code>, <code>node_modules</code>, etc. files).</p> <pre><code>zip -r ../yourfilename.zip * </code></pre> <p>For Windows:</p> <pre><code>Compress-Archive -LiteralPath node_modules, index.js -DestinationPath yourfilename.zip </code></pre>
41,916,722
How do I specify row heights in CSS Grid layout?
<p>I have a CSS Grid Layout in which I want to make <strong>some</strong> (middle 3) rows stretch to their maximum size. I'm probably looking for a property similar to what <code>flex-grow: 1</code> does with Flexbox but I can't seem to find a solution.</p> <blockquote> <p>Note: This is intended for an <a href="http://electron.atom.io/" rel="noreferrer">Electron</a> app only, so browser compatibility is not really a concern.</p> </blockquote> <p>I have the following CSS Grid Layout:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-template-columns: 1fr 1.5fr 1fr; grid-gap: 10px; height: calc(100vh - 10px); } .grid .box { background-color: grey; } .grid .box:first-child, .grid .box:last-child { grid-column-start: 1; grid-column-end: -1; } /* These rows should 'grow' to the max height available. */ .grid .box:nth-child(n+5):nth-child(-n+7) { grid-column-start: 1; grid-column-end: -1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;div class="box"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Which creates the following grid:</p> <p><a href="https://i.stack.imgur.com/asSZw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/asSZw.png" alt="Current Grid"></a></p> <p><br /><br /><br /> When none of the boxes contain any content I would like the grid to look something like this:</p> <p><a href="https://i.stack.imgur.com/iLhJE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iLhJE.png" alt="Preferred Grid"></a></p>
41,916,816
3
4
null
2017-01-29 01:25:54.657 UTC
22
2022-02-20 09:18:37.363 UTC
2018-06-20 13:14:35.9 UTC
null
123,671
null
743,512
null
1
86
html|css|grid-layout|css-grid
202,452
<p>One of the <a href="https://stackoverflow.com/a/32314236/743512">Related posts</a> gave me the (simple) answer.</p> <p>Apparently the <code>auto</code> value on the <code>grid-template-rows</code> property does exactly what I was looking for. </p> <pre><code>.grid { display:grid; grid-template-columns: 1fr 1.5fr 1fr; grid-template-rows: auto auto 1fr 1fr 1fr auto auto; grid-gap:10px; height: calc(100vh - 10px); } </code></pre>
6,774,143
Start upload after choosing a file, using jQuery.
<p>After having chosen a file for upload, I want the file to be uploaded to database without the click of a button. How is this done using jQuery?<br></p> <p>I would like to choose a file like this: <a href="http://i.stack.imgur.com/0408T.gif">http://i.stack.imgur.com/0408T.gif</a></p> <pre><code>&lt;input type="file" valign="baseline" /&gt; </code></pre>
6,774,164
3
0
null
2011-07-21 09:42:14.143 UTC
10
2018-05-05 07:46:16.893 UTC
2012-11-21 10:36:57.417 UTC
null
907,299
null
850,355
null
1
28
javascript|jquery
51,196
<p>Assuming you're using a form:</p> <pre><code>// select the file input (using a id would be faster) $('input[type=file]').change(function() { // select the form and submit $('form').submit(); }); </code></pre> <p><strong>EDIT:</strong> <em>To keep this answer up-to-date:</em></p> <p>There is a nice way to upload files via AJAX without hacks described here: <a href="http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/" rel="noreferrer">http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/</a></p>
6,595,252
MySQL: Creating a new table with information from a query
<p>In MySQL, I would like to create a new table with all the information in this query:</p> <pre><code>select * into consultaa2 from SELECT CONCAT( 'UPDATE customers SET customers_default_address_id= ', (SELECT a.address_book_id FROM address_book a where c.customers_id=a.customers_id order by address_book_id desc limit 1), ' WHERE customers_id = ', customers_id, ';') AS sql_statement FROM customers c where c.customers_id &gt; 3894; </code></pre> <p>The query is too long for the browser to show the concat and I need this to make this updates.</p>
6,595,298
3
1
null
2011-07-06 10:55:22.393 UTC
6
2019-07-22 03:41:58.963 UTC
2014-02-17 18:28:47.047 UTC
null
445,131
null
389,330
null
1
47
mysql|sql|insert|sql-update
98,388
<p>*Note that <strong>this method does not <em>create</em> a table</strong> (as per OP title). To do that see <a href="https://stackoverflow.com/a/6595301/8112776">this answer</a>.*</p> <hr> <p>Inserting into a table with information from a query is of the format</p> <pre><code>INSERT INTO &lt;TABLE-1&gt; SELECT * FROM &lt;TABLE-2&gt; </code></pre> <p>In your case, it would be</p> <pre><code>insert into consultaa2 SELECT CONCAT( 'UPDATE customers SET customers_default_address_id= ', (SELECT a.address_book_id FROM address_book a where c.customers_id=a.customers_id order by address_book_id desc limit 1), ' WHERE customers_id = ', customers_id, ';') AS sql_statement FROM customers c where c.customers_id &gt; 3894; </code></pre> <p>Just make sure the columns in the table you are inserting into and the columns returned from the select query match.</p>
6,345,250
How to add scroll bar to my dynamic table?
<p>If I defined an empty table in my <strong><em>index.html</em></strong>:</p> <pre><code>&lt;body&gt; &lt;table width="800" border="0" class="my-table"&gt; &lt;tr&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; </code></pre> <p>Then, I add row and columns to <strong><em>my-table</em></strong> by invoke the following Javascript code:</p> <pre><code>var myTable = $('.my-table'); var myArr=GET_FROM_SERVER //server returns an arry of object, myArr.length&gt;50 for(var i=0; i&lt;myArr.length) myTable.append("&lt;tr id="+i+"&gt;" +" &lt;td&gt;"+myArr[i].name+"&lt;/td&gt;" +"&lt;td&gt;"+myArr[i].address+"&lt;/td&gt;" +"&lt;/tr&gt;"); </code></pre> <p><code>myArr</code> is an array of object get from server, the length of this array could be more than 50. </p> <p>I got all of this working successfully, my question is, <strong>how can I add scroll bar to this table</strong> so that if there are too many rows, user could use scroll bar to check the table content.</p>
6,345,292
4
0
null
2011-06-14 14:35:02.247 UTC
2
2019-08-26 19:15:07.587 UTC
2019-08-26 19:15:07.587 UTC
null
4,370,109
null
740,018
null
1
9
javascript|jquery|html|css
38,120
<p>I would wrap the table with a div</p> <pre><code>&lt;body&gt; &lt;div style="overflow:scroll;height:80px;width:100%;overflow:auto"&gt; &lt;table width="800" border="0" class="my-table"&gt; &lt;tr&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
57,213,162
Why are my custom process.env not working within dotenv?
<p>Learning that it is a bad practice to include API secret keys I've done some research and trying to learn how to create custom <code>process.env</code>.</p> <p>After reading:</p> <ul> <li><a href="https://medium.com/the-node-js-collection/making-your-node-js-work-everywhere-with-environment-variables-2da8cdf6e786" rel="noreferrer">Node.js Everywhere with Environment Variables!</a></li> <li><a href="https://stackoverflow.com/questions/9198310/how-to-set-node-env-to-production-development-in-os-x">How to set NODE_ENV to production/development in OS X</a></li> <li><a href="https://stackoverflow.com/questions/42385158/how-to-set-process-env-from-the-file-in-nodejs">How to set process.env from the file in NodeJS?</a></li> <li><a href="https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables">dotenv file is not loading environment variables</a></li> </ul> <p>I'm trying to set an env file locally based on <code>process.env.NODE_ENV</code>. The application would be hosted on Heroku and in my .gitignore I have <code>dev.env</code> but when I try to use <a href="https://www.npmjs.com/package/dotenv" rel="noreferrer"><code>dotenv</code></a> locally I'm getting an <code>undefined</code>. I have set the environment locally with <code>export NODE_ENV=development</code> in my terminal. When I run the command <code>npm start</code> or <code>nodemon</code> both return <code>undefined</code> but in <em>env.js</em> I get <code>Testing for: development</code>, example:</p> <pre><code>nodemon [nodemon] 1.19.1 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node app.js` Testing for: development undefined </code></pre> <p>Here is what I have:</p> <p><em>app.js</em>:</p> <pre><code>const keys = require('./config/env') return console.log(process.env.PORT) </code></pre> <p><em>config/env.js</em>:</p> <pre><code>const env = process.env.NODE_ENV console.log(`Testing for: ${env}`) try { switch(env) { case 'undefined': Error('Environment undefined, if local in terminal: export NODE_ENV=development') break case 'development': require('dotenv').config({ path: './dev.env' }) break case 'production': require('dotenv').config({ path: './prod.env' }) break default: Error('Unrecognized Environment') } } catch (err) { Error('Error trying to run file') } </code></pre> <p><em>config/dev.env</em>:</p> <pre><code>## Port number to run Application PORT=4321 </code></pre> <p>but in <em>app.js</em> when I test with <code>return console.log(process.env.PORT)</code> or <code>return console.log(keys.PORT)</code> they both log <code>undefined</code>, why? I seem to be doing something wrong in <em>env.js</em> when using <code>dotenv</code>. </p> <p>To clarify I'm not even pushing to Heroku yet and <em>prod.env</em> will be validation. If there is a better approach please educate me.</p>
57,224,494
5
5
null
2019-07-26 04:20:26.253 UTC
6
2022-03-02 11:00:30.483 UTC
2019-07-26 12:44:32.693 UTC
null
1,952,287
null
1,952,287
null
1
16
node.js|environment-variables|local|dotenv
66,301
<p>I've figured where I was going wrong after re-reading the documentation regarding <a href="https://github.com/motdotla/dotenv#path" rel="noreferrer"><code>path</code></a>, example:</p> <pre><code>require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' }) </code></pre> <p>After changing:</p> <pre><code>case 'development': require('dotenv').config({ path: './dev.env' }) break </code></pre> <p>to:</p> <pre><code>case 'development': require('dotenv').config({ path: `${__dirname}/dev.env` }) break </code></pre> <p>it works. So my error was a scope issue. No need to set <code>const keys</code> so just using <code>require('./config/env')</code> I can access any custom processes, example:</p> <pre><code>process.env.CUSTOM </code></pre> <p>or in this case it would be:</p> <pre><code>process.env.PORT </code></pre> <p>from <em>app.js</em></p>
19,288,652
Difference between print and putStrLn in Haskell
<p>I am confused. I tried to use <code>print</code>, but I know people apply <code>putStrLn</code>. What are the real differences between them?</p> <pre><code>print $ function putStrLn $ function </code></pre>
19,289,943
1
2
null
2013-10-10 06:32:14.98 UTC
14
2019-05-13 15:54:39.857 UTC
2019-05-13 15:54:39.857 UTC
null
775,954
null
2,217,676
null
1
75
haskell|printing|ghc
47,326
<p>The function <code>putStrLn</code> takes a <code>String</code> and displays it to the screen, followed by a newline character (<strong>put</strong> a <strong>Str</strong>ing followed by a new <strong>L</strong>i<strong>n</strong>e).</p> <p>Because it only works with <code>String</code>s, a common idiom is to take any object, convert it to a <code>String</code>, and then apply <code>putStrLn</code> to display it. The generic way to convert an object to a <code>String</code> is with the <code>show</code> function, so your code would end up with a lot of</p> <pre><code>putStrLn (show 1) putStrLn (show [1, 2, 3]) putStrLn (show (Just 42)) </code></pre> <p>Once you notice that, it's not a very big stretch to define a function that converts to a <code>String</code> and displays the string in one step</p> <pre><code>print x = putStrLn (show x) </code></pre> <p>which is exactly what the <code>print</code> function is.</p>
60,854,215
tailwind use font from local files globally
<p>Currently I'm doing this in my style tags</p> <pre><code>@import url('https://fonts.googleapis.com/css?family=Roboto&amp;display=swap'); * { font-family: 'Roboto', sans-serif; } </code></pre> <p>but I downloaded the Roboto font and would like to know how I can configure Tailwind to use those files and the font globally for all elements.</p> <p><strong>Sidenote:</strong></p> <p>I'm using Vuejs and followed the guide on how to setup Tailwind for Vue from here</p> <p><a href="https://www.youtube.com/watch?v=xJcvpuELcZo" rel="noreferrer">https://www.youtube.com/watch?v=xJcvpuELcZo</a></p>
60,857,229
8
2
null
2020-03-25 17:32:06.347 UTC
11
2022-03-28 07:06:18.22 UTC
2020-03-26 08:21:30.517 UTC
null
7,764,329
null
7,764,329
null
1
38
javascript|html|css|tailwind-css
63,534
<p>You can customize Tailwind if it was installed as a dependency to your project using <code>npm install tailwindcss</code></p> <p>Steps:</p> <ul> <li><p>copy the downloaded font and place it inside a <code>fonts</code> folder inside your project.</p> </li> <li><p>run <code>npx tailwind init</code>, to generate an empty <code>tailwind.config.js</code></p> </li> <li><p>Inside <code>tailwind.config.js</code> add <code>fontFamily</code> inside <code>extend</code> and specify the font family to override (Tailwind's default family is <code>sans</code>). Place the newly added font family at the beginning (<a href="https://tailwindcss.com/docs/font-family/#customizing" rel="noreferrer">order matters</a>)</p> </li> </ul> <pre><code>module.exports = { theme: { extend: { fontFamily: { 'sans': ['Roboto', 'Helvetica', 'Arial', 'sans-serif'] } }, }, variants: {}, plugins: [] } </code></pre> <p><strong>Important</strong>: Using <code>extend</code> will add the newly specified font families without overriding Tailwind's entire font stack.</p> <p>Then in the main <code>tailwind.css</code> file (where you import all of tailwind features), you can import your local font family. Like this:</p> <pre><code>@tailwind base; @tailwind components; @font-face { font-family: 'Roboto'; src: local('Roboto'), url(./fonts/Roboto-Regular.ttf) format('ttf'); } @tailwind utilities; </code></pre> <p>Now recompile the CSS. If you're following <a href="https://tailwindcss.com/docs/installation#4-process-your-css-with-tailwind" rel="noreferrer">Tailwind's documentation</a>, this is typically done using <a href="https://github.com/postcss/postcss" rel="noreferrer">postcss</a>:</p> <pre><code>postcss css/tailwind.css -o public/tailwind.css </code></pre> <p>If you're not using postcss, you can run:</p> <pre><code>npx tailwindcss build css/tailwind.css -o public/tailwind.css </code></pre> <p>Your newly added font family should now be rendered.</p>
40,198,816
Is there any danger in using ConfigureAwait(false) in WebApi or MVC controllers?
<p>Say I have two scenarios:</p> <p><strong>1) WebApi Controller</strong></p> <pre><code> [System.Web.Http.HttpPost] [System.Web.Http.AllowAnonymous] [Route("api/registerMobile")] public async Task&lt;HttpResponseMessage&gt; RegisterMobile(RegisterModel model) { var registerResponse = await AuthUtilities.RegisterUserAsync(model, _userService, User); if (registerResponse.Success) { var response = await _userService.GetAuthViewModelAsync(model.Username, User); return Request.CreateResponse(HttpStatusCode.OK, new ApiResponseDto() { Success = true, Data = response }); } else { return Request.CreateResponse(HttpStatusCode.OK, registerResponse); } } </code></pre> <p><strong>2) MVC Controller</strong></p> <pre><code> [Route("public")] public async Task&lt;ActionResult&gt; Public() { if (User.Identity.IsAuthenticated) { var model = await _userService.GetAuthViewModelAsync(User.Identity.Name); return View("~/Views/Home/Index.cshtml", model); } else { var model = await _userService.GetAuthViewModelAsync(null); return View("~/Views/Home/Index.cshtml", model); } } </code></pre> <p>I've been reading up on when I should use <code>ConfigureAwait</code> and it seems like I should use <code>ConfigureAwait(false)</code> on ALL of my async calls that are not tied directly to the UI. I don't know what that means though... should I be using <code>.ConfigureAwait(false)</code> on all of the above <code>await</code> calls?</p> <p>I'm looking for some unambiguous guidelines around when exactly I should be using it.</p> <p>This question is NOT the same as the <a href="https://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code">Best practice to call ConfigureAwait for all server-side code</a> - I am looking for a straightforward answer on the use-case for this method in the context of WebApi and MVC, not as general C#.</p>
40,220,190
4
5
null
2016-10-23 01:57:56.577 UTC
12
2020-01-17 11:08:30.877 UTC
2017-05-23 11:54:58.043 UTC
null
-1
null
899,530
null
1
59
c#|.net|asp.net-mvc|asynchronous|asp.net-web-api
19,413
<blockquote> <p>it seems like I should use ConfigureAwait(false) on ALL of my async calls that are not tied directly to the UI.</p> </blockquote> <p>Not quite. That guideline doesn't make sense here, since there is no UI thread.</p> <p>The parameter passed to <code>ConfigureAwait</code> is <code>continueOnCapturedContext</code>, which explains more clearly the scenario. You want to use <code>ConfigureAwait(false)</code> whenever the rest of that <code>async</code> method does <em>not</em> depend on the current context.</p> <p>In ASP.NET 4.x, the "context" is the request context, which includes things like <code>HttpContext.Current</code> and culture. Also - and this is the undocumented part - a lot of the ASP.NET helper methods <em>do</em> depend on the request context.</p> <p>(Side note: ASP.NET Core no longer has a "context")</p> <blockquote> <p>should I be using .ConfigureAwait(false) on all of the above await calls?</p> </blockquote> <p>I haven't heard any firm guidance on this, but I suspect it's OK.</p> <p>In my own code, I never use <code>ConfigureAwait(false)</code> in my controller action methods, so that they complete already within the request context. It just seems more right to me.</p>
27,533,679
Google Analytics blocks Android App
<p>I use Google Analytics in my Android App and it works well. After updating the SDK (google play service) to the current version (6587000) the app hangs up at startup at following line 8 of 10 times:</p> <pre><code>GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); </code></pre> <p>There is no error in console. I added Achievements and Leaderboards too, but Analytics is called first. I also changed the context, but that works sometimes and sometimes not.</p> <p>The only time I get a reproducable result is, when I remove following lines from AndroidManifest.xml. Then there is no freeze at startup anymore.</p> <pre><code>&lt;meta-data android:name="com.google.android.gms.analytics.globalConfigResource" android:resource="@xml/analytics_global_config" /&gt; </code></pre> <p>But my configuration is correct:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;resources&gt; &lt;string name="ga_appName"&gt;TestAppName&lt;/string&gt; &lt;string name="ga_appVersion"&gt;Version1.0&lt;/string&gt; &lt;string name="ga_logLevel"&gt;verbose&lt;/string&gt; &lt;integer name="ga_dispatchPeriod"&gt;1000&lt;/integer&gt; &lt;bool name="ga_dryRun"&gt;true&lt;/bool&gt; &lt;/resources&gt; </code></pre> <p>And if I change the configuration there is the same result: 8 of 10 times the App freezes at startup.</p> <p>Does someone have a clue what the problem is or what else I can check to make my app running again without freezing at startup?</p>
27,542,483
3
2
null
2014-12-17 19:50:00.313 UTC
10
2015-03-20 22:21:36.463 UTC
null
null
null
null
2,751,935
null
1
30
android|google-analytics|android-manifest
4,262
<p>i had similar i removed the below code and application runs.. </p> <pre><code>&lt;meta-data android:name="com.google.android.gms.analytics.globalConfigResource" android:resource="@xml/analytics_global_config" /&gt; </code></pre> <p>and add following code for getTracker class... build the GoogleAnalytics using java code rather than XML approch</p> <pre><code>synchronized Tracker getTracker(TrackerName trackerId) { Log.d(TAG, "getTracker()"); if (!mTrackers.containsKey(trackerId)) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // Global GA Settings // &lt;!-- Google Analytics SDK V4 BUG20141213 Using a GA global xml freezes the app! Do config by coding. --&gt; analytics.setDryRun(false); analytics.getLogger().setLogLevel(Logger.LogLevel.INFO); //analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); // Create a new tracker Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.ga_tracker_config) : null; if (t != null) { t.enableAdvertisingIdCollection(true); } mTrackers.put(trackerId, t); } return mTrackers.get(trackerId); } </code></pre>
27,646,925
How do I return a Filter iterator from a function?
<p>I want something like that:</p> <pre><code>fn filter_one&lt;'a, T: Int&gt;(input: &amp;'a Vec&lt;T&gt;) -&gt; ??? { input.iter().filter(|&amp;x| x == Int::one()) } </code></pre> <p>What's the return type of that function? (I want to return the Iterator)</p> <p>(I hope this isn't too obvious, I've been trying for half an hour now and am just starting to get frustrated :p )</p> <p><strong>EDIT:</strong></p> <p>I tried to follow the instructions from <a href="https://stackoverflow.com/questions/27535289/correct-way-to-return-an-iterator">here</a> => <a href="http://is.gd/SZK4mM" rel="noreferrer">playpen link</a></p> <p>the compiler gives me the following error:</p> <pre><code>&lt;anon&gt;:5:1: 7:2 error: the trait `core::kinds::Sized` is not implemented for the type `for&lt;'r&gt; core::ops::Fn(&amp;'r T) -&gt; bool + 'a` &lt;anon&gt;:5 fn filter_one&lt;'a, T: Int&gt;(input: &amp;'a Vec&lt;T&gt;) -&gt; Filter&lt;&amp;T, Iter&lt;'a, T&gt;, Fn(&amp;T) -&gt; bool&gt;{ &lt;anon&gt;:6 input.iter().filter(|&amp;x| x == Int::one()) &lt;anon&gt;:7 } &lt;anon&gt;:5:1: 7:2 note: required by `core::iter::Filter` &lt;anon&gt;:5 fn filter_one&lt;'a, T: Int&gt;(input: &amp;'a Vec&lt;T&gt;) -&gt; Filter&lt;&amp;T, Iter&lt;'a, T&gt;, Fn(&amp;T) -&gt; bool&gt;{ &lt;anon&gt;:6 input.iter().filter(|&amp;x| x == Int::one()) &lt;anon&gt;:7 } &lt;anon&gt;:5:1: 7:2 error: the trait `for&lt;'r&gt; core::ops::Fn(&amp;'r &amp;'a T) -&gt; bool` is not implemented for the type `for&lt;'r&gt; core::ops::Fn(&amp;'r T) -&gt; bool + 'a` &lt;anon&gt;:5 fn filter_one&lt;'a, T: Int&gt;(input: &amp;'a Vec&lt;T&gt;) -&gt; Filter&lt;&amp;T, Iter&lt;'a, T&gt;, Fn(&amp;T) -&gt; bool&gt;{ &lt;anon&gt;:6 input.iter().filter(|&amp;x| x == Int::one()) &lt;anon&gt;:7 } &lt;anon&gt;:5:1: 7:2 note: required by `core::iter::Filter` &lt;anon&gt;:5 fn filter_one&lt;'a, T: Int&gt;(input: &amp;'a Vec&lt;T&gt;) -&gt; Filter&lt;&amp;T, Iter&lt;'a, T&gt;, Fn(&amp;T) -&gt; bool&gt;{ &lt;anon&gt;:6 input.iter().filter(|&amp;x| x == Int::one()) &lt;anon&gt;:7 } error: aborting due to 2 previous errors playpen: application terminated with error code 101 </code></pre> <p>How do I tell <code>rustc</code> that <code>Fn(&amp;T) -&gt; bool</code> is <code>Sized?</code>?</p>
27,649,089
2
3
null
2014-12-25 11:48:19.88 UTC
11
2020-04-15 13:41:43.09 UTC
2014-12-25 17:05:08.643 UTC
null
155,423
null
1,477,992
null
1
33
generics|iterator|rust
6,206
<h1>Rust 1.26</h1> <pre><code>fn filter_one(input: &amp;[u8]) -&gt; impl Iterator&lt;Item = &amp;u8&gt; { input.iter().filter(|&amp;&amp;x| x == 1) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec&lt;_&gt; = filter_one(&amp;nums).collect(); println!("{:?}", other); } </code></pre> <h1>Rust 1.0</h1> <pre><code>fn filter_one&lt;'a&gt;(input: &amp;'a [u8]) -&gt; Box&lt;Iterator&lt;Item = &amp;'a u8&gt; + 'a&gt; { Box::new(input.iter().filter(|&amp;&amp;x| x == 1)) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec&lt;_&gt; = filter_one(&amp;nums).collect(); println!("{:?}", other); } </code></pre> <p>This solution requires additional allocation. We create a <em>boxed trait object</em>. Here, the size of the object is always known (it's just a pointer or two), but the size of the object in the heap does not need to be known.</p> <p>As <a href="https://stackoverflow.com/a/27648199/155423">Vladimir Matveev points out</a>, if your predicate logic doesn't need any information from the environment, you can use a function instead of a closure:</p> <pre><code>use std::{iter::Filter, slice::Iter}; fn filter_one&lt;'a&gt;(input: &amp;'a [u8]) -&gt; Filter&lt;Iter&lt;u8&gt;, fn(&amp;&amp;u8) -&gt; bool&gt; { fn is_one(a: &amp;&amp;u8) -&gt; bool { **a == 1 } input.iter().filter(is_one) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec&lt;_&gt; = filter_one(&amp;nums).collect(); println!("{:?}", other); } </code></pre> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/q/27535289/155423">What is the correct way to return an Iterator (or any other trait)?</a></li> </ul>
5,444,197
converting host to ip by sockaddr_in gethostname etc
<p>i need help converting hostname to ip and inserting to sockaddr_in->sin_addr to be able assign to char. For example i input: localhost and it gives me 127.0.0.1</p> <p>I found code, but i dont know why it gives me wrong numbers</p> <pre><code>//--- #include &lt;sys/types.h&gt; #include &lt;netinet/in.h&gt; #include &lt;string.h&gt; #include &lt;sys/socket.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;errno.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;sys/fcntl.h&gt; #include &lt;netdb.h&gt; //--- ///CZY WPISANO HOST struct in_addr inaddr; inaddr.s_addr = inet_addr(argv[1]); if( inaddr.s_addr == INADDR_NONE) //if sHost is name and not IP { struct hostent* phostent = gethostbyname( argv[1]); if( phostent == 0) bail("gethostbyname()"); if( sizeof(inaddr) != phostent-&gt;h_length) bail("problem z inaddr"); // error something wrong, puts(argv[1]); inaddr.s_addr = *((unsigned long*) phostent-&gt;h_addr); //strdup( inet_ntoa(inaddr)); srvr_addr = inet_ntoa(adr_srvr.sin_addr); puts(srvr_addr); } </code></pre> <p>I also wrote own code but i dont know how transfer from sockaddr to sockaddr_in data:</p> <pre><code>///CZY WPISANO HOST if(argv[1][0]&gt;=(char)'a' &amp;&amp; argv[1][0]&lt;=(char)'Z') { struct hostent *hent; hent = gethostbyname(argv[1]); adr_srvr.sin_addr = (struct in_addr*)hent-&gt;h_addr_list; } </code></pre> <p>adr_srvr is a char* type</p> <p>I really need help, thanks!</p>
5,445,610
2
0
null
2011-03-26 18:08:39.68 UTC
8
2011-03-27 17:46:13.3 UTC
2011-03-27 17:46:13.3 UTC
null
619,673
null
619,673
null
1
7
c|ip|host
48,830
<p>Try something like this: </p> <pre><code> struct hostent *he; struct sockaddr_in server; int socket; const char hostname[] = "localhost"; /* resolve hostname */ if ( (he = gethostbyname(hostname) ) == NULL ) { exit(1); /* error */ } /* copy the network address to sockaddr_in structure */ memcpy(&amp;server.sin_addr, he-&gt;h_addr_list[0], he-&gt;h_length); server.sin_family = AF_INET; server.sin_port = htons(1337); /* and now you can connect */ if ( connect(socket, (struct sockaddr *)&amp;server, sizeof(server) ) { exit(1); /* error */ } </code></pre> <p>I wrote this code straight from my memory so I cannot guarantee that it works but I am pretty sure it should be OK.</p>
5,375,609
Wait for executable to finish running
<p>Can you run two executables in a batch file and wait for the first process to end before starting the next?</p>
5,375,658
2
4
null
2011-03-21 09:10:33.473 UTC
4
2015-10-22 14:28:50.627 UTC
null
null
null
null
576,921
null
1
8
windows|batch-file
50,449
<p>Use start /wait:</p> <pre><code>:NOTEPAD start /wait notepad.exe IF %ERRORLEVEL% == 0 goto NEXTITEM1 else goto QUIT :NEXTITEM1 start /wait mplayer.exe IF %ERRORLEVEL% == 0 goto NEXTITEM2 else goto QUIT :NEXTITEM2 start /wait explorer.exe IF %ERRORLEVEL% == 0 goto NEXTITEM3 else goto QUIT :NEXTITEM3 REM You get the idea... :QUIT exit </code></pre> <p>In addition, use NT CMD rather than BAT (myscript.cmd).</p> <p>In response to the comments, brackets removed from the above script around %ERRORLEVEL%. The following seems to behave as expected:</p> <pre><code>:NOTEPAD start /wait notepad.exe || goto QUIT :NEXTITEM1 start /wait mplayer2.exe || goto QUIT :NEXTITEM2 REM You get the idea... :QUIT exit </code></pre> <p>The statement after the double-pipe only executes if what is before it fails.</p>
16,415,740
jQuery - Resume form submit after ajax call
<p>Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?</p> <p>At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a> website.</p> <p>Thank you very much for any help in advance</p> <p>If it's not possible to do it this way, is there another way of getting it to work?</p> <pre><code>$(document).ready(function() { $('form').submit(function(e) { e.preventDefault(); $.ajax({ url: $('form').attr('action'), type: 'post', data: $('form').serialize(), success: function(data) { if (data == 'true') { $('form').attr('action', 'http://example.com'); $('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com } else { alert('Your username/password are incorrect'); } }, error: function() { alert('There has been an error, please alert us immediately'); } }); }); }); </code></pre> <p><strong>Edit:</strong></p> <p>Stackoverflow posts checked out for the code below:</p> <ul> <li><a href="https://stackoverflow.com/questions/15185431/resume-form-submission-after-ajax-call">Resume form submission after $.ajax call</a></li> <li><a href="https://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault">How to reenable event.preventDefault?</a></li> </ul> <p>I just thought I'd mention I have also tried this code without avail.</p> <pre><code>var ajaxSent = false; $(document).ready(function() { $('form').submit(function(e) { if ( !ajaxSent) e.preventDefault(); $.ajax({ url: $('form').attr('action'), type: 'post', data: $('form').serialize(), success: function(data) { if (data == 'true') { alert('submit form'); ajaxSent = true; $('form').attr('action', 'http://example.com'); $('form').submit(); return true; } else { alert('Your username/password are incorrect'); return false; } }, error: function() { alert('There has been an error, please alert us immediately'); return false; } }); }); }); </code></pre> <p>I have also tried this code without any luck as well.</p> <pre><code>$(document).ready(function() { $('form').submit(function(e) { e.preventDefault(); $.ajax({ url: $('form').attr('action'), type: 'post', data: $('form').serialize(), success: function(data) { if (data == 'true') { $('form').attr('action', 'http://example.com'); $('form').unbind('submit').submit(); return true; } else { alert('Your username/password are incorrect'); return false; } }, error: function() { alert('There has been an error, please alert us immediately'); return false; } }); }); }); </code></pre>
16,417,582
3
7
null
2013-05-07 09:34:46.873 UTC
5
2015-02-12 14:23:10.187 UTC
2017-05-23 11:46:27.44 UTC
null
-1
null
1,625,795
null
1
5
javascript|jquery
39,375
<p>Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.</p> <p>Here is my working code:</p> <pre><code>$(document).ready(function() { var testing = false; $('#btn-login').on('click', function() { $.ajax({ url: $('form').attr('action'), type: 'post', data: $('form').serialize(), async: false, success: function(data) { if (data == 'true') { testing = true; $('form').attr('action', 'https://example.com'); $('form').submit(); } else { alert('Your username/password are incorrect'); } }, error: function() { alert('There has been an error, please alert us immediately'); } }); return testing; }); }); </code></pre>
16,346,684
How to perform interpolation on a 2D array in MATLAB
<p>How can I make a function of 2 variables and given a 2D array, it would return an interpolated value?</p> <p>I have <code>N x M</code> array <code>A</code>. I need to interpolate it and somehow obtain the function of that surface so I could pick values on not-integer arguments. (I need to use that interpolation as a function of 2 variables) </p> <p>For example: </p> <pre><code>A[N,M] //my array // here is the method I'm looking for. Returns function interpolatedA interpolatedA(3.14,344.1) //That function returns interpolated value </code></pre>
16,346,743
4
1
null
2013-05-02 20:00:31.173 UTC
null
2017-01-31 15:47:45.357 UTC
2015-05-30 16:27:01.213 UTC
null
3,250,829
null
2,344,606
null
1
6
matlab|interpolation
47,322
<p>For data on a regular grid, use <a href="http://www.mathworks.com/help/matlab/ref/interp2.html" rel="nofollow noreferrer">interp2</a>. If your data is scattered, use <a href="http://www.mathworks.com/help/matlab/ref/griddata.html" rel="nofollow noreferrer">griddata</a>. You can create an <a href="http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html" rel="nofollow noreferrer">anonymous function</a> as a simplified wrapper around those calls.</p> <pre><code>M = 10; N = 5; A = rand(M,N); interpolatedA = @(y,x) interp2(1:N,1:M,A,x,y); %interpolatedA = @(y,x) griddata(1:N,1:M,A,x,y); % alternative interpolatedA(3.3,8.2) ans = 0.53955 </code></pre>
374,157
Using Windows DLL from Linux
<p>We need to interface to 3rd party app, but company behind the app doesn't disclose message protocol and provides only Windows DLL to interface to.</p> <p>Our application is Linux-based so I cannot directly communicate with DLL. I couldn't find any existing solution so I'm considering writing socket-based bridge between Linux and Windows, however I'm sure it is not such a unique problem and somebody should have done it before.</p> <p>Are you aware of any solution that allows to call Windows DDL functions from C app on Linux? It can use Wine or separate Windows PC - doesn't matter.</p> <p>Many thanks in advance.</p>
374,231
7
0
null
2008-12-17 10:20:53.85 UTC
13
2022-09-11 13:50:11.52 UTC
2021-06-20 14:38:45.177 UTC
null
28,494
qrdl
28,494
null
1
25
dll|linux|api
36,014
<p>Any solution is going to need a TCP/IP-based "remoting" layer between the DLL which is running in a "windows-like" environment, and your linux app. </p> <p>You'll need to write a simple PC app to expose the DLL functions, either using a homebrew protocol, or maybe XML-RPC, SOAP or JSON protocols. The <a href="http://www.remobjectssdk.com" rel="noreferrer">RemObjects SDK</a> might help you - but could be overkill.</p> <p>I'd stick with a 'real' or virtualized PC. If you use Wine, the DLL developers are unlikely to offer any support.</p> <p>MONO is also unlikely to be any help, because your DLL is probably NOT a .NET assembly.</p>
708,384
Automatically generate implementations of base class methods
<p>Is there a shortcut of some kind in C# (VS 2008) to automatically implement the virtual and abstract base class methods in a derived class?</p>
708,394
7
0
null
2009-04-02 05:15:27.57 UTC
7
2019-02-28 10:38:46.05 UTC
null
null
null
DancesWithBamboo
1,334
null
1
34
c#|visual-studio
46,662
<p>For virtual methods, you can type <code>override</code> and then a space. Intellisense should offer you a list of options.</p> <p>For abstract methods and properties, you can use the smart tag on the base class or interface (also, <kbd>Ctrl</kbd>+<kbd>.</kbd> or <kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>F10</kbd> will show the smart tag menu) to generate the concrete items.</p> <p>For example, in the following code snippet, you could place the caret at the end of <code>INotifyPropertyChanged</code> and press <kbd>Ctrl</kbd>+<kbd>.</kbd> to then select Implement Interface, and the <code>PropertyChanged</code> event would be added to <code>MyClass</code>:</p> <pre><code>class MyClass : INotifyPropertyChanged { } </code></pre>
1,192,978
Python - Get relative path of all files and subfolders in a directory
<p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p> <p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p> <pre><code>myFolder = "myfolder" fileSet = set() # yes, I need a set() for root, dirs, files in os.walk(myFolder): for fileName in files: fileSet.add(root.replace(myFolder, "") + os.sep + fileName) </code></pre> <p>Any other suggestions?</p> <p>Thanks</p>
13,617,120
7
2
null
2009-07-28 09:31:08.357 UTC
13
2021-09-09 09:06:55.16 UTC
null
null
null
null
53,911
null
1
49
python
62,387
<p>Use <a href="https://docs.python.org/3.8/library/os.path.html#os.path.relpath" rel="noreferrer"><code>os.path.relpath()</code></a>. This is exactly its intended use.</p> <pre><code>import os root_dir = &quot;myfolder&quot; file_set = set() for dir_, _, files in os.walk(root_dir): for file_name in files: rel_dir = os.path.relpath(dir_, root_dir) rel_file = os.path.join(rel_dir, file_name) file_set.add(rel_file) </code></pre> <p>Note that <code>os.path.relpath()</code> was added in Python 2.6 and is supported on Windows and Unix.</p>
561,327
Find the number of lines in a project with powershell
<p>I'm trying to find a way to count the total number of lines in all of the source files of a project I have. I've tried piping <code>dir -r -name</code> into <code>measure-object -line</code>, but that just counts the number of files I have.</p> <p>Does anyone have a script to do this?</p>
562,009
8
0
null
2009-02-18 14:44:21.21 UTC
14
2021-02-09 06:32:00.13 UTC
null
null
null
Dan Monego
32,771
null
1
44
powershell
27,339
<p>Thanks to everyone who answered. The way I ended up implementing this was</p> <pre><code>dir . -filter &quot;*.cs&quot; -Recurse -name | foreach{(GC $_).Count} | measure-object -sum </code></pre> <blockquote> <p>GC is alias for Get-Content<br /> dir is alias for Get-ChildItem</p> </blockquote>
1,288,297
jQuery - auto size text input (not textarea!)
<p>How do I auto-resize the input type="text" field with jQuery? I want it to be like 100px wide at the start, then make it auto-widening as user inputs text... is that possible?</p>
1,288,475
9
1
null
2009-08-17 14:35:52.487 UTC
17
2015-12-01 12:52:11.973 UTC
null
null
null
null
146,248
null
1
41
jquery|html|input
88,927
<p>Here's a plugin that'll do what you're after:</p> <p>The plugin:</p> <pre><code>(function($){ $.fn.autoGrowInput = function(o) { o = $.extend({ maxWidth: 1000, minWidth: 0, comfortZone: 70 }, o); this.filter('input:text').each(function(){ var minWidth = o.minWidth || $(this).width(), val = '', input = $(this), testSubject = $('&lt;tester/&gt;').css({ position: 'absolute', top: -9999, left: -9999, width: 'auto', fontSize: input.css('fontSize'), fontFamily: input.css('fontFamily'), fontWeight: input.css('fontWeight'), letterSpacing: input.css('letterSpacing'), whiteSpace: 'nowrap' }), check = function() { if (val === (val = input.val())) {return;} // Enter new content into testSubject var escaped = val.replace(/&amp;/g, '&amp;amp;').replace(/\s/g,' ').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;'); testSubject.html(escaped); // Calculate new width + whether to change var testerWidth = testSubject.width(), newWidth = (testerWidth + o.comfortZone) &gt;= minWidth ? testerWidth + o.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = (newWidth &lt; currentWidth &amp;&amp; newWidth &gt;= minWidth) || (newWidth &gt; minWidth &amp;&amp; newWidth &lt; o.maxWidth); // Animate width if (isValidWidthChange) { input.width(newWidth); } }; testSubject.insertAfter(input); $(this).bind('keyup keydown blur update', check); }); return this; }; })(jQuery); </code></pre> <p><strong>EDIT:</strong> Found on: <a href="https://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields">Is there a jQuery autogrow plugin for text fields?</a></p>
234,443
Adding a new project to an existing solution in TFS
<p>I added a project to an existing solution that is currently under source control using TFS, but for some reason I cannot check in the new project. When I view my pending changes, none of the files in the new project show up. None of the files have a plus (for a new file) next to them. What did I do wrong? How do I fix it? It's time to check in.</p>
2,216,802
9
1
null
2008-10-24 17:15:29.7 UTC
15
2021-12-24 14:44:47.58 UTC
null
null
null
Dana
3,018
null
1
73
visual-studio|tfs
54,258
<p>The problem is the solution has lost its binding. That's why it's not checking out automatically when you add the new project.</p> <p>In order to restore the binding in VS 2010, go to File->Source Control->Change Source Control. Look for the "Solution: <em>your solution name</em>" and if it's not bound it will say "no server". Click on it and then click "Bind" from the toolbar.</p> <p>in Visual Studio 2012/2013 it's File->Source Control-><em>Advanced</em>->Change Source Control (Thanks to danglund).</p> <p>This should create a new vssscc file that is correctly bound. Now add the new project and everything should work correctly.</p>
1,098,644
Switch statement without default when dealing with enumerations
<p>This has been a pet peeve of mine since I started using .NET but I was curious in case I was missing something. My code snippet won't compile (please forgive the forced nature of the sample) because (according to the compiler) a return statement is missing:</p> <pre><code>public enum Decision { Yes, No} public class Test { public string GetDecision(Decision decision) { switch (decision) { case Decision.Yes: return "Yes, that's my decision"; case Decision.No: return "No, that's my decision"; } } } </code></pre> <p>Now I know I can simply place a default statement to get rid of the complier warning, but to my mind not only is that redundant code, its dangerous code. If the enumeration was in another file and another developer comes along and adds <em>Maybe</em> to my enumeration it would be handled by my default clause which knows nothing about <em>Maybe</em>s and there's a really good chance we're introducing a logic error.</p> <p>Whereas, if the compiler let me use my code above, it could then identify that we have a problem as my case statement would no longer cover all the values from my enumeration. Sure sounds a lot safer to me.</p> <p>This is just so fundamentally wrong to me that I want to know if its just something I'm missing, or do we just have to be very careful when we use enumerations in switch statements?</p> <p><strong>EDIT:</strong> I know I can raise exceptions in the default or add a return outside of the switch, but this are still fundamentally hacks to get round a compiler error that shouldn't be an error.</p> <p>With regards an enum really just being an int, that's one of .NET's dirty little secrets which is quite embarassing really. Let me declare an enumeration with a finite number of possibilities please and give me a compilation for:</p> <pre><code>Decision fred = (Decision)123; </code></pre> <p>and then throw an exception if somebody tries something like:</p> <pre><code>int foo = 123; Decision fred = (Decision)foo; </code></pre> <p><strong>EDIT 2:</strong></p> <p>A few people have made comments about what happens when the enum is in a different assembly and how this would result in problems. My point is that this is the behaviour I think should happen. If I change a method signature this will lead to issues, my premis is that changing an enumeration should be this same. I get the impression that a lot of people don't think I understand about enums in .NET. I do I just think that the behaviour is wrong, and I'd hoped that someone might have known about some very obscure feature that would have altered my opinion about .NET enums. </p>
1,099,100
10
8
null
2009-07-08 15:04:15.313 UTC
4
2018-08-02 15:18:20.783 UTC
2009-07-08 17:59:25.71 UTC
null
116,671
null
116,671
null
1
39
c#|.net|enums|switch-statement
19,022
<p>Heck, the situation is far worse than just dealing with enums. We don't even do this for bools!</p> <pre><code>public class Test { public string GetDecision(bool decision) { switch (decision) { case true: return "Yes, that's my decision"; case false: return "No, that's my decision"; } } } </code></pre> <p>Produces the same error.</p> <p>Even if you solved all the problems with enums being able to take on any value, you'd still have this issue. The flow analysis rules of the language simply do not consider switches without defaults to be "exhaustive" of all possible code paths, even when you and I know they are.</p> <p>I would like very much to fix that, but frankly, we have many higher priorities than fixing this silly little issue, so we've never gotten around to it.</p>
279,236
How do I resize pngs with transparency in PHP?
<p>I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!</p> <pre><code>$this-&gt;image = imagecreatefrompng($filename); imagesavealpha($this-&gt;image, true); $newImage = imagecreatetruecolor($width, $height); // Make a new transparent image and turn off alpha blending to keep the alpha channel $background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagecolortransparent($newImage, $background); imagealphablending($newImage, false); imagesavealpha($newImage, true); imagecopyresampled($newImage, $this-&gt;image, 0, 0, 0, 0, $width, $height, $this-&gt;getWidth(), $this-&gt;getHeight()); $this-&gt;image = $newImage; imagepng($this-&gt;image,$filename); </code></pre> <p><br /> <strong>Update</strong> By 'not working' I meant to say the background color changes to black when I resize pngs.</p>
279,310
11
1
null
2008-11-10 21:28:35.627 UTC
17
2021-09-21 13:42:44.247 UTC
2008-11-10 23:59:03.563 UTC
Ryan Doherty
956
Ryan Doherty
956
null
1
45
php|png|gd|resize
64,847
<p>From what I can tell, you need to set the blending mode to <code>false</code>, and the save alpha channel flag to <code>true</code> <strong>before</strong> you do the imagecolorallocatealpha()</p> <pre><code>&lt;?php /** * https://stackoverflow.com/a/279310/470749 * * @param resource $image * @param int $newWidth * @param int $newHeight * @return resource */ public function getImageResized($image, int $newWidth, int $newHeight) { $newImg = imagecreatetruecolor($newWidth, $newHeight); imagealphablending($newImg, false); imagesavealpha($newImg, true); $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent); $src_w = imagesx($image); $src_h = imagesy($image); imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h); return $newImg; } ?&gt; </code></pre> <p><strong>UPDATE</strong> : This code is working only on background transparent with opacity = 0. If your image have 0 &lt; opacity &lt; 100 it'll be black background.</p>
5,724
Better windows command line shells
<p>Is there a better windows command line shell other than <code>cmd</code> which has better copy paste between Windows' windows and console windows?</p>
5,823
15
0
null
2008-08-08 06:15:11.033 UTC
22
2015-08-20 22:26:38.36 UTC
2009-10-23 11:23:17.587 UTC
Mark Biek
40,342
null
108,465
null
1
66
windows|shell|cmd
46,297
<p><a href="http://www.jpsoft.com/tcmddes.htm" rel="noreferrer">Take Command</a> does support Copy/Cut/Paste from the keyboard and the mouse. It's pretty handy if you do a lot of work from a command prompt. It also supports:</p> <ul> <li>Command and folder history, with popup windows to select prior commands or folders.</li> <li>Screen scroll back buffer</li> <li>Enhanced batch commands</li> <li>Built in FTP/HTTP file access</li> <li>A toolbar with programmable buttons</li> </ul> <p>Note: It's a paid tool, with price of $99.95.</p>
1,268,591
How to easily duplicate a Windows Form in Visual Studio?
<p>How can I easily duplicate a C#/VB Form in Visual Studio? If I copy &amp; paste in the Solution Explorer, it uses the same class internally and gets messed up. How do you do it? </p>
1,268,621
16
1
null
2009-08-12 20:38:24.683 UTC
13
2021-12-22 15:19:45.127 UTC
2014-07-28 10:24:03.603 UTC
null
451,518
null
41,021
null
1
55
winforms|visual-studio
145,095
<p>I usually copy the files in windows explorer, open them up in Notepad/Wordpad and just change the one mention of the class name at the top. Include those files in your project, and you'll be good to go.</p>
36,014
Why is .NET exception not caught by try/catch block?
<p>I'm working on a project using the <a href="http://antlr.org" rel="noreferrer">ANTLR</a> parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p> <p>The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:</p> <pre> Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C# Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C# </pre> <p>The code snippet from the bottom-most call in Parse() looks like:</p> <pre><code> try { // Execution stopped at parser.prog() TimeDefParser.prog_return prog_ret = parser.prog(); return prog_ret == null ? null : prog_ret.value; } catch (Exception ex) { throw new ParserException(ex.Message, ex); } </code></pre> <p>To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?</p> <p><strong>Update:</strong> I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.</p> <p>Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.</p> <p>One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.</p> <p>Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.</p> <p>Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?</p> <p><strong>Update 2:</strong> I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.</p> <p>I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.</p> <p><strong>Update 3:</strong> I've replicated this scenario in a <a href="http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip" rel="noreferrer">simplified VS 2008 project</a>. Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.</p> <p>If you can find a workaround, please do share your findings. Thanks again!</p> <hr> <p>Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.</p> <p>The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.</p>
41,208
25
0
2008-09-02 17:25:42.607 UTC
2008-08-30 14:57:13.05 UTC
14
2021-11-18 09:45:44.55 UTC
2012-03-24 08:46:10.86 UTC
Jeff Atwood
249,431
spoulson
3,347
null
1
54
c#|.net|exception|antlr
69,611
<p>I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it.</p> <p>In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this:</p> <pre> [External Code] > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# [External Code] TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [External Code] </pre> <p>If you right click in the callstack window and run turn on show external code you see this:</p> <pre> Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [Native to Managed Transition] [Managed to Native Transition] mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes </pre> <p>The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled. </p> <p>The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it.</p> <p>Things to play with to see how this looks for those who didn't repro the problem:</p> <ul> <li>Go to Tools/Options/Debugging and turn off "Enable Just My code (Managed only)". or option.</li> <li>Go to Debugger/Exceptions and turn off "User-unhandled" for Common-Language Runtime Exceptions.</li> </ul>
769,683
PostgreSQL: Show tables in PostgreSQL
<p>What's the equivalent to <code>show tables</code> (from MySQL) in PostgreSQL?</p>
769,706
27
1
null
2009-04-20 19:07:39.21 UTC
391
2022-05-25 10:25:55.787 UTC
2020-05-31 14:55:53.477 UTC
null
10,907,864
null
63,051
null
1
2,255
postgresql
2,353,872
<p>From the <code>psql</code> command line interface,</p> <p>First, choose your database</p> <pre><code>\c database_name </code></pre> <p>Then, this shows all tables in the current schema:</p> <pre><code>\dt </code></pre> <hr> <p>Programmatically (or from the <code>psql</code> interface too, of course):</p> <pre><code>SELECT * FROM pg_catalog.pg_tables; </code></pre> <p>The system tables live in the <code>pg_catalog</code> database.</p>
6,860,661
Jersey: Print the actual request
<p>How can I view the actual request that Jersey generates and sends to the server? I am having issues with a particular request and the fellow running the webserver asked to see the full request (with headers and the such).</p>
6,873,911
4
1
null
2011-07-28 14:29:49.253 UTC
21
2020-07-01 16:20:56.797 UTC
null
null
null
null
22,231
null
1
95
java|jersey
89,204
<p>If you're just using Jersey Client API, <a href="https://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/client/filter/LoggingFilter.html" rel="noreferrer">LoggingFilter</a> (client filter) should help you:</p> <pre><code>Client client = Client.create(); client.addFilter(new LoggingFilter(System.out)); WebResource webResource = client.resource("http://localhost:9998/"); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); </code></pre> <p>Otherwise, you can again log both request and response on server using other <a href="https://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/container/filter/LoggingFilter.html" rel="noreferrer">LoggingFilter</a> (container filter).</p>
6,967,463
Iterating over a numpy array
<p>Is there a less verbose alternative to this:</p> <pre><code>for x in xrange(array.shape[0]): for y in xrange(array.shape[1]): do_stuff(x, y) </code></pre> <p>I came up with this:</p> <pre><code>for x, y in itertools.product(map(xrange, array.shape)): do_stuff(x, y) </code></pre> <p>Which saves one indentation, but is still pretty ugly.</p> <p>I'm hoping for something that looks like this pseudocode:</p> <pre><code>for x, y in array.indices: do_stuff(x, y) </code></pre> <p>Does anything like that exist?</p>
6,967,491
4
3
null
2011-08-06 14:27:03.787 UTC
47
2021-01-30 02:00:41.317 UTC
null
null
null
null
76,701
null
1
149
python|numpy
211,431
<p>I think you're looking for the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html#numpy.ndenumerate" rel="noreferrer">ndenumerate</a>.</p> <pre><code>&gt;&gt;&gt; a =numpy.array([[1,2],[3,4],[5,6]]) &gt;&gt;&gt; for (x,y), value in numpy.ndenumerate(a): ... print x,y ... 0 0 0 1 1 0 1 1 2 0 2 1 </code></pre> <p>Regarding the performance. It is a bit slower than a list comprehension. </p> <pre><code>X = np.zeros((100, 100, 100)) %timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])]) 1 loop, best of 3: 376 ms per loop %timeit list(np.ndenumerate(X)) 1 loop, best of 3: 570 ms per loop </code></pre> <p>If you are worried about the performance you could optimise a bit further by looking at the implementation of <code>ndenumerate</code>, which does 2 things, converting to an array and looping. If you know you have an array, you can call the <code>.coords</code> attribute of the flat iterator. </p> <pre><code>a = X.flat %timeit list([(a.coords, x) for x in a.flat]) 1 loop, best of 3: 305 ms per loop </code></pre>
6,871,859
Piping command output to tee but also save exit code of command
<p>I have a shell script in which I wrap a command (mvn clean install), to redirect the output to a logfile. </p> <pre><code>#!/bin/bash ... mvn clean install $@ | tee $logfile echo $? # Does not show the return code of mvn clean install </code></pre> <p>Now if <code>mvn clean install</code> fails with an error, I want my wrapper shell script also fail with that error. But since I'm piping all the output to tee, I cannot access the return code of <code>mvn clean install</code>, so when I access <code>$?</code> afterwards, it's always 0 (since tee successes). </p> <p>I tried letting the command write the error output to a separate file and checking that afterwards, but the error output of mvn is always empty (seems like it only writes to stdout).</p> <p>How can I preserve the return code of <code>mvn clean install</code> but still piping the output to a logfile?</p>
6,871,917
4
0
null
2011-07-29 10:36:42.423 UTC
40
2016-09-27 16:57:05.463 UTC
null
null
null
null
319,905
null
1
223
bash|shell|pipe|sh|tee
74,564
<p>Since you're running <code>bash</code>, you can use its <a href="http://tldp.org/LDP/abs/html/internalvariables.html#PIPESTATUSREF" rel="noreferrer">$PIPESTATUS</a> variable instead of <code>$?</code>:</p> <pre><code>mvn clean install $@ | tee $logfile echo ${PIPESTATUS[0]} </code></pre>
6,928,306
Android USB host-to-serial connection?
<p>Apparently with Android 2.3.4 and 3.1 one can now access USB accessories.</p> <p>I have a Ardupilot Mega (based on Arduino) board with a USB cable connected to my laptop, and I can connect to it using a simple serial communications program over COM7 and 115,200 baud. This allows me into the command-line interface, and I can issue commands and get logs.</p> <p>Is it possible to write an Android app that will communicate over USB to my Ardupilot Mega board?</p> <p>I've seen many similar threads, but most of them were pre-USB host.</p>
11,371,178
5
5
null
2011-08-03 14:43:23.683 UTC
13
2022-06-03 07:11:55.553 UTC
2011-09-09 19:41:14.837 UTC
null
63,550
null
181,098
null
1
18
android|usb|arduino
46,309
<p><strong><a href="http://code.google.com/p/usb-serial-for-android/">usb-serial-for-android</a></strong> is my open source library written for exactly this need. It supports FTDI and CDC-ACM usb serial devices using Android's USB host support; no root or ADK necessary. It can talk most Arduinos.</p> <p>The project is still in its early days, but the basic support has worked well enough for several projects. There is also a <a href="http://groups.google.com/group/usb-serial-for-android">discussion list</a> where you can get help.</p>
6,680,631
django admin: separate read-only view and change view
<p>I'd like to use the django admin to produce a read-only view of an object which contains an "Edit" button which switches you to the usual change view of the same object.</p> <p>I know how to use the readonly attributes to produces a read-only view, but I don't know how to produce two views, one read-only and one that allows changes.</p> <p>I'd like to reuse as much of the admin interface for this as possible, rather than writing a view from scratch.</p> <p>Note that this question isn't about permissions: all users will have permission to change the objects. It's just that I would prefer that they not use the change_view unless they do intend to make changes, reducing the risk of accidental changes or simultaneous changes.</p>
6,694,488
5
0
null
2011-07-13 14:35:32.017 UTC
20
2014-02-23 18:19:44.293 UTC
null
null
null
null
380,225
null
1
28
django|django-admin
9,645
<p>Here's an answer that literally does what I asked with only a few lines of code and just a couple of template changes:</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): fieldsets = [...] def get_readonly_fields(self, request, obj=None): if 'edit' not in request.GET: return &lt;list all fields here&gt; else: return self.readonly_fields </code></pre> <p>Now the usual URL for the change_form will produce a read only change_form, but if you append "?edit=1" to the URL, you will be able to edit.</p> <p>The change_form template can also be customized depending on whether "?edit=1" is in the URL. To do this, put <code>'django.core.context_processors.request'</code> in <code>TEMPLATE_CONTEXT_PROCESSORS</code> in <code>settings.py</code>, and then use <code>request.GET.edit</code> in the template.</p> <p>For example, to add an "Edit" button when not in edit mode, insert</p> <pre><code> {% if not request.GET.edit %} &lt;li&gt;&lt;a href="?edit=1"&gt;Edit&lt;/a&gt;&lt;/li&gt; {% endif %} </code></pre> <p>just after <code>&lt;ul class="object-tools"&gt;</code> in <code>change_form.html</code>. </p> <p>As another example, changing <code>change_form.html</code> to contain</p> <pre><code>{% if save_on_top and request.GET.edit %}{% submit_row %}{% endif %} </code></pre> <p>will mean that the submit row will only be shown in edit mode. One can also hide the Delete buttons on inlines, etc, using this method.</p> <p>For reference, here is what I put in <code>settings.py</code>:</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.contrib.messages.context_processors.messages', # Above here are the defaults. 'django.core.context_processors.request', ) </code></pre>
6,354,317
How do I retrieve the available commands from a module?
<p>To know which PowerShell modules are available on a machine I use the command</p> <pre><code>Get-Module -ListAvailable </code></pre> <p>This returns a list with module-type, -name and the exported commands. But the exported commands are always empty and just displaying <code>{}</code>. Why is this not displayed?</p> <p>Do I have to use another parameter or is there another cmdlet or method to retrieve the available commands?</p>
6,354,525
5
0
null
2011-06-15 07:17:19.243 UTC
12
2022-05-11 12:28:31.92 UTC
2018-12-30 00:03:54.977 UTC
null
63,550
null
709,839
null
1
72
powershell|module|powershell-2.0
102,503
<p>Exported commands are not available if the module is not loaded. You need to load the module first and then execute <a href="https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/Get-Command" rel="noreferrer">Get-Command</a>:</p> <pre><code>Import-Module -Name &lt;ModuleName&gt; Get-Command -Module &lt;ModuleName&gt; </code></pre>
6,836,156
C# - Replace a character with nothing
<p>I have a <code>RichTextBox</code> that looks like this:</p> <pre><code>TEXT NEXT_TEXT 10.505 -174.994 0 TEXT NEXT_TEXT 100.005 174.994 90 TEXT NEXT_TEXT -10.000 -5.555 180 TEXT NEXT_TEXT -500.987 5.123 270 TEXT NEXT_TEXT 987.123 1.000 180 TEXT NEXT_TEXT 234.567 200.999 90 </code></pre> <p>and I want to replace the <strong>"."</strong> with nothing and place it into a <code>ListBox</code>...</p> <p>So the new file would look like this:</p> <pre><code>TEXT NEXT_TEXT 10505 -174994 0 TEXT NEXT_TEXT 100005 174994 90 TEXT NEXT_TEXT -10000 -5555 180 TEXT NEXT_TEXT -500987 5123 270 TEXT NEXT_TEXT 987123 1000 180 TEXT NEXT_TEXT 234567 200999 90 </code></pre> <p>I thought about multiplying the values by 1000 but I do not know how to properly do match calculations on a string.</p> <p>So the next thought was to do this <strong><em>(HOWEVER THIS DOES NOT WORK)</em></strong>:</p> <pre><code> // Splits the lines in the rich text boxes string[] listOneLines = oneRichTextBox.Text.Split('\n'); // Set the selection mode to multiple and extended. placementOneListBox.SelectionMode = SelectionMode.MultiExtended; // Shutdown the painting of the ListBox as items are added. placementOneListBox.BeginUpdate(); // Display the items in the listbox. foreach (var item in listOneLines) { item.Replace(".",""); placementOneListBox.Items.Add(item); } // Allow the ListBox to repaint and display the new items. placementOneListBox.EndUpdate(); </code></pre> <hr> <ul> <li>Can anyone help me figure out how to replace a "."?</li> </ul>
6,836,178
7
1
null
2011-07-26 20:27:13.393 UTC
1
2014-07-16 20:42:18.993 UTC
null
null
null
null
864,197
null
1
29
c#|replace|richtextbox
47,266
<p>Strings are immutable so this line is wrong:</p> <pre><code>item.Replace(".",""); </code></pre> <p>This returns the string after the replacement has been made, but <code>item</code> is unchanged. You need this:</p> <pre><code>foreach (var item in listOneLines) placementOneListBox.Items.Add(item.Replace(".","")); </code></pre>
15,506,199
Dynamic alternative to pivot with CASE and GROUP BY
<p>I have a table that looks like this:</p> <pre><code>id feh bar 1 10 A 2 20 A 3 3 B 4 4 B 5 5 C 6 6 D 7 7 D 8 8 D </code></pre> <p>And I want it to look like this:</p> <pre><code>bar val1 val2 val3 A 10 20 B 3 4 C 5 D 6 7 8 </code></pre> <p>I have this query that does this:</p> <pre><code>SELECT bar, MAX(CASE WHEN abc."row" = 1 THEN feh ELSE NULL END) AS "val1", MAX(CASE WHEN abc."row" = 2 THEN feh ELSE NULL END) AS "val2", MAX(CASE WHEN abc."row" = 3 THEN feh ELSE NULL END) AS "val3" FROM ( SELECT bar, feh, row_number() OVER (partition by bar) as row FROM "Foo" ) abc GROUP BY bar </code></pre> <p>This is a very make-shifty approach and gets unwieldy if there are a lot of new columns to be created. I was wondering if the <code>CASE</code> statements can be made better to make this query more dynamic? Also, I'd love to see other approaches to doing this.</p>
15,514,334
6
3
null
2013-03-19 17:16:48.66 UTC
34
2021-05-20 01:05:43.803 UTC
2013-03-20 02:44:34.203 UTC
null
939,860
null
664,576
null
1
31
sql|postgresql|pivot|crosstab|window-functions
51,124
<p>If you have not installed the additional module <a href="http://www.postgresql.org/docs/current/interactive/tablefunc.html" rel="noreferrer"><strong>tablefunc</strong></a>, run this command <em>once</em> per database:</p> <pre><code>CREATE EXTENSION tablefunc; </code></pre> <h2>Answer to question</h2> <p>A very basic crosstab solution for your case:</p> <pre><code>SELECT * FROM crosstab( 'SELECT bar, 1 AS cat, feh FROM tbl_org ORDER BY bar, feh') AS ct (bar text, val1 int, val2 int, val3 int); -- more columns? </code></pre> <p>The <strong>special difficulty</strong> here is, that there is no <em>category</em> (<code>cat</code>) in the base table. For the basic <strong>1-parameter form</strong> we can just provide a dummy column with a dummy value serving as category. The value is ignored anyway.</p> <p>This is one of the <strong>rare cases</strong> where the <strong>second parameter</strong> for the <code>crosstab()</code> function is <strong>not needed</strong>, because all <code>NULL</code> values only appear in dangling columns to the right by definition of this problem. And the order can be determined by the <em>value</em>.</p> <p>If we had an actual <em>category</em> column with names determining the order of values in the result, we'd need the <strong>2-parameter form</strong> of <code>crosstab()</code>. Here I synthesize a category column with the help of the window function <a href="http://www.postgresql.org/docs/current/interactive/functions-window.html" rel="noreferrer"><code>row_number()</code></a>, to base <code>crosstab()</code> on:</p> <pre><code>SELECT * FROM crosstab( $$ SELECT bar, val, feh FROM ( SELECT *, 'val' || row_number() OVER (PARTITION BY bar ORDER BY feh) AS val FROM tbl_org ) x ORDER BY 1, 2 $$ , $$VALUES ('val1'), ('val2'), ('val3')$$ -- more columns? ) AS ct (bar text, val1 int, val2 int, val3 int); -- more columns? </code></pre> <p>The rest is pretty much run-of-the-mill. Find more explanation and links in these closely related answers.</p> <p><em>Basics:</em><br> <sub><strong><em>Read this first if you are not familiar with the <code>crosstab()</code> function!</em></strong></sub> </p> <ul> <li><a href="https://stackoverflow.com/questions/3002499/postgresql-crosstab-query/11751905#11751905">PostgreSQL Crosstab Query</a></li> </ul> <p><em>Advanced:</em> </p> <ul> <li><a href="https://stackoverflow.com/questions/15415446/pivot-on-multiple-columns-using-tablefunc/15421607#15421607">Pivot on Multiple Columns using Tablefunc</a> </li> <li><a href="https://stackoverflow.com/questions/10109564/merge-a-table-and-a-change-log-into-a-view-in-postgresql/10110519#10110519">Merge a table and a change log into a view in PostgreSQL</a></li> </ul> <h3>Proper test setup</h3> <p>That's how you should provide a test case to begin with:</p> <pre><code>CREATE TEMP TABLE tbl_org (id int, feh int, bar text); INSERT INTO tbl_org (id, feh, bar) VALUES (1, 10, 'A') , (2, 20, 'A') , (3, 3, 'B') , (4, 4, 'B') , (5, 5, 'C') , (6, 6, 'D') , (7, 7, 'D') , (8, 8, 'D'); </code></pre> <h2>Dynamic crosstab?</h2> <p>Not very <em>dynamic</em>, yet, as <a href="https://stackoverflow.com/questions/15506199/dynamic-alternative-to-pivot-with-case-and-group-by/15514334#comment21984934_15514334">@Clodoaldo commented</a>. Dynamic return types are hard to achieve with plpgsql. But there <em>are</em> ways around it - <em>with some limitations</em>.</p> <p>So not to further complicate the rest, I demonstrate with a <strong><em>simpler</em></strong> test case:</p> <pre><code>CREATE TEMP TABLE tbl (row_name text, attrib text, val int); INSERT INTO tbl (row_name, attrib, val) VALUES ('A', 'val1', 10) , ('A', 'val2', 20) , ('B', 'val1', 3) , ('B', 'val2', 4) , ('C', 'val1', 5) , ('D', 'val3', 8) , ('D', 'val1', 6) , ('D', 'val2', 7); </code></pre> <p>Call:</p> <pre><code>SELECT * FROM crosstab('SELECT row_name, attrib, val FROM tbl ORDER BY 1,2') AS ct (row_name text, val1 int, val2 int, val3 int); </code></pre> <p>Returns:</p> <pre><code> row_name | val1 | val2 | val3 ----------+------+------+------ A | 10 | 20 | B | 3 | 4 | C | 5 | | D | 6 | 7 | 8 </code></pre> <h3>Built-in feature of <code>tablefunc</code> module</h3> <p>The tablefunc module provides a simple infrastructure for generic <code>crosstab()</code> calls without providing a column definition list. A number of functions written in <code>C</code> (typically very fast): <a href="http://www.postgresql.org/docs/current/interactive/tablefunc.html#AEN144256" rel="noreferrer"><pre><code><b>crosstab<i>N</i>()</b></code></pre></a></p> <p><code>crosstab1()</code> - <code>crosstab4()</code> are pre-defined. One minor point: they require and return all <code>text</code>. So we need to cast our <code>integer</code> values. But it simplifies the call:</p> <pre><code>SELECT * FROM crosstab4('SELECT row_name, attrib, val::text -- cast! FROM tbl ORDER BY 1,2') </code></pre> <p>Result:</p> <pre><code> row_name | category_1 | category_2 | category_3 | category_4 ----------+------------+------------+------------+------------ A | 10 | 20 | | B | 3 | 4 | | C | 5 | | | D | 6 | 7 | 8 | </code></pre> <h3>Custom <code>crosstab()</code> function</h3> <p>For <strong><em>more columns</em></strong> or <strong><em>other data types</em></strong>, we create our own <em>composite type</em> and <em>function</em> (once).<br> Type:</p> <pre><code>CREATE TYPE tablefunc_crosstab_int_5 AS ( row_name text, val1 int, val2 int, val3 int, val4 int, val5 int); </code></pre> <p>Function:</p> <pre><code>CREATE OR REPLACE FUNCTION crosstab_int_5(text) RETURNS SETOF tablefunc_crosstab_int_5 AS '$libdir/tablefunc', 'crosstab' LANGUAGE c STABLE STRICT; </code></pre> <p>Call:</p> <pre><code>SELECT * FROM crosstab_int_5('SELECT row_name, attrib, val -- no cast! FROM tbl ORDER BY 1,2'); </code></pre> <p>Result:</p> <pre><code> row_name | val1 | val2 | val3 | val4 | val5 ----------+------+------+------+------+------ A | 10 | 20 | | | B | 3 | 4 | | | C | 5 | | | | D | 6 | 7 | 8 | | </code></pre> <h2><em>One</em> polymorphic, dynamic function for all</h2> <p><em>This goes beyond what's covered by the <code>tablefunc</code> module.</em><br> To make the return type dynamic I use a polymorphic type with a technique detailed in this related answer:</p> <ul> <li><a href="https://stackoverflow.com/questions/11740256/refactor-a-pl-pgsql-function-to-return-the-output-of-various-select-queries/11751557#11751557">Refactor a PL/pgSQL function to return the output of various SELECT queries</a></li> </ul> <p></p></p> <p>1-parameter form:</p> <pre><code>CREATE OR REPLACE FUNCTION crosstab_n(_qry text, _rowtype anyelement) RETURNS SETOF anyelement AS $func$ BEGIN RETURN QUERY EXECUTE (SELECT format('SELECT * FROM crosstab(%L) t(%s)' , _qry , string_agg(quote_ident(attname) || ' ' || atttypid::regtype , ', ' ORDER BY attnum)) FROM pg_attribute WHERE attrelid = pg_typeof(_rowtype)::text::regclass AND attnum &gt; 0 AND NOT attisdropped); END $func$ LANGUAGE plpgsql; </code></pre> <p>Overload with this variant for the 2-parameter form:</p> <pre><code>CREATE OR REPLACE FUNCTION crosstab_n(_qry text, _cat_qry text, _rowtype anyelement) RETURNS SETOF anyelement AS $func$ BEGIN RETURN QUERY EXECUTE (SELECT format('SELECT * FROM crosstab(%L, %L) t(%s)' , _qry, _cat_qry , string_agg(quote_ident(attname) || ' ' || atttypid::regtype , ', ' ORDER BY attnum)) FROM pg_attribute WHERE attrelid = pg_typeof(_rowtype)::text::regclass AND attnum &gt; 0 AND NOT attisdropped); END $func$ LANGUAGE plpgsql; </code></pre> <p><code>pg_typeof(_rowtype)::text::regclass</code>: There is a row type defined for every user-defined composite type, so that attributes (columns) are listed in the system catalog <a href="http://www.postgresql.org/docs/current/interactive/catalog-pg-attribute.html" rel="noreferrer"><code>pg_attribute</code></a>. The fast lane to get it: cast the registered type (<code>regtype</code>) to <code>text</code> and cast this <code>text</code> to <code>regclass</code>.</p> <h3>Create composite types once:</h3> <p>You need to define once every return type you are going to use:</p> <pre><code>CREATE TYPE tablefunc_crosstab_int_3 AS ( row_name text, val1 int, val2 int, val3 int); CREATE TYPE tablefunc_crosstab_int_4 AS ( row_name text, val1 int, val2 int, val3 int, val4 int); ... </code></pre> <p>For ad-hoc calls, you can also just create a <strong>temporary table</strong> to the same (temporary) effect:</p> <pre><code>CREATE TEMP TABLE temp_xtype7 AS ( row_name text, x1 int, x2 int, x3 int, x4 int, x5 int, x6 int, x7 int); </code></pre> <p>Or use the type of an existing table, view or materialized view if available.</p> <h3>Call</h3> <p>Using above row types:</p> <p>1-parameter form (no missing values):</p> <pre><code>SELECT * FROM crosstab_n( 'SELECT row_name, attrib, val FROM tbl ORDER BY 1,2' , NULL::tablefunc_crosstab_int_<b>3</b>);</code></pre> <p>2-parameter form (some values can be missing):</p> <pre><code>SELECT * FROM crosstab_n( 'SELECT row_name, attrib, val FROM tbl ORDER BY 1' , $$VALUES ('val1'), ('val2'), ('val3')$$ , NULL::tablefunc_crosstab_int_<b>3</b>);</code></pre> <p>This <strong>one function</strong> works for all return types, while the <code>crosstab<i>N</i>()</code> framework provided by the <code>tablefunc</code> module needs a separate function for each.<br> If you have named your types in sequence like demonstrated above, you only have to replace the bold number. To find the maximum number of categories in the base table:</p> <pre><code>SELECT max(count(*)) OVER () FROM tbl -- returns 3 GROUP BY row_name LIMIT 1; </code></pre> <p>That's about as dynamic as this gets if you want <em>individual columns</em>. Arrays like <a href="https://stackoverflow.com/a/15513319/939860">demonstrated by @Clocoaldo</a> or a simple text representation or the result wrapped in a document type like <code>json</code> or <code>hstore</code> can work for any number of categories dynamically.</p> <p><strong>Disclaimer:</strong><br> It's always potentially dangerous when user input is converted to code. Make sure this cannot be used for SQL injection. Don't accept input from untrusted users (directly).</p> <h3>Call for original question:</h3> <pre><code>SELECT * FROM crosstab_n('SELECT bar, 1, feh FROM tbl_org ORDER BY 1,2' , NULL::tablefunc_crosstab_int_3); </code></pre>
50,949,594
Axios having CORS issue
<p>I added proxy in package.json and it worked great, but after npm run build the CORS issue has resurfaced again, does anyone know how to deal with CORS issue after npm run build in React.</p> <p>I have tried to add headers in axios request using various methods. However, I failed to add 'Access-Control-Allow-Origin':'*' in axios request. My code is as follwing:</p> <p>package.json</p> <pre><code> "proxy": { "*":{ "target" : "http://myurl"} } </code></pre> <p>GetData.js</p> <pre><code> axios.defaults.baseURL = 'http://myurl'; axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8'; axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'; axios.get(serviceUrl, onSuccess, onFailure) .then(resp =&gt; { let result = resp.data; onSuccess(result); }) .catch(error =&gt; { if(onFailure) { return onFailure(error); } }) } </code></pre> <p>Note: It has enabled from server side, it is still not working.Currently, I can't change code from server side, My work is limited to client side only.</p>
50,949,631
12
2
null
2018-06-20 13:36:20 UTC
20
2022-02-17 16:57:48.733 UTC
2018-12-18 02:45:25.883 UTC
null
8,940,641
null
8,940,641
null
1
112
reactjs|proxy|cors|axios
670,455
<p>your server should enable the cross origin requests, not the client. To do this, you can check <a href="https://enable-cors.org/server.html" rel="noreferrer">this nice page</a> with implementations and configurations for multiple platforms</p>
10,638,059
Javascript Debugging line by line using Google Chrome
<p>How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?</p> <p>For example, I am heavily using jQuery on my site, and I just want to debug the jQuery I have written, and not the javascript/jquery within the jquery libraries. How do I only step through my own jquery/javascript and not have to step through the millions of lines in the jquery libraries?</p> <p>So if I have the following:</p> <pre><code>function getTabFrame() { $.ajax({ url: 'get_tab_frame.aspx?rand=' + Math.random(), type: 'GET', dataType: 'json', error: function(xhr, status, error) { //alert('Error: ' + status + '\nError Text: ' + error + '\nResponse Text: ' + xhr.responseText); }, success: function(data) { $.each(data, function(index, item) { // do something here }); } }); } </code></pre> <p>if I place the breakpoint at <code>$.ajax({</code>, if I them start debugging that it where it stops, if I then press F11, it goes straight into the jQuery libraries. I don't want that to happen, I want it to go to the next line which is <code>url: 'get_tab_frame.aspx?rand=' + Math.random(),</code>.</p> <p>I have tried pressing F10 instead, but that goes straight to the closing <code>}</code> of the function. And F5 just goes to the next breakpoint without stepping through each line one by one.</p>
10,638,196
2
6
null
2012-05-17 14:49:13.083 UTC
32
2019-06-10 06:51:16.613 UTC
2016-06-21 08:23:39.863 UTC
null
2,790,036
null
364,312
null
1
45
javascript|jquery|debugging|google-chrome|google-chrome-devtools
111,520
<p>Assuming you're running on a Windows machine...</p> <ol> <li>Hit the <code>F12</code> key</li> <li>Select the <code>Scripts</code>, or <code>Sources</code>, tab in the developer tools</li> <li>Click the little folder icon in the top level</li> <li>Select <strong>your</strong> JavaScript file</li> <li>Add a breakpoint by clicking on the line number on the left (adds a little blue marker)</li> <li>Execute your JavaScript</li> </ol> <p>Then during execution debugging you can do a handful of stepping motions...</p> <ul> <li><code>F8</code> Continue: Will continue until the next breakpoint</li> <li><code>F10</code> Step over: Steps over next function call (<strong>won't</strong> enter the library)</li> <li><code>F11</code> Step into: Steps into the next function call (<strong>will</strong> enter the library)</li> <li><code>Shift + F11</code> Step out: Steps out of the current function</li> </ul> <p><strong>Update</strong></p> <p>After reading your updated post; to debug your code I would recommend temporarily using the <a href="http://code.jquery.com/jquery-latest.js">jQuery Development Source Code</a>. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.</p>
33,878,216
Factory Pattern without a Switch or If/Then
<p>I'm looking for a simple example of how to implement a factory class, but <em>without</em> the use of a Switch or an If-Then statement. All the examples I can find use one. For example, how could one modify this simple example (below) so that the actual factory does not depend on the Switch? It seems to me that this example violates the Open/Close principle. I'd like to be able to add concrete classes ('Manager', 'Clerk', 'Programmer', etc) without having to modify the factory class.</p> <p>Thanks!</p> <pre><code>class Program { abstract class Position { public abstract string Title { get; } } class Manager : Position { public override string Title { get { return "Manager"; } } } class Clerk : Position { public override string Title { get { return "Clerk"; } } } class Programmer : Position { public override string Title { get { return "Programmer"; } } } static class Factory { public static Position Get(int id) { switch (id) { case 0: return new Manager(); case 1: return new Clerk(); case 2: return new Programmer(); default: return new Programmer(); } } } static void Main(string[] args) { for (int i = 0; i &lt;= 2; i++) { var position = Factory.Get(i); Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title); } Console.ReadLine(); } } </code></pre> <p><strong>UPDATE:</strong></p> <p>Wow! Thanks everyone! I have learned a ton. After revewing all the feedback, I blended a few of the answers and came up with this. I'd be open to further dialog about a better way to do this.</p> <pre><code>class Program { public interface IPosition { string Title { get; } } class Manager : IPosition { public string Title { get { return "Manager"; } } } class Clerk : IPosition { public string Title { get { return "Clerk"; } } } class Programmer : IPosition { public string Title { get { return "Programmer"; } } } static class PositionFactory { public static T Create&lt;T&gt;() where T : IPosition, new() { return new T(); } } static void Main(string[] args) { IPosition position0 = PositionFactory.Create&lt;Manager&gt;(); Console.WriteLine("0: " + position0.Title); IPosition position1 = PositionFactory.Create&lt;Clerk&gt;(); Console.WriteLine("1: " + position1.Title); IPosition position2 = PositionFactory.Create&lt;Programmer&gt;(); Console.WriteLine("1: " + position2.Title); Console.ReadLine(); } } </code></pre> <p><strong>Another Edit:</strong></p> <p>It's also possible to create an instance of the Interface using an unknown type:</p> <pre><code>static class PositionFactory { public static IPosition Create(string positionName) { Type type = Type.GetType(positionName); return (IPosition)Activator.CreateInstance(type); } } </code></pre> <p>Which could then be called as follows:</p> <pre><code>IPosition position = PositionFactory.Create("Manager"); Console.WriteLine(position.Title); </code></pre>
33,878,676
4
6
null
2015-11-23 18:40:18.29 UTC
15
2017-10-11 19:22:21.697 UTC
2017-10-11 19:22:21.697 UTC
null
1,418,704
null
1,418,704
null
1
25
c#|factory|factory-pattern
22,644
<p>How about this (no Dictionary required and note that you will get an syntax error if your try to <code>Create&lt;Position&gt;()</code>):</p> <p><strong>EDIT</strong> - Updated to use an IPosition interface implemented explicitly. Only instances of IPosition can access the member functions (e.g. <code>&lt;implementation of Manager&gt;.Title</code> will not compile).</p> <p><strong>EDIT #2</strong> Factory.Create should return an IPosition not T when using the interface properly.</p> <pre><code>using System; using System.Collections.Generic; class Program { interface IPosition { string Title { get; } bool RequestVacation(); } class Manager : IPosition { string IPosition.Title { get { return "Manager"; } } bool IPosition.RequestVacation() { return true; } } class Clerk : IPosition { int m_VacationDaysRemaining = 1; string IPosition.Title { get { return "Clerk"; } } bool IPosition.RequestVacation() { if (m_VacationDaysRemaining &lt;= 0) { return false; } else { m_VacationDaysRemaining--; return true; } } } class Programmer : IPosition { string IPosition.Title { get { return "Programmer"; } } bool IPosition.RequestVacation() { return false; } } static class Factory { public static IPosition Create&lt;T&gt;() where T : IPosition, new () { return new T(); } } static void Main(string[] args) { List&lt;IPosition&gt; positions = new List&lt;IPosition&gt;(3); positions.Add(Factory.Create&lt;Manager&gt;()); positions.Add(Factory.Create&lt;Clerk&gt;()); positions.Add(Factory.Create&lt;Programmer&gt;()); foreach (IPosition p in positions) { Console.WriteLine(p.Title); } Console.WriteLine(); Random rnd = new Random(0); for (int i = 0; i &lt; 10; i++) { int index = rnd.Next(3); Console.WriteLine("Title: {0}, Request Granted: {1}", positions[index].Title, positions[index].RequestVacation()); } Console.ReadLine(); } } </code></pre>
13,710,631
Is there shorthand for returning a default value if None in Python?
<p>In C#, I can say <code>x ?? ""</code>, which will give me x if x is not null, and the empty string if x is null. I've found it useful for working with databases. </p> <p>Is there a way to return a default value if Python finds None in a variable?</p>
13,710,667
4
1
null
2012-12-04 19:42:31.81 UTC
30
2017-12-28 06:41:24.7 UTC
null
null
null
null
279,719
null
1
315
python
294,471
<p>You could use the <code>or</code> operator:</p> <pre><code>return x or "default" </code></pre> <p>Note that this also returns <code>"default"</code> if <code>x</code> is any falsy value, including an empty list, 0, empty string, or even <code>datetime.time(0)</code> (midnight).</p>
13,448,374
How to sleep the thread in node.js without affecting other threads?
<p>As per <a href="http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/">Understanding the node.js event loop</a>, node.js supports a single thread model. That means if I make multiple requests to a node.js server, it won't spawn a new thread for each request but will execute each request one by one. It means if I do the following for the first request in my node.js code, and meanwhile a new request comes in on node, the second request has to wait until the first request completes, including 5 second sleep time. Right?</p> <pre><code>var sleep = require('sleep'); sleep.sleep(5)//sleep for 5 seconds </code></pre> <p>Is there a way that node.js can spawn a new thread for each request so that the second request does not have to wait for the first request to complete, or can I call sleep on specific thread only?</p>
13,448,477
4
1
null
2012-11-19 05:50:55.353 UTC
19
2020-05-27 15:05:46 UTC
2013-05-30 21:40:16.187 UTC
null
425,313
null
3,222,249
null
1
82
multithreading|node.js|asynchronous
135,433
<p>If you are referring to the npm module <a href="https://npmjs.org/package/sleep" rel="noreferrer">sleep</a>, it notes in the readme that <code>sleep</code> will block execution. So you are right - it isn't what you want. Instead you want to use <a href="https://nodejs.org/dist/latest-v7.x/docs/api/timers.html#timers_settimeout_callback_delay_args" rel="noreferrer">setTimeout</a> which is non-blocking. Here is an example:</p> <pre><code>setTimeout(function() { console.log('hello world!'); }, 5000); </code></pre> <hr> <p>For anyone looking to do this using es7 async/await, this example should help:</p> <pre><code>const snooze = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms)); const example = async () =&gt; { console.log('About to snooze without halting the event loop...'); await snooze(1000); console.log('done!'); }; example(); </code></pre>
39,451,345
Using credentials from Jenkins store in a jenkinsfile
<p>I made a multibranch pipeline project in Jenkins. I need to use two repositories and both need credentials.</p> <p>I created a Jenkinsfile in repository1:</p> <pre><code>node ('label1'){ stage 'sanity check' sh 'echo sanity check' stage 'checkout other repository' checkout([ $class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: 'https://[email protected]/BRNTZN/repository2.git'],[credentialsId:'23b2eed1-2863-49d5-bc7b-bcccb9ad914d']] ]) stage 'log results' sh 'echo result = OK' } </code></pre> <p>When I push this file onto a branch of repository1 and start the build I get the following error in Jenkins:</p> <pre><code>Branch indexing Setting origin to https://[email protected]/BRNTZN/repository1.git Fetching origin... &gt; git rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository &gt; git config remote.origin.url https://[email protected]/BRNTZN/repository1.git # timeout=10 Fetching upstream changes from https://[email protected]/BRNTZN/repository1.git &gt; git --version # timeout=10 using .gitcredentials to set credentials &gt; git config --local credential.username BRNTZN # timeout=10 &gt; git config --local credential.helper store --file=/tmp/git1367320661933193799.credentials # timeout=10 &gt; git -c core.askpass=true fetch --tags --progress https://[email protected]/BRNTZN/repository1.git +refs/heads/*:refs/remotes/origin/* &gt; git config --local --remove-section credential # timeout=10 Checking out Revision d997a29e9d1f639d56eb425ec00e03309e099c7a (jenkinsfilebranch1) &gt; git config core.sparsecheckout # timeout=10 &gt; git checkout -f d997a29e9d1f639d56eb425ec00e03309e099c7a &gt; git rev-list f81d0d366fd751857a2640c587817f4d047a15af # timeout=10 [Pipeline] node Running on jenkins agent (i-07353fc08cb42f10e) in /var/jenkins/workspace/multiBranch/jenkinsfilebranch1 [Pipeline] { [Pipeline] stage (sanity check) Entering stage sanity check Proceeding [Pipeline] sh [jenkinsfilebranch1] Running shell script + echo sanity check sanity check [Pipeline] stage (checkout other repository) Entering stage checkout other repository Proceeding [Pipeline] checkout &gt; git rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository &gt; git config remote.origin.url https://[email protected]/BRNTZN/repository2.git # timeout=10 Fetching upstream changes from https://[email protected]/BRNTZN/repository2.git &gt; git --version # timeout=10 &gt; git -c core.askpass=true fetch --tags --progress https://[email protected]/BRNTZN/repository2.git +refs/heads/*:refs/remotes/origin/* ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException: Failed to fetch from https://[email protected]/BRNTZN/repository2.git at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:799) at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1055) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1086) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:109) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:83) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:73) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:52) at hudson.security.ACL.impersonate(ACL.java:213) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:49) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: hudson.plugins.git.GitException: Command "git -c core.askpass=true fetch --tags --progress https://[email protected]/BRNTZN/repository2.git +refs/heads/*:refs/remotes/origin/*" returned status code 128: stdout: stderr: remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile. fatal: Authentication failed for 'https://[email protected]/BRNTZN/repository2.git/' at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1723) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1459) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:63) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:314) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:152) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:145) at hudson.remoting.UserRequest.perform(UserRequest.java:153) at hudson.remoting.UserRequest.perform(UserRequest.java:50) at hudson.remoting.Request$2.run(Request.java:332) at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) at ......remote call to jenkins agent (i-07353fc08cb42f10e)(Native Method) at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1416) at hudson.remoting.UserResponse.retrieve(UserRequest.java:253) at hudson.remoting.Channel.call(Channel.java:781) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.execute(RemoteGitImpl.java:145) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.invoke(RemoteGitImpl.java:131) at com.sun.proxy.$Proxy75.execute(Unknown Source) at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:797) ... 13 more [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline ERROR: null Finished: FAILURE </code></pre> <p>The credentials should be correct:</p> <p><a href="https://i.stack.imgur.com/nMqnp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nMqnp.png" alt="Enter image description here"></a></p> <p>And using those credentials for that repository in a freestyle project gives no error:</p> <p><a href="https://i.stack.imgur.com/eMSZy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eMSZy.png" alt="Enter image description here"></a></p> <p><strong>Update</strong></p> <p>I created a freestyle project using SSH credentials and added that public key to my Bitbucket account to test if I can make SSH work:</p> <p><a href="https://i.stack.imgur.com/auwV7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/auwV7.png" alt="freestylecredentials SSH"></a></p> <p>This worked:</p> <pre><code> Started by user admin Building remotely on jenkins agent (i-039385e75b60d70f7) (label1) in workspace /var/jenkins/workspace/gitcredentials test &gt; git rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository &gt; git config remote.origin.url [email protected]:BRNTZN/repository2.git # timeout=10 Fetching upstream changes from [email protected]:BRNTZN/repository2.git &gt; git --version # timeout=10 using GIT_SSH to set credentials jenkinsmaster key &gt; git -c core.askpass=true fetch --tags --progress [email protected]:BRNTZN/repository2.git +refs/heads/*:refs/remotes/origin/* &gt; git rev-parse refs/remotes/origin/master^{commit} # timeout=10 &gt; git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10 Checking out Revision 1d51064143e7337cbc0b1910918166facc9c2330 (refs/remotes/origin/master) &gt; git config core.sparsecheckout # timeout=10 &gt; git checkout -f 1d51064143e7337cbc0b1910918166facc9c2330 First time build. Skipping changelog. Finished: SUCCESS </code></pre> <p>However when updating the jenkinsfile in the following way:</p> <pre><code>node ('label1'){ stage 'sanity check' sh 'echo sanity check' stage 'checkout other repository' checkout([ $class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: '[email protected]:BRNTZN/repository2.git'],[credentialsId:'jenkinsmaster']] ]) stage 'log results' sh 'echo result = OK' } </code></pre> <p>I still get the same error:</p> <pre><code>Started by user admin Setting origin to [email protected]:BRNTZN/repository1.git Fetching origin... &gt; git rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository &gt; git config remote.origin.url [email protected]:BRNTZN/repository1.git # timeout=10 Fetching upstream changes from [email protected]:BRNTZN/repository1.git &gt; git --version # timeout=10 using GIT_SSH to set credentials jenkinsmaster key &gt; git -c core.askpass=true fetch --tags --progress [email protected]:BRNTZN/repository1.git +refs/heads/*:refs/remotes/origin/* Checking out Revision 29fc47911827d829f5abe9456bd8df78bc478fe7 (jenkinsfilebranch1) &gt; git config core.sparsecheckout # timeout=10 &gt; git checkout -f 29fc47911827d829f5abe9456bd8df78bc478fe7 &gt; git rev-list 29fc47911827d829f5abe9456bd8df78bc478fe7 # timeout=10 [Pipeline] node Running on jenkins agent (i-039385e75b60d70f7) in /var/jenkins/workspace/multiBranch/jenkinsfilebranch1 [Pipeline] { [Pipeline] stage (sanity check) Entering stage sanity check Proceeding [Pipeline] sh [jenkinsfilebranch1] Running shell script + echo sanity check sanity check [Pipeline] stage (checkout other repository) Entering stage checkout other repository Proceeding [Pipeline] checkout &gt; git rev-parse --is-inside-work-tree # timeout=10 Fetching changes from the remote Git repository &gt; git config remote.origin.url [email protected]:BRNTZN/repository2.git # timeout=10 Fetching upstream changes from [email protected]:BRNTZN/repository2.git &gt; git --version # timeout=10 &gt; git -c core.askpass=true fetch --tags --progress [email protected]:BRNTZN/repository2.git +refs/heads/*:refs/remotes/origin/* ERROR: Error fetching remote repo 'origin' hudson.plugins.git.GitException: Failed to fetch from [email protected]:BRNTZN/repository2.git at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:799) at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1055) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1086) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:109) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:83) at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:73) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:52) at hudson.security.ACL.impersonate(ACL.java:213) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:49) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: hudson.plugins.git.GitException: Command "git -c core.askpass=true fetch --tags --progress [email protected]:BRNTZN/repository2.git +refs/heads/*:refs/remotes/origin/*" returned status code 128: stdout: stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1723) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1459) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:63) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:314) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:152) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:145) at hudson.remoting.UserRequest.perform(UserRequest.java:153) at hudson.remoting.UserRequest.perform(UserRequest.java:50) at hudson.remoting.Request$2.run(Request.java:332) at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) at ......remote call to jenkins agent (i-039385e75b60d70f7)(Native Method) at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1416) at hudson.remoting.UserResponse.retrieve(UserRequest.java:253) at hudson.remoting.Channel.call(Channel.java:781) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.execute(RemoteGitImpl.java:145) at sun.reflect.GeneratedMethodAccessor1180.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.invoke(RemoteGitImpl.java:131) at com.sun.proxy.$Proxy75.execute(Unknown Source) at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:797) ... 13 more [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline ERROR: null Finished: FAILURE </code></pre>
44,663,839
5
3
null
2016-09-12 13:20:46.443 UTC
7
2021-12-09 02:02:16.477 UTC
2018-08-12 06:50:37.25 UTC
null
63,550
null
5,106,596
null
1
20
git|jenkins|groovy|jenkins-pipeline
89,093
<p>Your GitSCM class instantiation is incorrect. You have created two UserRemoteConfig objects - one with a URL of '[email protected]:BRNTZN/repository2.git' and one with a credentialsId of 'jenkinsmaster'. Instead you want one object with both properties set.</p> <pre><code>checkout([ $class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: '[email protected]:BRNTZN/repository2.git'],[credentialsId:'jenkinsmaster']] ]) </code></pre> <p>Should be:</p> <pre><code>checkout([ $class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: '[email protected]:BRNTZN/repository2.git',credentialsId:'jenkinsmaster']] ]) </code></pre> <p>Notice there are no brackets around the comma in the "userRemoteConfigs" section in the second case.</p> <p>I had just ran into the same issue and connected up an Eclipse debugger to Jenkins to find the issue.</p> <p>See <em><a href="https://issues.jenkins-ci.org/browse/JENKINS-45007" rel="noreferrer">git-plugin GitSCM does not support ssh credentials when using checkout in a Jenkinsfile</a></em> (45007).</p>
24,156,451
PowerShell The term is not recognized as cmdlet function script file or operable program
<p>I am implementing a script in powershell and getting the below error. The sceen shot is there exactly what I entered and the resulting error.</p> <p><img src="https://i.stack.imgur.com/E7Pnl.png" alt="enter image description here" /></p> <p>At this path there is file <code>Get-NetworkStatistics.ps1</code> which I got from <a href="http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71" rel="noreferrer">Technet Gallery</a>. I am following the steps from it, though there are errors.</p>
24,156,643
3
2
null
2014-06-11 06:54:17.083 UTC
11
2021-09-27 02:01:36.353 UTC
2021-09-27 02:01:36.353 UTC
null
285,795
null
3,505,712
null
1
68
powershell|cmd|powershell-2.0|command-prompt
268,955
<p>You first have to 'dot' source the script, so for you :</p> <pre><code>. .\Get-NetworkStatistics.ps1 </code></pre> <p>The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use <code>set-ExecutionPolicy Unrestricted</code> or <code>set-ExecutionPolicy AllSigned</code> see(<a href="http://technet.microsoft.com/en-US/library/hh847748.aspx">the Execution Policy instructions</a>). </p>
3,456,382
jquery validation only digits
<p>I am having the jquery.validate.js plugin and it is working fine for me.</p> <p>My question is :</p> <p>I am having a textbox and this textbox is mandatory and should only accept digits.</p> <p>In the js, I can see that there is validation for the digits and the problem is that I do not know how to use it.</p> <p>I only knew how to make the field required by putting in the textbox field <code>&lt;class="required"&gt;</code></p> <p>So, how can I add one more validation criteria to accept only digits.</p> <p>Thanx</p>
3,456,415
2
0
null
2010-08-11 07:55:44.033 UTC
4
2019-09-08 04:34:16.337 UTC
2019-09-08 04:34:16.337 UTC
null
74,314
null
402,971
null
1
28
javascript|jquery|jquery-plugins|jquery-validate
104,016
<p>to check it add</p> <pre><code>$("#myform").validate({ rules: { amount: { required: true, digits: true } } }); </code></pre> <p><a href="http://docs.jquery.com/Plugins/Validation/Methods/digits" rel="noreferrer">http://docs.jquery.com/Plugins/Validation/Methods/digits</a></p>
3,429,878
Automatic creation date for Django model form objects
<p>What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?</p> <p><strong>models.py:</strong></p> <pre><code>created_at = models.DateTimeField(False, True, editable=False) updated_at = models.DateTimeField(True, True, editable=False) </code></pre> <p><strong>views.py:</strong></p> <pre><code>if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() return HttpResponseRedirect('obj_list') </code></pre> <p>I get the error:</p> <pre><code>objects_object.created_at may not be NULL </code></pre> <p>Do I have to manually set this value myself? I thought that was the point of the parameters passed to <code>DateTimeField</code> (or are they just defaults, and since I've set <code>editable=False</code> they don't get displayed on the form, hence don't get submitted in the request, and therefore don't get put into the form?).</p> <p>What's the best way of doing this? An <code>__init__</code> method?</p>
3,429,915
2
0
null
2010-08-07 09:21:28.12 UTC
58
2022-07-29 03:55:08.303 UTC
2022-07-29 03:55:08.303 UTC
null
7,758,804
null
347,999
null
1
226
python|django|django-models
171,650
<p>You can use the <a href="http://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.DateField.auto_now" rel="noreferrer"><code>auto_now</code></a> and <a href="http://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.DateField.auto_now_add" rel="noreferrer"><code>auto_now_add</code></a> options for <code>updated_at</code> and <code>created_at</code> respectively.</p> <pre><code>class MyModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) </code></pre>
45,639,660
Range.Find on a Date That is a Formula
<p>I receive a workbook that contains information about the processing volumes of a call center team. I have no way of modifying the format or layout of the workbook upstream.</p> <p>One sheet contains information about processing errors.<br /> <a href="https://i.stack.imgur.com/CsroO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CsroO.png" alt="screenshot" /></a><br /> (team members' user IDs redacted)</p> <p>Each date is represented by a merged 1x3 range with the date in question formatted as &quot;dd-mmm&quot; e.g. &quot;01-Jun&quot;</p> <p>That date is pulled via formula from another sheet with the same layout. The formula for one such range reads: <code>='QA Scores'!K2:M2</code></p> <p>I attempted to use <code>Range.Find</code> to locate the first day of a given month and an end date in that same month (based on user input) - e.g. June 1 through June 15.</p> <pre class="lang-vb prettyprint-override"><code>Set rngMin = .Find(What:=DateValue(minDate), _ LookIn:=xlFormulas, _ LookAt:=xlWhole) </code></pre> <p>In other uses, I located a date in this manner, but the added complexity of the value coming from a formula seems to be the issue here.</p> <p><strong>UPDATE:</strong><br /> I have written the following based on Ron Rosenfeld's answer:</p> <pre class="lang-vb prettyprint-override"><code>Dim UsedArr As Variant: UsedArr = SrcWS.UsedRange blFound = False For i = LBound(UsedArr, 1) To UBound(UsedArr, 1) For j = LBound(UsedArr, 2) To UBound(UsedArr, 2) If UsedArr(i, j) = MinDate Then blFound = True Exit For End If Next If blFound = True Then Exit For Next </code></pre>
45,641,402
4
7
null
2017-08-11 16:21:12.47 UTC
2
2021-01-25 08:10:33.233 UTC
2021-01-25 08:10:33.233 UTC
null
-1
null
8,451,775
null
1
4
vba|excel|date
39,158
<p>Dates are tricky to find with the <code>Range.Find</code> method. One of the issues is that in VBA, dates are of the <code>Date</code> data type, but the worksheet does not have that data type. Rather the data type is a number that is formatted to look like a date.</p> <p>One solution, if you can be certain of the format of the date on the worksheet, is to search for the string equivalent. Given your example, something like this will work:</p> <pre><code>Option Explicit Sub GetDates() Const findDate As Date = #5/11/2017# Dim findStr As String Dim R As Range, WS As Worksheet Set WS = Worksheets("Sheet1") findStr = Format(findDate, "dd-mmm") With WS Set R = .Cells.Find(what:=findStr, LookIn:=xlValues, lookat:=xlWhole) If Not R Is Nothing Then MsgBox findDate &amp; " found in " &amp; R.Address End With End Sub </code></pre> <p>but it is not very robust since, in many cases, the user can change the format.</p> <p>Another method that is more robust, would be to loop through the existing cells, looking for the numeric representation of the date (using the <code>Value2</code> property):</p> <pre><code>Sub GetDates2() Const findDate As Date = #5/11/2017# Dim R As Range, C As Range, WS As Worksheet Set WS = Worksheets("sheet1") Set R = WS.UsedRange For Each C In R If C.Value2 = CDbl(findDate) Then MsgBox findDate &amp; " found in " &amp; C.Address Next C End Sub </code></pre> <p>If you have a large range to search, this can be sped up by a factor of ten by reading the range into a VBA array and looping through the array.</p>
16,373,065
Complexity of factorial recursive algorithm
<p>Today in class my teacher wrote on the blackboard this recursive factorial algorithm:</p> <pre><code>int factorial(int n) { if (n == 1) return 1; else return n * factorial(n-1); } </code></pre> <p>She said that it has a cost of <code>T(n-1) + 1</code>. </p> <p>Then with iteration method she said that <code>T(n-1) = T(n-2) + 2 = T(n-3) + 3 ... T(n-j) + j</code>, so the algorithm stops when <code>n - j = 1</code>, so <code>j = n - 1</code>.</p> <p>After that, she substituted <code>j</code> in <code>T(n-j) + j</code>, and obtained <code>T(1) + n-1</code>.</p> <p>She directly said that for that n-1 = 2<sup>(log<sub>2</sub>n-1)</sup>, so the cost of the algorithm is exponential.</p> <p>I really lost the last two steps. Can someone please explain them to me? </p>
16,378,607
1
2
null
2013-05-04 10:05:31.94 UTC
9
2019-07-17 15:17:04.8 UTC
2019-07-17 15:17:04.8 UTC
null
8,101,287
null
1,090,403
null
1
23
complexity-theory|big-o|factorial
50,146
<p>Let's start off with the analysis of this algorithm. We can write a recurrence relation for the total amount of work done. As a base case, you do one unit of work when the algorithm is run on an input of size 1, so</p> <blockquote> <p>T(1) = 1</p> </blockquote> <p>For an input of size n + 1, your algorithm does one unit of work within the function itself, then makes a call to the same function on an input of size n. Therefore</p> <blockquote> <p>T(n + 1) = T(n) + 1</p> </blockquote> <p>If you expand out the terms of the recurrence, you get that</p> <ul> <li>T(1) = 1</li> <li>T(2) = T(1) + 1 = 2</li> <li>T(3) = T(2) + 1 = 3</li> <li>T(4) = T(3) + 1 = 4</li> <li>...</li> <li>T(n) = n</li> </ul> <p>So in general this algorithm will require n units of work to complete (i.e. T(n) = n).</p> <p>The next thing your teacher said was that</p> <blockquote> <p>T(n) = n = 2<sup>log<sub>2</sub> n</sup></p> </blockquote> <p>This statement is true, because 2<sup>log<sub>2</sub>x</sup> = x for any nonzero x, since exponentiation and logarithms are inverse operations of one another.</p> <p>So the question is: is this polynomial time or exponential time? I'd classify this as pseudopolynomial time. If you treat the input x as a number, then the runtime is indeed a polynomial in x. However, polynomial time is formally defined such that the runtime of the algorithm must be a polynomial with respect to the number of bits used to specify the input to the problem. Here, the number x can be specified in only &Theta;(log x) bits, so the runtime of 2<sup>log x</sup> is technically considered exponential time. I wrote about this as length in <a href="https://stackoverflow.com/questions/19647658/what-is-pseudopolynomial-time-how-does-it-differ-from-polynomial-time">this earlier answer</a>, and I'd recommend looking at it for a more thorough explanation.</p> <p>Hope this helps!</p>
16,083,995
groovy.lang.MissingPropertyException: No such property: manager for class: Script1
<p>I am trying to invoke Groovy inside Hudson (using groovy plugin) to get some properties for our build. But I am getting this exception:</p> <blockquote> <p>groovy.lang.MissingPropertyException: No such property: manager for class: Script1</p> </blockquote> <p>I get this with the following line:</p> <pre><code>def buildNUmber = manager.build.number </code></pre> <p>This happens when I run as an inline command within Jenkins as well as using a script:</p> <p>I tried the solution below, but it fails during the declaration itself (line two):</p> <pre><code>Binding binding = new Binding(); binding.setVariable(&quot;manager&quot;, manager); GroovyShell shell = new GroovyShell(binding); shell.evaluate(new File(&quot;d:/dev/others/hudson/userContent/ScriptStuff.groovy&quot;).text); </code></pre> <p>The above is run using: Groovy command. And when I run the build it errors and complains about the line - <code>binding.setVariable(&quot;manager&quot;, manager);</code></p> <p>When I use the Groovy script file, then it complains about:</p> <pre><code> def buildNumber = manager.build.number </code></pre> <p>Both errors are :</p> <blockquote> <p>groovy.lang.MissingPropertyException: No such property: manager for class: Script1</p> </blockquote> <p>Tried everything mentioned in this <a href="http://jenkins.361315.n4.nabble.com/Groovy-post-script-error-td3216762.html" rel="noreferrer">thread</a> as well:</p> <p>I am using Hudson 2.2.1 and Groovy 2.1.3. What could be wrong?</p>
16,134,974
4
1
null
2013-04-18 13:14:00.29 UTC
6
2021-04-27 22:35:09.477 UTC
2021-01-15 15:36:44.43 UTC
null
4,298,200
null
1,114,386
null
1
24
maven|groovy|jenkins|hudson|hudson-plugins
136,759
<p>Maybe I'm missing some part of your code, but where do you define the manager? If that's the complete Groovy script, you're trying to bind a variable which isn't declared anything, so it isn't surprising that it fails.</p> <p>Just define a manager it that's what you want, like:</p> <pre><code>def manager = &quot;my manager&quot; // probably not what you want </code></pre> <p>This should solve your current error.</p>
16,445,805
Call requires API level 16 (current min is 14): android.app.Notification.Builder#build
<p><img src="https://i.stack.imgur.com/nfv2M.png" alt="enter image description here">The documentation says Notification.Builder is Added in API level 11. Why I get this lint error?</p> <blockquote> <p>Call requires API level 16 (current min is 14): android.app.Notification.Builder#build</p> </blockquote> <pre><code>notification = new Notification.Builder(ctx) .setContentTitle("Title").setContentText("Text") .setSmallIcon(R.drawable.ic_launcher).build(); </code></pre> <p>Manifest:</p> <pre><code>&lt;uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" /&gt; </code></pre> <p>Am I missing something?</p> <p>Correct me if I am wrong but the API is added in level 11, right? <a href="http://developer.android.com/reference/android/app/Notification.Builder.html" rel="noreferrer">Added in API level 11</a></p>
16,445,949
5
3
null
2013-05-08 16:37:23.847 UTC
5
2018-01-16 17:43:47.65 UTC
2013-05-08 16:49:02.53 UTC
null
1,104,902
null
1,104,902
null
1
34
android|android-lint
37,653
<p><a href="http://developer.android.com/reference/android/app/Notification.Builder.html#build()" rel="noreferrer">NotificationBuilder.build()</a> requires API Level 16 or higher. Anything between API Level 11 &amp; 15 you should use <a href="http://developer.android.com/reference/android/app/Notification.Builder.html#getNotification%28%29" rel="noreferrer">NotificationBuilder.getNotification()</a>. So use</p> <pre><code>notification = new Notification.Builder(ctx) .setContentTitle("Title").setContentText("Text") .setSmallIcon(R.drawable.ic_launcher).getNotification(); </code></pre>
16,465,705
How to handle configuration in Go
<p>I'm new at Go programming, and I'm wondering: what is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use <em>properties</em> files or <em>ini</em> files for, in other contexts)?</p>
16,466,189
13
9
null
2013-05-09 15:41:12.993 UTC
88
2022-03-05 20:52:39.89 UTC
2018-10-27 04:54:33.313 UTC
null
1,828,296
null
1,118,101
null
1
330
go|configuration-files
222,402
<p>The <a href="http://golang.org/pkg/encoding/json/" rel="noreferrer">JSON</a> format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.</p> <p>See also <a href="https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/sAofmg2_lL8" rel="noreferrer">this golang-nuts thread</a>.</p> <p>The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.</p> <p>Example usage:</p> <p><strong>conf.json</strong>:</p> <pre><code>{ "Users": ["UserA","UserB"], "Groups": ["GroupA"] } </code></pre> <p><strong>Program to read the configuration</strong></p> <pre><code>import ( "encoding/json" "os" "fmt" ) type Configuration struct { Users []string Groups []string } file, _ := os.Open("conf.json") defer file.Close() decoder := json.NewDecoder(file) configuration := Configuration{} err := decoder.Decode(&amp;configuration) if err != nil { fmt.Println("error:", err) } fmt.Println(configuration.Users) // output: [UserA, UserB] </code></pre>
16,570,523
getResourceAsStream returns null
<p>I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:</p> <pre><code>/src/initialization/Lifepaths.txt </code></pre> <p>My code loads a file by calling <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)" rel="noreferrer"><code>Class::getResourceAsStream</code></a> to return a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html" rel="noreferrer"><code>InputStream</code></a>. </p> <pre><code>public class Lifepaths { public static void execute() { System.out.println(Lifepaths.class.getClass(). getResourceAsStream("/initialization/Lifepaths.txt")); } private Lifepaths() {} //This is temporary; will eventually be called from outside public static void main(String[] args) {execute();} } </code></pre> <p>The print out will always print <code>null</code>, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:</p> <ul> <li><code>"/src/initialization/Lifepaths.txt"</code></li> <li><code>"initialization/Lifepaths.txt"</code></li> <li><code>"Lifepaths.txt"</code></li> </ul> <p>Neither of these work. <a href="https://stackoverflow.com/questions/12262062/getresourceasstream-returns-null">I've</a> <a href="https://stackoverflow.com/questions/7017361/getresourceasstream-returning-null">read</a> <a href="https://stackoverflow.com/questions/2797162/getresourceasstream-is-always-returning-null">numerous</a> <a href="https://stackoverflow.com/questions/2195445/eclipse-getresourceasstream-returning-null">questions</a> so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load <code>filename</code>), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name. </p> <p>How do I solve this?</p>
16,571,046
24
9
null
2013-05-15 16:37:01.83 UTC
47
2022-08-09 16:48:58.66 UTC
2020-02-01 01:21:50.99 UTC
null
642,706
user1131435
null
null
1
234
java|file-io|resources
427,664
<p><code>Lifepaths.class.getClass().getResourceAsStream(...)</code> loads resources using system class loader, it obviously fails because it does not see your JARs</p> <p><code>Lifepaths.class.getResourceAsStream(...)</code> loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs</p>
41,827,918
loading a full hierarchy from a self referencing table with EntityFramework.Core
<p>Explanation why this question is different to: <a href="https://stackoverflow.com/questions/23497079/ef-multiple-includes-to-eager-load-hierarchical-data-bad-practice">EF - multiple includes to eager load hierarchical data. Bad practice?</a></p> <ol> <li>the possible duplicate is an opinion based question if this is a bad practice or not whereas my question tends to get the technical solution on how to do it, independent of the opinion if it is a good practice or not. I leave this decision up to the product owner, requirement engineer, project manager and the costumer who wants that feature.</li> <li>The given answers either explain why it is a bad practice or use an approach which is not working for me (using Include() and ThenInclude() produces a hard coded depth whereas I need a flexible depth).</li> </ol> <hr> <p>In the current project (a .NET core web api) I try to load a hierarchy from a self referencing table.</p> <p>After googling a lot I was surprised that such a task (which I thought would be trivial) seems not to be trivial.</p> <p>Well, I have this table to form my hierarchy:</p> <pre><code> CREATE TABLE [dbo].[Hierarchy] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Parent_Id] INT NULL, [Name] NVARCHAR (50) NOT NULL, PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_Hierarchy_Hierarchy] FOREIGN KEY ([Parent_Id]) REFERENCES [dbo].[Hierarchy] ([Id]) ); </code></pre> <p>In the web api I try to return the complete hierarchy. One maybe special thing (that could help) is the fact that I want to load the complete table.</p> <p>I also know that I could use eager loading and the navigation property (Parent and InverseParent for children)</p> <pre><code> _dbContext.Hierarchy.Include(h => h.InverseParent).ThenInclude(h => h.InverseParent)... </code></pre> <p>The problem with that is that this would load a hard coded depth (e.g. six levels if I use 1 Include() and 5 ThenInclude()) but my hierarchy has a flexible depth.</p> <p>Can anyone help me out by giving me some code how to load the full table (e.g. into memory in an optimal scenario with 1 DB call) and then make the method return the full hierarchy?</p>
41,837,737
1
8
null
2017-01-24 12:10:30.147 UTC
13
2018-02-20 14:06:54.077 UTC
2017-05-23 12:01:37.53 UTC
null
-1
null
639,019
null
1
21
c#|linq|asp.net-core|entity-framework-core
24,591
<p>In fact loading the <strong>whole</strong> hierarchy is quite easy thanks to the so called EF (Core) <em>relationship fixup</em>.</p> <p>Let say we have the following model:</p> <pre><code>public class Hierarchy { public int Id { get; set; } public string Name { get; set; } public Hierarchy Parent { get; set; } public ICollection&lt;Hierarchy&gt; Children { get; set; } } </code></pre> <p>Then the following code</p> <pre><code>var hierarchy = db.Hierarchy.Include(e =&gt; e.Children).ToList(); </code></pre> <p>will load the whole hierarchy with correctly populated <code>Parent</code> and <code>Children</code> properties.</p> <p>The problem described in the referenced posts arise when you need to load just part of the hierarchy, which is hard due to the lack of CTE like support in LINQ.</p>
29,022,756
How do I change the color of an md-icon in Angular Material?
<p>I started to use Angular Material in my project and I was wondering how I can change the svg color inside an <code>am-button</code>.</p> <p>This is my code:</p> <pre class="lang-html prettyprint-override"><code>&lt;md-button class="md-fab md-primary"&gt; &lt;md-icon class="ng-scope ng-isolate-scope md-default-theme" style="height: 14px; width: 14px;" md-svg-src="img/material-icons/core/arrow-forward.svg" &gt;&lt;/md-icon&gt; &lt;/md-button&gt; </code></pre> <p>What do I need to add to change the color of the svg from the curent black to white, just like in <a href="https://material.angularjs.org/latest/CSS/button#icon-button-using-font-icons">Google's button demo</a>? (section <em>"Icon button using Font-icons"</em>)</p>
30,006,097
12
5
null
2015-03-13 00:22:41.197 UTC
2
2020-08-26 01:34:50.607 UTC
2016-02-05 23:47:37.263 UTC
null
5,460,631
null
1,018,192
null
1
32
angularjs|angular-material
54,462
<p>For the people trying to color their md-icon, I found out that I had the same problem using Angular 1.3.x and Angular Material 0.8.x.</p> <p>I fixed the problem by <strong>editing my SVG files and deleting the "fill" attribute</strong> that was overriding any inherited color.</p> <p>After deleting this "fill" attribute in each SVG file, I could properly choose the color I wanted to assign to the icon thanks to CSS <a href="https://stackoverflow.com/questions/29022756/how-do-i-change-the-color-of-an-md-icon-in-angular-material/32400924#32400924">as specified by Jason Aunkst</a>.</p>
17,245,402
Android new build system (gradle) and aspectj
<p>In Google IO the new build system gradle is announced to replace ant. My project is using aspectj and I would like to use it in my project. I couldn't figure out some variables to get it working. I don't find android.* output classpath there. Anyone can help?</p> <p>Here is my current build.gradle:</p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.4' } } apply plugin: 'android' sourceCompatibility = 1.6 configurations { ajc } dependencies { compile fileTree(dir: 'libs', includes: ['*.jar']) ajc files('build-tools/aspectjtools.jar', 'libs/aspectjrt.jar') } android { compileSdkVersion 16 buildToolsVersion "17" defaultConfig { minSdkVersion 8 targetSdkVersion 16 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } instrumentTest.setRoot('test') } } gradle.projectsEvaluated { compileJava.doLast { tasks.compileAspectJ.execute() } println 'lalalalala' } task compileAspectJ { ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) ant.iajc(source: sourceCompatibility, target: sourceCompatibility, destDir: "?????????????????????", classpath: "????????????????????????????") { sourceroots{ android.sourceSets.main.java.srcDirs.each { pathelement(location: it.absolutePath) } } } } </code></pre> <p>This is the old ant code that works very well: <a href="http://code.google.com/p/anymemo/source/browse/custom_rules.xml" rel="nofollow">http://code.google.com/p/anymemo/source/browse/custom_rules.xml</a></p> <p>Edit:</p> <p>Updated the build.gradle according to the first answer.However I the iajc does not seem to recognize all the libraries and complain the classes in the libraries not found</p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.5.+' } } apply plugin: 'android' sourceCompatibility = 1.6 targetCompatibility = 1.6 repositories { mavenCentral() } android { compileSdkVersion 18 buildToolsVersion "18.1.0" defaultConfig { minSdkVersion 9 targetSdkVersion 16 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } // Move the tests to tests/java, tests/res, etc... instrumentTest.setRoot('tests') // Move the build types to build-types/&lt;type&gt; // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... // This moves them out of them default location under src/&lt;type&gt;/... which would // conflict with src/ being used by the main source set. // Adding new build types or product flavors should be accompanied // by a similar customization. debug.setRoot('build-types/debug') release.setRoot('build-types/release') } } configurations { ajc aspects ajInpath } ext.aspectjVersion = '1.7.3' dependencies { compile fileTree(dir: 'libs', include: '*.jar') ajc "org.aspectj:aspectjtools:${aspectjVersion}" compile "org.aspectj:aspectjrt:${aspectjVersion}" compile 'com.android.support:appcompat-v7:18.0.0' } android.applicationVariants.all { variant -&gt; variant.javaCompile.doLast { def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar" println 'AAAAAAAAAAAAAAAAA: ' + androidSdk def iajcClasspath = configurations.compile.asPath + ":" + androidSdk configurations.compile.dependencies.each { dep -&gt; if(dep.hasProperty("dependencyProject")) { iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar" } } println 'BBBBBBBBBBBBBB : ' + iajcClasspath ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) ant.iajc ( source:sourceCompatibility, target:targetCompatibility, destDir:"${project.buildDir}/classes/${variant.dirName}", maxmem:"512m", fork:"true", aspectPath:configurations.aspects.asPath, inpath:configurations.ajInpath.asPath, sourceRootCopyFilter:"**/.svn/*,**/*.java", classpath:iajcClasspath ){ sourceroots{ android.sourceSets.main.java.srcDirs.each{ pathelement(location:it.absolutePath) } pathelement(location:"${project.buildDir}/source/r/${variant.dirName}") } } } } </code></pre> <p>Errors:</p> <pre><code>1 [error] The method onPrepareOptionsMenu(Menu) of type FingerPaint must override or impl[3780/18642] rtype method [ant:iajc] public boolean onPrepareOptionsMenu(Menu menu) { [ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^ [ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:21 2 [error] The method onPrepareOptionsMenu(Menu) is undefined for the type GraphicsActivity [ant:iajc] super.onPrepareOptionsMenu(menu); [ant:iajc] ^^^^^^^^^^^ [ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:21 7 [error] The method onOptionsItemSelected(MenuItem) of type FingerPaint must override or implement a supertype method [ant:iajc] public boolean onOptionsItemSelected(MenuItem item) { [ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:22 8 [error] The constructor ColorPickerDialog(FingerPaint, FingerPaint, int) is undefined [ant:iajc] new ColorPickerDialog(this, this, mPaint.getColor()).show(); [ant:iajc] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:25 4 [error] The method onOptionsItemSelected(MenuItem) is undefined for the type GraphicsActivity [ant:iajc] return super.onOptionsItemSelected(item); [ant:iajc] ^^^^^^^^^^^^ [ant:iajc] /home/liberty/mp/android/AnyMemo/src/com/example/android/apis/graphics/FingerPaint.java:25 8 [error] The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applic able for the arguments (FingerPaint) [ant:iajc] SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); [ant:iajc] </code></pre> <p>EDIT: This the final build.gradle file that works for my project: <a href="https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&amp;r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820" rel="nofollow">https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&amp;r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820</a></p>
20,258,072
5
3
null
2013-06-21 22:46:55.327 UTC
10
2015-02-16 14:33:16.327 UTC
2014-05-07 21:34:33.893 UTC
null
2,510,534
null
2,510,534
null
1
17
java|android|gradle
6,351
<p>I figured out that the AAR can not be used as a jar library in my code. If you are using dependencies like this</p> <pre><code>compile 'com.android.support:appcompat-v7:18.0.0' </code></pre> <p>You need to find the jar file and add to the classpath. The following code will do it.</p> <pre><code>tree = fileTree(dir: "${project.buildDir}/exploded-bundles", include: '**/classes.jar') tree.each { jarFile -&gt; iajcClasspath += ":" + jarFile } </code></pre> <p>So the whole section would be:</p> <pre><code>variant.javaCompile.doLast { // Find the android.jar and add to iajc classpath def androidSdk = android.adbExe.parent + "/../platforms/" + android.compileSdkVersion + "/android.jar" println 'Android SDK android.jar path: ' + androidSdk def iajcClasspath = androidSdk + ":" + configurations.compile.asPath configurations.compile.dependencies.each { dep -&gt; if(dep.hasProperty("dependencyProject")) { iajcClasspath += ":" + dep.dependencyProject.buildDir + "/bundles/release/classes.jar" } } // handle aar dependencies pulled in by gradle (Android support library and etc) tree = fileTree(dir: "${project.buildDir}/exploded-bundles", include: '**/classes.jar') tree.each { jarFile -&gt; iajcClasspath += ":" + jarFile } println 'Classpath for iajc: ' + iajcClasspath ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) </code></pre> <p>For the full example please see the build.gradle for AnyMemo project here: <a href="https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&amp;r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820" rel="nofollow">https://code.google.com/p/anymemo/source/browse/build.gradle?spec=svnf85aaa4b2d78c62876d0e1f6c3e28252bf03f820&amp;r=f85aaa4b2d78c62876d0e1f6c3e28252bf03f820</a></p>
17,237,878
Changing console_script entry point interpreter for packaging
<p>I'm packaging some python packages using a well known third party packaging system, and I'm encountering an issue with the way entry points are created.</p> <p>When I install an entry point on my machine, the entry point will contain a shebang pointed at whatever python interpreter, like so:</p> <p>in <strong>/home/me/development/test/setup.py</strong></p> <pre><code>from setuptools import setup setup( entry_points={ "console_scripts": [ 'some-entry-point = test:main', ] } ) </code></pre> <p>in <strong>/home/me/.virtualenvs/test/bin/some-entry-point</strong>:</p> <pre><code>#!/home/me/.virtualenvs/test/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'test==1.0.0','console_scripts','some-entry-point' __requires__ = 'test==1.0.0' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('test==1.0.0', 'console_scripts', 'some-entry-point')() ) </code></pre> <p>As you can see, the entry point boilerplate contains a hard-coded path to the python interpreter that's in the virtual environment that I'm using to create my third party package.</p> <p>Installing this entry point using my third-party packaging system results in the entry point being installed on the machine. However, with this hard-coded reference to a python interpreter which doesn't exist on the target machine, the user must run <code>python /path/to/some-entry-point</code>.</p> <p>The shebang makes this pretty unportable. (which isn't a design goal of virtualenv for sure; but I just need to MAKE it a little more portable here.)</p> <p>I'd rather not resort to crazed find/xargs/sed commands. (Although that's my fallback.)</p> <p>Is there some way that I can change the interpreter path after the shebang using <code>setuptools</code> flags or configs?</p>
17,329,493
3
0
null
2013-06-21 14:34:41.96 UTC
9
2021-12-20 07:18:11.463 UTC
null
null
null
null
558,675
null
1
17
python|setuptools|distutils
4,854
<p>You can customize the console_scripts' shebang line by setting 'sys.executable' (learned this from a <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=548392">debian bug report</a>). That is to say...</p> <pre><code>sys.executable = '/bin/custom_python' setup( entry_points={ 'console_scripts': [ ... etc... ] } ) </code></pre> <p>Better though would be to include the 'execute' argument when building...</p> <pre><code>setup( entry_points={ 'console_scripts': [ ... etc... ] }, options={ 'build_scripts': { 'executable': '/bin/custom_python', }, } ) </code></pre>
24,594,112
When will the worst case of Merge Sort occur?
<p>I know that worst case on mergesort is O(nlogn), the same as the average case.</p> <p>However, if the data are ascending or descending, this results to the <em>minimum number of comparisons</em>, and therefore mergesort becomes faster than random data. So my question is: What kind of input data produces the <em>maximum number of comparisons</em> that result to mergesort to be slower?</p> <p>The answer at <a href="https://stackoverflow.com/questions/23042184/how-to-make-a-worst-case-in-mergesort-in-c">this</a> question says:</p> <blockquote> <p>For some sorting algorithms (e.g. quicksort), the initial order of the elements can affect the number of operations to be done. However it doesn't make any change for mergesort as it will have to do exactly the same number of operations anyway: recursively divide into small arrays and then merge them back, in total Θ(nlogn) time.</p> </blockquote> <p>However this is wrong. At the point we have two subarrays and we want to merge them if the initial data are sorted we will have only n/2 comparisons. That is all the elements of the first subarray with <em>only</em> the first element of the second array. However we can achieve more than that. I'm looking for that input data.</p>
24,594,419
2
10
null
2014-07-06 08:39:34.847 UTC
31
2015-10-29 08:40:58.717 UTC
2017-05-23 12:34:36.1 UTC
null
-1
null
2,824,542
null
1
34
arrays|algorithm|sorting|complexity-theory|time-complexity
78,185
<p>The worst case of merge sort will be the one where merge sort will have to do <strong>maximum number of comparisons.</strong></p> <p>So I will try building the worst case in bottom up manner:</p> <ol> <li><p>Suppose the array in final step after sorting is <code>{0,1,2,3,4,5,6,7}</code></p></li> <li><p>For worst case the array before this step must be <code>{0,2,4,6,1,3,5,7}</code> because here left subarray=<code>{0,2,4,6}</code> and right subarray=<code>{1,3,5,7}</code> will result in maximum comparisons.(<em>Storing alternate elemets in left and right subarray</em>) </p> <p><strong>Reason:</strong> Every element of array will be compared atleast once.</p></li> <li><p>Applying the same above logic for left and right subarray for previous steps : For array <code>{0,2,4,6}</code> the worst case will be if the previous array is <code>{0,4}</code> and <code>{2,6}</code> and for array <code>{1,3,5,7}</code> the worst case will be for <code>{1,5}</code> and <code>{3,7}</code>.</p></li> <li>Now applying the same for previous step arrays: <em>For worst cases</em>: <code>{0,4}</code> must be <code>{4,0}</code> , <code>{2,6}</code> must be <code>{6,2}</code> ,<code>{1,5}</code> must be <code>{5,1}</code> <code>{3,7}</code> must be <code>{7,3}</code> . Well if you look clearly this step is <strong>not necessary</strong> because if the size of set/array is 2 then every element will be compared atleast once even if array of size 2 is sorted.</li> </ol> <h2>Now going top down and analyzing the situation</h2> <pre><code>Applying Merge Sort using Divide and Conquer Input array arr[] = [4,0,6,2,5,1,7,3] / \ / \ [4,0,6,2] and [5,1,7,3] / \ / \ / \ / \ [4,0] [6,2] [5,1] [7,3] Every pair of 2 will be compared atleast once therefore maximum comparison here | | | | | | | | [0,4] [2,6] [1,5] [3,7] Maximum Comparison:Every pair of set is used in comparison \ / \ / \ / \ / [0,2,4,6] [1,3,5,7] Maximum comparison again: Every pair of set compared \ / \ / [0,1,2,3,4,5,6,7] </code></pre> <p><strong>Now you can apply the same logic for any array of size n</strong></p> <p>Below is the program which implements the above logic.</p> <p><em>Note:The below program isn't valid for powers of 2 only. It is a generalized method to provide the worst case for any array of size n. You can try different arrays for input by yourself.</em></p> <pre><code>class MergeWorstCase { public static void print(int arr[]) { System.out.println(); for(int i=0;i&lt;arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public static void merge(int[] arr, int[] left, int[] right) { int i,j; for(i=0;i&lt;left.length;i++) arr[i]=left[i]; for(j=0;j&lt;right.length;j++,i++) arr[i]=right[j]; } //Pass a sorted array here public static void seperate(int[] arr) { if(arr.length&lt;=1) return; if(arr.length==2) { int swap=arr[0]; arr[0]=arr[1]; arr[1]=swap; return; } int i,j; int m = (arr.length + 1) / 2; int left[] = new int[m]; int right[] = new int[arr.length-m]; for(i=0,j=0;i&lt;arr.length;i=i+2,j++) //Storing alternate elements in left subarray left[j]=arr[i]; for(i=1,j=0;i&lt;arr.length;i=i+2,j++) //Storing alternate elements in right subarray right[j]=arr[i]; seperate(left); seperate(right); merge(arr, left, right); } public static void main(String args[]) { int arr1[]={0,1,2,3,4,5,6,7}; seperate(arr1); System.out.print("For array 1:"); print(arr1); int arr2[]={0,1,2,3,4,5,6,7,8}; seperate(arr2); System.out.print("For array 2:"); print(arr2); } } </code></pre> <p>Output: </p> <pre><code>For array 1: 4 0 6 2 5 1 7 3 For array 2: 8 0 4 6 2 5 1 7 3 </code></pre>
19,393,700
C compiling - "undefined reference to"?
<p>I am making a reliable data transfer protocol and have the function prototype</p> <pre><code>void tolayer5(int, char data[]); </code></pre> <p>With the <code>structs</code></p> <pre><code>struct msg { char data[20]; }; struct pkt { int seqnum; int acknum; int checksum; char payload[20]; }; </code></pre> <p>And when I call the function in this format:</p> <pre><code>tolayer5(A, packet.payload); </code></pre> <p>Where <code>A</code> is an <code>int</code> and <code>packet.payload</code> is a <code>struct pkt</code>, I get the error "undefined reference to <code>'tolayer5(int, char*)'</code>. Can you help me see what I'm missing here?</p> <pre><code>void tolayer5(int AorB, char data[]) { int i; if (TRACE&gt;2) { printf("TOLAYER5: data received:"); for (i=0; i&lt;20; i++) printf("%c",data[i]); printf("\n"); } } </code></pre> <hr> <p>Thank you all for helping with the original issue! :) When trying to fix that one, however, I ran into an infinite loop that I think has something to do with me addressing characters in an array incorrectly (it's been awhile since I've done <code>C</code> like this. Can you help me to find where I'm creating an infinite loop?</p> <p>I have updated the above code to what I'm now working with. Notice the main changes have been to my function:</p> <pre><code>void tolayer5(int AorB, char data[]) </code></pre> <p>And this line inside the function: <code>printf("%c",msgReceived.data[i]);</code> since now it's just:</p> <pre><code>printf("%c",data[i]); </code></pre>
19,393,720
3
5
null
2013-10-16 01:14:00.68 UTC
1
2016-11-15 05:24:55.553 UTC
2016-11-15 05:24:55.553 UTC
null
7,055,233
null
2,581,023
null
1
9
c|data-structures
195,391
<p>seems you need to link with the obj file that implements tolayer5()</p> <p>Update: your function declaration doesn't match the implementation:</p> <pre><code> void tolayer5(int AorB, struct msg msgReceived) void tolayer5(int, char data[]) </code></pre> <p>So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().</p>
17,365,017
how to delete extra space between buttons?
<p>please check out <a href="http://jsfiddle.net/NPqSr/">this code in jsfiddle</a></p> <p>HTML:</p> <pre><code>&lt;div id="main"&gt; &lt;div id="menu"&gt; &lt;a href="#" class="buttons"&gt;Home&lt;/a&gt; &lt;a href="#" class="buttons"&gt;About Us&lt;/a&gt; &lt;a href="#" class="buttons"&gt;Pictures&lt;/a&gt; &lt;a href="#" class="buttons"&gt;Contact Us&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#main { width: 64em; height: 25em; } #menu { background-color: #00b875; height: 3em; } .buttons { text-decoration: none; color: #ffffff; line-height: 3em; display: inline-block; padding-left: 10px; padding-right: 10px; font-family: courier new; -moz-transition: 1s linear; -ms-transition: 1s linear; -o-transition: 1s linear; -webkit-transition: 1s linear; transition: 1s linear; } .buttons:hover { background-color: #0d96d6; } </code></pre> <p>when switching from one button to another very quickly, you'll notice that there is actually some gap in between two buttons. i want to get rid of this space. any ideas? if you do answer the question, please also explain why a certain property will fix this.</p> <p>i know that it is tweakable using padding and margin, but the result is likely to get distorted upon zoom. please point out a stable way of solving the problem.</p> <p>thanks</p>
17,365,061
9
4
null
2013-06-28 12:44:02.997 UTC
8
2019-07-16 15:45:26 UTC
2013-06-28 13:16:05.49 UTC
null
1,645,769
null
2,491,795
null
1
22
html|css|animation|button|web
43,824
<p>Look at this <a href="http://jsfiddle.net/NPqSr/2/"><strong>jsFiddle</strong></a></p> <p>I've updated <code>display:inline-block;</code> to <code>display:block;</code> on the menu links and added <code>float:left</code> to them.</p> <p>When you use <code>inline-block</code> you will have this ugly inline gap between elements caused by the whitespace between the elements in your <code>HTML</code> markup..</p>
17,375,340
Testing code that requires a Flask app or request context
<p>I am getting <code>working outside of request context</code> when trying to access <code>session</code> in a test. How can I set up a context when I'm testing something that requires one?</p> <pre><code>import unittest from flask import Flask, session app = Flask(__name__) @app.route('/') def hello_world(): t = Test() hello = t.hello() return hello class Test: def hello(self): session['h'] = 'hello' return session['h'] class MyUnitTest(unittest.TestCase): def test_unit(self): t = tests.Test() t.hello() </code></pre>
17,377,101
1
1
null
2013-06-29 00:03:15.723 UTC
29
2018-06-25 19:31:11.143 UTC
2016-04-20 17:32:52.537 UTC
null
400,617
null
155,857
null
1
91
python|flask
71,504
<p>If you want to make a request to your application, use the <a href="http://flask.pocoo.org/docs/latest/api/#flask.Flask.test_client" rel="noreferrer"><code>test_client</code></a>.</p> <pre><code>c = app.test_client() response = c.get('/test/url') # test response </code></pre> <p>If you want to test code which uses an application context (<code>current_app</code>, <code>g</code>, <code>url_for</code>), push an <a href="http://flask.pocoo.org/docs/latest/api/#flask.Flask.app_context" rel="noreferrer"><code>app_context</code></a>.</p> <pre><code>with app.app_context(): # test your app context code </code></pre> <p>If you want test code which uses a request context (<code>request</code>, <code>session</code>), push a <a href="http://flask.pocoo.org/docs/latest/api/#flask.Flask.test_request_context" rel="noreferrer"><code>test_request_context</code></a>.</p> <pre><code>with current_app.test_request_context(): # test your request context code </code></pre> <hr> <p>Both app and request contexts can also be pushed manually, which is useful when using the interpreter.</p> <pre><code>&gt;&gt;&gt; ctx = app.app_context() &gt;&gt;&gt; ctx.push() </code></pre> <p>Flask-Script or the new Flask cli will automatically push an app context when running the <code>shell</code> command.</p> <hr> <p><a href="http://pythonhosted.org/Flask-Testing/" rel="noreferrer"><code>Flask-Testing</code></a> is a useful library that contains helpers for testing Flask apps.</p>
36,848,352
How to select value from Dropdown without using Select class, Becuase in have dropdown as listbox in the span not select?
<pre><code>My HTML code is here: &lt;fieldset&gt; &lt;div class="clearfix"&gt; &lt;div class="clearfix"&gt; &lt;div class="clearfix"&gt; &lt;div class="clearfix"&gt; &lt;div class="qs-formfield-short qs-required"&gt; &lt;label for="stateCountry"&gt;State or Province&lt;/label&gt; &lt;span class="k-widget k-dropdown k-header" style="" title="" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-owns="stateCountry_listbox" aria-disabled="false" aria-readonly="false" aria-busy="false"&gt; &lt;span class="k-dropdown-wrap k-state-default" unselectable="on"&gt; &lt;span class="k-input" unselectable="on"&gt;Please Select...&lt;/span&gt; &lt;span class="k-select" unselectable="on"&gt; &lt;span class="k-icon k-i-arrow-s" unselectable="on"&gt;select&lt;/span&gt; &lt;/span&gt; &lt;/span&gt; </code></pre> <p>My Code is here:</p> <p>WebElement stateDropDown = driver.findElement( By.xpath("/html/body/form/div[3]/main/div/div/div/span/div/fieldset/div[4]/div[1]/span/span[1]")); List options = stateDropDown.findElements(By.xpath("/html/body/div[1]/div/ul/li[44]"));</p> <pre><code> for(WebElement opt : options){ if ("Texas".equals(opt.getText())); opt.click(); System.out.println(opt); </code></pre>
36,851,955
2
3
null
2016-04-25 18:28:24.93 UTC
1
2022-01-29 08:50:41.67 UTC
2016-04-26 12:53:04.997 UTC
null
6,252,833
null
6,252,833
null
1
0
selenium|select|webdriver|dropdown
41,595
<p>Try smth like this:</p> <pre><code>Actions action = new Actions(driver); WebElement optionsList = driver.findElement(By.xpath("//span[contains(@class, 'k-dropdown-wrap')]")); action.moveToElement(optionsList); List&lt;WebElement&gt; options = driver.getElemets(By.xpath("//span[contains(@class, 'k-input')]")); for(WebElement option : options) { if (option.getText().equals("Texas")) { option.click(); } } </code></pre> <p>Stop writing strange xpath to elements :)</p>
36,911,453
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
<p>when i was trying to read data from Oracle database using the following code i was getting exception</p> <pre><code>ResultSet res=stmt.executeQuery("select * from food"); </code></pre> <p>But this table is actually exist in my database when i use this command directly in the command prompt its working fine.And also for one table among the tables in database this code is working fine ,but for other table names its not working properly.So someone please explain why this is happening.</p> <pre><code>java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:193) at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:852) at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275) at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1477) at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:392) at connecttooracle.ConnectOracle.main(ConnectOracle.java:67) </code></pre> <p>I am accessing data from food table by Toad . THen why am I getting this error in java ? </p> <p>My full code is : </p> <pre><code>public class ConnectOracle { public static void main(String[] args) { String driver = "oracle.jdbc.driver.OracleDriver"; // String serverName = "10.11.201.84"; String portNumber = "1521"; String db = "XE"; String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + db; // connectOracle is the data // source name String user = "ORAP"; // username of oracle database String pwd = "ORAP"; // password of oracle database Connection con = null; ServerSocket serverSocket = null; Socket socket = null; DataInputStream dataInputStream = null; DataOutputStream dataOutputStream = null; try { Class.forName(driver);// for loading the jdbc driver System.out.println("JDBC Driver loaded"); con = DriverManager.getConnection(url, user, pwd);// for // establishing // connection // with database Statement stmt = (Statement) con.createStatement(); serverSocket = new ServerSocket(8888); System.out.println("Listening :8888"); while (true) { try { socket = serverSocket.accept(); System.out.println("Connection Created"); dataInputStream = new DataInputStream( socket.getInputStream()); dataOutputStream = new DataOutputStream( socket.getOutputStream()); System.out.println("ip: " + socket.getInetAddress()); // System.out.println("message: " + // dataInputStream.readUTF()); ResultSet res=stmt.executeQuery("select * from food"); while(res.next()){ System.out.println(res.getString(1)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (dataInputStream != null) { try { dataInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (dataOutputStream != null) { try { dataOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre>
36,911,696
13
5
null
2016-04-28 10:08:40.017 UTC
3
2022-07-29 16:50:32.463 UTC
2016-04-28 10:13:38.957 UTC
null
1,282,443
null
1,282,443
null
1
5
java|oracle
68,410
<p>If your table is located under schema A:</p> <pre><code>select * from A.food </code></pre> <p><strong>EDIT</strong></p> <p>If you can login via TOAD with user ORAP and execute the same query (select * from food) then you definitely have the table in ORAP schema. I see no reason for "select * from ORAP.food" to fail.</p>
37,004,579
Convenient way of checking equality for Optionals
<p>I'm looking for a more convenient way of proofing equality for an Optional value.</p> <p>This is what an <a href="http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html" rel="noreferrer">Oracle Blog post</a> suggests:</p> <pre><code>Optional&lt;USB&gt; maybeUSB = ...; maybeUSB.filter(usb -&gt; "3.0".equals(usb.getVersion()) .ifPresent(() -&gt; System.out.println("ok")); </code></pre> <p>IMHO results in something like</p> <pre><code>if (maybeUSB.filter(c -&gt; "3.0".equals(c.getVersion())).isPresent()) { ... } </code></pre> <p>Of course that's kind of a poor example because it compares the Version and not the instance of USB itself but I think it should still proof my point.</p> <p>Is this really as good as it gets?</p> <p>No</p> <pre><code>boolean presentAndEquals(Object) </code></pre> <p>or</p> <pre><code>boolean deepEquals(Object) </code></pre> <p>Am I missing something here?</p> <p><strong>EDIT:</strong></p> <p>I'm not that happy with Optionals.equals either. Do I really have to box an Object first to instantly unbox and check for equality ?</p> <p><strong>EDIT II:</strong></p> <p>Pretty damn happy with:</p> <pre><code>optional .filter(nonOptional::equals) .isPresent() </code></pre> <p>nowadays.</p> <p>After some years of functional programming, <code>if</code> looses a <strong>lot</strong> of relevance.</p>
37,005,067
3
5
null
2016-05-03 12:46:31.007 UTC
3
2019-10-29 16:28:15.8 UTC
2019-10-29 16:28:15.8 UTC
null
1,300,626
null
1,300,626
null
1
24
java|java-8|option-type
39,769
<p>You have many options.</p> <p>Already noted:</p> <pre><code>boolean isEqual = maybeFoo.equals(Optional.of(testFoo)); </code></pre> <p>Alternatively:</p> <pre><code>boolean isEqual = maybeFoo.isPresent() &amp;&amp; maybeFoo.get().equals(testFoo); </code></pre> <p>Or:</p> <pre><code>boolean isEqual = testFoo.equals(maybeFoo.orElse(null)); </code></pre> <p>These last two do have slightly different semantics: each returns a different value when <code>maybeFoo</code> is empty and <code>testFoo</code> is null. It's not clear which is the correct response (which I guess is one reason there's not a standard API method that does this).</p> <p>You can probably come up with others if you read the <code>Optional</code> API doc and apply some thought. There's nothing magic that's absent from the docs.</p> <p>More generally, if you're knocking against this often enough for it to bother you, you might be approaching <code>Optional</code> with the wrong philosophy.</p> <p>As I see it, <code>Optional</code> is about acknowledging that something won't always be present, and that you need (sometimes verbose) code to handle that.</p> <p>This should be the exception. Wherever possible, try and create variables that <strong>can't</strong> be null or <code>Optional.empty()</code>. </p> <p>In situations where this is unavoidable, embrace the fact that you need extra code.</p>
4,846,540
C++11 lambda in decltype
<p>For the following code:</p> <pre><code>auto F(int count) -&gt; decltype([](int m) { return 0; }) { return [](int m) { return 0; }; } </code></pre> <p>g++ 4.5 gives the errors:</p> <pre><code>test1.cpp:1:32: error: expected primary-expression before 'int' test1.cpp:1:32: error: expected ')' before 'int' </code></pre> <p>What is the problem? What is the correct way to return a lambda from a function?</p>
4,846,597
3
0
null
2011-01-31 00:15:03.613 UTC
6
2019-12-11 21:51:49.01 UTC
2012-02-15 08:43:26.043 UTC
null
141,719
null
141,719
null
1
33
c++|lambda|c++11|decltype
15,941
<p>You cannot use a lambda expression except by actually creating that object- that makes it impossible to pass to type deduction like decltype.</p> <p>Ironically, of course, the lambda return rules make it so that you CAN return lambdas from lambdas, as there are some situations in which the return type doesn't have to be specified.</p> <p>You only have two choices- return a polymorphic container such as <code>std::function</code>, or make F itself an actual lambda.</p> <pre><code>auto F = [](int count) { return [](int m) { return 0; }; }; </code></pre>
5,219,283
How to add animated splash screen in our application
<p>How to add animated splash screen in our application.</p>
5,219,440
4
2
null
2011-03-07 11:44:38.673 UTC
9
2012-10-05 12:11:00.77 UTC
null
null
null
null
623,101
null
1
8
iphone|objective-c
21,397
<p>You can use sequence of images, here is code:</p> <pre><code>for(NSInteger i=1;i&lt;=totalImages;i++){ NSString *strImage = [NSString stringWithFormat:@"Activity_%d",i]; UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:strImage ofType:@"png"]]; [imageArray addObject:image]; } splashImageView.animationImages = imageArray; splashImageView.animationDuration = 0.8; </code></pre> <p>and just call startAnimation and endAnimation method of UIImageView.</p>
9,606,455
How to specify 64 bit integers in c
<p>I'm trying to use 64 bit integers in C, but am getting mixed signals as to whether it should be possible.</p> <p>When I execute the printf:</p> <pre><code>printf("Size of long int:%d\nSize of long long int:%d\n\n",(int)sizeof(long int), (int)sizeof(long long int)); </code></pre> <p>The response I get is:</p> <p>Size of long int:4 Size of long long int:8</p> <p>This makes me feel that a long long int has 8 bytes = 64 bits.</p> <p>However, when I try to declare the following variables:</p> <pre><code>long long int a2 = 0x00004444; long long int b2 = 0x000044440; long long int c2 = 0x0000444400; long long int d2 = 0x00004444000; long long int e2 = 0x000044440000; long long int f2 = 0x0000444400004; long long int g2 = 0x00004444000044; long long int h2 = 0x000044440000444; long long int i2 = 0x0000444400004444; </code></pre> <p>The last 4 variables (f2,g2,h2,i2) give me the error message: </p> <p>warning: integer constant is too large for ‘long’ type </p> <p>I get the same result when I replace 'long long int' with 'int64_t'. I assume 'int64_t' was recognized, since it didn't generate any error messages of its own.</p> <p>So, it appears my 8 byte long long int is really a 6 byte long long int, and I don't understand what I'm missing here. If it's any help, here is the information on my gcc compiler:</p> <pre><code>me@ubuntu:~$ gcc -v Using built-in specs. Target: i686-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ - -enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu Thread model: posix gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5) </code></pre> <p>If anyone knows how (or if) 64 bit integers are accessible to me, I'd really appreciate any help. Thanks....</p>
9,606,507
5
3
null
2012-03-07 17:38:54.827 UTC
14
2017-06-28 02:27:43.38 UTC
2017-06-28 02:27:43.38 UTC
null
264,052
null
1,245,262
null
1
60
c|64-bit|sizeof
189,293
<p>Use <code>stdint.h</code> for specific sizes of integer data types, and also use appropriate suffixes for integer literal constants, e.g.:</p> <pre><code>#include &lt;stdint.h&gt; int64_t i2 = 0x0000444400004444LL; </code></pre>
18,611,565
How do I correctly reuse Jackson ObjectMapper?
<p>I am happy with how the ObjectMapper works and general use within my application. What I would like to understand is the best way to implement the ObjectMapper to ensure it is re-used and I'm not creating unnecessary instances within my application?</p> <p>My thoughts are that I can declare the ObjectMapper in a Utils class as follows:</p> <pre><code>public class Utils { public final static ObjectMapper mapper = new ObjectMapper(); } </code></pre> <p>I could then reference this from the various places I need to using code such as:</p> <pre><code>JsonSimple jsonSimple = Utils.mapper.readValue(jsonString, JsonSimple.class); </code></pre> <p>I came across this other question (<a href="https://stackoverflow.com/questions/3907929/should-i-make-jacksons-objectmapper-as-static-final">Should I declare Jackson&#39;s ObjectMapper as a static field?</a>) that prompted my approach. I think maybe the key difference is that I want to share my ObjectMapper instance across many different classes, not just within a single class.</p> <p>Does this approach sound appropriate or am I missing something?</p> <p>Thanks</p>
18,615,839
4
1
null
2013-09-04 10:38:54.877 UTC
9
2016-02-24 13:08:58.51 UTC
2017-05-23 12:26:26.683 UTC
null
-1
null
2,323,210
null
1
75
java|jackson
71,417
<p>It's fine to use a single instance per application provided you don't call any configuration methods after it's been made visible i.e. you should do all your initialization inside a static block.</p>
18,301,898
Generating typescript declaration files from javascript
<p>Say for example, you have a npm library, in my case <code>mongoose</code>, how would you go about generating <code>d.ts</code> files?</p>
18,302,200
6
2
null
2013-08-18 17:36:39.967 UTC
18
2021-09-08 23:34:15.503 UTC
null
null
null
null
1,624,921
null
1
74
typescript
78,102
<p>JavaScript doesn't always contain enough type information for the TypeScript compiler to infer the structures in your code - so automatically generating a definition based on JavaScript is rarely an option.</p> <p>There are instructions on how to write them from scratch here:</p> <p><a href="https://www.stevefenton.co.uk/2013/01/complex-typescript-definitions-made-easy/" rel="noreferrer">https://www.stevefenton.co.uk/2013/01/complex-typescript-definitions-made-easy/</a></p> <p>But there is one trick that might work (it only works in a limited set of cases).</p> <p>If you paste the JavaScript into a new TypeScript file, fix any trivial errors you may get and compile it using the definition flag, it may be able to get you a file that would at least be a starting point.</p> <pre><code>tsc --declaration js.ts </code></pre>
18,316,166
Symfony2 - How to validate an email address in a controller
<p>There is an email validator in symfony that can be used in a form: <a href="http://symfony.com/doc/current/reference/constraints/Email.html">http://symfony.com/doc/current/reference/constraints/Email.html</a></p> <p>My question is: How can I use this validator in my controlelr in order to validate an email address?</p> <p>This is possible by using the PHP preg_match for usere, but my question is if there is a possibility to use the Symfony already built in email validator.</p> <p>Thank you in advance.</p>
18,316,620
6
0
null
2013-08-19 14:20:09.227 UTC
10
2020-10-31 18:37:48.313 UTC
null
null
null
null
1,018,270
null
1
23
php|validation|symfony|email-validation
47,494
<p>By using <a href="http://api.symfony.com/2.0/Symfony/Component/Validator/Validator.html#method_validateValue">validateValue</a> method of the <a href="http://api.symfony.com/2.0/Symfony/Component/Validator/Validator.html">Validator</a> service</p> <pre><code>use Symfony\Component\Validator\Constraints\Email as EmailConstraint; // ... public function customAction() { $email = 'value_to_validate'; // ... $emailConstraint = new EmailConstraint(); $emailConstraint-&gt;message = 'Your customized error message'; $errors = $this-&gt;get('validator')-&gt;validateValue( $email, $emailConstraint ); // $errors is then empty if your email address is valid // it contains validation error message in case your email address is not valid // ... } // ... </code></pre>
20,096,297
Explicit type casting example in Java
<p>I have come across this example on <a href="http://www.javabeginner.com/learn-java/java-object-typecasting">http://www.javabeginner.com/learn-java/java-object-typecasting</a> and in the part where it talks about explicit type casting there is one example which confuses me.</p> <p>The example:</p> <pre><code>class Vehicle { String name; Vehicle() { name = "Vehicle"; } } class HeavyVehicle extends Vehicle { HeavyVehicle() { name = "HeavyVehicle"; } } class Truck extends HeavyVehicle { Truck() { name = "Truck"; } } class LightVehicle extends Vehicle { LightVehicle() { name = "LightVehicle"; } } public class InstanceOfExample { static boolean result; static HeavyVehicle hV = new HeavyVehicle(); static Truck T = new Truck(); static HeavyVehicle hv2 = null; public static void main(String[] args) { result = hV instanceof HeavyVehicle; System.out.print("hV is an HeavyVehicle: " + result + "\n"); result = T instanceof HeavyVehicle; System.out.print("T is an HeavyVehicle: " + result + "\n"); result = hV instanceof Truck; System.out.print("hV is a Truck: " + result + "\n"); result = hv2 instanceof HeavyVehicle; System.out.print("hv2 is an HeavyVehicle: " + result + "\n"); hV = T; //Sucessful Cast form child to parent T = (Truck) hV; //Sucessful Explicit Cast form parent to child } } </code></pre> <p>In the last line where T is assigned the reference hV and typecast as (Truck), why does it say in the comment that this is a Successful Explicit Cast from parent to child? As I understand casting (implicit or explicit) will only change the declared type of object, not the actual type (which shouldn't ever change, unless you actually assign a new class instance to that object's field reference). If hv was already assigned an instance of a HeavyVehicle class which is a super class of the Truck class, how can then this field be type cast into a more specific subclass called Truck which extends from the HeavyVehicle class?</p> <p>The way I understand it is that casting serves the purpose of limiting access to certain methods of an object (class instance). Therefore you can't cast an object as a more specific class which has more methods then the object's actual assigned class. That means that the object can only be cast as a superclass or the same class as the class from which it was actually instantiated. Is this correct or am I wrong here? I am still learning so I am not sure if this is the correct way of looking at things.</p> <p>I also understand that this should be an example of downcasting, but I am not sure how this actually works if the actual type doesn't have the methods of the class to which this object is being downcasted. Does explicit casting somehow change the actual type of object (not just the declared type), so that this object is no longer an instance of HeavyVehicle class but now becomes an instance of Truck class?</p>
20,097,325
6
3
null
2013-11-20 12:42:08 UTC
30
2022-01-10 20:25:34.927 UTC
2021-01-07 00:09:43.383 UTC
null
697,630
null
2,008,196
null
1
34
java|casting|downcast
85,311
<p><strong>Reference vs Object vs Types</strong></p> <p>The key, for me, is understanding the difference between an object and its references, or put in other words the difference between an object and its types.</p> <p>When we create an object in Java, we declare its true nature, which will never change (e.g. <code>new Truck()</code>). But any given object in Java is likely to have <em>multiple types.</em> Some of these types are obviously given by the class hierarchy, others are not so obvious (i.e. generics, arrays).</p> <p>Specifically for reference types, the class hierarchy dictates the subtyping rules. For instance in your example <em>all trucks are heavy vehicles</em>, and <em>all heavy vehicles are vehicle</em>s. Therefore, this hierarchy of is-a relationships dictates that a truck has <em>multiple compatible types</em>.</p> <p>When we create a <code>Truck</code>, we define a &quot;reference&quot; to get access to it. This reference must have one of those compatible types.</p> <pre><code>Truck t = new Truck(); //or HeavyVehicle hv = new Truck(); //or Vehicle h = new Truck() //or Object o = new Truck(); </code></pre> <p>So the key point here is the realization that <em>the reference to the object is not the object itself</em>. The nature of the object being created is never going to change. But we can use different kinds of compatible references to gain access to the object. This is one of the features of polymorphism here. The same object may be accessed through references of different &quot;compatible&quot; types.</p> <p>When we do any kind of casting, we are simply assuming the nature of this compatibility between different types of references.</p> <p><strong>Upcasting or Widening Reference Conversion</strong></p> <p>Now, having a reference of type <code>Truck</code>, we can easily conclude that it's always compatible with a reference of type <code>Vehicle</code>, because <em>all Trucks are Vehicles</em>. Therefore, we could upcast the reference, without using an explicit cast.</p> <pre><code>Truck t = new Truck(); Vehicle v = t; </code></pre> <p>It is also called a <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.5" rel="nofollow noreferrer">widening reference conversion</a>, basically because as you go up in the type hierarchy, the type gets more general.</p> <p>You could use an explicit cast here if you wanted, but it would be unnecessary. We can see that the actual object being referenced by <code>t</code> and <code>v</code> is the same. It is, and will always be a <code>Truck</code>.</p> <p><strong>Downcasting or Narrowing Reference Conversion</strong></p> <p>Now, having a reference of type <code>Vechicle</code> we cannot &quot;safely&quot; conclude that it actually references a <code>Truck</code>. After all it may also reference some other form of Vehicle. For instance</p> <pre><code>Vehicle v = new Sedan(); //a light vehicle </code></pre> <p>If you find the <code>v</code> reference somewhere in your code without knowing to which specific object it is referencing, you cannot &quot;safely&quot; argument whether it points to a <code>Truck</code> or to a <code>Sedan</code> or any other kind of vehicle.</p> <p>The compiler knows well that it cannot give any guarantees about the true nature of the object being referenced. But the programmer, by reading the code, may be sure of what s/he is doing. Like in the case above, you can clearly see that <code>Vehicle v</code> is referencing a <code>Sedan</code>.</p> <p>In those cases, we can do a downcast. We call it that way because we are going down the type hierarchy. We also call this a <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.6" rel="nofollow noreferrer">narrowing reference conversion</a>. We could say</p> <pre><code>Sedan s = (Sedan) v; </code></pre> <p>This always requires an explicit cast, because the compiler cannot be sure this is safe and that's why this is like asking the programmer, &quot;are you sure of what you are doing?&quot;. If you lie to the compiler you will throw you a <code>ClassCastException</code> at run time, when this code is executed.</p> <p><strong>Other Kinds of Subtyping Rules</strong></p> <p>There are other rules of subtyping in Java. For instance, there is also a concept called numeric promotion that automatically coerce numbers in expressions. Like in</p> <pre><code>double d = 5 + 6.0; </code></pre> <p>In this case an expression composed of two different types, integer and double, upcasts/coerces the integer to a double before evaluating the expression, resulting in a double value.</p> <p>You may also do primitive upcasting and downcasting. As in</p> <pre><code>int a = 10; double b = a; //upcasting int c = (int) b; //downcasting </code></pre> <p>In these cases, an explicit cast is required when information can be lost.</p> <p>Some subtyping rules may not be so evident, like in the cases of arrays. For instance, all reference arrays are subtypes of <code>Object[]</code>, but primitive arrays are not.</p> <p>And in the case of generics, particularly with the use of wildcards like <code>super</code> and <code>extends</code>, things get even more complicated. Like in</p> <pre><code>List&lt;Integer&gt; a = new ArrayList&lt;&gt;(); List&lt;? extends Number&gt; b = a; List&lt;Object&gt; c = new ArrayList&lt;&gt;(); List&lt;? super Number&gt; d = c; </code></pre> <p>Where the type of <code>a</code> is a subtype of the type of <code>b</code>. And the type of <code>c</code> is a subtype of the type of <code>d</code>.</p> <p>Using covariance, wherever <code>List&lt;? extends Number&gt;</code> appears you can pass a <code>List&lt;Integer&gt;</code>, therefore <code>List&lt;Integer&gt;</code> is a subtype of <code>List&lt;? extends Number&gt;</code>.</p> <p>Contravariance produce a similar effect and wherever the type <code>List&lt;? super Number&gt;</code> appears, you could pass a <code>List&lt;Object&gt;</code>, which makes of <code>List&lt;Object&gt;</code> a subtype of <code>List&lt;? super Number&gt;</code>.</p> <p>And also boxing and unboxing are subject to some casting rules (yet again this is also some form of coercion in my opinion).</p>
27,437,779
WebStorm: search does not work
<p>I know that is used to search : <kbd>Ctrl+Shift+F</kbd> or Edit | Find | Find in Path and it worked before, but now always returns the empty set, although I know that what I'm looking for - there is in the project</p> <p>Maybe someone had this problem?</p>
28,900,582
8
6
null
2014-12-12 06:04:02.067 UTC
18
2022-01-12 17:26:09.73 UTC
2017-11-22 08:56:11.543 UTC
null
4,632,019
null
3,705,609
null
1
131
search|intellij-idea|phpstorm|webstorm
34,272
<p>As lena said, the following should fix it for you:</p> <ol> <li>Click File -> Invalidate Caches / Restart..</li> <li>Click the button "Invalidate and Restart"</li> <li>After restart, try run the search again</li> </ol>
15,063,963
Python: is thread still running
<p>How do I see whether a thread has completed? I tried the following, but threads_list does not contain the thread that was started, even when I know the thread is still running.</p> <pre><code>import thread import threading id1 = thread.start_new_thread(my_function, ()) #wait some time threads_list = threading.enumerate() # Want to know if my_function() that was called by thread id1 has returned def my_function() #do stuff return </code></pre>
15,064,436
3
0
null
2013-02-25 09:39:06.033 UTC
2
2020-07-21 15:32:42.197 UTC
null
null
null
null
984,003
null
1
22
python|multithreading
84,547
<p>The key is to start the thread using threading, not thread:</p> <pre><code>t1 = threading.Thread(target=my_function, args=()) t1.start() </code></pre> <p>Then use</p> <pre><code>z = t1.is_alive() # Changed from t1.isAlive() based on comment. I guess it would depend on your version. </code></pre> <p>or</p> <pre><code>l = threading.enumerate() </code></pre> <p>You can also use join():</p> <pre><code>t1 = threading.Thread(target=my_function, args=()) t1.start() t1.join() # Will only get to here once t1 has returned. </code></pre>
38,171,471
Eclipse not recognizing Gradle dependencies
<p>I am new to Gradle and I was trying this tutorial <a href="https://spring.io/guides/gs/rest-service/" rel="noreferrer">https://spring.io/guides/gs/rest-service/</a> I was able to compile the jar with the required dependencies and run it. However, I find it annoying that the libraries are not recognized by the IDE.</p> <p><a href="https://i.stack.imgur.com/D79wZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/D79wZ.jpg" alt="enter image description here"></a></p> <p>Is there anyway to do it? </p>
38,171,826
11
5
null
2016-07-03 15:30:00.51 UTC
15
2021-03-22 16:03:40.56 UTC
2016-07-03 15:34:30.023 UTC
null
2,446,208
null
6,066,596
null
1
40
java|eclipse|gradle|dependencies
73,322
<p>You should use the gradle eclipse plugin. Add this to your <code>build.gradle</code> file:</p> <pre><code>apply plugin: "eclipse" </code></pre> <p>This will add eclipse related tasks to your build. By executing</p> <pre><code>gradlew cleanEclipse eclipse </code></pre> <p>Gradle will regenerate all eclipse project and classpath files based on the current dependencies of your project(s). You will however need to refresh your IDE to make the changes visible.</p> <p>There is one more thing to consider. As eclipse is not really aware of the gradle dependencies - it knows them only by the generated classpath files - new dependencies will be visible to eclipse only after regenerating these files. Furthermore dependencies added in eclipse will not be visible to your gradle build and will be removed once the classpath files are regenerated.</p>
28,265,230
Could not resolve '...' from state ''
<p>This is first time i am trying to use ui-router.</p> <p>Here is my app.js</p> <pre><code>angular.module('myApp', ['ionic']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova &amp;&amp; window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise("/index.html"); $stateProvider.state('index', { url: '/' template: "index.html", controller: 'loginCtrl' }); $stateProvider.state('register', { url: "/register" template: "register.html", controller: 'registerCtrl' }); }) </code></pre> <p>As you can see, i have two states. I'm trying to register state like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;a ui-sref="register"&gt; &lt;button class="button button-balanced"&gt; Create an account &lt;/button&gt; &lt;/a&gt; </code></pre> <p>But i am getting </p> <blockquote> <p>Could not resolve 'register' from state ''</p> </blockquote> <p>exception. What is the problem here?</p>
28,265,429
6
3
null
2015-02-01 16:57:19.723 UTC
16
2021-12-08 13:55:26.46 UTC
2017-09-27 09:17:05.257 UTC
null
863,110
null
624,636
null
1
101
angularjs|angular-ui-router
161,030
<p>This kind of error usually means that some parts of (JS) code were not loaded. That the state which is inside of <code>ui-sref</code> is missing. </p> <p>There is <a href="http://plnkr.co/edit/JpiliT6C6XGULRGQD6UF?p=preview" rel="nofollow noreferrer">a working example</a></p> <p><em>I am not an expert in ionic, so this example should show that it would be working, but I used some more tricks (parent for tabs)</em></p> <p>This is a bit adjusted state def:</p> <pre><code>.config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise("/index.html"); $stateProvider .state('app', { abstract: true, templateUrl: "tpl.menu.html", }) $stateProvider.state('index', { url: '/', templateUrl: "tpl.index.html", parent: "app", }); $stateProvider.state('register', { url: "/register", templateUrl: "tpl.register.html", parent: "app", }); $urlRouterProvider.otherwise('/'); }) </code></pre> <p>And here we have the parent view with tabs, and their content:</p> <pre><code>&lt;ion-tabs class="tabs-icon-top"&gt; &lt;ion-tab title="Index" icon="icon ion-home" ui-sref="index"&gt; &lt;ion-nav-view name=""&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;ion-tab title="Register" icon="icon ion-person" ui-sref="register"&gt; &lt;ion-nav-view name=""&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;/ion-tabs&gt; </code></pre> <p><em>Take it more than an example of how to make it running and later use ionic framework the right way...Check that example <a href="http://plnkr.co/edit/JpiliT6C6XGULRGQD6UF?p=preview" rel="nofollow noreferrer">here</a></em></p> <p>Here is similar Q &amp; A with an example using the named views <em>(for sure better solution)</em> <a href="https://stackoverflow.com/q/25904197/1679310">ionic routing issue, shows blank page</a></p> <p>Improved version with named views in a tab is here: <a href="http://plnkr.co/edit/Mj0rUxjLOXhHIelt249K?p=preview" rel="nofollow noreferrer">http://plnkr.co/edit/Mj0rUxjLOXhHIelt249K?p=preview</a></p> <pre><code> &lt;ion-tab title="Index" icon="icon ion-home" ui-sref="index"&gt; &lt;ion-nav-view name="index"&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;ion-tab title="Register" icon="icon ion-person" ui-sref="register"&gt; &lt;ion-nav-view name="register"&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; </code></pre> <p>targeting named views:</p> <pre><code> $stateProvider.state('index', { url: '/', views: { "index" : { templateUrl: "tpl.index.html" } }, parent: "app", }); $stateProvider.state('register', { url: "/register", views: { "register" : { templateUrl: "tpl.register.html", } }, parent: "app", }); </code></pre>
28,012,943
What is the actual use of "signed" keyword?
<p>I know that unsigned integers are only positive numbers (and 0), and can have double the value compared to a normal int. Are there any difference between </p> <pre><code>int variable = 12; </code></pre> <p>And:</p> <pre><code>signed int variable = 12; </code></pre> <p>When and why should you use the signed keyword? </p>
28,013,000
4
4
null
2015-01-18 17:59:01.727 UTC
6
2016-05-06 06:47:28.987 UTC
2015-01-18 18:06:53.853 UTC
null
4,262,157
null
4,262,157
null
1
63
c++
9,740
<p>There is only one instance where you might want to use the <code>signed</code> keyword. <code>signed char</code> is always a different type from "plain" <code>char</code>, which may be a signed or an unsigned type depending on the implementation.</p> <p>C++14 3.9.1/1 says:</p> <blockquote> <p>It is implementation-defined whether a <code>char</code> object can hold negative values. Characters can be explicitly declared <code>unsigned</code> or <code>signed</code>. Plain <code>char</code>, <code>signed char</code>, and <code>unsigned char</code> are three distinct types [...]</p> </blockquote> <p>In other contexts <code>signed</code> is redundant.</p> <hr> <p>Prior to C++14, (and in C), there was a second instance: bit-fields. It was implementation-defined whether, for example, <code>int x:2;</code> (in the declaration of a class) is the same as <code>unsigned int x:2;</code> or the same as <code>signed int x:2</code>. </p> <p>C++11 9.6/3 said:</p> <blockquote> <p>It is implementation-defined whether a plain (neither explicitly signed nor unsigned) <code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, or <code>long long</code> bit-field is signed or unsigned.</p> </blockquote> <p>However, since C++14 this has been changed so that <code>int x:2;</code> always means <code>signed int</code>. <a href="https://stackoverflow.com/questions/33723631/signed-bit-field-in-c14">Link to discussion</a></p>
7,767,340
change strength of antialiasing in matplotlib
<p>Is it possible to increase the antialiasing in matplotlib? I can still see some aliasing in my data, I tried several backends and it is still there. The antialiasing flag of the lines is set.</p> <p>Here you can see what I mean </p> <p><img src="https://i.stack.imgur.com/3UVnr.png" alt="enter image description here"></p> <p>It's a sample taken from a Screenshot. It's probably not the best example but I guess one can see the stairs in the line. It was taken with the wxagg backend.</p> <p>I'm using matplotlib version 1.01 with Windows 7.</p> <p>Update: I don't have the code which produced the previous picture anymore, but I still have the problem. Below is a simple code example which shows the aliasing.</p> <pre><code>import numpy as np import matplotlib matplotlib.use('wxAgg') import matplotlib.pyplot as pl print 'Backend:', pl.get_backend() x = np.linspace(0,6,100) y = np.sin(x) for a in range(10): pl.plot( x, a/10.*x, linewidth=1) pl.show() </code></pre> <p>It print's <code>Backend: WXAgg</code> And the resulting plot looks like the following. <img src="https://i.stack.imgur.com/J7mx1.png" alt="aliasing"></p> <p>Especially the lower red curve shows clear aliasing. </p>
9,089,343
2
8
null
2011-10-14 12:07:29.013 UTC
5
2013-11-07 01:38:43.273 UTC
2012-01-31 19:54:34.357 UTC
null
639,650
null
639,650
null
1
28
python|matplotlib|antialiasing
6,484
<p>The picture you added to your question is already perfectly anti-aliased. It doesn't get any better than this. Have a look at a zoomed version of the image:</p> <p><img src="https://i.stack.imgur.com/F6bYb.png" alt="Upscaled version of the image in question"></p>
8,363,325
using only part of an array
<p>I have a dynamically allocated array of float and I need to pass this array as an argument to three different functions but each function need to get a different range of the array. Is there some way I can send the array with elements 0 to 23 to one function, elements 24 to 38 to another, and elements 39 to 64 to a third function.</p> <p>In some languages(like python I think) you can do something like this:</p> <pre><code>somefunction(my_array[0:23]); somefunction(my_array[24:38]); somefunction(my_array[39:64]); </code></pre> <p>However I am using c++ and I am not aware of any way to do this in c++.</p> <p>Does anybody know how to do this?</p> <p>somefunction(); is a function from an API so I can not modify the arguments it takes.</p>
8,363,510
7
4
null
2011-12-02 22:10:34.49 UTC
5
2021-01-28 23:18:38.657 UTC
2011-12-03 00:14:43.84 UTC
null
950,456
null
950,456
null
1
14
c++|arrays
42,118
<p>The python example is making copies. If that's okay for your use case, you could do something like this (I'm swapping out your vanilla arrays for std::vector):</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; void somefunction(std::vector&lt;int&gt; v) { std::cout &lt;&lt; "vector has " &lt;&lt; v.size() &lt;&lt; " elements," &lt;&lt; " first value is " &lt;&lt; *v.begin() &lt;&lt; "," &lt;&lt; " last value is " &lt;&lt; *(v.end()-1) &lt;&lt; std::endl; } int main() { std::vector&lt;int&gt; a; for (int i=0; i&lt;65; i++) { a.push_back(i); } somefunction(std::vector&lt;int&gt;(a.begin(),a.begin()+23)); somefunction(std::vector&lt;int&gt;(a.begin()+24,a.begin()+38)); somefunction(std::vector&lt;int&gt;(a.begin()+39,a.begin()+65)); } </code></pre> <p>which outputs:</p> <pre><code>vector has 23 elements, first value is 0, last value is 22 vector has 15 elements, first value is 23, last value is 37 vector has 27 elements, first value is 38, last value is 64 </code></pre> <p>But it sounds like you can't use std::vector, because somefunction() has a signature you can't change. Luckily, you can do similar gymnastics just manually copying parts of the array, as below:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string.h&gt; void somefunction(int v[], int len) { std::cout &lt;&lt; "vector has " &lt;&lt; len &lt;&lt; " elements," &lt;&lt; " first value is " &lt;&lt; v[0] &lt;&lt; "," &lt;&lt; " last value is " &lt;&lt; v[len-1] &lt;&lt; std::endl; } int main() { int a[65]; for (int i=0; i&lt;65; i++) { a[i] = i; } int b[23]; memcpy(b, a, 23*sizeof(int)); somefunction(b, 23); int c[15]; memcpy(c, a+23, 15*sizeof(int)); somefunction(c, 15); int d[27]; memcpy(d, a+38, 27*sizeof(int)); somefunction(d, 27); } </code></pre> <p>which again outputs:</p> <pre><code>vector has 23 elements, first value is 0, last value is 22 vector has 15 elements, first value is 23, last value is 37 vector has 27 elements, first value is 38, last value is 64 </code></pre>
8,831,278
How do you get multiple arguments in Perl functions?
<p>In my code, I'm been using the fairly primitive method of extraction parameters from a function call as follows:</p> <pre><code>sub addSix ($$$$$$) { my ($a, $b, $c, $d, $e, $f) = (shift, shift, shift, shift, shift, shift); return $a + $b + $c + $d + $e + $f; } print addSix (1, 2, 3, 4, 5, 6) . "\n"; </code></pre> <p>(forget the primitive code, the salient bit is the multiple <code>shift</code> calls).</p> <p>Now that seems rather messy to me and I though Perl may have something like:</p> <pre><code>my ($a, $b, $c, $d, $e, $f) = shift (6); </code></pre> <p>or something similar.</p> <p>But I cannot find anything like that. I know I can use arrays for this but I think I'd still have to unpack the array into individual scalars. That wouldn't be too bad for the example case above, where the six parameters are similar, but I'm more interested in the case where they're not really suitable as an array.</p> <p>How can you extract parameters without ending up with a morass of <code>shift</code> keywords?</p>
8,831,290
3
4
null
2012-01-12 07:02:39.973 UTC
9
2017-01-09 11:42:42.163 UTC
2013-10-18 18:51:29.583 UTC
null
14,860
null
14,860
null
1
18
perl|shift
36,974
<p>You can simply type:</p> <pre><code>my ($a, $b, $c, $d, $e, $f) = (@_); </code></pre> <p>If you didn't have that prototype, and if that sub got called with more than six arguments, the ones after the sixth are simply "not matched", <code>$f</code> would be set to the sixth argument.</p> <p>If you want to catch all the arguments after the sixth, you can do it like this.</p> <pre><code>my ($a, $b, $c, $d, $e, $f, @others) = (@_); </code></pre> <p>If your list of scalars is longer than the list on the right side, the last elements will be <code>undef</code>.</p>
8,568,347
Razor intellisense error: Feature 'extension method' cannot be used because it is not part of the ISO-2 C# language specification
<p>Goal: </p> <ul> <li>Use cshtml <code>Razor</code> templates to format data</li> <li>Embed cshtml Razor templates in Class Library as <code>Embedded Resources</code></li> <li>Use <code>Linq</code> statements and extension methods in the cshtml template</li> </ul> <p>I created a new class library project, then adapted <a href="http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx" rel="noreferrer" title="Scott Hanselman&#39;s">Scott Hanselman's</a> instructions on how to integrate MVC3 into a WebForms application to get it to work in a Class Library. Then I use the NuGet package RazorEngine to apply the template to an object.</p> <p>So far it works great, with one hiccup: <em>The intellisense does not recognize Linq statements or extension methods</em> (a pretty important part of MVC) when editing cshtml files. </p> <p>So for the following cshtml file:</p> <pre><code>@model Customer[] @Model.Count() @if (Model.Where(customer =&gt; customer.Type == 'New').Any()) { &lt;span&gt;Found at least one new customer.&lt;/span&gt; } </code></pre> <p>...it displays the following errors:</p> <p><code>Feature 'extension method' cannot be used because it is not part of the ISO-2 C# language specification</code></p> <p><code>Feature 'lambda expression' cannot be used because it is not part of the ISO-2 C# language specification</code></p> <p><strong>Does anyone know what I'm missing?</strong> Thank you in advance--I've spent hours searching for the answer to this.</p> <hr> <h2>Some additional details</h2> <p>The following is my <code>web.config</code> in the <strong>Views</strong> folder:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"&gt; &lt;section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /&gt; &lt;section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;system.web.webPages.razor&gt; &lt;host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;pages pageBaseType="System.Web.Mvc.WebViewPage"&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web.webPages.razor&gt; &lt;appSettings&gt; &lt;add key="webpages:Enabled" value="false" /&gt; &lt;/appSettings&gt; &lt;system.web&gt; &lt;httpHandlers&gt; &lt;add path="*" verb="*" type="System.Web.HttpNotFoundHandler" /&gt; &lt;/httpHandlers&gt; &lt;pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"&gt; &lt;controls&gt; &lt;add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" /&gt; &lt;/controls&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;system.webServer&gt; ... &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>And I added a <code>web.config</code> file to the root of the project. It contains the following:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.0"&gt; &lt;assemblies&gt; &lt;add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;/assemblies&gt; &lt;/compilation&gt; ... &lt;pages&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Helpers" /&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="System.Web.WebPages" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web&gt; ... &lt;/configuration&gt; </code></pre> <p>And here are the references for the project:</p> <p><img src="https://i.stack.imgur.com/u8ubh.png" alt="Project References"></p> <p>The Class Library has a target framework of <code>.NET Framework 4</code> and under Advanced Build Settings, the Language Version is set to <code>C# 3.0</code>.</p> <h2>Update</h2> <p>The project builds and runs properly when using extension methods and Linq. It's just the intellisense that is throws the error.</p>
8,580,722
6
5
null
2011-12-19 22:20:35.287 UTC
10
2019-05-29 14:36:44.843 UTC
2011-12-20 02:40:15.643 UTC
null
386,806
null
386,806
null
1
32
c#|visual-studio-2010|asp.net-mvc-3|razor
18,814
<p>After a couple hours more of tinkering, I found it had something to do with standard Visual Studio extensions not loading correctly. </p> <p>I was receiving the error: </p> <blockquote> <p>'VSTS for Database Professionals Sql Server Data-tier Application' package did not load correctly</p> </blockquote> <p>I found the answer on <a href="http://connect.microsoft.com/VisualStudio/feedback/details/532121/tons-of-package-did-not-load-correctly-errors" rel="nofollow" title="here">on Microsoft Connect</a>. </p> <p><strong>How to fix</strong></p> <p>1) Run the following installers from the Visual Studio media: </p> <blockquote> <p>\WCU\DAC\DACFramework_enu.msi</p> <p>\WCU\DAC\DACProjectSystemSetup_enu.msi</p> <p>\WCU\DAC\TSqlLanguageService_enu.msi</p> </blockquote> <p>2) Restart VS</p> <p>Hope this can be of help to someone else.</p>
5,160,362
PHP fopen() not creating file if it doesn't already exist
<p>As part of application logging, I'm attempting to open a local file, and if that file doesn't already exist, to create the new one. Here's what I have:</p> <pre><code>$path = '/home/www/phpapp/logs/myawesome_logfile.txt'; $f = (file_exists($path))? fopen($path, "a+") : fopen($path, "w+"); fwrite($f, $msg); fclose($f); chmod($path, 0777); </code></pre> <p>I've double-checked, and the <code>/logs</code> directory is chmod 0777, and I even went the extra step of chown'ing it to apache:apache for good measure. Still, when the script goes to open the file, it gives me the warning that the file doesn't exist and bombs out. No file is ever created.</p> <p>Do I need to suppress the <code>fopen()</code> warning to get it to create the file?</p>
5,160,423
6
3
null
2011-03-01 21:08:06.303 UTC
8
2018-09-17 20:51:45.37 UTC
2012-12-24 00:46:39.213 UTC
null
367,456
null
77,972
null
1
25
php
77,904
<p>When you're working with paths in PHP, the context can matter a great deal. If you're working with urls in a redirection context -- then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives. </p> <p>However, when you're dealing with file system commands such as <code>fopen</code>, the root directory ('/') is the system root. Not your domain root. </p> <p>To fix this, try giving the full path to the log file you want to open from the system root. For example: <code>/var/www/phpapplication/logs/myLogFile.txt</code></p> <p>Or you could use <code>$_SERVER['DOCUMENT_ROOT']</code> as suggested in other answers to access your server's stored value for the path to the document root. The <code>/var/www</code> part. </p> <p>You can also use the <code>__DIR__</code> magic constant in some cases. Note that <code>__DIR__</code> will be the directory the current file is in, which is not necessarily the same as your application's root. So for example, if your application's root is <code>/var/www/application</code> and you're working in <code>/var/www/application/src/controllers/my_controller.php</code>, then <code>__DIR__</code> will be <code>/var/www/application/src/controllers</code>. <a href="http://php.net/manual/en/language.constants.predefined.php" rel="noreferrer">See here in the PHP documentation.</a></p>
5,175,728
How to get the current date/time in Java
<p>What's the best way to get the current date/time in Java?</p>
5,175,900
28
4
null
2011-03-03 01:48:09.583 UTC
204
2021-02-08 10:48:27.72 UTC
2018-05-03 05:44:17.203 UTC
null
617,450
null
496,949
null
1
807
java|datetime
2,132,745
<p>It depends on what form of date / time you want:</p> <ul> <li><p>If you want the date / time as a single numeric value, then <code>System.currentTimeMillis()</code> gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java <code>long</code>). This value is a delta from a UTC time-point, and is independent of the local time-zone<sup>1</sup>.</p> </li> <li><p>If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:</p> <ul> <li><p><code>new Date()</code> gives you a <code>Date</code> object initialized with the current date / time. The problem is that the <code>Date</code> API methods are mostly flawed ... and deprecated.</p> </li> <li><p><code>Calendar.getInstance()</code> gives you a <code>Calendar</code> object initialized with the current date / time, using the default <code>Locale</code> and <code>TimeZone</code>. Other overloads allow you to use a specific <code>Locale</code> and/or <code>TimeZone</code>. Calendar works ... but the APIs are still cumbersome.</p> </li> <li><p><code>new org.joda.time.DateTime()</code> gives you a <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-time</a> object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. <a href="https://stackoverflow.com/questions/6280829.">https://stackoverflow.com/questions/6280829.</a>)</p> </li> <li><p>in Java 8, calling <code>java.time.LocalDateTime.now()</code> and <code>java.time.ZonedDateTime.now()</code> will give you representations<sup>2</sup> for the current date / time.</p> </li> </ul> </li> </ul> <p>Prior to Java 8, most people who know about these things recommended <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-time</a> as having (by far) the best Java APIs for doing things involving time point and duration calculations.</p> <p>With Java 8 and later, the standard <code>java.time</code> package is recommended. Joda time is now considered &quot;obsolete&quot;, and the Joda maintainers are recommending that people migrate.<sup>3</sup>.</p> <hr /> <p><sup>1 - <code>System.currentTimeMillis()</code> gives the &quot;system&quot; time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.<br> 2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: <em>&quot;It cannot represent an instant on the time-line without additional information such as an offset or time-zone.&quot;</em><br> 3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official &quot;end of life&quot; for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.</sup></p>
29,673,336
iOS 8.3: UIActivityViewController shows extraneous row
<p>I have a <code>UIActivityViewController</code> for which I have excluded (using <code>excludedActivityTypes</code>) all the <code>UIActivityCategoryAction</code> activity types.</p> <p>In iOS 8.2, the <code>UIActivityViewController</code> would only show one line, for the <code>UIActivityCategoryShare</code> activity types.</p> <p>In iOS 8.3, I get an empty line for <code>UIActivityCategoryAction</code>. See the screenshot below where the second line just has "More".</p> <p>How can I remove the <code>UIActivityCategoryAction</code> in a <code>UIActivityViewController</code> in iOS 8.3?</p> <p><img src="https://i.stack.imgur.com/PadJV.png" alt="enter image description here"></p>
30,329,385
5
8
null
2015-04-16 11:29:16.523 UTC
2
2017-04-14 10:17:52.863 UTC
2015-05-06 11:20:51.22 UTC
null
707,381
null
707,381
null
1
39
ios|uiactivityviewcontroller|ios8.3
3,502
<blockquote> <p>In iOS 8, UIActivityViewController is still an API that only provides custom functions, but not custom UI. You can't change the way it looks. The only part of the visual style you can change is the icon of your custom UIActivity subclasses. (<a href="http://getnotebox.com/developer/uiactivityviewcontroller-ios-8/" rel="nofollow noreferrer">ref</a>)</p> </blockquote> <p>This is how Apple implements this, and it cannot be changed as of 8.3. If you really want to avoid the extra row and the "More" button, you can implement a UIActivityViewController replacement. Here are a couple that have been recently maintained:</p> <hr> <h2><a href="https://github.com/overshare/overshare-kit" rel="nofollow noreferrer">OvershareKit</a></h2> <p><img src="https://i.stack.imgur.com/3Qn3U.png" alt="OvershareKit"></p> <hr> <h2><a href="https://github.com/urbn/URBNShareKit" rel="nofollow noreferrer">URBNShareKit</a></h2> <p><img src="https://i.stack.imgur.com/fg4Pj.png" alt="URBNShareKit"></p> <hr> <p><strong>References:</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/29333055/uiactivityviewcontroller-hide-more-from-actions">UIActivityViewController Hide More from Actions</a></li> <li><a href="https://stackoverflow.com/questions/25904740/uiactivityviewcontroller-on-ios-8-show-more-button-with-custom-activities">UIActivityViewController on iOS 8 show &quot;more&quot; button with custom activities</a></li> <li><a href="https://stackoverflow.com/questions/28672773/can-i-exclude-more-button-in-uiactivityviewcontroller">Can I exclude &quot;More&quot; Button in UIActivityViewController?</a></li> <li><a href="http://getnotebox.com/developer/uiactivityviewcontroller-ios-8/" rel="nofollow noreferrer">http://getnotebox.com/developer/uiactivityviewcontroller-ios-8/</a></li> </ul>
29,718,833
Why window onscroll event does not work?
<p>I want to execute the window <code>onscroll</code> event, but I don't know why it doesn't work on all browsers(firefox, chrome, etc), and there is no errors occurred. </p> <p><strong>Full code:</strong> <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var elem = document.getElementById('repeat'); var show = document.getElementById('show'); for (i = 1; i &lt;= 300; i++) { elem.innerHTML += i + "&lt;br/&gt;"; } window.onscroll = function () { show.innerHTML = document.body.scrollTop; };</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#show { display:block; position:fixed; top:0px; left:300px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre id="repeat"&gt;&lt;/pre&gt; &lt;div style="position:relative;"&gt; &lt;div id="show"&gt;x&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Also jsfiddle: <a href="http://jsfiddle.net/sqo0140j" rel="noreferrer">http://jsfiddle.net/sqo0140j</a></p> <p><strong>What is the problem ?</strong></p>
29,719,278
6
11
null
2015-04-18 14:48:27.5 UTC
2
2021-12-20 13:53:53.13 UTC
2015-04-18 15:06:55.257 UTC
null
459,943
null
459,943
null
1
10
javascript|events|onscroll
57,360
<p>You said something interesting:</p> <blockquote> <p>x changed to 0 and remains as is.</p> </blockquote> <p>The only way in your code that can happen is if the <code>onscroll</code> function block makes a change because your HTML sets x.</p> <p>If your <code>window.onscroll = function()</code> is indeed firing, but you are not getting the right scroll position (i.e. 0), try changing the way the scroll position is returned:</p> <pre><code>window.onscroll = function () { show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop; }; </code></pre> <p>I found out that <code>document.documentElement.scrollTop</code> always returns 0 on Chrome. This is because WebKit uses <code>body</code> for keeping track of scrolling, but Firefox and IE use <code>html</code>.</p> <p>Please try your updated snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var elem = document.getElementById('repeat'); var show = document.getElementById('show'); for (i = 1; i &lt;= 300; i++) { elem.innerHTML += i + "&lt;br/&gt;"; } window.onscroll = function () { show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop; };</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#show { display:block; position:fixed; top:0px; left:300px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre id="repeat"&gt;&lt;/pre&gt; &lt;div style="position:relative;"&gt; &lt;div id="show"&gt;x&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
12,507,016
Load properties file in Servlet/JSP
<p>I've created a <code>jar</code> from my <code>Java project</code> and wanted to use the same jar in a <code>JSP Servlet Project</code>. I'm trying to load a property file let say sample.properties from my <code>JSP Servlet Project</code> kept in <code>WEB/properties/sample.properties</code> which should be read by a class in the <code>jar</code>.I'm using the following code wriiten in a class of jar to access it.</p> <pre><code>Properties prop=new Properties(); prop.load(/WEB-INF/properties/sample.properties); </code></pre> <p>But each time I'm getting <code>fileNotFound exception</code>.<br> Please suggest me the solution.</p> <p>Here is the structure</p> <pre><code>WEB-INF | lib | myproject.jar | myclass (This class needs to read sample.properties) | properties |sample.properties </code></pre>
12,523,396
5
1
null
2012-09-20 06:19:40.867 UTC
5
2012-09-21 06:50:37.863 UTC
2012-09-20 06:54:31.727 UTC
null
1,289,817
null
1,289,817
null
1
6
java|jsp|servlets|properties
57,657
<p>The <code>/WEB-INF</code> folder is <strong>not</strong> part of the classpath. So any answer here which is thoughtless suggesting <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29" rel="noreferrer"><code>ClassLoader#getResourceAsStream()</code></a> will <strong>never</strong> work. It would only work if the properties file is placed in <code>/WEB-INF/classes</code> which is indeed part of the classpath (in an IDE like Eclipse, just placing it in Java source folder root ought to be sufficient).</p> <p>Provided that the properties file is really there where you'd like to keep it, then you should be getting it as web content resource by <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream%28java.lang.String%29" rel="noreferrer"><code>ServletContext#getResourceAsStream()</code></a> instead.</p> <p>Assuming that you're inside a <code>HttpServlet</code>, this should do:</p> <pre><code>properties.load(getServletContext().getResourceAsStream(&quot;/WEB-INF/properties/sample.properties&quot;)); </code></pre> <p><em>(the <code>getServletContext()</code> is inherited from the servlet superclass, you don't need to implement it yourself; so the code is as-is)</em></p> <p>But if the class is by itself not a <code>HttpServlet</code> at all, then you'd really need to move the properties file into the classpath.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/2161054/where-to-place-configuration-properties-files-in-a-jsp-servlet-web-application/2161583#2161583">Where to place and how to read configuration resource files in servlet based application?</a></li> </ul>
12,291,573
MYSQL cursor loop, runs one extra round, why?
<p>I'm looping through a cursor result set in a MYSQL stored procedure. I'm facing an issue which is that the loop always run thorough the last record twice. Here is my code,</p> <pre><code>BEGIN DECLARE not_found_creadit INT DEFAULT 0; DECLARE cur_credit CURSOR FOR SELECT customer_id, amount, status, user_type, employee, note FROM credit WHERE status = 'approved' AND customer_id = int_cust_id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found_creadit = 1; OPEN cur_credit; SET not_found_creadit = 0; credit_loop : LOOP IF not_found_creadit THEN CLOSE cur_credit; LEAVE credit_loop; END IF; FETCH cur_credit INTO vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note; SELECT vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note; ...... ...... END LOOP; END; </code></pre> <p>Means if I have 3 records, loop runs 4 times, if it is 10 records loop runs 11 times, etc. Any idea whats happening here?</p>
12,291,719
2
0
null
2012-09-06 00:43:26.937 UTC
8
2021-12-23 16:00:10.893 UTC
2021-12-23 16:00:10.893 UTC
null
4,294,399
null
1,228,293
null
1
17
mysql|loops|stored-procedures|database-cursor
11,355
<p>The handler, which sets <code>not_found_creadit = 1</code>, is fired when the <code>FETCH</code> returns no rows, but you are checking its value <em>before</em> executing <code>FETCH</code>, so the main body of your loop will execute one extra time when the <code>FETCH</code> fails, then the loop loop exits at the start of the <em>next</em> iteration.</p> <p>Rearrange your code to check the value of your variable immediately <em>after</em> the <code>FETCH</code>:</p> <pre><code>credit_loop : LOOP FETCH cur_credit INTO vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note; IF not_found_creadit THEN CLOSE cur_credit; LEAVE credit_loop; END IF; SELECT vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note; ...... ...... END LOOP; </code></pre> <p><br/></p> <p>Also, consider correcting the spelling of your variable to <code>not_found_credit</code></p>
12,259,331
for loop for multiple extension and do something with each file
<p>I'm trying to write a for loop in bash to get the files with extension of jpg, jpeg, png, this i my attempt, but does not work</p> <pre><code>for file in "${arg}"/*.{jpg,jpeg,png}; do echo ${arg}-something.jpg &gt; z.txt ; done; </code></pre> <p>basically, i want to get the name of the file with those extension in the current folder, and do something with each file, then output the filename back with a new extension.</p>
12,259,376
2
1
null
2012-09-04 08:14:42.787 UTC
10
2016-12-14 09:49:15.21 UTC
null
null
null
null
787,171
null
1
18
bash
16,997
<p>You are not using <code>$file</code> anywhere. Try</p> <pre><code>for file in "$arg"/*.{jpg,jpeg,png} ; do echo "$file" &gt; z.txt done </code></pre>
12,125,277
How to read several (file) inputs with the same name from a multipart form with Jersey?
<p>I have successfully developed a service, in which I read files uploaded in a multipart form in Jersey. Here's an extremely simplified version of what I've been doing:</p> <pre><code>@POST @Path("FileCollection") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException { //handle the file } </code></pre> <p>This works just fine but I've been given a new requirement. In addition to the file I'm uploading, I have to handle an arbitrary number of resources. Let's assume these are image files.</p> <p>I figured I'd just provide the client with a form with one input for the file, one input for the first image and a button to allow adding more inputs to the form (using AJAX or simply plain JavaScript).</p> <pre><code>&lt;form action="blahblahblah" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" /&gt; &lt;input type="file" name="image" /&gt; &lt;input type="button" value="add another image" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>So the user can append the form with more inputs for images, like this:</p> <pre><code>&lt;form action="blahblahblah" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" /&gt; &lt;input type="file" name="image" /&gt; &lt;input type="file" name="image" /&gt; &lt;input type="file" name="image" /&gt; &lt;input type="button" value="add another image" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>I hoped it would be simple enough to read the fields with the same name as a collection. I've done it successfully with text inputs in MVC .NET and I thought it wouldn't be harder in Jersey. It turns out I was wrong.</p> <p>Having found no tutorials on the subject, I started experimenting. </p> <p>In order to see how to do it, I dumbed the problem down to simple text inputs.</p> <pre><code>&lt;form action="blahblabhblah" method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;legend&gt;Multiple inputs with the same name&lt;/legend&gt; &lt;input type="text" name="test" /&gt; &lt;input type="text" name="test" /&gt; &lt;input type="text" name="test" /&gt; &lt;input type="text" name="test" /&gt; &lt;input type="submit" value="Upload It" /&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>Obviously, I needed to have some sort of collection as a parameter to my method. Here's what I tried, grouped by collection type.</p> <h2>Array</h2> <p>At first, I checked whether Jersey was smart enough to handle a simple array:</p> <pre><code>@POST @Path("FileCollection") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(@FormDataParam("test") String[] inputs) { //handle the request } </code></pre> <p>but the array wasn't injected as expected.</p> <h2>MultiValuedMap</h2> <p>Having failed miserably, I remembered that <code>MultiValuedMap</code> objects could be handled out of the box. </p> <pre><code>@POST @Path("FileCollection") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(MultiValuedMap&lt;String, String&gt; formData) { //handle the request } </code></pre> <p>but it doesn't work either. This time, I got an exception</p> <pre><code>SEVERE: A message body reader for Java class javax.ws.rs.core.MultivaluedMap, and Java type javax.ws.rs.core.MultivaluedMap&lt;java.lang.String, java.lang.String&gt;, and MIME media type multipart/form-data; boundary=----WebKitFormBoundaryxgxeXiWk62fcLALU was not found. </code></pre> <p>I was told that this exception could be gotten rid of by including the <code>mimepull</code> library so I added the following dependency to my pom:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.jvnet&lt;/groupId&gt; &lt;artifactId&gt;mimepull&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Unfortunately the problem persists. It's probably a matter of choosing the right body reader and using different parameters for the generic. I'm not sure how to do this. I want to consume both file and text inputs, as well as some others (mostly <code>Long</code> values and custom parameter classes).</p> <h2>FormDataMultipart</h2> <p>After some more research, I found the <a href="http://jersey.java.net/nonav/apidocs/1.8/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataMultiPart.html" rel="noreferrer">FormDataMultiPart</a> class. I've successfully used it to extract the string values from my form</p> <pre><code>@POST @Path("upload2") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadMultipart(FormDataMultiPart multiPart){ List&lt;FormDataBodyPart&gt; fields = multiPart.getFields("test"); System.out.println("Name\tValue"); for(FormDataBodyPart field : fields){ System.out.println(field.getName() + "\t" + field.getValue()); //handle the values } //prepare the response } </code></pre> <p>The problem is, this is a solution to the simplified version of my problem. While I know that every single parameter injected by Jersey is created by parsing a string at some point (no wonder, it's HTTP after all) and I have some experience writing my own parameter classes, I don't really how to convert these fields to <code>InputStream</code> or <code>File</code> instances for further processing.</p> <p>Therefore, before diving into Jersey source code to see how these objects are created, I decided to ask here whether there is an easier way to read a set (of unknown size) of files. Do you know how to solve this conundrum?</p>
12,177,926
3
0
null
2012-08-25 20:08:52.47 UTC
18
2015-05-07 16:58:39.127 UTC
null
null
null
null
1,407,656
null
1
24
java|forms|jersey|jax-rs|multipart
20,715
<p>I have found the solution by following the example with <code>FormDataMultipart</code>. It turns out I was very close to the answer.</p> <p>The <code>FormDataBodyPart</code> class provides a method that allows its user to read the value as <code>InputStream</code> (or theoretically, any other class, for which a message body reader is present).</p> <p>Here's the final solution:</p> <h2>Form</h2> <p>The form remains unchanged. I have a couple of fields with the same name, in which I can place files. It's possible to use both <a href="http://www.w3.org/TR/html-markup/input.file.html#input.file.attrs.multiple"><code>multiple</code></a> form inputs (you want these when uploading many files from a directory) and numerous inputs that share a name (Flexible way to upload an unspecified number of files from different location). It's also possible to append the form with more inputs using JavaScript.</p> <pre><code>&lt;form action="/files" method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;legend&gt;Multiple inputs with the same name&lt;/legend&gt; &lt;input type="file" name="test" multiple="multiple"/&gt; &lt;input type="file" name="test" /&gt; &lt;input type="file" name="test" /&gt; &lt;/fieldset&gt; &lt;input type="submit" value="Upload It" /&gt; &lt;/form&gt; </code></pre> <h2>Service - using <a href="http://jersey.java.net/nonav/apidocs/1.5/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataMultiPart.html"><code>FormDataMultipart</code></a></h2> <p>Here's a simplified method that reads a collection of files from a multipart form. All inputs with the same are assigned to a <code>List</code> and their values are converted to <code>InputStream</code> using the <a href="http://jersey.java.net/nonav/apidocs/1.1.4/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataBodyPart.html#getValueAs%28java.lang.Class%29"><code>getValueAs</code></a> method of <a href="http://jersey.java.net/nonav/apidocs/1.1.4/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataBodyPart.html"><code>FormDataBodyPart</code></a>. Once you have these files as <code>InputStream</code> instances, it's easy to do almost anything with them. </p> <pre><code>@POST @Path("files") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException{ List&lt;FormDataBodyPart&gt; fields = multiPart.getFields("test"); for(FormDataBodyPart field : fields){ handleInputStream(field.getValueAs(InputStream.class)); } //prepare the response } private void handleInputStream(InputStream is){ //read the stream any way you want } </code></pre>
3,245,265
how to set border color of a texbox using jquery
<p>How to set a default border color of a control using jquery.</p> <pre><code> if (_userName.val().trim() == "") { errMsg += "\nUserName is a mandatory field."; _userName.css('border-color', 'red'); } else { _userName.css('border-color', 'red');//Set border-color as loaded //when page was loaded } </code></pre> <p>How to Set border-color as loaded when page was loaded.</p>
3,245,290
4
0
null
2010-07-14 10:32:04.33 UTC
null
2010-07-14 12:44:53.593 UTC
null
null
null
null
203,262
null
1
7
javascript|jquery|css
48,200
<p>Get the border color at page load and store in a variable:</p> <pre><code>$(function(){ var color = _userName.css('border-color'); }); </code></pre> <p>And then you can use it later:</p> <pre><code> if (_userName.val().trim() == "") { errMsg += "\nUserName is a mandatory field."; _userName.css('border-color', color); } else { _userName.css('border-color', color); } </code></pre> <p>Also make sure that there is a border at least eg <code>border:1px solid #colorcode</code></p>
3,418,268
Script (or some other means) to convert RGB to CMYK in PDF?
<p>Is it possible to write a script for Adobe Illustrator or some other tool that will read the contents of a number of PDF files and convert all the RGB colours to CMYK?</p> <p>If so, could somebody please point out some of the steps involved, or where to find more information on this?</p>
3,423,503
4
0
null
2010-08-05 19:10:10.313 UTC
12
2017-11-07 10:58:07.49 UTC
2011-12-19 21:52:26.503 UTC
null
359,307
null
181,771
null
1
14
pdf|rgb|ghostscript|adobe-illustrator|cmyk
13,856
<p>This answer is not for Illustrator, but for <em>'some other tool'</em>, namely <a href="http://ghostscript.com/releases/" rel="noreferrer">Ghostscript</a> (download <code>gs871w32.exe</code> or <code>gs871w64.exe</code>).</p> <p>Ghostscript allows you to 're-distill' PDFs (<strong><em>without</em></strong> an intermediate conversion to PostScript, the dreaded 'refrying' detour). Try this command:</p> <pre><code>gswin32c.exe ^ -o c:/path/to/output-cmyk.pdf ^ -sDEVICE=pdfwrite ^ -dUseCIEColor ^ -sProcessColorModel=DeviceCMYK ^ -sColorConversionStrategy=CMYK ^ -sColorConversionStrategyForImages=CMYK ^ input-rgb.pdf </code></pre> <p>And if you are able to wait for a few more weeks, Ghostscript 9.00 will be released. This new version will sport support of colormanagement (based on LCMS) with ICC profiles for the first time ever...</p> <p><strong>UPDATE:</strong> I updated above command because I missed to put in the option to also convert images.</p> <hr> <h3>Update 2</h3> <p>If color conversion does not work as desired and if you see a message like <em>"Unable to convert color space to Gray, reverting strategy to LeaveColorUnchanged"</em> then...</p> <ol> <li>your Ghostscript probably is a newer release from the <em>9.x version series</em>, and</li> <li>your source PDF likely uses an embedded <em>ICC color profile</em></li> </ol> <p>In this case add <strong><code>-dOverrideICC</code></strong> to the command line and see if it changes the result as desired.</p>