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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
573,825 | How to cultivate algorithm intuition? | <p>When faced with a problem in software I usually see a solution right away. Of course, what I see is usually somewhat off, and I always need to sit down and design (admittedly, I usually don't design enough), but I get a certain <strong><em>intuition</em></strong> right away.</p>
<p>My problem is I don't get that same intuition when it comes to advanced algorithms. I feel much more up to the task of building another <a href="http://www.facebook.com" rel="noreferrer">Facebook</a> then building another <a href="http://www.google.com" rel="noreferrer">Google</a> search, or a <a href="http://www.pandora.com/mgp.shtml" rel="noreferrer">Music Genom project</a>. It's probably because I've been <em>building</em> software for quite some time, but I have little experience with <em>composing</em> algorithms.</p>
<p><strong>I would like the community's advice on what to read and what projects to undertake to be better at composing algorithms.</strong></p>
<p>(This question has nothing to do with <a href="http://en.wikipedia.org/wiki/Algorithmic_composition" rel="noreferrer">Algorithmic composition</a>. Well, almost nothing)</p> | 573,967 | 6 | 0 | null | 2009-02-21 22:18:11.05 UTC | 16 | 2019-01-13 11:00:02.52 UTC | null | null | null | Asaf R | 6,827 | null | 1 | 20 | algorithm | 2,691 | <p>+1 To whoever said experience is the best teacher.</p>
<p>There are several online portals which have a lot of programming problems, that you can submit your own solutions to, and get an automated pass/fail indication.</p>
<ol>
<li><a href="http://www.spoj.pl/" rel="nofollow noreferrer">http://www.spoj.pl/</a></li>
<li><a href="http://uva.onlinejudge.org/" rel="nofollow noreferrer">http://uva.onlinejudge.org/</a></li>
<li><a href="http://www.topcoder.com/tc" rel="nofollow noreferrer">http://www.topcoder.com/tc</a></li>
<li><a href="http://code.google.com/codejam/contests.html" rel="nofollow noreferrer">http://code.google.com/codejam/contests.html</a></li>
<li><a href="http://projecteuler.net/" rel="nofollow noreferrer">http://projecteuler.net/</a></li>
<li><a href="https://codeforces.com" rel="nofollow noreferrer">https://codeforces.com</a></li>
<li><a href="https://leetcode.com" rel="nofollow noreferrer">https://leetcode.com</a></li>
</ol>
<p>The <a href="http://train.usaco.org/usacogate" rel="nofollow noreferrer">USACO training site</a> is the training program that all USA computing olympiad participants go through. It goes step by step, introducing more and more complex algorithms as you go.</p> |
1,230,854 | Objective C - Why do constants start with k | <p>Why do constants in all examples I've seen always start with k? And should I #define constants in header or .m file?</p>
<p>I'm new to Objective C, and I don't know C. Is there some tutorial somewhere that explains these sorts of things without assuming knowledge of C?</p> | 1,230,863 | 6 | 1 | null | 2009-08-05 02:14:04.803 UTC | 9 | 2017-11-22 15:47:01.03 UTC | 2016-04-13 06:47:39.197 UTC | null | 148,195 | null | 148,195 | null | 1 | 45 | objective-c|naming-conventions|constants | 17,010 | <p>Starting constants with a "k" is a legacy of the pre-Mac OS X days. In fact, I think the practice might even come from <em>way</em> back in the day, when the Mac OS was written mostly in Pascal, and the predominant development language was Pascal. In C, <code>#define</code>'d constants are typically written in ALL CAPS, rather than prefixing with a "k".</p>
<p>As for where to <code>#define</code> constants: <code>#define</code> them where you're going to use them. If you expect people who <code>#import</code> your code to use the constants, put them in the header file; if the constants are only going to be used internally, put them in the <code>.m</code> file.</p> |
122,388 | How would you implement MVC in a Windows Forms application? | <p>I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.</p>
<p>Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?</p> | 122,565 | 6 | 1 | null | 2008-09-23 17:16:24.813 UTC | 34 | 2018-01-19 23:43:10.32 UTC | 2015-05-04 04:13:11.86 UTC | null | 63,550 | Chris Pietschmann | 7,831 | null | 1 | 68 | winforms|model-view-controller | 71,084 | <p>What I've done in the past is use something similar, <a href="http://download.microsoft.com/download/3/a/7/3a7fa450-1f33-41f7-9e6d-3aa95b5a6aea/MSDNMagazineAugust2006en-us.chm" rel="noreferrer">Model-View-Presenter</a>.</p>
<p>[NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! <em>sigh</em>]</p>
<p>The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results.</p>
<p>If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way:</p>
<ul>
<li>The form is the <strong>view</strong>. It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model.</li>
<li>The <strong>controller</strong> is a class that subscribes to the view's events and sends commands to the view and to the model.</li>
<li>The <strong>model</strong> raises events that the view subscribes to.</li>
</ul>
<p>This would fit with <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="noreferrer">the classic MVC diagram</a>. The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.</p> |
436,276 | Configuring Hibernate logging using Log4j XML config file? | <p>I haven't been able to find any documentation on how to configure Hibernate's logging using the XML style configuration file for Log4j.</p>
<p>Is this even possible or do I have use a properties style configuration file to control Hibernate's logging?</p>
<p>If anyone has any information or links to documentation it would appreciated.</p>
<p><strong>EDIT:</strong><br/>
Just to clarify, I am looking for an example of the actual XML syntax to control Hibernate.</p>
<p><strong>EDIT2:</strong><br/>
Here is what I have in my XML config file.</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="info"/>
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="rolling-file" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="Program-Name.log"/>
<param name="MaxFileSize" value="1000KB"/>
<!-- Keep one backup file -->
<param name="MaxBackupIndex" value="4"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %l - %m%n"/>
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="console" />
<appender-ref ref="rolling-file" />
</root>
</log4j:configuration>
</code></pre>
<p>Logging works fine but I am looking for a way to step down and control the hibernate logging in way that separate from my application level logging, as it currently is flooding my logs. I have found examples of using the preference file to do this, I was just wondering how I can do this in a XML file.</p> | 436,687 | 6 | 3 | null | 2009-01-12 17:40:33.69 UTC | 71 | 2015-03-27 19:28:12.203 UTC | 2011-04-08 14:38:34.327 UTC | nemo | 20,774 | nemo | 20,774 | null | 1 | 89 | xml|hibernate|logging|configuration|log4j | 183,109 | <p>From <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging" rel="noreferrer">http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging</a></p>
<p>Here's the list of logger categories:</p>
<pre><code>Category Function
org.hibernate.SQL Log all SQL DML statements as they are executed
org.hibernate.type Log all JDBC parameters
org.hibernate.tool.hbm2ddl Log all SQL DDL statements as they are executed
org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache Log all second-level cache activity
org.hibernate.transaction Log transaction related activity
org.hibernate.jdbc Log all JDBC resource acquisition
org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing
org.hibernate.secure Log all JAAS authorization requests
org.hibernate Log everything (a lot of information, but very useful for troubleshooting)
</code></pre>
<p>Formatted for pasting into a log4j XML configuration file:</p>
<pre><code><!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />
</code></pre>
<p>NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.</p>
<p>And a category is specified as such:</p>
<pre><code><logger name="org.hibernate">
<level value="ALL" />
<appender-ref ref="FILE"/>
</logger>
</code></pre>
<p>It must be placed before the root element.</p> |
429,470 | Naming conventions for abstract classes | <p>I distinctly remember that, at one time, the guideline pushed by Microsoft was to add the "Base" suffix to an abstract class to obviate the fact that it was abstract. Hence, we have classes like <code>System.Web.Hosting.VirtualFileBase</code>, <code>System.Configuration.ConfigurationValidatorBase</code>, <code>System.Windows.Forms.ButtonBase</code>, and, of course, <code>System.Collections.CollectionBase</code>.</p>
<p>But I've noticed that, of late, a lot of abstract classes in the Framework don't seem to be following this convention. For example, the following classes are all abstract but don't follow this convention:</p>
<ul>
<li><p><code>System.DirectoryServices.ActiveDirectory.DirectoryServer</code></p>
</li>
<li><p><code>System.Configuration.ConfigurationElement</code></p>
</li>
<li><p><code>System.Drawing.Brush</code></p>
</li>
<li><p><code>System.Windows.Forms.CommonDialog</code></p>
</li>
</ul>
<p>And that's just what I could drum up in a few seconds. So I went looking up what the official documentation had to say, to make sure I wasn't crazy. I found the <a href="http://msdn.microsoft.com/en-us/library/ms229040.aspx" rel="noreferrer">Names of Classes, Structs, and Interfaces</a> on MSDN at <a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" rel="noreferrer">Design Guidelines for Developing Class Libraries</a>. Oddly, I can find no mention of the guideline to add "Base" to the end of an abstract class's name. And the guidelines are no longer available for version 1.1 of the Framework.</p>
<p>So, am I losing it? Did this guideline ever exist? Has it just been abandoned without a word? Have I been creating long class names all by myself for the last two years for nothing?</p>
<p>Someone throw me a bone here.</p>
<p><strong>Update</strong>
I'm not crazy. The guideline existed. <a href="https://docs.microsoft.com/en-us/archive/blogs/kcwalina/i-dont-like-the-base-suffix" rel="noreferrer">Krzysztof Cwalina gripes about it in 2005.</a></p> | 429,494 | 6 | 2 | null | 2009-01-09 19:56:12.73 UTC | 12 | 2022-09-13 15:41:25.49 UTC | 2021-08-09 16:21:27.277 UTC | Mike Hofer | 88,709 | Mike Hofer | 47,580 | null | 1 | 112 | .net|naming-conventions|abstract-class | 37,739 | <p>In <a href="http://www.amazon.co.uk/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756/ref=sr_1_2?ie=UTF8&qid=1231531546&sr=8-2" rel="noreferrer">Framework Design Guidelines</a> p 174 states:</p>
<blockquote>
<p><strong>Avoid</strong> naming base classes with a "Base" suffix if the class is intended for use in public APIs.</p>
</blockquote>
<p>Also : <a href="http://blogs.msdn.com/kcwalina/archive/2005/12/16/BaseSuffix.aspx" rel="noreferrer">http://blogs.msdn.com/kcwalina/archive/2005/12/16/BaseSuffix.aspx</a></p> |
42,222,096 | No module named packaging | <p>I work on Ubuntu 14. I install python3 and pip3.
When I try to use pip3, I have this error</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/pip3", line 6, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 70, i
n <module>
import packaging.version
ImportError: No module named 'packaging'
</code></pre>
<p>Does someone know what is the issue?</p>
<p>Many thanks</p> | 42,225,189 | 4 | 4 | null | 2017-02-14 09:18:01.113 UTC | 6 | 2022-04-16 22:46:04.543 UTC | 2017-02-14 11:13:04.193 UTC | null | 3,374,996 | null | 6,454,030 | null | 1 | 19 | python|python-3.x|ubuntu|pip | 53,323 | <p>If I understand well, the issue that causes confusion in other's replies is that you have an error while running pip itself, which prevents self-updates of pip or installation of the missing package.</p>
<p>As requested, please state <em>exactly</em> how you installed Python 3 and pip. Ubuntu 14 does not come with Python 3.5.</p>
<p>For diagnosis, please give the output of</p>
<pre><code>which python3
</code></pre>
<p>that is probably <code>/usr/bin/python3</code> and refers to the system-wide python3 while your pip is located in <code>/usr/local/bin/pip3</code>.</p>
<p>Suggested solution: Uninstall system pip with <code>apt-get remove python3-pip</code> and try again with either <code>pip3</code> or <code>python3.5 -m pip</code>.</p> |
39,357,887 | What does a && operator do when there is no left side in C? | <p>I saw a program in C that had code like the following:</p>
<pre><code>static void *arr[1] = {&& varOne,&& varTwo,&& varThree};
varOne: printf("One") ;
varTwo: printf("Two") ;
varThree: printf("Three") ;
</code></pre>
<p>I am confused about what the <code>&&</code> does because there is nothing to the left of it. Does it evaluate as null by default? Or is this a special case?</p>
<p>Edit:
Added some more information to make the question/code more clear for my question.
Thank you all for the help. This was a case of the gcc specific extension.</p> | 39,359,469 | 3 | 10 | null | 2016-09-06 21:09:42.817 UTC | 6 | 2016-09-07 20:30:03.7 UTC | 2016-09-07 00:55:03.487 UTC | null | 5,458,252 | null | 5,458,252 | null | 1 | 50 | c|gcc|goto|language-extension | 3,831 | <p>It's a gcc-specific extension, a unary <code>&&</code> operator that can be applied to a label name, yielding its address as a <code>void*</code> value.</p>
<p>As part of the extension, <code>goto *ptr;</code> is allowed where <code>ptr</code> is an expression of type <code>void*</code>.</p>
<p>It's documented <a href="https://gcc.gnu.org/onlinedocs/gcc-6.2.0/gcc/Labels-as-Values.html">here</a> in the gcc manual.</p>
<blockquote>
<p>You can get the address of a label defined in the current function (or
a containing function) with the unary operator <code>&&</code>. The value has
type <code>void *</code>. This value is a constant and can be used wherever a
constant of that type is valid. For example:</p>
<pre><code>void *ptr;
/* ... */
ptr = &&foo;
</code></pre>
<p>To use these values, you need to be able to jump to one. This is done
with the computed goto statement, <code>goto *exp;</code>. For example,</p>
<pre><code>goto *ptr;
</code></pre>
<p>Any expression of type <code>void *</code> is allowed.</p>
</blockquote>
<p>As zwol points out in a comment, gcc uses <code>&&</code> rather than the more obvious <code>&</code> because a label and an object with the same name can be visible simultaneously, making <code>&foo</code> potentially ambiguous if <code>&</code> means "address of label". Label names occupy their own namespace (not in the C++ sense), and can appear only in specific contexts: defined by a <em>labeled-statement</em>, as the target of a <code>goto</code> statement, or, for gcc, as the operand of unary <code>&&</code>.</p> |
32,271,731 | Why is my Java heap dump size much smaller than used memory? | <h1>Problem</h1>
<p>We are trying to find the culprit of a big memory leak in our web application. We have pretty limited experience with finding a memory leak, but we found out how to make a java heap dump using <code>jmap</code> and analyze it in Eclipse MAT. </p>
<p>However, with our application using 56/60GB memory, the heap dump is only 16GB in size and is even less in Eclipse MAT. </p>
<h2>Context</h2>
<p>Our server uses Wildfly 8.2.0 on Ubuntu 14.04 for our java application, whose process uses 95% of the available memory. When making the dump, our buffers/cache used space was at 56GB.</p>
<p>We used the following command to create the dump: <code>sudo -u {application user} jmap -dump:file=/mnt/heapdump/dump_prd.bin {pid}</code></p>
<p>The heap dump file size is 16,4GB and when analyzing it with Eclipse MAT, it says there are around 1GB live objects and ~14,8GB unreachable/shallow heap. </p>
<p><strong>EDIT:</strong> Here is some more info about the problem we see happening. We monitor our memory usage, and we see it grow and grow, until there is ~300mb free memory left. Then it stays around that amount of memory, until the process crashes, unfortunately without error in the application log. </p>
<p>This makes us assume it is a hard OOM error because this only happens when the memory is near-depleted. We use the settings <code>-Xms25000m -Xmx40000m</code> for our JVM. </p>
<h2>Question</h2>
<p>Basically, we are wondering why the majority of our memory isn't captured in this dump. The top retained size classes don't look too suspicious, so we are wondering if there is something heap dump-related what we are doing wrong. </p> | 32,271,875 | 2 | 10 | null | 2015-08-28 13:02:58.51 UTC | 11 | 2016-11-23 10:20:45.213 UTC | 2015-08-28 13:31:17.807 UTC | null | 1,437,096 | null | 1,437,096 | null | 1 | 20 | java|memory-leaks|heap-memory|heap-dump|jmap | 22,153 | <p>When dumping its heap, the JVM will first run a garbage collection cycle to free any unreachable objects.</p>
<p><a href="https://stackoverflow.com/questions/1268336/how-can-i-take-a-heap-dump-on-java-5-without-garbage-collecting-first">How can I take a heap dump on Java 5 without garbage collecting first?</a></p>
<p>In my experience, in a true OutOfMemoryError where your application is simply demanding more heap space than is available, this GC is a fool's errand and the final heap dump will be the size of the max. heap size.</p>
<p>When the heap dump is much smaller, that means the system was not truly out of memory, but perhaps had memory pressure. For example, there is the <code>java.lang.OutOfMemoryError: GC overhead limit exceeded</code> error, which means that the JVM may have been able to free enough memory to service some new allocation request, but it had to spend too much time collecting garbage.</p>
<p>It's also possible that you don't have a memory problem. What makes you think you do? You didn't mention anything about heap usage or an OutOfMemoryError. You've only mentioned the JVM's memory footprint on the operating system.</p> |
1,596,530 | Multi-dimensional arraylist or list in C#? | <p>Is it possible to create a multidimensional list in C#?
I can create an multidimensional array like so:</p>
<pre><code> string[,] results = new string[20, 2];
</code></pre>
<p>But I would like to be able to use some of the features in a list or arraylist like being able to add and delete elements.</p> | 1,596,563 | 5 | 1 | null | 2009-10-20 18:39:14.62 UTC | 9 | 2019-01-04 10:12:00.463 UTC | 2018-07-10 02:25:38.097 UTC | null | 2,093,802 | null | 97,736 | null | 1 | 16 | c#|list|arraylist | 160,642 | <p>You can create a list of lists</p>
<pre><code> public class MultiDimList: List<List<string>> { }
</code></pre>
<p>or a Dictionary of key-accessible Lists</p>
<pre><code> public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDicList = new MultiDimDictList ();
myDicList.Add("ages", new List<int>());
myDicList.Add("Salaries", new List<int>());
myDicList.Add("AccountIds", new List<int>());
</code></pre>
<p>Generic versions, to implement suggestion in comment from @user420667</p>
<pre><code> public class MultiDimList<T>: List<List<T>> { }
</code></pre>
<p>and for the dictionary,</p>
<pre><code> public class MultiDimDictList<K, T>: Dictionary<K, List<T>> { }
// to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", new List<T>());
myDicList["ages"].Add(23);
myDicList["ages"].Add(32);
myDicList["ages"].Add(18);
myDicList.Add("salaries", new List<T>());
myDicList["salaries"].Add(80000);
myDicList["salaries"].Add(100000);
myDicList.Add("accountIds", new List<T>());
myDicList["accountIds"].Add(321123);
myDicList["accountIds"].Add(342653);
</code></pre>
<p>or, even better, ...</p>
<pre><code> public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
{
public void Add(K key, T addObject)
{
if(!ContainsKey(key)) Add(key, new List<T>());
if (!base[key].Contains(addObject)) base[key].Add(addObject);
}
}
// and to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", 23);
myDicList.Add("ages", 32);
myDicList.Add("ages", 18);
myDicList.Add("salaries", 80000);
myDicList.Add("salaries", 110000);
myDicList.Add("accountIds", 321123);
myDicList.Add("accountIds", 342653);
</code></pre>
<p>EDIT: to include an Add() method for nested instance: </p>
<pre><code>public class NestedMultiDimDictList<K, K2, T>:
MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
public void Add(K key, K2 key2, T addObject)
{
if(!ContainsKey(key)) Add(key,
new MultiDimDictList<K2, T>());
if (!base[key].Contains(key2))
base[key].Add(key2, addObject);
}
}
</code></pre> |
2,169,828 | Is there a better (more modern) tool than lex/flex for generating a tokenizer for C++? | <p>I recent added source file parsing to an existing tool that generated output files from complex command line arguments. </p>
<p>The command line arguments got to be so complex that we started allowing them to be supplied as a file that was parsed as if it was a very large command line, but the syntax was still awkward. So I added the ability to parse a source file using a more reasonable syntax. </p>
<p>I used flex 2.5.4 for windows to generate the tokenizer for this custom source file format, and it worked. But I hated the code. global variables, wierd naming convention, and the c++ code it generated was awful. The existing code generation backend was glued to the output of flex - I don't use yacc or bison. </p>
<p>I'm about to dive back into that code, and I'd like to use a better/more modern tool. Does anyone know of something that.</p>
<ul>
<li>Runs in Windows command prompt (Visual studio integration is ok, but I use make files to build)</li>
<li>Generates a proper encapsulated C++ tokenizer. (No global variables)</li>
<li>Uses regular expressions for describing the tokenizing rules (compatible with lex syntax a plus)</li>
<li>Does not force me to use the c-runtime (or fake it) for file reading. (parse from memory)</li>
<li>Warns me when my rules force the tokenizer to backtrack (or fixes it automatically)</li>
<li>Gives me full control over variable and method names (so I can conform to my existing naming convention)</li>
<li>Allows me to link multiple parsers into a single .exe without name collisions</li>
<li>Can generate a UNICODE (16bit UCS-2) parser if I want it to</li>
<li>Is NOT an integrated tokenizer + parser-generator (I want a lex replacement, not a lex+yacc replacement)</li>
</ul>
<p>I could probably live with a tool that just generated the tokenizing tables if that was the only thing available. </p> | 2,169,912 | 5 | 2 | null | 2010-01-30 23:01:13.48 UTC | 11 | 2013-09-26 15:21:03.537 UTC | 2010-02-01 19:19:18.95 UTC | null | 234,815 | null | 234,815 | null | 1 | 23 | c++|windows|lex|tokenize | 5,225 | <p>Ragel: <a href="http://www.complang.org/ragel/" rel="noreferrer">http://www.complang.org/ragel/</a> It fits most of your requirements.</p>
<ul>
<li>It runs on Windows</li>
<li>It doesn't declare the variables, so you can put them inside a class or inside a function as you like.</li>
<li>It has nice tools for analyzing regular expressions to see when they would backtrack. (I don't know about this very much, since I never use syntax in Ragel that would create a backtracking parser.)</li>
<li>Variable names can't be changed.</li>
<li>Table names are prefixed with the machine name, and they're declared "const static", so you can put more than one in the same file and have more than one with the same name in a single program (as long as they're in different files).</li>
<li>You can declare the variables as any integer type, including UChar (or whatever UTF-16 type you prefer). It doesn't automatically handle surrogate pairs, though. It doesn't have special character classes for Unicode either (I think).</li>
<li>It only does regular expressions... has no bison/yacc features.</li>
</ul>
<p>The code it generates interferes very little with a program. The code is also incredibly fast, and the Ragel syntax is more flexible and readable than anything I've ever seen. It's a rock solid piece of software. It can generate a table-driven parser or a goto-driven parser.</p> |
2,191,294 | What do the parentheses signify in (x:xs) when pattern matching? | <p>when you split a list using x:xs syntax why is it wrapped in a parentheses? what is the significance of the parentheses? why not [x:xs] or just x:xs?</p> | 2,196,592 | 5 | 2 | null | 2010-02-03 10:43:46.573 UTC | 9 | 2011-04-18 22:00:56.817 UTC | 2011-04-18 22:00:56.817 UTC | null | 83,805 | null | 131,667 | null | 1 | 30 | haskell|syntax | 11,405 | <p>The cons cell doesn't have to be parenthesized in every context, but in most contexts it is because </p>
<h1>Function application binds tighter than any infix operator.</h1>
<p>Burn this into your brain in letters of fire.</p>
<p>Example:</p>
<pre><code>length [] = 0
length (x:xs) = 1 + length xs
</code></pre>
<p>If parentheses were omitted the compiler would think you had an argument <code>x</code> followed by an ill-placed infix operator, and it would complain bitterly. On the other hand this is OK</p>
<pre><code>length l = case l of [] -> 0
x:xs -> 1 + length xs
</code></pre>
<p>In this case neither <code>x</code> nor <code>xs</code> can possibly be construed as part of a function application so no parentheses are needed.</p>
<p>Note that the same wonderful rule <strong>function application binds tighter than any infix operator</strong> is what allows us to write <code>length xs</code> in <code>1 + length xs</code> without any parentheses. The infix rule giveth and the infix rule taketh away.</p> |
1,411,336 | Accessing parent data in nested repeater, in the HeaderTemplate | <p>Simple question, not sure there's a simple answer!</p>
<p>So here's the code: (I've simplified it a lot to make it easier to read)</p>
<pre><code><asp:Repeater runat="server>
<ItemTemplate>
<asp:Repeater runat="server">
<HeaderTemplate>
<h1>My header here for: <%# OuterContainer.DataItem.MyItemName %> </h1>
</HeaderTemplate>
<ItemTemplate>
My items code here
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>How, in the HeaderTemplate - can I access the DataItem in the parent repeater?</p> | 1,411,385 | 5 | 0 | null | 2009-09-11 14:46:14.117 UTC | 11 | 2018-09-02 12:17:29.547 UTC | null | null | null | null | 148,366 | null | 1 | 61 | asp.net|nested-repeater | 47,693 | <p>I have found the answer actually:</p>
<p>Use:</p>
<pre><code><HeaderTemplate>
<%# ((RepeaterItem)Container.Parent.Parent).DataItem %>
</HeaderTemplate>
</code></pre> |
1,523,814 | Units of a Fourier Transform (FFT) when doing Spectral Analysis of a Signal | <p>My question has to do with the physical meaning of the results of doing a spectral analysis of a signal, or of throwing the signal into an FFT and interpreting what comes out using a suitable numerical package, </p>
<p>Specifically:</p>
<ul>
<li>take a signal, say a time-varying voltage v(t)</li>
<li>throw it into an FFT (you get back a sequence of complex numbers)</li>
<li>now take the modulus (abs) and square the result, i.e. |fft(v)|^2. </li>
</ul>
<p>So you now have real numbers on the y axis -- shall I call these spectral coefficients?</p>
<ul>
<li>using the sampling resolution, you follow a cookbook recipe and associate the spectral coefficients to frequencies. </li>
<li>AT THIS POINT, you have a frequency spectrum g(w) with frequency on the x axis, <strong>but WHAT PHYSICAL UNITS on the y axis?</strong></li>
</ul>
<p>My understanding is that this frequency spectrum shows how much of the various frequencies are present in the voltage signal -- they are spectral coefficients in the sense that they are the coefficients of the sines and cosines of the various frequencies required to reconstitute the original signal.</p>
<p>So the first question is, <strong>what are the UNITS of these spectral coefficients?</strong></p>
<p>The reason this matters is that spectral coefficients can be tiny and enormous, so I want to use a dB scale to represent them. </p>
<p>But to do that, I have to make a choice: </p>
<ul>
<li>Either I use the 20log10 dB conversion, corresponding to a field measurement, like voltage. </li>
<li>Or I use the 10log10 dB conversion, corresponding to an energy measurement, like power. </li>
</ul>
<p><strong>Which scaling I use depends on what the units are.</strong></p>
<p>Any light shed on this would be greatly appreciated!</p> | 1,524,535 | 5 | 4 | null | 2009-10-06 05:54:54.027 UTC | 41 | 2020-10-31 23:24:23.163 UTC | 2014-04-21 22:18:36.443 UTC | null | 181,638 | null | 181,638 | null | 1 | 71 | math|physics|fft|measurement|spectrum | 104,564 | <blockquote>
<p>take a signal, a time-varying voltage v(t)</p>
</blockquote>
<p>units are <em>V</em>, values are real.</p>
<blockquote>
<p>throw it into an FFT -- ok, you get back a sequence of complex numbers</p>
</blockquote>
<p>units are still <em>V</em>, values are complex ( not <em>V/Hz</em> - the FFT a DC signal becomes a point at the DC level, not an dirac delta function zooming off to infinity )</p>
<blockquote>
<p>now take the modulus (abs) </p>
</blockquote>
<p>units are still <em>V</em>, values are real - magnitude of signal components</p>
<blockquote>
<p>and square the result, i.e. |fft(v)|^2</p>
</blockquote>
<p>units are now <em>V<sup>2</sup></em>, values are real - square of magnitudes of signal components</p>
<blockquote>
<p>shall I call these spectral coefficients?</p>
</blockquote>
<p>It's closer to an power density rather than usual use of spectral coefficient. If your sink is a perfect resistor, it will be power, but if your sink is frequency dependent it's "the square of the magnitude of the FFT of the input voltage". </p>
<blockquote>
<p>AT THIS POINT, you have a frequency spectrum g(w): frequency on the x axis, and... WHAT PHYSICAL UNITS on the y axis?</p>
</blockquote>
<p>Units are <em>V<sup>2</sup></em> </p>
<blockquote>
<p>The other reason the units matter is that the spectral coefficients can be tiny and enormous, so I want to use a dB scale to represent them. But to do that, I have to make a choice: do I use the 20log10 dB conversion (corresponding to a field measurement, like voltage)? Or do I use the 10log10 dB conversion (corresponding to an energy measurement, like power)? </p>
</blockquote>
<p>You've already squared the voltage values, giving equivalent power into a perfect 1 Ohm resistor, so use 10log10.</p>
<p><em>log(x<sup>2</sup>)</em> is <em>2 log(x)</em>, so <em>20log10 |fft(v)| = 10log10 ( |fft(v)|<sup>2</sup>)</em>, so alternatively if you did not square the values you could use 20log10.</p> |
1,679,384 | Converting Dictionary to List? | <p>I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.</p>
<pre><code>#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"
#lists
temp = []
dictList = []
#My attempt:
for key, value in dict.iteritems():
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
aKey = ""
aValue = ""
</code></pre>
<p>That's my attempt at it... but I can't work out what's wrong?</p> | 1,679,406 | 7 | 2 | null | 2009-11-05 09:34:18.413 UTC | 69 | 2020-01-31 06:45:45.217 UTC | 2019-06-29 18:20:21.797 UTC | user212218 | 355,230 | null | 154,280 | null | 1 | 268 | python|list|dictionary | 1,002,901 | <p>Your problem is that you have <code>key</code> and <code>value</code> in quotes making them strings, i.e. you're setting <code>aKey</code> to contain the string <code>"key"</code> and not the value of the variable <code>key</code>. Also, you're not clearing out the <code>temp</code> list, so you're adding to it each time, instead of just having two items in it.</p>
<p>To fix your code, try something like:</p>
<pre><code>for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
</code></pre>
<p>You don't need to copy the loop variables <code>key</code> and <code>value</code> into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done <code>dictlist.append([key,value])</code> if we wanted to be as brief as possible.</p>
<p>Or just use <code>dict.items()</code> as has been suggested.</p> |
2,213,024 | UITableView flexible/dynamic heightForRowAtIndexPath | <h2>Case</h2>
<p>Normally you would use the <code>cellForRowAtIndexPath</code> delegate method to setup your cell. The information set for the cell is important for how the cell is drawn and what the size will be.</p>
<p>Unfortunatly the <code>heightForRowAtIndexPath</code> delegate method is called before the <code>cellForRowAtIndexPath</code> delegate method so we can't simply tell the delegate to return the height of the cell, since this will be zero at that time.</p>
<p>So we need to calculate the size before the cell is drawn in the table. Luckily there is a method that does just that, <code>sizeWithFont</code>, which belongs to the NSString class. However there is problem, in order to calculate the correct size dynamically it needs to know how the elements in the cell will be presented. I will make this clear in an example:</p>
<p>Imagine a <code>UITableViewCell</code>, which contains a label named <code>textLabel</code>. Within the <code>cellForRowAtIndexPath</code> delegate method we place <code>textLabel.numberOfLines = 0</code>, which basically tells the label it can have as many lines as it needs to present the text for a specific width. The problem occurs if we give textLabel a text larger then the width originally given to textLabel. The second line will appear, but the height of the cell will not be automatically adjusted and so we get a messed up looking table view.</p>
<p>As said earlier, we can use <code>sizeWithFont</code> to calculate the height, but it needs to know which Font is used, for what width, etc. If, for simplicity reasons, we just care about the width, we could hardcode that the width would be around 320.0 (not taking padding in consideration). But what would happen if we used UITableViewStyleGrouped instead of plain the width would then be around 300.0 and the cell would again be messed up. Or what happends if we swap from portrait to landscape, we have much more space, yet it won't be used since we hardcoded 300.0.</p>
<p>This is the case in which at some point you have to ask yourself the question how much can you avoid hardcoding.</p>
<h2>My Own Thoughts</h2>
<p>You could call the <code>cellForRowAtIndexPath</code> method that belongs to the UITableView class to get the cell for a certain section and row. I read a couple of posts that said you don't want to do that, but I don't really understand that. Yes, I agree it will already allocate the cell, but the <code>heightForRowAtIndexPath</code> delegate method is only called for the cells that will be visible so the cell will be allocated anyway. If you properly use the <code>dequeueReusableCellWithIdentifier</code> the cell will not be allocated again in the <code>cellForRowAtIndexPath</code> method, instead a pointer is used and the properties are just adjusted. Then what's the problem? </p>
<p>Note that the cell is NOT drawn within the <code>cellForRowAtIndexPath</code> delegate method, when the table view cell becomes visible the script will call the <code>setNeedDisplay</code> method on the UITableVieCell which triggers the <code>drawRect</code> method to draw the cell. So calling the <code>cellForRowAtIndexPath</code> delegate directly will not lose performance because it needs to be drawn twice.</p>
<p>Okay so by calling the <code>cellForRowAtIndexPath</code> delegate method within the <code>heightForRowAtIndexPath</code> delegate method we receive all the information we need about the cell to determine it's size. </p>
<p>Perhaps you can create your own <code>sizeForCell</code> method that runs through all the options, what if the cell is in Value1 style, or Value2, etc.</p>
<h2>Conclusion/Question</h2>
<p>It's just a theory I described in my thoughts, I would like to know if what I wrote is correct. Or that maybe there is another way to accomplish the same thing. Note that I want to be able to do things as flexible as possible.</p> | 6,667,335 | 7 | 0 | null | 2010-02-06 12:11:14.597 UTC | 25 | 2014-10-21 06:46:44.79 UTC | 2014-07-06 16:23:17.103 UTC | null | 321,731 | null | 174,655 | null | 1 | 60 | iphone|uitableview | 26,338 | <blockquote>
<p>Yes, I agree it will already allocate the cell, but the heightForRowAtIndexPath delegate method is only called for the cells that will be visible so the cell will be allocated anyway. </p>
</blockquote>
<p>This is incorrect. The table view needs to call <code>heightForRowAtIndexPath</code> (if it's implemented) for all rows that are in the table view, not just the ones currently being displayed. The reason is that it needs to figure out its total height to display the correct scroll indicators.</p> |
1,596,432 | Getter and setter, pointers or references, and good syntax to use in c++? | <p>I would like to know a good syntax for C++ getters and setters.</p>
<pre><code>private:
YourClass *pMember;
</code></pre>
<p>the setter is easy I guess:</p>
<pre><code>void Member(YourClass *value){
this->pMember = value; // forget about deleting etc
}
</code></pre>
<p>and the getter?
should I use references or const pointers?</p>
<p>example:</p>
<pre><code>YourClass &Member(){
return *this->pMember;
}
</code></pre>
<p>or</p>
<pre><code>YourClass *Member() const{
return this->member;
}
</code></pre>
<p>whats the difference between them?</p>
<p>Thanks,</p>
<p>Joe</p>
<p>EDIT:</p>
<p>sorry, I will edit my question... I know about references and pointers, I was asking about references and const pointers, as getters, what would be the difference between them in my code, like in hte future, what shoud I expect to lose if I go a way or another...</p>
<p>so I guess I will use const pointers instead of references</p>
<p>const pointers can't be delete or setted, right?</p> | 1,596,448 | 8 | 3 | null | 2009-10-20 18:20:56.81 UTC | 12 | 2010-09-05 19:55:24.51 UTC | 2010-09-05 19:55:24.51 UTC | null | 2,509 | null | 127,735 | null | 1 | 12 | c++|pointers|reference|setter|getter | 26,197 | <p>As a general law:</p>
<ul>
<li>If NULL is a valid parameter or return value, use pointers.</li>
<li>If NULL is <strong>NOT</strong> a valid parameter or return value, use references.</li>
</ul>
<p>So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.</p>
<p>If it's valid to call the getter of a object containing a NULL pointer, it should return a pointer. If such a case is an illegal invariant, the return value should be a reference. The getter then should throw a exception, if the member variable is NULL.</p> |
1,470,792 | How to calculate the IP range when the IP address and the netmask is given? | <p>When a IP-Range is written as aaa.bbb.ccc.ddd/netmask (<a href="http://en.wikipedia.org/wiki/CIDR_notation" rel="noreferrer">CIDR Notation</a>) I need to calculate the first and the last included ip address in this range with C#.</p>
<p><strong>Example:</strong></p>
<p><strong>Input:</strong> 192.168.0.1/25</p>
<p><strong>Result:</strong> 192.168.0.1 - 192.168.0.126</p> | 1,470,835 | 8 | 1 | null | 2009-09-24 10:08:33.117 UTC | 31 | 2020-11-15 08:45:39.39 UTC | 2011-04-13 15:43:54.063 UTC | null | 194,653 | null | 5,703 | null | 1 | 44 | c#|ip|netmask | 138,158 | <p>my good friend <a href="https://typps.blogspot.com/" rel="nofollow noreferrer">Alessandro</a> have a <a href="https://typps.blogspot.com/2007/10/bitwise-operators-in-c-or-xor-and-not.html" rel="nofollow noreferrer">nice post</a> regarding bit operators in C#, you should read about it so you know what to do.</p>
<p><strong>It's pretty easy</strong>. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.</p>
<p>For example:</p>
<pre><code>ip 192.168.33.72 mask 255.255.255.192
11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)
</code></pre>
<p>The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:</p>
<pre><code>11000000.10101000.00100001.01000000 (192.168.33.64)
</code></pre>
<p>If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):</p>
<pre><code>11000000.10101000.00100001.01111111 (192.168.33.127)
</code></pre>
<p>So for my example:</p>
<pre><code>the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127
</code></pre> |
1,894,453 | Development time in various languages | <p>Does anybody know of any research or benchmarks of how long it takes to develop the same application in a variety of languages? Really I'm looking for Java vs. C++ but any comparisons would be useful. I have the feeling there is a section in Code Complete about this but my copy is at work.</p>
<p><strong>Edit:</strong></p>
<p>There are a lot of interesting answers to this question but it seems like there is a lack of really good research. I have made a <a href="https://meta.stackexchange.com/questions/32833/stackoverflow-lanaguage-research">proposal</a> over at meta about this problem.</p> | 1,894,570 | 15 | 8 | null | 2009-12-12 19:33:05.227 UTC | 22 | 2021-11-22 17:53:24.187 UTC | 2017-03-20 10:29:34.447 UTC | null | -1 | null | 361 | null | 1 | 37 | programming-languages|performance | 11,141 | <p>Pratt & Whitney, purveyors of jet engines for civilian and military applications, did a study on this many years ago, without actually intending to do the study.</p>
<p>They went on the same metrics kick everyone else went on in the 1990s. They collected a bunch of data about their jet engine controller projects, including timecard data. They crunched it. The poor sap who got to crunch the data noticed something in the results: the military projects uniformly had twice the programmer productivity and one/fourth the defect density as the civilian projects.</p>
<p>This, by itself, is significant. It means you only need half as many programmers, and you aren't going to spend quite as much time fixing bugs. What is even more important is that this was an apples-to-apples comparison. A jet engine controller is a jet engine controller.</p>
<p>He then went looking for candidate explanations. All of the usual candidates: individual experience, team size, toolsets, software processes, requirements stability, everything, were trotted out, and they were ruled out when it was seen that the story on those items was uniformly the same on both sides of the aisle. At the end of the day, only one statistically significant difference showed up.</p>
<p>The civilian projects were written in every language you could think of. The military projects were all written in Ada.</p>
<p>IN EVERY SINGLE CASE, against every other comer, for jet engine controllers at Pratt & Whitney, using Ada gave double the productivity and one/fourth the defect density.</p>
<p>I know what the flying code monkeys are going to say. "You can do good work in any language." In theory, that's true. In practice, however, it appears that, at least at Pratt & Whitney, language made a difference.</p>
<p>Last I heard about this, Pratt & Whitney upper management decreed that ALL jet engine controller projects would be done in Ada.</p>
<p>No, I don't have a citation. No paper was ever written. My source on this story was the poor sap who crunched the numbers. Here's a similar study from 1995:</p>
<p><a href="http://archive.adaic.com/intro/ada-vs-c/cada_art.html" rel="nofollow noreferrer">http://archive.adaic.com/intro/ada-vs-c/cada_art.html</a></p>
<p>This, incidentally, was BEFORE Boeing did the 777, and BEFORE the 777 brake subcontractor story happened. But that's another story.</p> |
1,683,531 | How to import existing Git repository into another? | <p>I have a Git repository in a folder called <strong>XXX</strong>, and I have second Git repository called <strong>YYY</strong>.</p>
<p>I want to import the <strong>XXX</strong> repository into the <strong>YYY</strong> repository as a subdirectory named <strong>ZZZ</strong> and add all <strong>XXX</strong>'s change history to <strong>YYY</strong>.</p>
<p>Folder structure before:</p>
<pre><code>├── XXX
│ ├── .git
│ └── (project files)
└── YYY
├── .git
└── (project files)
</code></pre>
<p>Folder structure after:</p>
<pre><code>YYY
├── .git <-- This now contains the change history from XXX
├── ZZZ <-- This was originally XXX
│ └── (project files)
└── (project files)
</code></pre>
<p>Can this be done, or must I resort to using sub-modules?</p> | 1,684,694 | 17 | 3 | null | 2009-11-05 20:55:03.207 UTC | 299 | 2021-09-27 23:00:18.187 UTC | 2019-11-23 07:39:18.163 UTC | null | 4,245,859 | null | 80,369 | null | 1 | 557 | git|merge|git-merge | 243,997 | <p>Probably the simplest way would be to pull the <strong>XXX</strong> stuff into a branch in <strong>YYY</strong> and then merge it into master:</p>
<p>In <strong>YYY</strong>:</p>
<pre><code>git remote add other /path/to/XXX
git fetch other
git checkout -b ZZZ other/master
mkdir ZZZ
git mv stuff ZZZ/stuff # repeat as necessary for each file/dir
git commit -m "Moved stuff to ZZZ"
git checkout master
git merge ZZZ --allow-unrelated-histories # should add ZZZ/ to master
git commit
git remote rm other
git branch -d ZZZ # to get rid of the extra branch before pushing
git push # if you have a remote, that is
</code></pre>
<p>I actually just tried this with a couple of my repos and it works. Unlike <a href="https://stackoverflow.com/questions/1683531/how-to-import-existing-git-repository-into-another/1684435#1684435">Jörg's answer</a> it won't let you continue to use the other repo, but I don't think you specified that anyway.</p>
<p>Note: Since this was originally written in 2009, git has added the subtree merge mentioned in the answer below. I would probably use that method today, although of course this method does still work.</p> |
1,355,876 | Export table to file with column headers (column names) using the bcp utility and SQL Server 2008 | <p>I have seen a number of hacks to try to get the bcp utility to export column names along with the data. If all I am doing is dumping a table to a text file what is the most straightforward method to have bcp add the column headers?</p>
<p>Here's the bcp command I am currently using:</p>
<pre><code>bcp myschema.dbo.myTableout myTable.csv /SmyServer01 /c /t, -T
</code></pre> | 5,312,852 | 19 | 1 | null | 2009-08-31 05:07:10.22 UTC | 23 | 2022-03-02 02:21:06.55 UTC | 2020-04-12 21:59:56.893 UTC | null | 63,550 | null | 37,751 | null | 1 | 45 | sql-server|csv|header|bcp | 228,581 | <p>The easiest is to use the <code>queryout</code> option and use <code>union all</code> to link a column list with the actual table content</p>
<pre><code> bcp "select 'col1', 'col2',... union all select * from myschema.dbo.myTableout" queryout myTable.csv /SmyServer01 /c /t, -T
</code></pre>
<p>An example:</p>
<pre><code>create table Question1355876
(id int, name varchar(10), someinfo numeric)
insert into Question1355876
values (1, 'a', 123.12)
, (2, 'b', 456.78)
, (3, 'c', 901.12)
, (4, 'd', 353.76)
</code></pre>
<p>This query will return the information with the headers as first row (note the casts of the numeric values):</p>
<pre><code>select 'col1', 'col2', 'col3'
union all
select cast(id as varchar(10)), name, cast(someinfo as varchar(28))
from Question1355876
</code></pre>
<p>The bcp command will be:</p>
<pre><code>bcp "select 'col1', 'col2', 'col3' union all select cast(id as varchar(10)), name, cast(someinfo as varchar(28)) from Question1355876" queryout myTable.csv /SmyServer01 /c /t, -T
</code></pre> |
8,792,440 | How can I find the missing value more concisely? | <p>The following code checks if <code>x</code> and <code>y</code> are distinct values (the variables <code>x</code>, <code>y</code>, <code>z</code> can only have values <code>a</code>, <code>b</code>, or <code>c</code>) and if so, sets <code>z</code> to the third character:</p>
<pre><code>if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' and y == 'c' or x == 'c' and y == 'a':
z = 'b'
</code></pre>
<p>Is is possible to do this in a more, concise, readable and efficient way?</p> | 8,792,467 | 11 | 2 | null | 2012-01-09 17:21:31.223 UTC | 15 | 2012-01-26 09:27:21.4 UTC | 2012-01-10 07:48:04.35 UTC | null | 110,204 | null | 236,106 | null | 1 | 75 | python|benchmarking|microbenchmark | 3,278 | <pre><code>z = (set(("a", "b", "c")) - set((x, y))).pop()
</code></pre>
<p>I am assuming that one of the three cases in your code holds. If this is the case, the set <code>set(("a", "b", "c")) - set((x, y))</code> will consist of a single element, which is returned by <code>pop()</code>.</p>
<p><strong>Edit:</strong> As suggested by Raymond Hettinger in the comments, you could also use tuple unpacking to extract the single element from the set:</p>
<pre><code>z, = set(("a", "b", "c")) - set((x, y))
</code></pre> |
46,342,930 | Puppeteer Button Press | <p>According to <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepresskey-options" rel="noreferrer">https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepresskey-options</a>, you can simulate the pressing of a keyboard button with Puppeteer.</p>
<p>Here's what I do:</p>
<pre><code>// First, click the search button
await page.click('#outer-container > nav > span.right > span.search-notification-wrapper > span > form > input[type="text"]');
// Focus on the input field
await page.focus('#outer-container > nav > span.right > span.search-notification-wrapper > span > form > input[type="text"]');
// Enter some text into the input field
await page.type("Bla Bla");
// Press Enter to search -> this doesn't work!
await page.press("Enter");
</code></pre>
<p>The pressing of the button doesn't produce anything. It's basically ignored.</p>
<p>How can I simulate the Enter key to submit the form?</p> | 46,425,727 | 6 | 5 | null | 2017-09-21 11:35:52.793 UTC | 3 | 2020-03-24 09:03:01.193 UTC | 2020-03-17 22:10:51.357 UTC | null | 4,283,581 | null | 1,174,325 | null | 1 | 24 | javascript|node.js|google-chrome-devtools|puppeteer|headless-browser | 93,732 | <p>I've figured it out finally. I found inside that same form an anchor element whose type was submit. I then clicked on it and the form was submitted.</p>
<p>Here's the code I've used:</p>
<pre><code>const form = await page.$('a#topbar-search');
await form.evaluate( form => form.click() );
</code></pre>
<p>You can also use the $eval method instead of evaluate:</p>
<pre><code>await page.$eval( 'a#topbar-search', form => form.click() );
</code></pre> |
17,944,987 | Picking up an audio file android | <p>I need to fetch an audio file from SD Card and play it. I think this can be done by getting URI of an audio file. So, to pick an audio file I'm using following code:</p>
<pre><code>Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), reqCode);
</code></pre>
<p>Now, I can browse for audio files and select one of them.</p>
<p><strong>QUESTION:</strong> How to read the URI of picked file in my onActivityResult?</p> | 17,945,257 | 5 | 1 | null | 2013-07-30 10:50:24.183 UTC | 11 | 2020-08-24 09:47:05.857 UTC | 2018-04-18 06:27:45.283 UTC | null | 2,416,082 | null | 2,416,082 | null | 1 | 24 | android | 32,795 | <p>You can put below codes in your project when you want to select audio.</p>
<pre><code>Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
</code></pre>
<p>And override onActivityResult in the same Activity, as below</p>
<pre><code>@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
</code></pre> |
18,191,893 | Generate pdf from HTML in div using Javascript | <p>I have the following html code:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>
<p>don't print this to pdf</p>
<div id="pdf">
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
</code></pre>
<p>All I want to do is to print to pdf whatever is found in the div with an id of "pdf". This must be done using JavaScript. The "pdf" document should then be automatically downloaded with a filename of "foobar.pdf"</p>
<p>I've been using jspdf to do this, but the only function it has is "text" which accepts only string values. I want to submit HTML to jspdf, not text. </p> | 24,825,130 | 16 | 2 | null | 2013-08-12 16:18:31.98 UTC | 156 | 2022-07-24 14:15:23.02 UTC | 2020-06-16 13:28:01.19 UTC | null | 863,110 | null | 2,266,042 | null | 1 | 324 | javascript|jspdf | 1,247,482 | <p><strong>jsPDF is able to use plugins.</strong> In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:</p>
<ol>
<li>Go to <a href="https://github.com/MrRio/jsPDF" rel="noreferrer">https://github.com/MrRio/jsPDF</a> and download the latest Version.</li>
<li>Include the following Scripts in your project:
<ul>
<li>jspdf.js</li>
<li>jspdf.plugin.from_html.js</li>
<li>jspdf.plugin.split_text_to_size.js</li>
<li>jspdf.plugin.standard_fonts_metrics.js</li>
</ul></li>
</ol>
<p>If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
</code></pre>
<p>Then you use the following JavaScript code to open the created PDF in a PopUp:</p>
<pre><code>var doc = new jsPDF();
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
</code></pre>
<p>For me this created a nice and tidy PDF that only included the line 'print this to pdf'.</p>
<p>Please note that the special element handlers only deal with IDs in the current version, which is also stated in a <a href="https://github.com/MrRio/jsPDF/issues/34" rel="noreferrer">GitHub Issue</a>. It states: </p>
<blockquote>
<p>Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.</p>
</blockquote>
<p>Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:</p>
<pre><code>var elementHandler = {
'#ignoreElement': function (element, renderer) {
return true;
},
'#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
</code></pre>
<p>From the <a href="http://mrrio.github.io/jsPDF/examples/basic.html" rel="noreferrer">examples</a> it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:</p>
<blockquote>
<p>We support special element handlers. Register them with jQuery-style
ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
There is no support for any other type of selectors (class, of
compound) at this time.</p>
</blockquote>
<p><strong>One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:</strong></p>
<pre class="lang-html prettyprint-override"><code><body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>
</code></pre> |
44,732,915 | Why did Java 9 introduce the JMOD file format? | <p>Java 9 has three ways to package compiled code in files:</p>
<ul>
<li>JAR</li>
<li>JMOD</li>
<li>JIMAGE </li>
</ul>
<p>JIMAGE is optimized for speed and space and used by the JVM at runtime so it makes sense why JIMAGE was introduced. JIMAGE files are not supposed to be published to maven repos or used at compile or link time. </p>
<p>The docs claim that JMOD can store native code and other things that can't be stored by JAR files and that developers can make and distribute their own JMOD files. The JDK ships with <code>jmods/</code> directory containing all the modules of the JDK for users to depend on. </p>
<p><strong>Questions:</strong> </p>
<ul>
<li>Why did Java 9 introduce the JMOD file format?</li>
<li>Should a library author distribute a JMOD file or a JAR file or both? </li>
<li>Should jmod files be published to maven repos? </li>
</ul> | 64,202,720 | 2 | 7 | null | 2017-06-24 04:56:38.57 UTC | 28 | 2021-11-02 18:36:44.537 UTC | 2020-10-07 14:49:47.203 UTC | null | 1,746,118 | null | 438,319 | null | 1 | 78 | java|java-9|java-platform-module-system|jmod | 18,769 | <p>The purpose of JMODs are not well documented and existing documentation is rather sparse. Here is an in-depth explanation of system, from my understanding.</p>
<p><em>A warning</em>: Parts of this answer are rather long, verbose, partially redundant, and a tough read. Constructive, structural, or grammatical edits are more than welcome to improve readability for future readers.</p>
<hr>
<h1>Short(er) Answer</h1>
<p>Java 9's new module system, <a href="https://openjdk.java.net/projects/jigsaw/" rel="noreferrer">Project Jigsaw</a>, introduces the notion of a new optional <em>link time</em> phase, which occurs when the using the CLI tool <a href="https://docs.oracle.com/javase/9/tools/jlink.htm" rel="noreferrer"><code>jlink</code></a> to build a custom space-optimized JRE. <code>jlink</code> bundles all explicit/transitive JAR modules/JMOD dependencies into a minified JRE; all other unreachable dependencies in the dependency graph (starting from specified root modules) are <em>not</em> bundled into the built JRE. As of JDK 9+, all of Java's standard library has been broken up into JMODs, located at <code><jdk>/jmods</code>.</p>
<p>Whereas JARs can only contain <code>.class</code> and resource files, JMODs (i.e. <code>.jmod</code> files) contain additional files that are consumed specifically in the new optional <em>link time</em> phase to customize the JRE (e.g. executables, native libraries, configurations, legal licenses, etc). These additional files are not available as resources at run time in the classpath, but are instead installed under various locations in the built JRE (e.g. executables and native libraries are placed under <code><jre>/bin</code>). From the relevant bundled JARs and JMODs dependencies, classes and file resources will be written into a single optimized JIMAGE file, located at <code><jre>/lib/modules</code> (replacing <code><jre>/lib/rt.jar</code> in Java 8 and prior versions). The role of JMODs is at compile time and link time, and are <em>not</em> designed to be used at run time.</p>
<p>For the average library/application, only JARs should be built and pushed, instead of JMODs; only under certain conditions will JMODs offer critical functionality that is needed during the <em>link time</em> phase. At the time of writing, Maven does not appear to offer strong support for JMODs beyond the alpha release plugin <a href="https://maven.apache.org/plugins/maven-jmod-plugin/" rel="noreferrer"><code>org.apache.maven.plugins:maven-jmod-plugin</code></a>.</p>
<hr>
<h1>Long Answer</h1>
<p>This long-winded answer is more complexly motivated and sheds some light into how the new module system fundamentally operates. There is a strong emphasis throughout this post on the CLI tool <code>jlink</code>, since JMODs are designed specifically for this new optional <em>link time</em> phase that the tool introduces.</p>
<h2>The Introduction of Project Jigsaw</h2>
<p>Java 9 introduced <a href="https://openjdk.java.net/projects/jigsaw/" rel="noreferrer">Project Jigsaw</a> in '<a href="http://openjdk.java.net/jeps/261" rel="noreferrer">JEP 261: Module System</a>', a novel module system that can be used to minimize startup times and the size of JREs. As part of this release, the CLI utilities <a href="https://docs.oracle.com/javase/9/tools/jmod.htm" rel="noreferrer"><code>jmod</code></a>, <code>jimage</code>, and <a href="https://docs.oracle.com/javase/9/tools/jlink.htm" rel="noreferrer"><code>jlink</code></a> were introduced along with new file formats for JMODs/<code>.jmod</code>s (ZIP-based) and JIMAGEs/<code>.jimage</code>s.</p>
<p>A significant takeaway of this new module system is that the CLI tool <code>jlink</code> enables developers to build a custom JRE that contains only relevant standard library and external dependencies for their applications. This introduces a new notion of an optional <em>link time</em> phase between the traditional phases in the <code>compile time -> run time</code> pipeline.</p>
<p>For an example of the advantages of using <code>jlink</code>, a minimalist JRE built from JDK 15 with only the <code>java.base</code> module comes out to roughly ~40MB in size, in stark juxtaposition to JDK 15's ~310MB size. This is especially useful for shipping a minimal custom JRE, such as for lean Docker images. The new module system brings significant benefits to the Java ecosystem that have been discussed at length elsewhere, and are thus not further elaborated in detail here.</p>
<h2>The 3 J's: JARs, JMODs, and JIMAGEs</h2>
<p>The high level description of a JARs, JMODs, and JIMAGEs do not quickly lend themselves to an explanation that strongly differentiates between the roles of the three file formats. Here is a non-exhaustive overview of the purposes of each:</p>
<ul>
<li><p><strong>JARs:</strong> The classical format based on the ZIP file format for bundling classes and resources into the classpath at <em>run time</em>. This is the de-facto mainstream standard set forth since JDK 1.1 in 1997. JARs can be added to the classpath with the <code>java</code> <code>-cp</code>/<code>-classpath</code> flags. Almost every library or dependency <em>has</em>, <em>is</em>, and <em>will</em> be using this format, so it is glossed over in this section.</p>
</li>
<li><p><strong>JMODs:</strong> A new format based on the ZIP file format for bundling the same contents that a JAR can contain, but with support for additional files (e.g. executables, native libraries, configurations, legal licenses, etc) that are consumed at the optional <em>link time</em> phase when building a custom JRE. JMODs are designed to be used at both compile time and link time, but <em>not</em> at run time. This new format was likely introduced (instead of extending JARs) because there is a special meaning for directories within this new archive-based format that is <em>not</em> backwards compatible with JARs that already use the same directory names.</p>
<ul>
<li>A JMOD can be constructed from a JAR module (i.e. contains a valid <code>module-info.class</code>) with the CLI tool <a href="https://docs.oracle.com/javase/9/tools/jmod.htm" rel="noreferrer"><code>jmod</code></a>.</li>
<li>As of JDK 9 and onward, all Java standard modules are stored under <code><jdk>/jmods</code> in a JDK installation.</li>
<li>JMODs can be published for use by other developers and upstream applications; at the time of writing, I am unsure if JMODs may be pushed to Maven repositories, but various sources seem to indicate likely not for the time being.</li>
<li>JMOD classes and resources <em>cannot</em> be used at <em>run time</em> in the classpath with the <code>java</code> <code>-cp</code>/<code>-classpath</code> flags, as the classes and resources inside of the JMOD archive are stored under <code>classes</code> and not in the archive root.</li>
</ul>
</li>
</ul>
<blockquote>
<p>Note: There may be a way to add easily JMODs to the classpath at <em>run time</em>; however, research did not explicitly state any functionality relating to this. Merely adding a JMOD to the classpath will not be sufficient for using the classes and resources. A custom <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ClassLoader.html" rel="noreferrer"><code>ClassLoader</code></a> could be used to resolve class and resource files correctly in the JMOD archive at run time, however; this is generally not recommended and is not the purpose of JMODs.</p>
</blockquote>
<ul>
<li><strong>JIMAGEs</strong>: A special file format introduced in '<a href="http://openjdk.java.net/jeps/220" rel="noreferrer">JEP 220: Modular Run-Time Images</a>' that is a <em>runtime</em> image containing all necessary classes and resources for a JRE (i.e. the standard library). Prior to JRE/JDK 9, a single large non-modular uber JAR was used, located at <code><jre>/lib/rt.jar</code>; it has since been removed in favor of a single optimized JIMAGE stored located at <code><jre>/lib/modules</code>. This format is <em>not</em> based on the ZIP format and uses a custom format that is significantly more time and space efficient than the original legacy JAR format, reducing startup times.
<ul>
<li>When building a custom JRE image with the CLI tool <code>jlink</code>, all relevant (explicit or transistive) module dependencies' classes and resources (from JAR modules or JMODs) are compiled into a single optimized JIMAGE file (again, stored under <code><jre>/lib/modules</code>).</li>
<li>The JIMAGE file format is modular and can be created, modified, disassembled, or inspected with the CLI tool <code>jimage</code>. E.g. <code>jimage list $JAVA_HOME/lib/modules</code></li>
<li>JIMAGEs should generally not be be published, but instead shipped with a specific custom JRE version; the file format may be subject to changes in the future.</li>
</ul>
</li>
</ul>
<h2>The Substance: Detailed Purpose of JMOD</h2>
<h3>A New, Optional <em>Link Time</em> Phase</h3>
<p>As stated a few times previously, the CLI tool <a href="https://docs.oracle.com/javase/9/tools/jlink.htm" rel="noreferrer"><code>jlink</code></a> introduces a new optional stage in the normal Java pipeline - the <em><strong>link time phase</strong></em>. This link time phase is used to generate a custom built JRE from a set of Java 9 modules (either a JAR with a <code>module-info.java</code> descriptor or a JMOD).</p>
<p>The high level stages are briefly described as follows:</p>
<ul>
<li><p><strong>compile time</strong> (<code>javac</code>): As described on the <a href="https://docs.oracle.com/javase/9/tools/javac.htm" rel="noreferrer"><code>javac</code> documentation</a>, the compile time phase...</p>
<blockquote>
<p>...reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. It can also process annotations in Java source files and classes.</p>
</blockquote>
</li>
<li><p><strong>link time</strong> (<code>jlink</code>): As described on '<a href="https://openjdk.java.net/jeps/282" rel="noreferrer">JEP 282: jlink: The Java Linker</a>', the link time phase is...</p>
<blockquote>
<p>...an optional phase between the phases of compile time (the javac command) and run-time (the java run-time launcher). Link time requires a linking tool that will assemble and optimize a set of modules and their transitive dependencies to create a run-time image or executable.<br><br>
Link time is an opportunity to do whole-world optimizations that are otherwise difficult at compile time or costly at run-time. An example would be to optimize a computation when all its inputs become constant (i.e., not unknown). A follow-up optimization would be to remove code that is no longer reachable.</p>
</blockquote>
</li>
<li><p><strong>run time</strong> (<code>java</code>): As described on the <a href="https://docs.oracle.com/javase/9/tools/java.htm" rel="noreferrer"><code>javac</code> documentation</a>, the run time phase...</p>
<blockquote>
<p>...starts a Java application. It does this by starting the Java Runtime Environment (JRE), loading the specified class, and calling that class's main() method.</p>
</blockquote>
</li>
</ul>
<h3>Introduction of JMODs</h3>
<p>During the link time phase, all classes and resources from modules (valid JAR modules or form JMODs' <code>classes</code>) are compiled into a single optimized JIMAGE runtime image located at <code><jre>/lib/modules</code>. Modules not explicitly or transitively included will <em>not</em> be included into this final JIMAGE, saving a significant amount of space. However, when building a custom JRE, some additional files might be necessary inside of the JRE; e.g. executable commands or native libraries. For JAR modules, the story ends here - this is no way for a JAR to add files (beyond the classes included in the JIMAGE) into the built JRE without ambiguities.</p>
<p>Introducing JMODs: <strong>JMODs have the ability to add additional files into the custom built JRE</strong>; some examples (but not necessarily exhaustive): executable commands, configuration files, header files, legal notices and licenses, native libraries, and manual pages. This allows a module dependency to shape the built JRE in its own way. The behavior of how these additional files are inserted into the built JRE by the CLI tool <code>jlink</code> are documented within the next section.</p>
<p>JMODs are destined for <em>solely</em> for the compile time and link time phases, as described in '<a href="http://openjdk.java.net/jeps/261" rel="noreferrer">JEP 261: Module System</a>':</p>
<blockquote>
<p>JMOD files can be used at compile time and link time, but not at run time. To support them at run time would require, in general, that we be prepared to extract and link native-code libraries on-the-fly. This is feasible on most platforms, though it can be very tricky, and we have not seen many use cases that require this capability, so for simplicity we have chosen to limit the utility of JMOD files in this release.</p>
</blockquote>
<h3>The New Format - No Backwards Compatibility with JARs</h3>
<p>A good question might be "why not enable JARs to add link-time behavior?". A sneaking suspicion here is that this does not enable sufficient backwards-compatibility support with existing JARs and tooling. There is no specification for reserved filenames in the JAR archive file format. If an existing library stores any resources under the directories intended for link time, <code>jlink</code> could not accurately guess whether it is meant to be consumed during link time or needed at run time. A new file format specification with reserved directory names would resolve this clashing issue - such as the new JMOD format. With JMODs, there is no ambiguity about what resources are designated for link time and run time. Furthermore, the JMOD format can be also extended to add new functionalities in later JDK versions, without backwards-compatibility issues.</p>
<p>The JMOD file format is similar to a JAR in that it is based on the ZIP file format. A JMOD file has the following reserved directory names with the following behavior (this is not necessarily an exhaustive list!):</p>
<ul>
<li><code>bin</code> (<code>--cmds</code>): Executable commands that are copied to <code><jre>/bin</code></li>
<li><code>classes</code> (<code>--class-path</code>): Intended for including into the final built JIMAGE, stored at <code><jre>/lib/modules</code></li>
<li><code>conf</code> (<code>--config</code>): Additional configurations copied to <code><jre>/conf</code>; likely used to control configuration for any bundled modules, if required</li>
<li><code>include</code> (<code>--header-files</code>): Additional C header files that are copied to <code><jre>/include/</code> for building C libraries for the JVM using JNI; e.g. in <code>java.base</code>, the JNI interfaces are exported</li>
<li><code>legal</code> (<code>--legal-notices</code>): Legal notices and licenses for the module that are copied to <code><jre>/legal/<module name>/</code></li>
<li><code>lib</code> (<code>--libs</code>): Native libraries that are copied to <code><jre>/bin</code></li>
</ul>
<blockquote>
<p>For the curiously inclined, standard library JMODs (located under <code>$JAVA_HOME/jmods</code> in a JDK 9+) can be inspected with any application that reads ZIP archives.</p>
</blockquote>
<h3>Mainstream Support...?</h3>
<p>A significant part of the reason that JMODs have not been rapidly adopted and have poor documentation availability is that, quite simply put, they are not necessary for the vast majority of libraries and module dependencies. While they still are useful for specific use cases, modules should use the JAR format that already has mainstream support since it was defined with JDK 1.1 in 1997 (with <code>module-info.java</code> module support added with JDK 9 in 2017).</p>
<p>From the documentation of the CLI tool <a href="https://docs.oracle.com/en/java/javase/15/docs/specs/man/jmod.html" rel="noreferrer"><code>jmod</code></a>:</p>
<blockquote>
<p>For most development tasks, including deploying modules on the module path or publishing them to a Maven repository, continue to package modules in modular JAR files. The jmod tool is intended for modules that have native libraries or other configuration files or for modules that you intend to link, with the jlink tool, to a runtime image.</p>
</blockquote>
<p><strong>An opinion</strong>: JMODs will likely not gain any significant adoption by developers for at least a <em>very</em> long time. Most developers will never hear or know the purpose of a JMOD - nor will they need to. JMODs serve a critical purpose behind the scenes for building JREs (all of the Java standard library modules are JMODs), but do not affect the vast majority of applications and projects due to their niche use case at link time. Java 9 was released in 2017 and dependencies in the Java ecosystem still struggle to reliably have a <code>module-info.class</code> descriptor to make a JAR a valid fully-fledged module...</p>
<h2>Takeaways</h2>
<ul>
<li>JMODs are a fundamental new feature for creating JREs with the CLI tool <code>jlink</code> that enables customizing the custom built JRE with additional files.</li>
<li>Deploy JARs instead of JMODs, unless some features from JMODs are specifically needed. JAR modules are also compatible with <code>jlink</code>, so it is not necessary to ship a JMOD that only includes classes and resources. Ecosystem support and tooling is not necessarily going to adopt JMODs anytime soon and will certainly have compatibility issues for years to come.</li>
<li>Java documentation for this area of the ecosystem could <em>really</em> use some improvement.</li>
</ul>
<hr>
<h1>Disclaimer</h1>
<p>At the time of writing this answer, there was sparse documentation on the purpose of JMODs for Java 9 and onward. In fact, the Google search phrases "java jmods" and "jmod format" bring this very same StackOverflow question as the second search hit result. Therefore, some aspects may not be accurately explained, but are generally "directionally correct"; furthermore, it may not paint the full picture. If you find any issues or caveats, leave a comment and I will try to reconcile it with this answer.</p> |
6,796,866 | PHP date yesterday | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4780333/get-timestamp-of-today-and-yesterday-in-php">Get timestamp of today and yesterday in php</a> </p>
</blockquote>
<p>I was wondering if there was a simple way of getting yesterday's date through this format:</p>
<pre><code>date("F j, Y");
</code></pre> | 6,796,877 | 3 | 0 | null | 2011-07-22 22:44:24.893 UTC | 16 | 2018-07-18 05:03:41.243 UTC | 2017-05-23 12:03:02.24 UTC | null | -1 | user580523 | null | null | 1 | 129 | php|date | 218,976 | <p><a href="http://php.net/date"><code>date()</code></a> itself is only for formatting, but it accepts a second parameter.</p>
<pre><code>date("F j, Y", time() - 60 * 60 * 24);
</code></pre>
<p>To keep it simple I just subtract 24 hours from the unix timestamp.</p>
<p>A modern oop-approach is using <a href="http://php.net/book.datetime"><code>DateTime</code></a></p>
<pre><code>$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
</code></pre>
<p>Or in your case (more readable/obvious)</p>
<pre><code>$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
</code></pre>
<p>(Because <code>DateInterval</code> is negative here, we must <a href="http://php.net/datetime.add"><code>add()</code></a> it here)</p>
<p>See also: <a href="http://php.net/datetime.sub"><code>DateTime::sub()</code></a> and <a href="http://php.net/class.dateinterval"><code>DateInterval</code></a></p> |
6,540,106 | Change href value using jQuery | <p>How do I rewrite an href value, using jQuery?</p>
<p>I have links with a default city</p>
<pre><code><a href="/search/?what=parks&city=Paris">parks</a>
<a href="/search/?what=malls&city=Paris">malls</a>
</code></pre>
<p>If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.</p>
<p>So far I have</p>
<pre><code>var newCity = $("#city").val();
</code></pre> | 6,540,265 | 4 | 1 | null | 2011-06-30 19:31:23.633 UTC | 5 | 2018-02-16 23:55:29.617 UTC | 2018-02-16 23:55:29.617 UTC | null | 731,218 | null | 731,218 | null | 1 | 12 | javascript|jquery | 39,975 | <p>Given you have unique <code>href</code> values (<code>?what=parks</code>, and <code>?what=malls</code>) I would suggest <em>not</em> writing a path into the <code>$.attr()</code> method; you would have to have one call to <code>$.attr()</code> for each unique <code>href</code>, and that would grow to be very redundant, very quickly - not to mention difficult to manage.</p>
<p>Below I'm making one call to <code>$.attr()</code> and using a function to replace only the <code>&city=</code> portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the <code>href</code> values on each link.</p>
<pre><code>$("#city").change(function(o){
$("a.malls").attr('href', function(i,a){
return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
});
});
</code></pre>
<p>One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the <code>.toLowerCase()</code> JavaScript method, and you can replace the spaces with another call to <code>.replace()</code> as I've down below:</p>
<pre><code>'$1'+o.target.value.replace(/\s+/, '');
</code></pre>
<p>Online Demo: <a href="http://jsbin.com/ohejez/" rel="noreferrer">http://jsbin.com/ohejez/</a></p> |
6,387,907 | Whether to escape ( and ) in regex using GNU sed | <p>I've noticed several posts on this site which say that with gnu sed you should use <code>(</code> and <code>)</code> in regex rather than <code>\(</code> and <code>\)</code>. But then I looked in the <a href="http://www.gnu.org/software/sed/manual/sed.html#The-_0022s_0022-Command" rel="noreferrer">gnu sed manual</a> and saw that they specify that <code>\(</code> and <code>\)</code> must be used. What's up?</p> | 6,390,351 | 4 | 8 | null | 2011-06-17 15:13:16.853 UTC | 8 | 2018-05-13 02:48:29.417 UTC | 2018-05-13 02:48:29.417 UTC | null | 608,639 | null | 749,668 | null | 1 | 30 | regex|bash|sed|gnu | 28,494 | <p>Thanks to rocker, murga, and chris. Each of you helped me understand the issue. I'm answering my own question here in order to (hopefully) put the whole story together in one place.</p>
<p>There are two major versions of sed in use: gnu and bsd. Both of them require parens in basic regex to be escaped when used for grouping but not escaped when used in extended regex. They diff in that the -r option enables extended regex for gnu but -E does so for bsd.</p>
<p>The standard sed in mac OSX is bsd. I believe much of the rest of the world uses gnu sed as the standard but I don't know precisely who uses what. If you are unsure which you are using try:</p>
<pre><code>> sed -r
</code></pre>
<p>If you get a </p>
<pre><code>> sed: illegal option -- r
</code></pre>
<p>reply then you have bsd.</p> |
56,910,797 | iOS13 Navigation bar large titles not covering status bar | <p>On ios13, with iphone x, the large title navigation does not cover the status bar however when scrolling and transitioning into the traditional nav bar, it works perfectly. This doesn't affect devices without the notch.</p>
<p>Large titles
<a href="https://i.stack.imgur.com/0B8Sx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0B8Sx.png" alt="enter image description here"></a></p>
<p>Traditional navigation bar<br>
<a href="https://i.stack.imgur.com/0vWfp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0vWfp.png" alt=""></a> </p>
<p>It's all embedded within a navigation controller so i'm lost as to why this is happening. Cheers</p> | 57,031,470 | 3 | 4 | null | 2019-07-06 02:32:49.433 UTC | 11 | 2020-03-29 06:46:45.937 UTC | 2019-07-09 04:51:56.253 UTC | null | 4,384,775 | null | 11,117,382 | null | 1 | 48 | swift | 20,271 | <p>The official way to customize the UINavigationBar, pre iOS 13, is this:</p>
<pre class="lang-swift prettyprint-override"><code>// text/button color
UINavigationBar.appearance().tintColor = .white
// background color
UINavigationBar.appearance().barTintColor = .purple
// required to disable blur effect & allow barTintColor to work
UINavigationBar.appearance().isTranslucent = false
</code></pre>
<p>iOS 13 has changed how navigation bars work, so you'll need to do things slightly differently to support both old & new:</p>
<pre class="lang-swift prettyprint-override"><code>if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = .purple
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
} else {
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().barTintColor = .purple
UINavigationBar.appearance().isTranslucent = false
}
</code></pre> |
18,706,859 | Why is this an undefined behavior? | <p>My answer to <a href="https://stackoverflow.com/q/18706587/845092">this question</a> was this function:</p>
<pre><code>inline bool divisible15(unsigned int x)
{
//286331153 = (2^32 - 1) / 15
//4008636143 = (2^32) - 286331153
return x * 4008636143 <= 286331153;
}
</code></pre>
<p>It perfectly worked on my machine with VS2008 compiler, however <a href="http://ideone.com/HKqjiw" rel="nofollow noreferrer">here</a> it doesn't work at all.</p>
<p>Does anyone has an idea, why it I get different results on different compilers? <code>unsigned</code> overflow isn't undefined behavior.</p>
<p><strong>Important note:</strong> after some test it was confirmed it is faster than taking the remainder of the division by 15. (However not on all compilers)</p> | 18,707,097 | 2 | 16 | null | 2013-09-09 20:54:30.747 UTC | 3 | 2014-02-10 13:48:13.01 UTC | 2017-05-23 11:44:22.297 UTC | user2857423 | -1 | null | 1,237,747 | null | 1 | 59 | c++|c|undefined-behavior | 2,667 | <p>It's not Undefined Behavior, it's just a breaking change in the C language standard between C89 and C99.</p>
<p>In C89, integer constants like 4008636143 that don't fit in an <code>int</code> or <code>long int</code> but do fit in an <code>unsigned int</code> are unsigned, but in C99, they are either <code>long int</code> or <code>long long int</code> (depending on whichever one is the smallest one that can hold the value). As a result, the expressions all get evaluated using 64 bits, which results in the incorrect answer.</p>
<p>Visual Studio is a C89 compiler and so results in the C89 behavior, but that Ideone link is compiling in C99 mode.</p>
<p>This becomes more evident if you compile with GCC using <code>-Wall</code>:</p>
<pre><code>test.c: In function ‘divisible15’:
test.c:8:3: warning: this decimal constant is unsigned only in ISO C90
</code></pre>
<p>From C89 §3.1.3.2:</p>
<blockquote>
<p>The type of an integer constant is the first of the corresponding
list in which its value can be represented. Unsuffixed decimal: int,
long int, unsigned long int; unsuffixed octal or hexadecimal: int,
unsigned int, long int, unsigned long int; [...]</p>
</blockquote>
<p>C99 §6.4.4.1/5-6:</p>
<blockquote>
<p>5) The type of an integer constant is the first of the corresponding list in which its value can
be represented.</p>
<pre><code>Suffix | Decimal Constant | Octal or Hexadecimal Constant
-------+------------------+------------------------------
none | int | int
| long int | unsigned int
| long long int | long int
| | unsigned long int
| | long long int
| | unsigned long long int
-------+------------------+------------------------------
[...]
</code></pre>
<p>6) If an integer constant cannot be represented by any type in its list, it may have an
extended integer type, if the extended integer type can represent its value. If all of the
types in the list for the constant are signed, the extended integer type shall be signed. [...]</p>
</blockquote>
<p>For completeness, C++03 actually does have Undefined Behavior for when the integer constant is too big to fit in a <code>long int</code>. From C++03 §2.13.1/2:</p>
<blockquote>
<p>The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has
the first of these types in which its value can be represented: <code>int</code>, <code>long int</code>; if the value cannot be represented
as a <code>long int</code>, the behavior is undefined. If it is octal or hexadecimal and has no suffix, it has the
first of these types in which its value can be represented: <code>int</code>, <code>unsigned int</code>, <code>long int</code>, <code>unsigned
long int</code>. [...]</p>
</blockquote>
<p>The C++11 behavior is identical to C99, see C++11 §2.14.2/3.</p>
<p>To ensure that the code behaves consistently when compiled as either C89, C99, C++03, and C++11, the simple fix is to make the constant 4008636143 unsigned by suffixing it with <code>u</code> as <code>4008636143u</code>.</p> |
19,216,971 | Get selected text from dropdown in PHP | <p>I am totally new in PHP, in fact the reason I am doing this is to customize a wordpress plugin so it can fit my need. So far I have a default form, what I am doing now is to add a country dropdown. Here's how I add it</p>
<pre><code><div class="control-group">
<label class="control-label" for="Country">Country :</label>
<div class="controls">
<select id="itemType_id" name="cscf[country]" class="input-xlarge">
<option value="[email protected]">Malaysia</option>
<option value="[email protected]">Indonesia</option>
</select>
<span class="help-inline"></span>
</div>
</div>
</code></pre>
<p>So far I only able to retrieve the value of selected item with </p>
<pre><code>$cscf['country'];
</code></pre>
<p>How can I get the display text which is the country name in this case ?</p> | 19,218,327 | 4 | 2 | null | 2013-10-07 04:16:24.733 UTC | 3 | 2014-12-02 15:23:46.797 UTC | 2013-10-07 04:24:38.083 UTC | null | 2,794,221 | null | 1,412,803 | null | 1 | 4 | php|html|wordpress|forms | 56,906 | <p>You can use a hidden field, and with JavaScript and jQuery you can set the value to this field, when the selected value of your dropdown changes.</p>
<pre><code><select id="itemType_id" name="cscf[country]" class="input-xlarge">
<option value="[email protected]">Malaysia</option>
<option value="[email protected]">Indonesia</option>
</select>
<input type="hidden" name="country" id="country_hidden">
<script>
$(document).ready(function() {
$("#itemType_id").change(function(){
$("#country_hidden").val(("#itemType_id").find(":selected").text());
});
});
</script>
</code></pre>
<p>Then when your page is submitted, you can get the name of the country by using</p>
<pre><code>$_POST["country"]
</code></pre> |
40,224,272 | Using a Jenkins pipeline to checkout multiple git repos into same job | <p>I'm using the Jenkins Multiple SCM plugin to check out three git repositories into three sub directories in my Jenkins job. I then execute one set of commands to build a single set of artifacts with information and code drawn from all three repositories.</p>
<p>Multiple SCM is now depreciated, and the text recommends moving to pipelines. I tried, but I can't figure out how to make it work.</p>
<p>Here is the directory structure I'm interested in seeing from the top level of my Jenkins job directory:</p>
<pre><code>$ ls
Combination
CombinationBuilder
CombinationResults
</code></pre>
<p>Each of those three sub-directories has a single git repo checked out. With the Multiple SCM, I used git, and then added the "checkout to a subdirectory" behavior. Here was my attempt with a pipeline script:</p>
<pre><code>node('ATLAS && Linux') {
sh('[ -e CalibrationResults ] || mkdir CalibrationResults')
sh('cd CalibrationResults')
git url: 'https://github.com/AtlasBID/CalibrationResults.git'
sh('cd ..')
sh('[ -e Combination ] || mkdir Combination')
sh('cd Combination')
git url: 'https://github.com/AtlasBID/Combination.git'
sh('cd ..')
sh('[ -e CombinationBuilder ] || mkdir CombinationBuilder')
sh('cd CombinationBuilder')
git url: 'https://github.com/AtlasBID/CombinationBuilder.git'
sh 'cd ..'
sh('ls')
sh('. CombinationBuilder/build.sh')
}
</code></pre>
<p>However, the git command seems to execute at the top level directory of the workspace (which makes some sense), and according to the syntax too, there doesn't seem to be the checkout-to-sub-directory behavior.</p> | 40,225,216 | 5 | 3 | null | 2016-10-24 17:36:08.877 UTC | 23 | 2022-08-12 14:14:02.92 UTC | 2017-05-16 09:58:11.23 UTC | null | 572,939 | null | 69,455 | null | 1 | 90 | git|jenkins|jenkins-pipeline | 123,429 | <p>You can use the <code>dir</code> command to execute a pipeline step in a subdirectory:</p>
<pre class="lang-js prettyprint-override"><code>node('ATLAS && Linux') {
dir('CalibrationResults') {
git url: 'https://github.com/AtlasBID/CalibrationResults.git'
}
dir('Combination') {
git url: 'https://github.com/AtlasBID/Combination.git'
}
dir('CombinationBuilder') {
git url: 'https://github.com/AtlasBID/CombinationBuilder.git'
}
sh('ls')
sh('. CombinationBuilder/build.sh')
}
</code></pre> |
33,995,384 | Why attempt to print uninitialized variable does not always result in an error message | <p>Some may find it similar to the SO question <a href="https://stackoverflow.com/questions/24990691/will-java-final-variables-have-default-values?lq=1">Will Java Final variables have default values?</a> but that answer doesn't completely solve this, as that question doesn't directly print the value of x within instance initializer block. </p>
<p>The problem arises when I try to print x directly inside the instance initializer block, while having assigned a value to x before the end of the block :</p>
<h2>Case 1</h2>
<pre><code>class HelloWorld {
final int x;
{
System.out.println(x);
x = 7;
System.out.println(x);
}
HelloWorld() {
System.out.println("hi");
}
public static void main(String[] args) {
HelloWorld t = new HelloWorld();
}
}
</code></pre>
<p>This gives a compile time error stating that variable x might not have been initialized.</p>
<pre><code>$ javac HelloWorld.java
HelloWorld.java:6: error: variable x might not have been initialized
System.out.println(x);
^
1 error
</code></pre>
<h2>Case 2</h2>
<p>Instead of directly printing, I am calling a function to print:</p>
<pre><code>class HelloWorld {
final int x;
{
printX();
x = 7;
printX();
}
HelloWorld() {
System.out.println("hi");
}
void printX() {
System.out.println(x);
}
public static void main(String[] args) {
HelloWorld t = new HelloWorld();
}
}
</code></pre>
<p>This compiles correctly and gives output</p>
<pre><code>0
7
hi
</code></pre>
<p>What is the conceptual difference between the two cases?</p> | 33,995,839 | 6 | 18 | null | 2015-11-30 09:35:02.857 UTC | 9 | 2016-01-08 10:38:55.773 UTC | 2017-05-23 11:46:21.563 UTC | null | -1 | null | 5,315,585 | null | 1 | 55 | java|initialization|final | 10,237 | <p>In the JLS, <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.3">§8.3.3. Forward References During Field Initialization</a>, its stated that there's a compile-time error when:</p>
<blockquote>
<p>Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables
are in scope. Specifically, it is a compile-time error if all of the
following are true:</p>
<ul>
<li><p>The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;</p></li>
<li><p>The use is a simple name in either an instance variable initializer of C or an instance initializer of C;</p></li>
<li><p>The use is not on the left hand side of an assignment;</p></li>
<li><p>C is the innermost class or interface enclosing the use.</p></li>
</ul>
</blockquote>
<p>The following rules come with a few examples, of which the closest to yours is this one:</p>
<pre><code>class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
</code></pre>
<p>Accesses [to static or instance variables] by <strong>methods are not checked in this way</strong>, so the code above produces output <code>0</code>, because the variable initializer for <code>i</code> uses the class method <code>peek()</code> to access the value of the variable <code>j</code> before <code>j</code> has been initialized by its variable initializer, at which point it still has its default value (<a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5">§4.12.5 Initial Values of Variables</a>).</p>
<p>So, to summarize, your second example compiles and executes fine, because the compiler does not check if the <code>x</code> variable was already initialized when you invoke <code>printX()</code> and when <code>printX()</code> actually takes place at Runtime, the <code>x</code> variable will be assigned with its default value (<code>0</code>).</p> |
51,480,324 | Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton | <p>What is the proper way to register a custom hosted service in ASP.NET Core 2.1? For example, I have a custom hosted service derived from <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=aspnetcore-2.1" rel="noreferrer">BackgroundService</a> named <code>MyHostedService</code>. How should I register it?</p>
<pre><code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
services.AddSingleton<IHostedService, MyHostedService>();
}
</code></pre>
<p>or</p>
<pre><code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
services.AddHostedService<MyHostedService>();
}
</code></pre>
<p>?</p>
<p><a href="https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/" rel="noreferrer">Here</a> we can see the first case, but <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1" rel="noreferrer">here</a> there is a second case.</p>
<p>Are these methods equal?</p> | 51,480,627 | 2 | 3 | null | 2018-07-23 13:44:15.397 UTC | 13 | 2021-09-09 08:28:10.92 UTC | 2021-01-04 10:37:44.93 UTC | null | 4,981,637 | null | 5,195,032 | null | 1 | 62 | c#|asp.net-core|.net-core|dependency-injection|asp.net-core-hosted-services | 52,657 | <h2>Update</h2>
<blockquote>
<p>Somewhere between .Net Core 2.2 and 3.1 the behavior has changed, AddHostedService is now adding a Singleton instead of the previous Transient service.
Credit - <a href="https://stackoverflow.com/questions/51480324/proper-way-to-register-hostedservice-in-asp-net-core-addhostedservice-vs-addsin#comment110186397_51480627">Comment</a> by <a href="https://stackoverflow.com/users/329143/leong">LeonG</a></p>
</blockquote>
<pre><code>public static class ServiceCollectionHostedServiceExtensions
{
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, THostedService>());
return services;
}
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services, Func<IServiceProvider, THostedService> implementationFactory)
where THostedService : class, IHostedService
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService>(implementationFactory));
return services;
}
}
</code></pre>
<p>Reference <a href="https://source.dot.net/#Microsoft.Extensions.Hosting.Abstractions/ServiceCollectionHostedServiceExtensions.cs,44c8ac8d84044702" rel="noreferrer">ServiceCollectionHostedServiceExtensions</a></p>
<hr />
<h2>Original Answer</h2>
<p>They are similar but not completely</p>
<p><code>AddHostedService</code> is part of <code>Microsoft.Extensions.Hosting.Abstractions</code>.</p>
<p>It belongs to <code>Microsoft.Extensions.Hosting.Abstractions</code> in the <a href="https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting.Abstractions/ServiceCollectionHostedServiceExtensions.cs" rel="noreferrer"><code>ServiceCollectionHostedServiceExtensions</code></a> class</p>
<pre><code>using Microsoft.Extensions.Hosting;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionHostedServiceExtensions
{
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
=> services.AddTransient<IHostedService, THostedService>();
}
}
</code></pre>
<p>Note it is using <code>Transient</code> life time scope and not <code>Singleton</code></p>
<p>Internally the framework add all the hosted services to another service <a href="https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/Internal/HostedServiceExecutor.cs#L18" rel="noreferrer"><em>(<code>HostedServiceExecutor</code>)</em></a></p>
<pre><code>public HostedServiceExecutor(ILogger<HostedServiceExecutor> logger,
IEnumerable<IHostedService> services) //<<-- note services collection
{
_logger = logger;
_services = services;
}
</code></pre>
<p>at startup that is a singleton via the <a href="https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/Internal/WebHost.cs#L79" rel="noreferrer">WebHost Constructor</a>.</p>
<pre><code>_applicationServiceCollection.AddSingleton<HostedServiceExecutor>();
</code></pre> |
51,210,633 | Android P displaying API compatibility error message | <p>Running an app built against SDK level 27 on Android P somewhat unpredictably displays the following dialog (the dialog title is the name of the application):</p>
<p><a href="https://i.stack.imgur.com/8U6SP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8U6SP.png" alt="Mysterious dialog"></a></p>
<blockquote>
<p>Detected problems with API compatibility (visit g.co/dev/appcompat for more info)</p>
</blockquote>
<p>The URL leads to <a href="https://developer.android.com/preview/restrictions-non-sdk-interfaces" rel="noreferrer">this page about restrictions on non-SDK interfaces</a>. My application doesn't use reflection itself, but it does use Gson.</p>
<p>There are no immediately obvious log messages in Logcat, except may messages such as:</p>
<blockquote>
<p>Accessing hidden field Landroid/widget/AbsListView;->mIsChildViewEnabled:Z (light greylist, reflection)</p>
</blockquote> | 51,210,634 | 2 | 3 | null | 2018-07-06 12:36:20.127 UTC | 8 | 2019-01-16 13:35:04.587 UTC | null | null | null | null | 154,306 | null | 1 | 19 | android-9.0-pie | 14,033 | <p>Turns out that one of my Gson models exposed a getter that returned File. Gson uses reflection to recursively inspect the fields of classes, and in doing so, violates the reflection of disallowed SDK interfaces.</p>
<p>Reading the restriction document linked in the question got me to take a closer look at the log messages, and sure enough, one caught my attention:</p>
<blockquote>
<p>Accessing hidden field [...] (dark greylist, reflection)</p>
</blockquote>
<p>I don't recall exactly the message, but the point here is that it was in the <em>dark</em> greylist.</p>
<p>I discovered this by targeting SDK level 28 and enabling the new StrictMode feature <code>detectNonSdkApiUsage()</code>, upon which my application would crash with a stack trace:</p>
<pre><code>if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectNonSdkApiUsage()
.penaltyLog()
.build());
}
</code></pre>
<p>The stack trace wasn't immediately insightful, but it pointed me in the right direction.</p> |
4,912,966 | Link-local and global IPs on IPv6 interfaces | <p>I'm currently trying to understand how IPv6 adresses work. There are link-local and site-local adresses used for small and organisational networks respectively. But if one of those clients also has internet access, it would need two IPs, correct? One link/site-local and one global adress. How is that managed by the interface and the routers? One interface would need two IPs, since there is no NAT in IPv6.</p> | 4,918,560 | 2 | 3 | null | 2011-02-06 11:25:00.273 UTC | 9 | 2016-05-19 10:15:16.753 UTC | 2011-02-06 11:31:57.383 UTC | null | 368,354 | null | 368,354 | null | 1 | 8 | ipv6 | 17,740 | <p>In general, interfaces have one link-local scope unicast address and zero or more global scope unicast addresses. (They may be also members of some finite number of multicast groups.) Addresses may be assigned manually or by DHCPv6 as in IPv4, but they may also sometimes (not always) be automatically generated when the router advertisements permit it. Some host implementations will automatically generate a persistent global address for each prefix the router advertises and an ancillary privacy address to go along with it, c.f. <a href="https://www.rfc-editor.org/rfc/rfc4191" rel="nofollow noreferrer">RFC 4191</a>. Where DHCPv6 is used to assign addresses, hosts might request one or more temporary addresses to use instead of privacy addresses.</p>
<p>Don't use site-local addresses. They're deprecated by <a href="https://www.rfc-editor.org/rfc/rfc3879" rel="nofollow noreferrer">RFC 3879</a>, mainly because the <code>sin6_scope_id</code> field isn't well-defined for site-local addresses. Applications that see them in the list returned from <code>getifaddrs()</code> should probably discard them with a diagnostic message to the standard error stream. Applications should expect that network administrators will use Unique Local Addresses (ULA) instead of site-local addresses, c.f. <a href="https://www.rfc-editor.org/rfc/rfc4941" rel="nofollow noreferrer">RFC 4941</a>.</p>
<p>The reachability of ULA addresses is not generally decidable by application software. The only thing you know for certain about them is that they aren't reachable by any path that passes through the global public default-free zone. They may be reachable from anywhere on the Internet where the routes to the ULA prefix are exchanged in bilateral agreements between autonomous systems. On the other hand, they will often be advertised by IPv6 home gateways for subscriber local use only, and won't be reachable anywhere outside the home, c.f. <a href="https://datatracker.ietf.org/doc/html/draft-ietf-v6ops-ipv6-cpe-router" rel="nofollow noreferrer">I-D.ietf-v6ops-ipv6-cpe-router</a>.</p> |
4,972,696 | How do I connect to an existing database in ASP.NET MVC? | <p>I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the <code>App_Data</code> folder. I don't want to do this.</p>
<p>I'd like to create a new version of Nerd Dinner and move the connection string to the <code>web.config</code>, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.</p>
<p>What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?</p> | 4,972,739 | 2 | 0 | null | 2011-02-11 18:32:25.363 UTC | 3 | 2016-02-20 22:46:41.15 UTC | 2011-02-11 19:53:19.527 UTC | null | 16,587 | null | 421,020 | null | 1 | 16 | c#|sql-server|asp.net-mvc | 62,749 | <p>I always go to <a href="http://www.connectionstrings.com/" rel="noreferrer">http://www.connectionstrings.com/</a> when I forget how a connectionstring is written.</p>
<p><strong>Standard security SQL Server 2008</strong></p>
<p><code>Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;</code></p>
<p>Here is an article on MSDN talking about <a href="http://msdn.microsoft.com/en-us/library/ms178411.aspx" rel="noreferrer">How to: Read Connection Strings from the Web.config</a>.</p>
<p>You have a section almost at the top in your <code>Web.config</code> called connectionstrings, it could look something like this:</p>
<pre><code><connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
</code></pre>
<p>I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to <a href="http://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx" rel="noreferrer">ADO.NET Entity Framework here</a>. But first of all you should focus on getting your connection up and running to your database using the information at the top.</p> |
5,260,314 | Isn't an Int64 equal to a long in C#? | <p>I have been playing around with SQL and databases in C# via <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28v=vs.100%29.aspx" rel="noreferrer">SqlCeConnection</a>. I have been using <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader%28v=vs.110%29.aspx" rel="noreferrer">ExecuteReader</a> to read results and <a href="https://msdn.microsoft.com/en-us/library/ms187745.aspx" rel="noreferrer">BigInt</a> values for record IDs which are read into Longs.</p>
<p>Today I have been playing with SQL statements that use COUNT based statements ('SELECT COUNT(*) FROM X') and have been using <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.90%29.aspx" rel="noreferrer">ExecuteScalar</a> to read these single valued results.</p>
<p>However, I ran into an issue. I can't seem to store the values into a Long data type, which I have been using up to now. I can store them into Int64's.</p>
<p>I have been using BigInt for record IDs to get the maximum potential number of records.</p>
<p>A BigInt 8 bytes therefore is an Int64. Isn't a Long equal to an Int64 as both are 64-bit signed integers?</p>
<p>Therefore, why can't I cast an Int64 into a Long?</p>
<pre><code>long recordCount =0;
recordCount = (long)selectCommand.ExecuteScalar();
</code></pre>
<p>The error is:</p>
<blockquote>
<p>Specified cast is not valid.</p>
</blockquote>
<p>I can read a BigInt into a Long. It is not a problem.
I can't read an SQL COUNT into a long.</p>
<p>COUNT returns an Int (Int32), so the problem is in fact casting an Int32 into a long.</p> | 5,260,369 | 2 | 2 | null | 2011-03-10 13:35:44.47 UTC | 2 | 2015-07-08 15:53:53.927 UTC | 2015-07-08 11:10:07.387 UTC | null | 63,550 | user427165 | null | null | 1 | 32 | c#|sql-server-ce|long-integer|int64|int32 | 53,022 | <p><code>long</code> is <code>Int64</code> <a href="http://msdn.microsoft.com/en-us/library/ctetwysk%28v=vs.71%29.aspx" rel="noreferrer">in .NET</a>; it is just an alias in C#. Your problem is casting the return value to <code>long</code> and unless we know the type coming back from your query for sure, we would not know why you get an error. SQL BigInt must be convertable to <code>long</code>.</p>
<p>If it is the COUNT(*) which is coming back, then it is Int32. You need to use the <a href="https://msdn.microsoft.com/en-us/library/system.convert%28v=vs.110%29.aspx" rel="noreferrer"><code>Convert</code></a> class:</p>
<pre><code>long l = Convert.ToInt64(selectCommand.ExecuteScalar());
</code></pre> |
5,034,685 | What is the Haskell syntax to import modules in subdirectories? | <p>What is Haskell's syntax for importing modules in another directory?</p>
<p>I'm getting started with Haskell and want to practice writing simple functions TDD style with HUnit. I'm having trouble figuring out how to structure my files, though. The example that comes with HUnit seems to be a flat directory structure. </p>
<p>I'd like to have my tests and HUnit code in a different folder than my actual code. I'd appreciate a quick example import statement and a suggestion as to how I might structure my files. </p>
<p>If it matters, I'm using GHCi and NotePad++ to do my coding right now.</p> | 5,035,046 | 2 | 2 | null | 2011-02-17 21:09:17.55 UTC | 6 | 2021-04-20 02:14:01.34 UTC | 2015-09-05 19:10:39.437 UTC | null | 371,184 | null | 532,797 | null | 1 | 35 | haskell|hunit | 17,084 | <p>You don't actually do it from the Haskell source code; instead you tell the compiler where to look. The usual method is in the .cabal file. See <a href="https://www.haskell.org/cabal/users-guide/developing-packages.html" rel="noreferrer">the cabal user guide</a> for details. You want the "hs-source-dirs" parameter.</p>
<p>Alternatively you can pass the path directly to the compiler. However, Cabal is the better method.</p>
<p>Each pathname in the "hs-source-dirs" parameter specifies a root of a module hierarchy. Basically if you import a module called "Data.Foo.Bar" then the compiler looks for a file with the relative pathname "Data/Foo/Bar.hs" in each directory given by "hs-source-dirs" and imports the first one it finds.</p> |
16,526,814 | How would I implement 'copy url to clipboard' from a link or button using javascript or dojo without flash | <p>I got stucked in implementing this feature on my web application. All the other possibilities are mostly by using flash content. Could someone explain how I can achieve it by using plain javascript or by Dojo. </p> | 16,544,474 | 5 | 5 | null | 2013-05-13 16:24:57.747 UTC | 3 | 2021-12-07 07:35:45.677 UTC | 2015-09-11 13:58:41.507 UTC | null | 82,595 | null | 2,117,376 | null | 1 | 4 | javascript|dojo | 44,996 | <p>I have been working on the exact same issue for a while. For me flash isn't a viable solution so I came up with this simple work around:</p>
<p><code><button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard','copy me')">Click to Copy</button></code></p>
<p>It requires some extra work on the users end but at least it doesn't require flash or external libraries.</p>
<p><a href="http://jsfiddle.net/zYFJf/" rel="noreferrer">example fiddle</a></p> |
1,077,216 | How do you Make A Repeat-Until Loop in C++? | <p>How do you Make A Repeat-Until Loop in C++? As opposed to a standard While or For loop. I need to check the condition at the end of each iteration, rather than at the beginning.</p> | 1,077,229 | 7 | 0 | null | 2009-07-02 23:36:19.127 UTC | 2 | 2021-02-28 19:11:48.94 UTC | null | null | null | null | null | null | 1 | 28 | c++|loops|for-loop|while-loop | 177,825 | <pre><code>do
{
// whatever
} while ( !condition );
</code></pre> |
776,950 | JavaScript: undefined !== undefined? | <p><em>NOTE: As per <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.1.3" rel="noreferrer">ECMAScript5.1, section 15.1.1.3</a>, window.undefined is read-only.</em></p>
<ul>
<li><em>Modern browsers implement this correctly. for example: Safari 5.1, Firefox 7, Chrome 20, etc.</em></li>
<li><em>Undefined is still changeable in: Chrome 14, ...</em></li>
</ul>
<p>When I recently integrated <a href="http://en.wikipedia.org/wiki/Facebook_Platform#Facebook_Connect" rel="noreferrer">Facebook Connect</a> with <a href="http://www.tersus.com" rel="noreferrer">Tersus</a>, I initially received the error messages <code>Invalid Enumeration Value</code> and <code>Handler already exists</code> when trying to call Facebook API functions.</p>
<p>It turned out that the cause of the problem was</p>
<pre><code>object.x === undefined
</code></pre>
<p>returning false when there is no property 'x' in 'object'.</p>
<p>I worked around the problem by replacing strict equality with regular equality in two Facebook functions:</p>
<pre><code>FB.Sys.isUndefined = function(o) { return o == undefined;};
FB.Sys.containsKey = function(d, key) { return d[key] != undefined;};
</code></pre>
<p>This made things work for me, but seems to hint at some sort of collision between Facebook's JavaScript code and my own.</p>
<p>What could cause this?</p>
<p>Hint: It is well documented that <code>undefined == null</code> while <code>undefined !== null</code>. This is not the issue here. The question is how comes we get <code>undefined !== undefined</code>.</p> | 790,615 | 7 | 3 | null | 2009-04-22 12:23:14.203 UTC | 29 | 2014-11-26 12:02:01.877 UTC | 2014-03-09 10:16:25.737 UTC | null | 63,550 | null | 94,259 | null | 1 | 68 | javascript | 115,946 | <p>It turns out that you can set window.undefined to whatever you want, and so get <code>object.x !== undefined</code> when object.x is the <em>real</em> undefined. In my case I inadvertently set undefined to null.</p>
<p>The easiest way to see this happen is:</p>
<pre><code>window.undefined = null;
alert(window.xyzw === undefined); // shows false
</code></pre>
<p>Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.</p>
<pre><code>var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
</code></pre> |
299,128 | SQL Server Dependencies | <p>Is there an easy way to chase down table/stored procedure/function dependencies in SQL Server 2005+? I've inherited a giant application with lots of tables and even more stored procedures and functions that are long and interlinked. </p>
<p>At the end of the day is there a way to build a dependency tree? Ideally what I'm looking for goes in both directions:</p>
<p><strong>For a table/procedure - what depends ON it?</strong>: Show me all the stored procedures that eventually reference it (ideally in a tree view such that sub procedures nest out to the bigger procedures that call them)</p>
<p><strong>For a procedure - what does IT depend on?</strong>: Show me all the procedures and tables that a given procedure will (or could) touch when running.</p>
<p>It seems this tool shouldn't be that hard to make and would be incredibly useful for DB maintenance generally. Is anyone aware of such a thing? If this doesn't exist, why the heck not?</p>
<p>The built-in functionality in Management Studio is nice but the information does not appear to be complete at all.</p> | 299,157 | 8 | 0 | null | 2008-11-18 15:47:01.423 UTC | 9 | 2015-11-26 10:21:35.597 UTC | 2011-08-24 16:40:14.7 UTC | Cory | 23,199 | Cory | 8,207 | null | 1 | 11 | sql-server | 13,607 | <p>Red Gate has a pretty useful tool called <a href="http://www.red-gate.com/products/SQL_Dependency_Tracker/index.htm" rel="noreferrer">SQL Dependency Tracker</a>. We've successfully used it for the type of results you're wishing to obtain.</p> |
261,219 | Class Variables in Javascript | <p>I'm having a bit of trouble trying to get class variables to work in javascript. </p>
<p>I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables.</p>
<p>This is why this bit of code confuses me.</p>
<p>What is the correct way to implement class variables?</p>
<pre><code>function classA() {};
classA.prototype.shared = 0;
a = new classA;
//print both values to make sure that they are the same
classA.prototype.shared;
a.shared;
//increment class variable
classA.prototype.shared++;
//Verify that they are each 1 (Works)
classA.prototype.shared;
a.shared;
//now increment the other reference
a.shared++;
//Verify that they are each 2 (Doesn't Work)
classA.prototype.shared;
a.shared;
</code></pre>
<p>UPDATE:
So it seems that everyone is confirming the fact that by incrementing the instance's variable we don't affect the prototype. This is fine, this is what I have documented in my example, but doesn't this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance's var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object. </p>
<p>I also understand that this isn't java/c++/ruby/python, it's a different language. I'm just curious as to why this behavior might be good. </p> | 261,948 | 8 | 1 | null | 2008-11-04 08:07:10.007 UTC | 4 | 2014-11-25 23:35:50.37 UTC | 2008-11-04 16:48:37.473 UTC | esiegel | 28,486 | esiegel | 28,486 | null | 1 | 17 | javascript|oop|inheritance | 38,778 | <pre><code>I assumed that since prototypes will be shared between objects then so will their variables.
</code></pre>
<p>They are, but this:</p>
<pre><code>a.shared++
</code></pre>
<p>is not doing what you think it's doing. It's in fact (approximately) sugar syntax for:</p>
<pre><code>(a.shared= a.shared+1)-1
</code></pre>
<p>(the -1 being to return the pre-increment value, not that you're actually using the retrun value, but still.)</p>
<p>So this is actually doing an assigment to a.shared. When you assign to an instance member you are always writing to that instance's own members, <em>not</em> touching any members of any of its prototypes. It's the same as saying:</p>
<pre><code>classA.prototype.shared= 1;
a.shared= 2;
</code></pre>
<p>So your new a.shared hides the prototype.shared without altering it. Other instances of classA would continue to show the prototype's value 1. If you deleted a.shared you would once again be able to see the prototype's variable that was hidden behind it.</p> |
584,285 | Detecting IE6 using jQuery.support | <p>Anyone have any ideas on how to test for something specific for IE6 (and not IE7) using jquery.support?</p>
<p>My problem is that IE6 supports :hover psuedo-class only for anchor elements and IE7 does support it for all elements (as FF, Chrome, etc). So I want to do something special in case the browser does not support :hover for all elements... thus I need a way to test for this feature. (don't want to use jQuery.browser). Any ideas?</p> | 584,417 | 8 | 1 | null | 2009-02-25 00:30:33.687 UTC | 22 | 2013-09-06 19:14:59.043 UTC | 2013-09-06 19:14:59.043 UTC | null | 881,229 | null | 33,160 | null | 1 | 34 | jquery|browser-detection | 62,739 | <p>While it's good practice to check for feature support rather then user agent, there's no simple way to check for something like support of a css property using JavaScript. I recommend you either follow the above posters suggestion of using conditional comments or use jQuery.browser. A simple implementation (not validated for performance or bugs) could look like this:</p>
<pre><code>if ($.browser.msie && $.browser.version.substr(0,1)<7) {
// search for selectors you want to add hover behavior to
$('.jshover').hover(
function() {
$(this).addClass('over');
},
function() {
$(this).removeClass('over');
}
}
</code></pre>
<p>In your markup, add the .jshover class to any element you want hover css effects on. In your css, add rules like this:</p>
<pre><code>ul li:hover, ul li.over { rules here }
</code></pre> |
349,520 | Built-in helper to parse User.Identity.Name into Domain\Username | <p>Is there any built-in utility or helper to parse <code>HttpContext.Current.User.Identity.Name</code>, e.g. <code>domain\user</code> to get separately domain name if exists and user?</p>
<p>Or is there any other class to do so?</p>
<p>I understand that it's very easy to call <code>String.Split("\")</code> but just interesting</p> | 350,142 | 8 | 1 | null | 2008-12-08 13:14:37.34 UTC | 9 | 2014-12-18 22:47:26.867 UTC | 2014-12-18 22:47:26.867 UTC | null | 41,956 | abatishchev | 41,956 | null | 1 | 47 | c#|asp.net|.net|authentication|active-directory | 45,265 | <p>This is better (<em>easier to use, no opportunity of <code>NullReferenceExcpetion</code> and conforms MS coding guidelines about treating empty and null string equally</em>):</p>
<pre><code>public static class Extensions
{
public static string GetDomain(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop) : string.Empty;
}
public static string GetLogin(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();
</code></pre>
<p>This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.</p> |
1,053,060 | file put contents with array | <p>I am using <code>file_put_contents($file, $data);</code> function for putting contents in file, because these files are created on fly with name of sessions, <strong>$data</strong> is an multi-dimensional array, when i am echoing array it prints out fine but in file no contents get recorded except the word <strong>Array</strong></p>
<p>What should i do or is there any other function which automatically creates the file and records the data (array)?</p>
<p>Thank You.</p> | 1,053,069 | 9 | 0 | null | 2009-06-27 15:45:27.583 UTC | 6 | 2020-07-16 03:23:31.17 UTC | null | null | null | null | 107,129 | null | 1 | 18 | php | 54,506 | <p>You want to <code>serialize()</code> the array on writting, and <code>unserialize()</code> after reading the file.</p>
<pre><code>$array = array('foo' => 'bar');
file_put_contents('foo.txt', serialize($array));
$array = unserialize(file_get_contents('foo.txt')));
</code></pre>
<p>Oh, and I really don't now how you echo'd your array, but <code>echo array('foo' => 'bar');</code> will always print <code>Array</code>.</p> |
932,721 | Efficient heaps in purely functional languages | <p>As an exercise in Haskell, I'm trying to implement heapsort. The heap is usually implemented as an array in imperative languages, but this would be hugely inefficient in purely functional languages. So I've looked at binary heaps, but everything I found so far describes them from an imperative viewpoint and the algorithms presented are hard to translate to a functional setting. How to efficiently implement a heap in a purely functional language such as Haskell?</p>
<p><em>Edit:</em> By efficient I mean it should still be in O(n*log n), but it doesn't have to beat a C program. Also, I'd like to use purely functional programming. What else would be the point of doing it in Haskell?</p> | 932,945 | 9 | 0 | null | 2009-05-31 19:52:23.24 UTC | 15 | 2014-01-15 17:14:16.64 UTC | 2010-01-31 07:19:03.61 UTC | Roger Pate | null | null | 46,450 | null | 1 | 38 | haskell|functional-programming|binary-heap|heapsort|purely-functional | 11,157 | <p>There are a number of Haskell heap implementations in an appendix to Okasaki's <a href="http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#cup98" rel="noreferrer"><em>Purely Functional Data Structures</em></a>. (The source code can be downloaded at the link. The book itself is well worth reading.) None of them are binary heaps, per se, but the <a href="http://en.wikipedia.org/wiki/Leftist_tree" rel="noreferrer">"leftist" heap</a> is very similar. It has O(log n) insertion, removal, and merge operations. There are also more complicated data structures like <a href="http://en.wikipedia.org/wiki/Skew_heap" rel="noreferrer">skew heaps</a>, <a href="http://en.wikipedia.org/wiki/Binomial_heap" rel="noreferrer">binomial heaps</a>, and <a href="http://en.wikipedia.org/wiki/Splay_heap" rel="noreferrer">splay heaps</a> which have better performance.</p> |
616,149 | How and why do I set up a C# build machine? | <p>I'm working with a small (4 person) development team on a C# project. I've proposed setting up a build machine which will do nightly builds and tests of the project, because I understand that this is a Good Thing. Trouble is, we don't have a whole lot of budget here, so I have to justify the expense to the powers that be. So I want to know:</p>
<p>
<li> What kind of tools/licenses will I need? Right now, we use Visual Studio and Smart Assembly to build, and Perforce for source control. Will I need something else, or is there an equivalent of a cron job for running automated scripts?
<li> What, exactly, will this get me, other than an indication of a broken build? Should I set up test projects in this solution (sln file) that will be run by these scripts, so I can have particular functions tested? We have, at the moment, two such tests, because we haven't had the time (or frankly, the experience) to make good unit tests.
<li> What kind of hardware will I need for this?
<li> Once a build has been finished and tested, is it a common practice to put that build up on an ftp site or have some other way for internal access? The idea is that this machine makes <em>the</em> build, and we all go to it, but can make debug builds if we have to.<br>
<li> How often should we make this kind of build?
<li> How is space managed? If we make nightly builds, should we keep around all the old builds, or start to ditch them after about a week or so?
<li> Is there anything else I'm not seeing here?
</p>
<p>I realize that this is a very large topic, and I'm just starting out. I couldn't find a duplicate of this question here, and if there's a book out there I should just get, please let me know.</p>
<p>EDIT: I finally got it to work! Hudson is completely fantastic, and FxCop is showing that some features we thought were implemented were actually incomplete. We also had to change the installer type from Old-And-Busted vdproj to New Hotness WiX.</p>
<p>Basically, for those who are paying attention, if you can run your build from the command line, then you can put it into hudson. Making the build run from the command line via MSBuild is a useful exercise in itself, because it forces your tools to be current.</p> | 616,230 | 9 | 2 | null | 2009-03-05 19:03:47.483 UTC | 111 | 2016-05-27 11:59:54.74 UTC | 2010-05-03 23:12:37.043 UTC | mmr | 56,285 | mmr | 21,981 | null | 1 | 144 | c#|build|continuous-integration|build-automation|hudson | 41,008 | <p>Update: <a href="http://jenkins-ci.org/" rel="nofollow noreferrer"><strong>Jenkins</strong></a> is the most up to date version of Hudson. Everyone should be using Jenkins now. I'll be updating the links accordingly.</p>
<p><a href="https://wiki.jenkins-ci.org/display/JENKINS/Meet+Jenkins" rel="nofollow noreferrer"><strong>Hudson</strong></a> is free and extremely easy to configure and will easily run on a VM.</p>
<p>Partly from an old post of mine:</p>
<p>We use it to</p>
<ul>
<li>Deploy Windows services</li>
<li>Deploy web services</li>
<li>Run MSTests & display as much information as any junit tests</li>
<li>Keep track of low,med,high tasks</li>
<li>trendgraph warnings and errors</li>
</ul>
<p>Here are some of the built in .net stuff that Hudson supports</p>
<ul>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/MSBuild+Plugin" rel="nofollow noreferrer">MSBuild</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/NAnt+Plugin" rel="nofollow noreferrer">NAnt</a></li>
<li><a href="https://stackoverflow.com/questions/352703/integrating-hudson-with-ms-test/512092#512092">MSTest</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/NUnit+Plugin" rel="nofollow noreferrer">Nunit</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/Team+Foundation+Server+Plugin" rel="nofollow noreferrer">Team Foundation Server</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/Violations" rel="nofollow noreferrer">fxcop</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/Violations" rel="nofollow noreferrer">stylecop</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/Warnings+Plugin" rel="nofollow noreferrer">compiler warnings</a></li>
<li><a href="https://wiki.jenkins-ci.org/display/JENKINS/Task+Scanner+Plugin" rel="nofollow noreferrer">code tasks</a></li>
</ul>
<p>Also, god forbid you are using visual source safe, <a href="https://wiki.jenkins-ci.org/display/JENKINS/Visual+SourceSafe+Plugin" rel="nofollow noreferrer">it supports that as well</a>. I'd recommend you take a look at <a href="http://redsolo.blogspot.com/2008/04/guide-to-building-net-projects-using.html" rel="nofollow noreferrer">Redsolo's article on building .net projects using Hudson</a></p>
<p><strong>Your questions</strong></p>
<ul>
<li><p><strong>Q</strong>: What kind of tools/licenses will I need? Right now, we use Visual Studio and Smart Assembly to build, and Perforce for source control. Will I need something else, or is there an equivalent of a cron job for running automated scripts?</p></li>
<li><p><strong>A:</strong> I just installed visual studio on a fresh copy of a VM running a fresh, patched, install of a windows server OS. So you'd need the licenses to handle that. Hudson will install itself as a windows service and run on port 8080 and you will configure how often you want it to scan your code repository for updated code, or you can tell it to build at a certain time. All configurable through the browser.</p></li>
<li><p><strong>Q:</strong> What, exactly, will this get me, other than an indication of a broken build? Should I set up test projects in this solution (sln file) that will be run by these scripts, so I can have particular functions tested? We have, at the moment, two such tests, because we haven't had the time (or frankly, the experience) to make good unit tests.</p>
<p><strong>A:</strong> You will get an email on the first time a build fails, or becomes unstable. A build is unstable if a unit test fails or it can be marked unstable through any number of criteria that you set. When a unit test or build fails you will be emailed and it will tell you where, why and how it failed. With my configuration, we get:</p>
<ul>
<li>list of all commits since the last working build</li>
<li>commit notes of those commits</li>
<li>list of files changed in the commits </li>
<li>console output from the build itself, showing the error or test failure</li>
</ul></li>
<li><p><strong>Q:</strong> What kind of hardware will I need for this?</p>
<p><strong>A:</strong> A VM will suffice</p></li>
<li><p><strong>Q:</strong> Once a build has been finished and tested, is it a common practice to put that build up on an ftp site or have some other way for internal access? The idea is that this machine makes the build, and we all go to it, but can make debug builds if we have to.</p>
<p><strong>A:</strong> Hudson can do whatever you want with it, that includes ID'ing it via the md5 hash, uploading it, copying it, archiving it, etc. It does this automatically and provides you with a long running history of build artifacts.</p></li>
<li><p><strong>Q:</strong> How often should we make this kind of build?</p>
<p><strong>A:</strong> We have ours poll SVN every hour, looking for code changes, then running a build. Nightly is ok, but somewhat worthless IMO since what you've worked on yesterday wont be fresh in your mind in the morning when you get in.</p></li>
<li><p><strong>Q:</strong> How is space managed? If we make nightly builds, should we keep around all the old builds, or start to ditch them after about a week or so?</p>
<p><strong>A:</strong> Thats up to you, after so long I move our build artifacts to long term storage or delete them, but all the data which is stored in text files / xml files I keep around, this lets me store the changelog, trend graphs, etc on the server with verrrry little space consumed. Also you can set Hudson up to only keep artifacts from a trailing # of builds</p></li>
<li><p><strong>Q:</strong> Is there anything else I'm not seeing here?</p>
<p><strong>A:</strong> No, Go get Hudson right now, you wont be disappointed!</p></li>
</ul> |
1,249,394 | How to SELECT a dropdown list item by value programmatically | <p>How to SELECT a drop down list item by value programatically in C#.NET?</p> | 1,249,467 | 10 | 4 | null | 2009-08-08 17:15:53.84 UTC | 15 | 2020-03-05 10:47:16.187 UTC | 2017-04-04 12:07:59.167 UTC | null | 1,033,581 | null | 44,973 | null | 1 | 45 | c#|.net|drop-down-menu | 286,878 | <p>If you know that the dropdownlist contains the value you're looking to select, use:</p>
<pre><code>ddl.SelectedValue = "2";
</code></pre>
<p>If you're not sure if the value exists, use (or you'll get a null reference exception):</p>
<pre><code>ListItem selectedListItem = ddl.Items.FindByValue("2");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
</code></pre> |
16,007 | How do I convert a file path to a URL in ASP.NET | <p>Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.</p>
<pre><code>if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
</code></pre> | 16,039 | 10 | 0 | null | 2008-08-19 11:24:55.907 UTC | 5 | 2018-01-12 23:36:23.397 UTC | 2015-03-06 04:32:53.627 UTC | null | 249,341 | Andy Rose | 1,762 | null | 1 | 47 | asp.net|url|image | 114,864 | <p>As far as I know, there's no method to do what you want; at least not directly. I'd store the <code>photosLocation</code> as a path relative to the application; for example: <code>"~/Images/"</code>. This way, you could use MapPath to get the physical location, and <code>ResolveUrl</code> to get the URL (with a bit of help from <code>System.IO.Path</code>):</p>
<pre><code>string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
if (files.Length > 0)
{
string filenameRelative = photosLocation + Path.GetFilename(files[0])
return Page.ResolveUrl(filenameRelative);
}
}
</code></pre> |
1,101,957 | Are there any standard exit status codes in Linux? | <p>A process is considered to have completed correctly in Linux if its exit status was 0.</p>
<p>I've seen that segmentation faults often result in an exit status of 11, though I don't know if this is simply the convention where I work (the applications that failed like that have all been internal) or a standard.</p>
<p>Are there standard exit codes for processes in Linux?</p> | 1,104,641 | 10 | 1 | null | 2009-07-09 05:24:04.413 UTC | 145 | 2022-04-24 18:59:00.2 UTC | 2022-04-24 18:41:29.137 UTC | null | 63,550 | null | 1,084 | null | 1 | 356 | linux|error-handling|exit-code | 324,080 | <p>8 bits of the return code and 8 bits of the number of the killing signal are mixed into a single value on the return from <a href="http://linux.die.net/man/2/wait" rel="noreferrer"><code>wait(2)</code> & co.</a>.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
int main() {
int status;
pid_t child = fork();
if (child <= 0)
exit(42);
waitpid(child, &status, 0);
if (WIFEXITED(status))
printf("first child exited with %u\n", WEXITSTATUS(status));
/* prints: "first child exited with 42" */
child = fork();
if (child <= 0)
kill(getpid(), SIGSEGV);
waitpid(child, &status, 0);
if (WIFSIGNALED(status))
printf("second child died with %u\n", WTERMSIG(status));
/* prints: "second child died with 11" */
}
</code></pre>
<p>How are you determining the exit status? Traditionally, the shell only stores an 8-bit return code, but sets the high bit if the process was abnormally terminated.</p>
<pre>
$ sh -c 'exit 42'; echo $?
42
$ sh -c 'kill -SEGV $$'; echo $?
Segmentation fault
139
$ expr 139 - 128
11
</pre>
<p>If you're seeing anything other than this, then the program probably has a <code>SIGSEGV</code> signal handler which then calls <code>exit</code> normally, so it isn't actually getting killed by the signal. (Programs can chose to handle any signals aside from <code>SIGKILL</code> and <code>SIGSTOP</code>.)</p> |
951,320 | How to Concatenate Numbers and Strings to Format Numbers in T-SQL? | <p>I have the following function </p>
<pre><code>ALTER FUNCTION [dbo].[ActualWeightDIMS]
(
-- Add the parameters for the function here
@ActualWeight int,
@Actual_Dims_Lenght int,
@Actual_Dims_Width int,
@Actual_Dims_Height int
)
RETURNS varchar(50)
AS
BEGIN
DECLARE @ActualWeightDIMS varchar(50);
--Actual Weight
IF (@ActualWeight is not null)
SET @ActualWeightDIMS = @ActualWeight;
--Actual DIMS
IF (@Actual_Dims_Lenght is not null) AND
(@Actual_Dims_Width is not null) AND (@Actual_Dims_Height is not null)
SET @ActualWeightDIMS= @Actual_Dims_Lenght + 'x' + @Actual_Dims_Width + 'x' + @Actual_Dims_Height;
RETURN(@ActualWeightDIMS);
END
</code></pre>
<p>but when i tried to use it, i got the following error "Conversion failed when converting the varchar value 'x' to data type int." when i use the following select statement</p>
<pre><code>select
BA_Adjustment_Detail.ID_Number [ID_Number],
BA_Adjustment_Detail.Submit_Date [Submit_Date],
BA_Category.Category [category],
BA_Type_Of_Request.Request [Type_Of_Request],
dbo.ActualWeightDIMS(BA_Adjustment_Detail.ActualWeight,BA_Adjustment_Detail.Actual_Dims_Lenght,BA_Adjustment_Detail.Actual_Dims_Width,BA_Adjustment_Detail.Actual_Dims_Height) [Actual Weight/DIMS],
BA_Adjustment_Detail.Notes [Notes],
BA_Adjustment_Detail.UPSCustomerNo [UPSNo],
BA_Adjustment_Detail.TrackingNo [AirbillNo],
BA_Adjustment_Detail.StoreNo [StoreNo],
BA_Adjustment_Detail.Download_Date [Download_Date],
BA_Adjustment_Detail.Shipment_Date[ShipmentDate],
BA_Adjustment_Detail.FranchiseNo [FranchiseNo],
BA_Adjustment_Detail.CustomerNo [CustomerNo],
BA_Adjustment_Detail.BillTo [BillTo],
BA_Adjustment_Detail.Adjustment_Amount_Requested [Adjustment_Amount_Requested]
from BA_Adjustment_Detail
inner join BA_Category
on BA_Category.ID = BA_Adjustment_Detail.CategoryID
inner join BA_Type_Of_Request
on BA_Type_Of_Request.ID = BA_Adjustment_Detail.TypeOfRequestID
</code></pre>
<p>What I want to do is if the ActualWeight is not null then return the ActualWeight for the "Actual Weight/DIMS" or else use the Actual_Dims_Lenght, Width and Height.</p>
<p>If it is DIMS then i want to format the output to be LenghtxWidhtxHeight (15x10x4). The ActualWeight, Adcutal_Dims_Lenght, Width and Height are all int (integer) value but the output for "Actual Weight/DIMS" should be varchar(50).</p>
<p>Where am i getting it wrong?</p>
<p>thank</p>
<p>edit: The user can only pick either Weight or DIMS on ASP.net page and if user selected DIMS then they must supply Length, Width and Height. Else it will throw error on the ASP.net page. Should i worry about it on the sql side? </p> | 951,365 | 10 | 0 | null | 2009-06-04 15:34:11.257 UTC | 11 | 2016-05-16 21:40:00.293 UTC | 2009-06-04 16:01:50.27 UTC | null | 28,647 | null | 28,647 | null | 1 | 117 | sql|tsql | 312,919 | <p>A couple of quick notes:</p>
<ul>
<li>It's "length" not "lenght"</li>
<li>Table aliases in your query would probably make it a lot more readable</li>
</ul>
<p>Now onto the problem...</p>
<p>You need to explicitly convert your parameters to VARCHAR before trying to concatenate them. When SQL Server sees @my_int + 'X' it thinks you're trying to add the number "X" to @my_int and it can't do that. Instead try:</p>
<pre><code>SET @ActualWeightDIMS =
CAST(@Actual_Dims_Lenght AS VARCHAR(16)) + 'x' +
CAST(@Actual_Dims_Width AS VARCHAR(16)) + 'x' +
CAST(@Actual_Dims_Height AS VARCHAR(16))
</code></pre> |
752,758 | Is using a lot of static methods a bad thing? | <p>I tend to declare as static all the methods in a class when that class doesn't require to keep track of internal states. For example, if I need to transform A into B and don't rely on some internal state C that may vary, I create a static transform. If there is an internal state C that I want to be able to adjust, then I add a constructor to set C and don't use a static transform.</p>
<p>I read various recommendations (including on StackOverflow) NOT to overuse static methods but I still fail to understand what it wrong with the rule of thumb above.</p>
<p>Is that a reasonable approach or not?</p> | 752,805 | 15 | 1 | null | 2009-04-15 17:12:37.707 UTC | 38 | 2018-05-15 02:23:07.413 UTC | 2013-07-02 17:46:37.463 UTC | null | 439,427 | null | 91,208 | null | 1 | 120 | language-agnostic|static-methods | 42,407 | <p>There are two kinds of common static methods:</p>
<ul>
<li>A "safe" static method will always give the same output for the same inputs. It modifies no globals and doesn't call any "unsafe" static methods of any class. Essentially, you are using a limited sort of functional programming -- don't be afraid of these, they're fine.</li>
<li>An "unsafe" static method mutates global state, or proxies to a global object, or some other non-testable behavior. These are throwbacks to procedural programming and should be refactored if at all possible.</li>
</ul>
<p>There are a few common uses of "unsafe" statics -- for example, in the Singleton pattern -- but be aware that despite any pretty names you call them, you're just mutating global variables. Think carefully before using unsafe statics.</p> |
496,233 | What are your best Swing design patterns and tips? | <p>I'm writing a GUI for an application using Swing, and in the interests of code maintenance and readability, I want to follow a consistent pattern throughout the whole system.</p>
<p>Most of the articles and books (or at least book sections) that I've read appear to provide plenty of examples on how to create and arrange various components, but ignore the bigger picture of writing a full GUI.</p>
<p>What are your best tips for application GUI design, and what patterns do you follow when designing or refactoring a GUI application?</p> | 496,252 | 16 | 1 | 2009-01-30 16:45:59.023 UTC | 2009-01-30 16:45:59.287 UTC | 29 | 2011-10-31 16:34:18.22 UTC | null | null | null | Mr Potato Head | 40,581 | null | 1 | 37 | java|user-interface|design-patterns|swing | 24,177 | <p>Use layout managers. You might think it's simpler just to position everything with hard coded positions now (especially if you use a graphical layout tool), but when it comes time to update the gui, or internationalize it, your successors will hate you. (Trust me on this, I was the guy saying to use the layout managers from the start, and the successor to the guy who ignored me.)</p> |
376,036 | Algorithm to mix sound | <p>I have two raw sound streams that I need to add together. For the purposes of this question, we can assume they are the same bitrate and bit depth (say 16 bit sample, 44.1khz sample rate).</p>
<p>Obviously if I just add them together I will overflow and underflow my 16 bit space. If I add them together and divide by two, then the volume of each is halved, which isn't correct sonically - if two people are speaking in a room, their voices don't become quieter by half, and a microphone can pick them both up without hitting the limiter.</p>
<ul>
<li>So what's the correct method to add these sounds together in my software mixer? </li>
<li>Am I wrong and the correct method is to lower the volume of each by half? </li>
<li>Do I need to add a compressor/limiter or some other processing stage to get the volume and mixing effect I'm trying for?</li>
</ul>
<p>-Adam</p> | 376,133 | 20 | 5 | null | 2008-12-17 21:08:19.533 UTC | 37 | 2018-12-06 09:28:16.947 UTC | null | null | null | Adam Davis | 2,915 | null | 1 | 66 | algorithm|audio | 51,377 | <p>You should add them together, but clip the result to the allowable range to prevent over/underflow.</p>
<p>In the event of the clipping occuring, you <strong>will</strong> introduce distortion into the audio, but that's unavoidable. You can use your clipping code to "detect" this condition and report it to the user/operator (equivalent of red 'clip' light on a mixer...)</p>
<p>You could implement a more "proper" compressor/limiter, but without knowing your exact application, it's hard to say if it would be worth it. </p>
<p>If you're doing lots of audio processing, you might want to represent your audio levels as floating-point values, and only go back to the 16-bit space at the end of the process. High-end digital audio systems often work this way.</p> |
1,074,006 | Is it possible to disable floating headers in UITableView with UITableViewStylePlain? | <p>I'm using a <code>UITableView</code> to layout content 'pages'. I'm using the headers of the table view to layout certain images etc. and I'd prefer it if they didn't float but stayed static as they do when the style is set to <code>UITableViewStyleGrouped</code>.</p>
<p>Other then using <code>UITableViewStyleGrouped</code>, is there a way to do this? I'd like to avoid using grouped as it adds a margin down all my cells and requires disabling of the background view for each of the cells. I'd like full control of my layout. Ideally they'd be a "UITableViewStyleBareBones", but I didn't see that option in the docs...</p>
<p>Many thanks,</p> | 1,074,115 | 31 | 4 | null | 2009-07-02 12:09:19.29 UTC | 76 | 2022-03-05 18:06:44.393 UTC | 2019-05-15 17:47:36.36 UTC | null | 2,272,431 | null | 113,461 | null | 1 | 208 | ios|objective-c|iphone|cocoa-touch|uikit | 139,385 | <p>You should be able to fake this by using a custom cell to do your header rows. These will then scroll like any other cell in the table view.</p>
<p>You just need to add some logic in your <code>cellForRowAtIndexPath</code> to return the right cell type when it is a header row. </p>
<p>You'll probably have to manage your sections yourself though, i.e. have everything in one section and fake the headers. (You could also try returning a hidden view for the header view, but I don't know if that will work)</p> |
6,348,215 | how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET | <p>given this JSON:</p>
<pre><code>[
{
"$id": "1",
"$type": "MyAssembly.ClassA, MyAssembly",
"Email": "[email protected]",
},
{
"$id": "2",
"$type": "MyAssembly.ClassB, MyAssembly",
"Email": "[email protected]",
}
]
</code></pre>
<p>and these classes:</p>
<pre><code>public abstract class BaseClass
{
public string Email;
}
public class ClassA : BaseClass
{
}
public class ClassB : BaseClass
{
}
</code></pre>
<p>How can I deserialize the JSON into:</p>
<pre><code>IEnumerable<BaseClass> deserialized;
</code></pre>
<p>I can't use <code>JsonConvert.Deserialize<IEnumerable<BaseClass>>()</code> because it complains that <code>BaseClass</code> is abstract.</p> | 6,495,299 | 5 | 0 | null | 2011-06-14 18:26:29.57 UTC | 22 | 2020-12-28 12:50:39.86 UTC | 2015-11-14 18:12:03.863 UTC | null | 275,567 | null | 28,543 | null | 1 | 77 | c#|json.net | 82,583 | <p>You need:</p>
<pre><code>JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
string strJson = JsonConvert.SerializeObject(instance, settings);
</code></pre>
<p>So the JSON looks like this:</p>
<pre><code>{
"$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",
"$values": [
{
"$id": "1",
"$type": "MyAssembly.ClassA, MyAssembly",
"Email": "[email protected]",
},
{
"$id": "2",
"$type": "MyAssembly.ClassB, MyAssembly",
"Email": "[email protected]",
}
]
}
</code></pre>
<p>Then you can deserialize it:</p>
<pre><code>BaseClass obj = JsonConvert.DeserializeObject<BaseClass>(strJson, settings);
</code></pre>
<p>Documentation: <a href="http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm" rel="noreferrer"><strong>TypeNameHandling setting</strong></a></p> |
6,322,245 | Should I switch from using boost::shared_ptr to std::shared_ptr? | <p>I would like to enable support for C++0x in GCC with <code>-std=c++0x</code>. I don't absolutely necessarily need any of the <a href="http://gcc.gnu.org/projects/cxx0x.html" rel="noreferrer">currently supported C++11 features</a> in GCC 4.5 (and soon 4.6), but I would like to start getting used to them. For example, in a few places where I use iterators, an <code>auto</code> type would be useful.</p>
<p>But again, I don't <strong>need</strong> any of the currently supported features. The goal here is to encourage me to incorporate the features of the new standard into my programming "vocabulary". </p>
<p>From what you know of the C++11 support, is it a good idea to enable it in GCC, and then embrace it by, for example, switching from using <code>boost::shared_ptr</code> to <code>std::shared_ptr</code> exclusively as the two don't mix?</p>
<p>PS: I'm aware of <a href="https://stackoverflow.com/questions/1086798/differences-between-different-flavours-of-shared-ptr">this good question</a> which compares the different flavors of <code>shared_ptr</code> but I'm asking a higher level advice on which to use before the standard is finalized. Another way of putting that is, when a compiler like GCC says it supports an "experimental feature", does that mean I am likely to encounter weird errors during compilation that will be major time sinks and a source of cryptic questions on StackOverflow?</p>
<p><strong>Edit</strong>: I decided to switch back from <code>std::shared_ptr</code> because I just don't trust its support in GCC 4.5 as <a href="https://stackoverflow.com/q/6322364/627517">shown by example in this question</a>.</p> | 6,323,298 | 8 | 3 | null | 2011-06-12 13:38:15.543 UTC | 21 | 2018-06-25 07:53:20.133 UTC | 2017-05-23 12:02:48.803 UTC | null | -1 | null | 627,517 | null | 1 | 71 | c++|boost|stl|c++11|shared-ptr | 35,132 | <p>There are a couple of reasons to switch over to <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>std::shared_ptr</code></a>:</p>
<ul>
<li>You remove a dependency on Boost.</li>
<li>Debuggers. Depending on your compiler and debugger, the debugger may be "smart" about <code>std::shared_ptr</code> and show the pointed to object directly, where it wouldn't for say, boost's implementation. At least in Visual Studio, <code>std::shared_ptr</code> looks like a plain pointer in the debugger, while <code>boost::shared_ptr</code> exposes a bunch of boost's innards.</li>
<li>Other new features defined in your linked question.</li>
<li><s>You get an implementation which is almost guaranteed to be move-semantics enabled, which might save a few refcount modifications. (Theoretically -- I've not tested this myself)</s> As of 2014-07-22 at least, <code>boost::shared_ptr</code> understands move semantics.</li>
<li><s><code>std::shared_ptr</code> correctly uses <code>delete []</code> on array types, while <code>boost::shared_ptr</code> causes undefined behavior in such cases (you must use <code>shared_array</code> or a custom deleter)</s> (Actually I stand corrected. See <a href="https://stackoverflow.com/questions/8624146/c11-standard-scoped-array-wrappers">this</a> -- the specialization for this is for <code>unique_ptr</code> only, not <code>shared_ptr</code>.)</li>
</ul>
<p>And one major glaring reason not to:</p>
<ul>
<li>You'd be limiting yourself to C++11 compiler and standard library implementations.</li>
</ul>
<p>Finally, you don't really have to choose. (And if you're targeting a specific compiler series (e.g. MSVC and GCC), you could easily extend this to use <code>std::tr1::shared_ptr</code> when available. Unfortunately there doesn't seem to be a standard way to detect TR1 support)</p>
<pre><code>#if __cplusplus > 199711L
#include <memory>
namespace MyProject
{
using std::shared_ptr;
}
#else
#include <boost/shared_ptr.hpp>
namespace MyProject
{
using boost::shared_ptr;
}
#endif
</code></pre> |
45,573,829 | Weird uitableview behaviour in iOS11. Cells scroll up with navigation push animation | <p>I have recently migrated some code to new iOS 11 beta 5 SDK. </p>
<p>I now get a very confusing behaviour from UITableView. The tableview itself is not that fancy. I have custom cells but in most part it is just for their height.</p>
<p>When I push my view controller with tableview I get an additional animation where cells "scroll up" (or possibly the whole tableview frame is changed) and down along push/pop navigation animation. Please see gif:</p>
<p><a href="https://i.stack.imgur.com/C6vZc.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/C6vZc.gif" alt="wavy tableview"></a></p>
<p>I manually create <code>tableview</code> in <code>loadView</code> method and setup auto layout constraints to be equal to leading, trailing, top, bottom of tableview's superview. The superview is root view of view controller.</p>
<p>View controller pushing code is very much standard: <code>self.navigationController?.pushViewController(notifVC, animated: true)</code></p>
<p>The same code provides normal behaviour on iOS 10.</p>
<p>Could you please point me into direction of what is wrong?</p>
<p>EDIT: I have made a very simple tableview controller and I can reproduce the same behavior there. Code:</p>
<pre><code>class VerySimpleTableViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = String(indexPath.row)
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let vc = VerySimpleTableViewController.init(style: .grouped)
self.navigationController?.pushViewController(vc, animated: true)
}
}
</code></pre>
<p>EDIT 2: I was able to narrow issue down to my customisation of UINavigationBar. I have a customisation like this:</p>
<p><code>rootNavController.navigationBar.setBackgroundImage(createFilledImage(withColor: .white, size: 1), for: .default)</code></p>
<p>where <code>createFilledImage</code> creates square image with given size and color.</p>
<p>If I comment out this line I get back normal behaviour.</p>
<p>I would appreciate any thoughts on this matter.</p> | 45,578,760 | 12 | 4 | null | 2017-08-08 16:44:45.49 UTC | 42 | 2019-03-22 10:04:14.127 UTC | 2017-09-15 15:21:56.47 UTC | null | 8,187,134 | null | 8,187,134 | null | 1 | 120 | ios|uitableview|animation|uinavigationcontroller | 43,786 | <p>This is due to <code>UIScrollView's</code> <strong>(UITableView is a subclass of UIScrollview)</strong> new <strong><code>contentInsetAdjustmentBehavior</code></strong> property, which is set to <strong><code>.automatic</code></strong> by default.</p>
<p>You can override this behavior with the following snippet in the viewDidLoad of any affected controllers:</p>
<pre><code> tableView.contentInsetAdjustmentBehavior = .never
</code></pre>
<p><a href="https://developer.apple.com/documentation/uikit/uiscrollview/2902261-contentinsetadjustmentbehavior" rel="noreferrer">https://developer.apple.com/documentation/uikit/uiscrollview/2902261-contentinsetadjustmentbehavior</a></p> |
16,017,294 | Singleton types in Haskell | <p>As part of doing a survey on various dependently typed formalization techniques, I have ran across a paper advocating the use of singleton types (types with one inhabitant) as a way of supporting dependently typed programming.</p>
<p>Acording to this source, in Haskell, there is a separation betwen runtime values and compile-time types that can be blurred when using singleton types, due to the induced type/value isomorphism. </p>
<p>My question is: How do singleton types differ from type-classes or from quoted/reified structures in this respect? </p>
<p>I would also particularly appreciate some intuitive explaination with respect to the type-theoretical importance/advantages to using singleton types and to the extent to which they can emulate dependent types in general.</p> | 16,018,937 | 1 | 3 | null | 2013-04-15 14:05:46.483 UTC | 10 | 2016-07-10 17:04:21.98 UTC | 2016-07-10 17:04:21.98 UTC | null | 1,523,776 | null | 2,265,811 | null | 1 | 32 | haskell|dependent-type|type-theory|singleton-type | 7,789 | <p>As you describe, singleton types are those which have only one value (let's ignore <code>⊥</code> for the moment). Thus, the value of a singleton type has a unique type representing the value. The crux of dependent-type theory (DTT) is that types can depend on values (or, said another way, values can parameterise types). A type theory that allows types to depend on types can use singleton types to let types depend on singleton values. In contrast, type classes provide <em>ad hoc polymorphism</em>, where values can depend on types (the other way round to DTT where types depend on values).</p>
<p>A useful technique in Haskell is to define a class of related singleton types. The classic example is of natural numbers:</p>
<pre><code>data S n = Succ n
data Z = Zero
class Nat n
instance Nat Z
instance Nat n => Nat (S n)
</code></pre>
<p>Provided further instances aren't added to <code>Nat</code>, the <code>Nat</code> class describes singleton types whose values/types are inductively defined natural numbers. Note that, <code>Zero</code> is the only inhabitant of <code>Z</code> but the type <code>S Int</code>, for example, has many inhabitants (it is not a singleton); the <code>Nat</code> class restricts the parameter of <code>S</code> to singleton types. Intuitively, any data type with more than one data constructor is not a singleton type. </p>
<p>Give the above, we can write the dependently-typed successor function:</p>
<pre><code>succ :: Nat n => n -> (S n)
succ n = Succ n
</code></pre>
<p>In the type signature, the type variable <code>n</code> can be seen as a value since the <code>Nat n</code> constraint restricts <code>n</code> to the class of singleton types representing natural numbers. The return type of the <code>succ</code> then <em>depends</em> on this value, where <code>S</code> is parameterised by the value <code>n</code>. </p>
<p>Any value that can be inductively defined can be given a unique singleton type representation.</p>
<p>A useful technique is to use GADTs to parameterise non-singleton types with singleton types (i.e. with values). This can be used, for example, to give a type-level representation of the shape of an inductively defined data type. The classic example is a sized-list:</p>
<pre><code>data List n a where
Nil :: List Z a
Cons :: Nat n => a -> List n a -> List (S n) a
</code></pre>
<p>Here the natural number singleton types parameterise the list-type by its length. </p>
<p>Thinking in terms of the polymorphic lambda calculus, <code>succ</code> above takes two arguments, the type <code>n</code> and then a value parameter of type <code>n</code>. Thus, singleton types here provides a kind of <a href="http://en.wikipedia.org/wiki/Intuitionistic_type_theory#.CE.A0-types">Π-type</a>, where <code>succ :: Πn:Nat . n -> S(n)</code> where the argument to <code>succ</code> in Haskell provides both the dependent product parameter <code>n:Nat</code> (passed as the type parameter) and then the argument value.</p> |
15,528,795 | Liquibase lock - reasons? | <p>I get this when running a lot of liquibase-scripts against a Oracle-server. SomeComputer is me.</p>
<pre class="lang-none prettyprint-override"><code>Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Liquibase Update Failed: Could not acquire change log lock. Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
SEVERE 2013-03-20 16:59:liquibase: Could not acquire change log lock. Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
liquibase.exception.LockException: Could not acquire change log lock. Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
at liquibase.lockservice.LockService.waitForLock(LockService.java:81)
at liquibase.Liquibase.tag(Liquibase.java:507)
at liquibase.integration.commandline.Main.doMigration(Main.java:643)
at liquibase.integration.commandline.Main.main(Main.java:116)
</code></pre>
<p>Could it be that the number of simultaneous sessions/transactions are reached? Anyone has any ideas?</p> | 19,081,612 | 11 | 4 | null | 2013-03-20 16:06:15.593 UTC | 72 | 2022-02-18 23:15:26.433 UTC | 2017-01-05 14:39:39.63 UTC | null | 4,800,355 | null | 900,743 | null | 1 | 362 | database|oracle|liquibase | 286,482 | <p>Sometimes if the update application is abruptly stopped, then the lock remains stuck.</p>
<p>Then running</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;
</code></pre>
<p>against the database helps.</p>
<p>You may also need to replace <code>LOCKED=0</code> with <code>LOCKED=FALSE</code>.</p>
<p>Or you can simply drop the <code>DATABASECHANGELOGLOCK</code> table, it will be recreated.</p> |
10,274,669 | How can I float two tables next to each other left to right? | <p>If I had two tables?</p>
<pre><code><table class="one"> and... <table class="two">
</code></pre>
<p>And the CSS looks like:</p>
<pre><code>table.one {
position: relative;
float: left;
}
table.two {
position: relative;
float: right;
}
</code></pre>
<p>It is not working...</p> | 10,274,694 | 5 | 3 | null | 2012-04-23 04:06:14.153 UTC | 2 | 2017-07-06 17:47:14.68 UTC | 2017-07-06 17:47:14.68 UTC | null | 6,224,823 | null | 1,309,066 | null | 1 | 13 | html|css | 88,454 | <p>Don't use position:relative, just provide width for each table in order to float properly.</p>
<pre><code>table.one {
float:left;
width:45%;
}
table.two {
width:45%;
float:right;
}
</code></pre> |
31,937,632 | Fail vs. raise in Ruby : Should we really believe the style guide? | <p>Ruby offers two possibilities to cause an exception programmatically: <code>raise</code> and <code>fail</code>, both being <code>Kernel</code> methods. According to the documents, they are absolutely equivalent. </p>
<p>Out of a habit, I used only <code>raise</code> so far. Now I found several recommendations (for example <a href="https://www.relishapp.com/womply/ruby-style-guide/docs/exceptions">here</a>), to use <code>raise</code> for exceptions to be caught, and <code>fail</code> for serious errors which are not meant to be handled.</p>
<p>But does it really make sense? When you are writing a class or module, and cause a problem deep inside, which you signal by <code>fail</code>, your programming colleagues who are reviewing the code, might happily understand your intentions, but the person who is <em>using</em> my code will most likely not look at my code and has no way of knowing, whether the exception was caused by a <code>raise</code> or by <code>fail</code>. Hence, my careful usage of <code>raise</code> or <code>fail</code> can't have any influence on his decision, whether she should or should not handle it.</p>
<p>Could someone see flaws in my arguments? Or are there other criteria, which might me want to use <code>fail</code> instead of <code>raise</code>?</p> | 31,937,869 | 2 | 3 | null | 2015-08-11 09:10:18.31 UTC | 4 | 2017-04-17 10:08:50.96 UTC | 2016-06-16 06:46:02.83 UTC | null | 2,423,164 | null | 1,934,428 | null | 1 | 45 | ruby|exception|coding-style|conventions | 18,509 | <blockquote>
<p>use 'raise' for exceptions to be caught, and 'fail' for serious errors which are not meant to be handled</p>
</blockquote>
<p>This is not what the <a href="https://github.com/bbatsov/ruby-style-guide#exceptions" rel="noreferrer">official style guide</a> or the link you provided say on the matter.</p>
<p>What is meant here is use <code>raise</code> only in <code>rescue</code> blocks. Aka use <code>fail</code> when you want to say something is <em>failing</em> and use <code>raise</code> when <em>rethrowing</em> an exception.</p>
<p>As for the <em>"does it matter"</em> part - it is not one of the most hardcore strictly followed rules, but you could make the same argument for any convention. You should follow in that order:</p>
<ol>
<li>Your project style guide</li>
<li>Your company style guide</li>
<li>The community style guide</li>
</ol>
<p>Ideally, the three should be the same.</p>
<hr>
<p><strong>Update</strong>: As of <a href="https://github.com/bbatsov/ruby-style-guide/issues/512" rel="noreferrer">this PR</a> (December 2015), the convention is to always use <code>raise</code>.</p> |
31,941,753 | How to make a circular ripple on a button when it's being clicked? | <h2>Background</h2>
<p>On the dialer app of Android, when you start searching for something, and you click the arrow button on the left of the EditText, you get a circular ripple effect on it :</p>
<p><a href="https://i.stack.imgur.com/1q30Y.png"><img src="https://i.stack.imgur.com/1q30Y.png" alt="enter image description here"></a></p>
<h2>The problem</h2>
<p>I've tried to have it too, but I got a rectangular one:</p>
<pre><code> <ImageButton
android:id="@+id/navButton"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dp"
android:background="?android:attr/selectableItemBackground"
android:src="@drawable/search_ic_back_arrow"/>
</code></pre>
<h2>The question</h2>
<p>How do I make the button have a circular ripple effect when being clicked? Do I have to create a new drawable, or is there a built in way for that?</p> | 49,933,191 | 13 | 4 | null | 2015-08-11 12:26:23.253 UTC | 52 | 2022-06-12 15:02:36.58 UTC | null | null | null | null | 878,126 | null | 1 | 155 | android|button|rippledrawable | 92,383 | <p>If you already have a background image, here is an example of a ripple that looks close to selectableItemBackgroundBorderless:</p>
<pre><code> <ImageButton
android:id="@+id/btn_show_filter_dialog"
android:layout_width="24dp"
android:layout_height="24dp"
android:background="@drawable/ic_filter_state"/>
</code></pre>
<p>ic_filter_state.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/state_pressed_ripple"/>
<item
android:state_enabled="true"
android:drawable="@drawable/ic_filter" />
</selector>
</code></pre>
<p>state_pressed_ripple.xml: (opacity set to 10% on white background) 1AFFFFFF </p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#1AFFFFFF"/>
</shape>
<color android:color="#FFF"/>
</item>
</ripple>
</code></pre> |
56,496,638 | Activity indicator in SwiftUI | <p>Trying to add a full screen activity indicator in SwiftUI.</p>
<p>I can use <code>.overlay(overlay: )</code> function in <code>View</code> Protocol. </p>
<p>With this, I can make any view overlay, but I can't find the iOS default style <code>UIActivityIndicatorView</code> equivalent in <code>SwiftUI</code>.</p>
<p>How can I make a default style spinner with <code>SwiftUI</code>?</p>
<p><strong>NOTE:</strong> This is not about adding activity indicator in UIKit framework.</p> | 56,496,896 | 16 | 3 | null | 2019-06-07 14:51:55.58 UTC | 69 | 2022-05-14 07:42:25.737 UTC | 2020-09-14 06:24:43.723 UTC | null | 5,623,035 | null | 899,573 | null | 1 | 203 | swiftui | 121,188 | <p>As of <strong>Xcode 12 beta</strong> (<strong>iOS 14</strong>), a new view called <code>ProgressView</code> is <a href="https://developer.apple.com/documentation/swiftui/progressview?changes=latest_major" rel="noreferrer">available to developers</a>, and that can display both determinate and indeterminate progress.</p>
<p>Its style defaults to <code>CircularProgressViewStyle</code>, which is exactly what we're looking for.</p>
<pre><code>var body: some View {
VStack {
ProgressView()
// and if you want to be explicit / future-proof...
// .progressViewStyle(CircularProgressViewStyle())
}
}
</code></pre>
<hr />
<p><strong>Xcode 11.x</strong></p>
<p>Quite a few views are not yet represented in <code>SwiftUI</code>, but it's easily to port them into the system.
You need to wrap <code>UIActivityIndicator</code> and make it <code>UIViewRepresentable</code>.</p>
<p>(More about this can be found in the excellent WWDC 2019 talk - <a href="https://developer.apple.com/wwdc19/231" rel="noreferrer">Integrating SwiftUI</a>)</p>
<pre class="lang-swift prettyprint-override"><code>struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool
let style: UIActivityIndicatorView.Style
func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
return UIActivityIndicatorView(style: style)
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
</code></pre>
<p>Then you can use it as follows - here's an example of a loading overlay.</p>
<p>Note: I prefer using <code>ZStack</code>, rather than <code>overlay(:_)</code>, so I know exactly what's going on in my implementation.</p>
<pre class="lang-swift prettyprint-override"><code>struct LoadingView<Content>: View where Content: View {
@Binding var isShowing: Bool
var content: () -> Content
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.content()
.disabled(self.isShowing)
.blur(radius: self.isShowing ? 3 : 0)
VStack {
Text("Loading...")
ActivityIndicator(isAnimating: .constant(true), style: .large)
}
.frame(width: geometry.size.width / 2,
height: geometry.size.height / 5)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.primary)
.cornerRadius(20)
.opacity(self.isShowing ? 1 : 0)
}
}
}
}
</code></pre>
<p>To test it, you can use this example code:</p>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
var body: some View {
LoadingView(isShowing: .constant(true)) {
NavigationView {
List(["1", "2", "3", "4", "5"], id: \.self) { row in
Text(row)
}.navigationBarTitle(Text("A List"), displayMode: .large)
}
}
}
}
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/bVdE4l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bVdE4l.png" alt="enter image description here" /></a></p> |
33,885,235 | Should a Go package ever use log.Fatal and when? | <p>I have so far avoided use of <code>log.Fatal</code>, but I recently co-incidentally discovered these questions; <a href="https://stackoverflow.com/questions/33873305/how-to-get-100-code-coverage-in-golang">code-coverage</a> and <a href="https://stackoverflow.com/questions/30688554/how-to-test-go-function-containing-log-fatal">tests-using-log-fatal</a>. </p>
<p>One of the comments from the 100 code coverage questions says: </p>
<blockquote>
<p>... In the vast majority of cases <code>log.Fatal</code> should be only be used in main, or init functions (or possibly some things meant to be called only directly from them)"</p>
</blockquote>
<p>It go me thinking, so I began to look at the standard library code provided with Go. There are lots of examples where the <strong>test</strong> code in the library makes use of <code>log.Fatal</code> which seems fine. There are a few examples outside of the test code, such as in <a href="https://golang.org/src/net/http/transport.go?h=log.Fatal#L408" rel="noreferrer"><code>net/http</code></a>, shown below:</p>
<pre><code>// net/http/transport.go
func (t *Transport) putIdleConn(pconn *persistConn) bool {
...
for _, exist := range t.idleConn[key] {
if exist == pconn {
log.Fatalf("dup idle pconn %p in freelist", pconn)
}
}
...
}
</code></pre>
<p>If its is best practice to avoid use of <code>log.Fatal</code>, why is it used at all in the standard libraries, I would have expected just return an error. It seems unfair to the user of the library to cause <code>os.Exit</code> to be called and not providing any chance for the application to clean-up.</p>
<p>I may be naive, so hence my question as a better practice would seem to be to call <code>log.Panic</code> which can be recovered and my theoretical long running stable application might have a chance of rising from the ashes.</p>
<p>So what would best-practise say for Go about when should log.Fatal should be used?</p> | 33,890,104 | 3 | 8 | null | 2015-11-24 04:02:36.363 UTC | 15 | 2021-11-23 09:34:50.663 UTC | 2017-05-23 11:52:44.27 UTC | null | -1 | null | 302,164 | null | 1 | 57 | go|fatal-error | 50,147 | <p>It might be just me, but here is how I use <code>log.Fatal</code>. As per UNIX conventions, a process which encounters an error should fail as early as possible with a non-zero exit code. This lead me to the following guidelines to use <code>log.Fatal</code> when…</p>
<ol>
<li>…an error happens in any of my <code>func init()</code>, as these happen when the imports are processed or before the main func is called, respectively. Conversely, I only do stuff not directly affecting the unit of work the library or cmd is supposed to do. For example, I set up logging and check wether we have a sane environment and parameters. No need to run main if we have invalid flags, right? And if we can not give proper feedback, we should tell this early.</li>
<li>…an error happens of which I know is irrecoverable. Let's assume we have a program which creates a thumbnail of an image file given on the command line. If this file does not exist or is unreadable because of insufficient permissions, there is no reason to continue and this error can not be recovered from. So we adhere to the conventions and fail.</li>
<li>…an error occurs during a process which might not be reversible. This is kind of a soft definition, I know. Let me illustrate that. Let's assume we have an implementation of <code>cp</code>, and it was started to be non-interactive and recursively copy a directory. Now, let's assume we encounter a file in the target directory which has the same name (but different content) as a file to be copied there. Since we can not ask the user to decide what to do and we can not copy this file, we have a problem. Because the user will assume that the source and the target directories are exact copies when we finish with exit code zero, we can not simply skip the file in question. However, we can not simply overwrite it, since this might potentially destroy information. This is a situation we can not recover from per explicit request by the user, and so I'd use <code>log.Fatal</code> to explain the situation, hereby obeying the principle to fail as early as possible.</li>
</ol> |
53,279,989 | With API 28 and "androidx.appcompat" library project says "AppCompatActivity" symbol not found | <p>I updated my build and target version to 28 (Pie) and replaced the relevant dependencies. Now my project says Symbol not found on <code>AppCompatActivity</code>. I have tried to </p>
<ul>
<li>Clean project</li>
<li>Rebuild project</li>
<li>Invalidate Caches / Restart</li>
</ul>
<p>But the result is the same. Moreover when I try <kbd>Ctrl</kbd>+<kbd>Space</kbd> after extends keyword in activity class there is no <code>"AppCompatActivity</code> suggestion. I tried to investigate if its present in <code>libraries</code> folder, it's present there.</p>
<p><a href="https://i.stack.imgur.com/h0iTb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h0iTb.png" alt="enter image description here"></a></p>
<p>Now, what should I do to make it work? If there is any variation/alternative with <code>androidx</code> libs please let me know. Here is my complete <code>build.gradle</code> file</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.invogen.messagingapp"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// implementation 'com.android.support:appcompat-v7:28.0.0'
// implementation 'com.android.support.constraint:constraint-layout:1.1.3'
// implementation 'com.android.support:design:28.0.0'
// implementation 'com.android.support:support-v4:28.0.0'
// Libs for newer API 28
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0-alpha01'
implementation 'androidx.cardview:cardview:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// Libs for Firebase Functionality
implementation 'com.google.firebase:firebase-core:16.0.5'
// implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.firebase:firebase-storage:16.0.4'
// Lib for Firebase UI Elements
implementation 'com.firebaseui:firebase-ui-database:4.2.1'
// Libs for QR Code
implementation 'com.google.zxing:core:3.2.1'
implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
// Lib for Circle Image View (Profile Image)
implementation 'de.hdodenhof:circleimageview:2.2.0'
// Lib for Loading Images
implementation 'com.squareup.picasso:picasso:2.71828'
//Lib for Cropping Images
api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
<p>Some other posts suggest adding the below two parameters in <code>Manifest</code> file</p>
<pre><code>android:appComponentFactory="anystrings be placeholder"
tools:replace="android:appComponentFactory"
</code></pre>
<p>But with these two lines project sync with multiple error and Android Studio says </p>
<blockquote>
<p>Compilation failed; see the compiler error output for details.</p>
</blockquote>
<p>If I have to add more detail to the question please let me know.</p> | 53,294,653 | 3 | 4 | null | 2018-11-13 11:24:45.453 UTC | 4 | 2019-09-24 16:29:33.54 UTC | null | null | null | null | 5,055,401 | null | 1 | 23 | android|android-studio|gradle|android-appcompat|androidx | 38,128 | <p><strong>Edit:</strong> Now you can easily migrate your project to <code>androidx</code>, Just click <code>Refactor => Migrate to Androidx</code> from menubar.
<a href="https://i.stack.imgur.com/qXe0u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qXe0u.png" alt="enter image description here"></a></p>
<p><strong>Previously I did as follow.</strong><br>
With <code>Clean and build</code> and <code>Rebuild project</code> android studio did not clean the unused imports like imports from <code>android.support.v7</code> so I removed them all manually from all activities. Now android studio suggests <code>AppCompatActivity</code> from the correct library <code>androidx.appcompat</code>.</p>
<p>Hope so it will help someone.</p> |
33,350,175 | C++ override inherited methods | <p>I have the following two classes. Since <code>Child</code> inherits from <code>Father</code>, I think that <code>Child::init()</code> overrides <code>Father::init()</code>. Why, when I run the program, I get "I'm the Father" and not "I'm the Child"? How to execute <code>Child::init()</code>?</p>
<p>You can test it here: <a href="https://ideone.com/6jFCRm" rel="noreferrer">https://ideone.com/6jFCRm</a></p>
<pre><code>#include <iostream>
using namespace std;
class Father {
public:
void start () {
this->init();
};
void init () {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () {
cout << "I'm the child" << endl;
};
};
int main (int argc, char** argv) {
Child child;
child.start();
}
</code></pre> | 33,350,221 | 3 | 8 | null | 2015-10-26 15:56:23.263 UTC | 10 | 2015-10-26 16:05:30.703 UTC | null | null | null | null | 42,636 | null | 1 | 24 | c++|oop|c++11|inheritance | 42,013 | <p>Currently <code>Child::init</code> is <em>hiding</em> <code>Father::init</code>, not overriding it. Your <code>init</code> member function needs to be <code>virtual</code> in order to get dynamic dispatch:</p>
<pre><code>virtual void init () {
cout << "I'm the father" << endl;
};
</code></pre>
<p>Optionally, you could mark <code>Child::init</code> as <code>override</code> to be explicit that you want to override a virtual function (requires C++11):</p>
<pre><code>void init () override {
cout << "I'm the child" << endl;
};
</code></pre> |
22,701,405 | "aapt" IOException error=2, No such file or directory" why can't I build my gradle on jenkins? | <p>I have a little problem.</p>
<p><strong>The Problem:</strong><br>
I am trying to build a gradle of my Android Project on Jenkins and now I am standing on this problem i can't resolve.
During the Building I have this Error message:</p>
<pre><code>:Client:mergeDebugResources
/var/lib/jenkins/workspace/LMA-Client/Client/build/exploded-aar/com.google.android.gms/play-services/3.1.59/res/drawable-hdpi/common_signin_btn_text_focus_light.9.png:
Error: Cannot run program "/opt/android-sdk/build-tools/19.0.1/aapt": java.io.IOException: error=2, No such file or directory
:Client:mergeDebugResources FAILED
</code></pre>
<p>You can imagine that this aapt... yep its there and the png... its there too, so the mistake must be somewhere else.</p>
<p><strong>The Solution?</strong><br>
Now I googled 1-2 hours around, surfed on this great Website and what I found is that if Jenkins runs on a 64-bit system, I need to install the ia32-libs. Like that:</p>
<pre><code>sudo apt-get install ia32-libs
</code></pre>
<p>now I tried that, and I couldn't install it:</p>
<pre><code>The following packages have unmet dependencies:
ia32-libs : Depends: ia32-libs-multiarch
</code></pre>
<p>so I tried to install <em>"ia32-libs-multiarch"</em>, but again:</p>
<pre><code>The following packages have unmet dependencies:
ia32-libs-multiarch:i386 : Depends: libgphoto2-2:i386 but it is not going to be installed
Depends: libsane:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code></pre>
<p><strong>Finally</strong><br>
so finally im standing here and asking me: is that really the solution? And why should I install this thing? And how? So please help me, I think I am not far away from the answer.
<br></p> | 23,201,209 | 4 | 2 | null | 2014-03-27 23:35:20.123 UTC | 33 | 2016-08-25 14:56:10.607 UTC | 2016-04-17 21:30:35.55 UTC | null | 2,411,320 | null | 917,672 | null | 1 | 126 | java|android|jenkins|gradle|aapt | 43,424 | <p>I had the following similar error on Ubuntu 13.10:</p>
<p><code>Cannot run program "/usr/local/android-sdk-linux/build-tools/19.0.3/aapt": error=2, No such file or directory</code></p>
<p>And <a href="https://stackoverflow.com/a/18930424/514483">this answer</a> fixed it for me:</p>
<blockquote>
<p>To get aapt working (this fixed my issues with the avd as well) just install these two packages:</p>
<pre><code>sudo apt-get install lib32stdc++6 lib32z1
</code></pre>
</blockquote> |
13,719,593 | How to set object property (of object property of..) given its string name in JavaScript? | <p>Suppose we are only given</p>
<pre class="lang-js prettyprint-override"><code>var obj = {};
var propName = "foo.bar.foobar";
</code></pre>
<p>How can we set the property <code>obj.foo.bar.foobar</code> to a certain value (say "hello world")?
So I want to achieve this, while we only have the property name in a string:</p>
<pre class="lang-js prettyprint-override"><code>obj.foo.bar.foobar = "hello world";
</code></pre> | 13,719,799 | 16 | 2 | null | 2012-12-05 09:08:00.517 UTC | 20 | 2022-08-09 08:22:06.613 UTC | 2014-09-06 02:25:39.147 UTC | null | 2,864,740 | null | 1,546,844 | null | 1 | 59 | javascript|string|properties|nested | 32,959 | <pre><code>function assign(obj, prop, value) {
if (typeof prop === "string")
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === "[object Object]"
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}
var obj = {},
propName = "foo.bar.foobar";
assign(obj, propName, "Value");
</code></pre> |
13,633,395 | How do you access the individual elements of a glsl mat4? | <p>Is it possible to access the individual elements of a glsl mat4 type matrix? How?</p> | 13,635,701 | 1 | 9 | null | 2012-11-29 19:40:46.53 UTC | 13 | 2012-11-29 22:11:20.323 UTC | null | null | null | null | 111,307 | null | 1 | 66 | glsl | 61,446 | <p>The Section 5.6 of the GLSL reference manual says you can access <code>mat4</code> array elements using <code>operator[][]</code> style syntax in the following way:</p>
<pre><code>mat4 m;
m[1] = vec4(2.0); // sets the second column to all 2.0
m[0][0] = 1.0; // sets the upper left element to 1.0
m[2][3] = 2.0; // sets the 4th element of the third column to 2.0
</code></pre>
<p>Remember, OpenGL defaults to <strong>column major matrices</strong>, which means access is of the format <code>mat[col][row]</code>. In the example, <code>m[2][3]</code> sets the 4th ROW (index 3) of the 3rd COLUMN (index 2) to 2.0. In the example <code>m[1]=vec4(2.0)</code>, it is setting an entire column at once (because <code>m[1]</code> refers to column #2, when only ONE index is used it means that COLUMN. <code>m[1]</code> refers to the SECOND COLUMN VECTOR).</p> |
9,506,056 | Is it possible to force PowerShell script to throw if a required parameter is omitted? | <p>I would like the second function call in this script to throw an error:</p>
<pre><code>function Deploy
{
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$BuildName
)
Write-Host "Build name is: $BuildName"
}
Deploy "Build123"
Deploy #Currently prompts for input
</code></pre>
<p>Prompting is great for using the script interactively, but this will also be executed by our build server.</p>
<p>Is my best bet just doing some custom validation with an <code>if</code> or something?</p> | 9,506,253 | 2 | 2 | null | 2012-02-29 20:24:45.293 UTC | 8 | 2016-01-18 11:20:22.227 UTC | null | null | null | null | 532,797 | null | 1 | 44 | powershell | 22,162 | <p>Once the parameter is marked as mandatory PowerShell will prompt for value. That said, if you remove the mandatory attribute then you can set a default value with a throw statement:</p>
<pre><code>function Deploy
{
param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$BuildName=$(throw "BuildName is mandatory, please provide a value.")
)
Write-Host "Build name is: $BuildName"
}
</code></pre> |
16,192,087 | Undefined reference to `initscr' Ncurses | <p>I'm trying to compile my project and I use the lib ncurse. And I've got some errors when compiler links files.</p>
<p>Here is my flags line in Makefile:</p>
<pre><code>-W -Wall -Werror -Wextra -lncurses
</code></pre>
<p>I've included ncurses.h</p>
<p>Some layouts :</p>
<pre><code>prompt$> dpkg -S curses.h
libslang2-dev:amd64: /usr/include/slcurses.h
libncurses5-dev: /usr/include/ncurses.h
libncurses5-dev: /usr/include/curses.h
prompt$> dpkg -L libncurses5-dev | grep .so
/usr/lib/x86_64-linux-gnu/libncurses.so
/usr/lib/x86_64-linux-gnu/libcurses.so
/usr/lib/x86_64-linux-gnu/libmenu.so
/usr/lib/x86_64-linux-gnu/libform.so
/usr/lib/x86_64-linux-gnu/libpanel.s
</code></pre>
<p>And here are my erros :</p>
<pre><code>gcc -W -Wall -Werror -Wextra -I./Includes/. -lncurses -o Sources/NCurses/ncurses_init.o -c Sources/NCurses/ncurses_init.c
./Sources/NCurses/ncurses_init.o: In function `ncruses_destroy':
ncurses_init.c:(.text+0x5): undefined reference to `endwin'
./Sources/NCurses/ncurses_init.o: In function `ncurses_write_line':
ncurses_init.c:(.text+0xc5): undefined reference to `mvwprintw'
./Sources/NCurses/ncurses_init.o: In function `ncurses_init':
ncurses_init.c:(.text+0xee): undefined reference to `initscr'
collect2: error: ld returned 1 exit status
</code></pre>
<p>Thanks a lot</p> | 16,192,128 | 4 | 2 | null | 2013-04-24 12:29:10.47 UTC | 11 | 2019-09-23 11:57:57.197 UTC | null | null | null | null | 2,086,502 | null | 1 | 25 | c|compilation|linker|ncurses|undefined-reference | 35,961 | <p>You need to change your makefile so that the <code>-lncurses</code> directive comes <em>after</em> your object code on the gcc command line, i.e. it needs to generate the command:</p>
<pre><code>gcc -W -Wall -Werror -Wextra -I./Includes/. -o Sources/NCurses/ncurses_init.o -c Sources/NCurses/ncurses_init.c -lncurses
</code></pre>
<p>This is because object files and libraries are linked in order in a single pass.</p> |
16,094,510 | Rubymine reveal current document in project tree / project drawer | <p>If i'm working on a file in RubyMine, is there a shortcut key or context menu option where I can "reveal in sidebar" and it basically would expand the project tree down to the file I currently am working on?</p>
<p>This is a feature in both TextMate and Sublime Text 2, but I haven't found it RubyMine yet.</p> | 16,101,102 | 5 | 0 | null | 2013-04-18 23:01:27.843 UTC | 2 | 2020-01-14 08:51:29.953 UTC | null | null | null | null | 1,516,124 | null | 1 | 30 | rubymine | 5,841 | <p><code>Navigate</code> | <code>Select In</code>, <strong>Project View</strong>. Shortcut would depend on keymap, default is <kbd>Alt</kbd>+<kbd>F1</kbd>.</p> |
16,571,981 | gluPerspective parameters- what do they mean? | <p>I wonder about the <code>gluPerspective</code> parameters.</p>
<p>In all examples I see <code>fovy</code> is set to around 45-60degrees
I've tried to set it to different values and the object just disappears
what's the explanation for it? </p>
<p>The <code>aspect</code> value should always be the ratio? why would one change it?</p>
<p><code>zNear, zFar</code> - once again the usual values are around 10 and 500+ what does it reflect?</p> | 16,574,087 | 1 | 1 | null | 2013-05-15 18:02:49.41 UTC | 23 | 2015-04-17 13:12:12.25 UTC | 2013-05-15 20:08:40.163 UTC | null | 872,616 | null | 1,371,992 | null | 1 | 51 | opengl|perspective|perspectivecamera | 41,218 | <p>The purpose of the 4 parameters is to define a <strong>view frustum</strong>, like this:</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Field_of_view_angle_in_view_frustum.png/400px-Field_of_view_angle_in_view_frustum.png" alt="perspective frustum"></p>
<p>where nothing outside of the frustum should be is visible on screen ( To accomplish this, the parameters are used to calculate a 4x4 matrix, which is then used to transform each vertex into the so-called clip space. There, testing if a vertex is inside the frustum or not is trivial )</p>
<p><strong>The field of view</strong> parameter is basically the angle in between a plane passing through the camera position as well as the top of your screen & another plane passing through the camera position and the bottom of your screen. The bigger this angle is, the more you can see of the world - but at the same time, the objects you can see will become smaller. </p>
<p>To observe its influence, I'd suggest coding a simple app where you can gradually increase / decrease the fov via keypress - then render some spheres or other basic objects & see what happens as you change it.</p>
<p><strong>The aspect ratio</strong> is your viewport's aspect ratio. ( In the graphic above, the viewport is located at the the near clipping plane ) Being able to define it at will makes sense, since your viewport's aspect ratio may vary.</p>
<p><strong>The zNear & zFar</strong> values define the distance between the camera position & the near and far clipping planes, respectively. Nothing that's closer to the camera than zNear or farther away than zFar will be visible. Both values must be > 0, and obviously, zFar > zNear.
zFar should ideally be chosen so that everything you want to render is visible, but making it larger than necessary wastes depth buffer prescision & may lead to flickering effects, called z-fighting. Likewise, setting zNear too close to the camera may cause the same effect - in fact, having a reasonable zNear value is more important than zFar. If you want to know exactly why this happens, you should read some in-depth explanations, like <a href="http://www.sjbaker.org/steve/omniv/love_your_z_buffer.html" rel="noreferrer">this one</a> or <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html" rel="noreferrer">this one</a></p> |
16,287,559 | Mysql adding user for remote access | <p>I created user <code>user@'%'</code> with <code>password 'password</code>. But I can not connect with:</p>
<pre><code>mysql_connect('localhost:3306', 'user', 'password');
</code></pre>
<p>When I created user <code>user@'localhost'</code>, I was able to connect. Why? Doesn't '%' mean from ANY host?</p> | 16,288,118 | 5 | 1 | null | 2013-04-29 20:24:16.047 UTC | 91 | 2022-05-09 21:04:59.003 UTC | 2015-07-28 09:59:34.777 UTC | null | 4,662,759 | null | 2,333,586 | null | 1 | 183 | mysql|remote-access | 440,249 | <p>In order to connect remotely, you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such <em>.</em> See below:</p>
<p>my.cnf (my.ini on windows)</p>
<pre><code>#Replace xxx with your IP Address
bind-address = xxx.xxx.xxx.xxx
</code></pre>
<p>Then:</p>
<pre><code>CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
</code></pre>
<p>Then:</p>
<pre><code>GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
FLUSH PRIVILEGES;
</code></pre>
<p>Depending on your OS, you may have to open port 3306 to allow remote connections.</p> |
15,140,237 | enabled and disabled text input on checkbox checked and unchecked | <p>i've checkbox and text input</p>
<p>What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox</p>
<p>I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.</p>
<pre><code><input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
</code></pre>
<p>any help ~ thanks</p> | 15,140,254 | 5 | 0 | null | 2013-02-28 16:10:36.51 UTC | 4 | 2020-08-19 15:23:34.233 UTC | null | null | null | null | 893,513 | null | 1 | 6 | javascript | 70,735 | <p>You just need to add a <code>!</code> in front of <code>this.checked</code>.</p>
<p>Here's an example that shows the change:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').disabled = !this.checked;
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" /></code></pre>
</div>
</div>
</p> |
17,529,766 | View contents of database file in Android Studio | <p>I have been using <strong>Android Studio</strong> to develop my app since it's was released.</p>
<p>Everything works nice until recently, I have to debug together with checking the database file. Since I don't know how to see the database directly, When I debugged to generate the database file, I have to export the database file from my phone to the PC. </p>
<p>In order to do this, I have to open <code>DDMS > File Explorer</code>. Once I open the DDMS, I have to reconnect the USB, and I lose my debug thread. After checking the database file, I have to close the DDMS and reconnect the USB again to get back to the debug mode. </p>
<p>It's just too complicated. Does anyone have a better way to do this in Android Studio (I know it's easier in Eclipse) ? </p> | 20,559,136 | 31 | 1 | null | 2013-07-08 14:54:14.88 UTC | 150 | 2022-04-10 11:35:27.963 UTC | 2016-03-18 20:07:22.137 UTC | null | 4,230,345 | null | 1,213,267 | null | 1 | 291 | android|android-studio|android-sqlite|ddms | 532,078 | <p>Finally, i found a simplest solution which do not need to open the DDMS.</p>
<p>Actually, the solution is based on what @Distwo mentioned, but it don't have to be that complicated. </p>
<p><strong>First</strong>, remember the path of your database file in the device, it should aways the same.
For example mine is:<code>/data/data/com.XXX.module/databases/com.XXX.module.database</code></p>
<p><strong>Second</strong>, execute this command which pulls your database file onto you PC</p>
<pre><code> adb pull /data/data/com.XXX.module/databases/com.XXX.module.database /Users/somePathOnYourPC/
</code></pre>
<p>What you need to do is just copy and store this command, then you can use it again and again.</p>
<p><strong>Third</strong>, if you got Permission Denied or something like that, just run <code>adb root</code> before the previous command.</p> |
17,645,634 | OCaml and Opam: unbound module Core | <p>I'm trying to get an OCaml environment set up, and I've followed the instructions from appendix A of the Real World OCaml beta. I set up opam, and installed a version of OCaml with the command</p>
<pre><code>$ opam switch 4.01.0dev+trunk
</code></pre>
<p>which passed fine. I then did an</p>
<pre><code>$ eval `opam config env`
</code></pre>
<p>to pull in the changes. I'm running the correct top level, as</p>
<pre><code>$ which ocaml
</code></pre>
<p>outputs</p>
<pre><code>/home/bryan/.opam/4.01.0dev+trunk/bin/ocaml
</code></pre>
<p>I installed the Core package from Jane street, with the command</p>
<pre><code>$ opam install core
</code></pre>
<p>Both ocamlfind and opam search show that the package was installed correctly. However when I try to open it either from the repl or in a file, I get the error 'unbound module Core'. e.g.</p>
<pre><code>$ ocaml
# open Core;;
Error: Unbound module Core
</code></pre>
<p>Is there something I'm missing here? Why can't OCaml find my installed module?</p> | 17,645,892 | 2 | 0 | null | 2013-07-15 01:48:15.617 UTC | 16 | 2021-01-31 13:44:16.953 UTC | 2021-01-31 13:44:16.953 UTC | null | 10,871,073 | null | 154,744 | null | 1 | 60 | ocaml|opam | 24,763 | <p>So I jumped the gun a bit. I forgot to add some items to my ~/.ocamlinit file. Specifically I forgot to add</p>
<pre><code>#use "topfind"
#camlp4o
#thread
#require "core.top"
#require "core.syntax"
</code></pre>
<p>as mentioned in Chapter 1. D'oh!</p> |
17,515,699 | Node Express sending image files as API response | <p>I Googled this but couldn't find an answer but it must be a common problem. This is the same question as <a href="https://stackoverflow.com/questions/17004990/node-request-read-image-stream-pipe-back-to-response">Node request (read image stream - pipe back to response)</a>, which is unanswered.</p>
<p>How do I send an image file as an Express .send() response? I need to map RESTful urls to images - but how do I send the binary file with the right headers? E.g.,</p>
<pre><code><img src='/report/378334e22/e33423222' />
</code></pre>
<p>Calls...</p>
<pre><code>app.get('/report/:chart_id/:user_id', function (req, res) {
//authenticate user_id, get chart_id obfuscated url
//send image binary with correct headers
});
</code></pre> | 17,516,733 | 2 | 1 | null | 2013-07-07 19:50:44.28 UTC | 17 | 2019-07-03 15:18:58.03 UTC | 2017-05-23 10:31:35.96 UTC | null | -1 | null | 1,060,489 | null | 1 | 91 | image|node.js|express | 168,132 | <p>There is an api in Express.</p>
<p><code>res.sendFile</code></p>
<pre><code>app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
</code></pre>
<p><a href="http://expressjs.com/en/api.html#res.sendFile">http://expressjs.com/en/api.html#res.sendFile</a></p> |
23,294,091 | Hide scroll bar of nested div, but still make it scrollable | <p><a href="https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll">This</a> is a reference that I used, which explains how to make a div scrollable with its scroll bar hidden. The only difference is that I have nested divs. Check my <a href="http://jsfiddle.net/5GCsJ/877/" rel="nofollow noreferrer">fiddle</a></p>
<p><strong>HTML:</strong></p>
<pre><code><div id="main">
<div id="sub-main">
<div id="content">
<div id="item-container">
<div class="item">a</div>
<div class="item">b</div>
<div class="item">c</div>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>#main {
width: 500px;
height: 500px;
}
#sub-main {
width: 500px;
height: 500px;
overflow: hidden;
}
#content {
background-color: red;
width: 500px;
height: 500px;
overflow: auto;
}
#item-container {
width: 1500px;
height: 500px;
}
.item {
width: 500px;
height: 500px;
font-size: 25em;
text-align: center;
float: left;
}
</code></pre>
<p>Like above, I have a overflowed horizontal div and I want to hide its scroll bar. I have to make it still scrollable because <code>$.scrollTo()</code> wouldn't work otherwise.</p>
<p><strong>UPDATE:</strong></p>
<p>I have read all the answers, but I still have not resolved my problem and don't know what's causing it. This is the live that's having troubles.
Basically, I am trying to follow <a href="http://demos.flesler.com/jquery/localScroll/" rel="nofollow noreferrer">this</a> almost exactly the same, but there must be some reason that my website isn't working as expected. There are two problems.</p>
<ol>
<li>When I set <code>overflow: hidden</code> to a parent container of scrollable items, I cannot scroll (native javascript scroll functions do not work too).</li>
<li>I want to scroll just the overflowed container, not the entire window. This can be done by setting a target in <code>$.localScroll({ target: '#projects-content' })</code> but nothing scrolls when I set the target. If I don't, scrolling works as long as <code>overflow:hidden</code> is not applied.
Again, any help would be greatly appreciated.</li>
</ol>
<p><strong>HTML:</strong></p>
<pre><code><div id="projects"> <!-- start of entire projects page -->
<div id="project-sidebar">
<a href="#project-first">
<div class="sidebar-item sidebar-first">first</div>
</a>
<a href="#project-second">
<div class="sidebar-item sidebar-second">second</div>
</a>
<a href="#">
<div class="sidebar-item sidebar-third">third</div>
</a>
</div>
<div id="project-content"> <!-- this must be the scrollable itmes' container, not the entire window -->
<div id="project-first" class="project-item">
<!-- these items should be scrollable -->
<div class="project-subitem" id="first-sub1">
<a href='#first-sub2' class='next'>next</a>
</div>
<div class='project-subitem' id='first-sub2'>
<a href='#first-sub1' class='prev'>prev</a>
</div>
<!-- end of scrollable items -->
</div>
</div> <!-- end of scroll scroll container -->
</div> <!-- end of entire projects page -->
<script>
// FIXME: when I set target, nothing scrolls.
// But I don't want the entire window to scroll
$('#projects').localScroll({
//target: '#project-content',
hash: false
});
</script>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#project-content {
width: 80%;
height: 100%;
position: relative;
float: left;
}
#project-sidebar {
float: left;
width: 20%;
height: 100%;
}
.project-item {
width: 300%;
height: 100%;
}
.project-subitem {
height: 100%;
width: 33.33%;
position: relative;
float: left;
}
</code></pre>
<p><strong>Update:</strong></p>
<p>After I added <code>overflow:scroll</code> to <code>#project-content</code>, the scrolling works as expected. All I need now is making scroll bars disappear in <code>#project-content</code>. I tried adding <code>overflow:hidden</code> to its parent but had no success. I also tried adding it to <code>html, body</code>, but then the entire document refuses to accept any scrolling functions like <code>scrollTop()</code>.</p>
<p>Any help will be greatly appreciated!</p> | 23,336,415 | 8 | 7 | null | 2014-04-25 13:07:38.227 UTC | 2 | 2015-03-06 11:14:26.01 UTC | 2017-05-23 12:02:04.963 UTC | null | -1 | null | 1,815,412 | null | 1 | 13 | javascript|html|css|scroll | 45,997 | <h2>Theory :</h2>
<p>The technique is to use a parent container that is shorter than the child element with scrollbar. This image shows what I mean :</p>
<p><img src="https://i.stack.imgur.com/PlNgi.jpg" alt="Hide scollbar"> </p>
<h2>Practice :</h2>
<p>In your case, I suggest using absolute positionning and negative bottom value on <code>#project-content</code> so it overflows it's parent container (<code>#projects</code>) at the bottom.</p>
<p>The point is now what negative value? It should be the same value as the with of a scroll <strong>but</strong> scrollbars are never the same width according to browsers. So I suggest giving a bigger value : <code>-30px</code>to be sure it is hidden. You will just need to be carefull that you don't have content to close to the bottom that can be hidden on browesers with thin scrollbars.</p>
<p>This is the CSS you should add to your website :</p>
<pre><code>#projects{
position: relative;
}
#project-content{
position: absolute;
top: 0;
left: 20%;
bottom: -30px;
/* remove:
height: 100%;
position: relative;
float: left;
padding-bottom: -15px
/*
}
</code></pre> |
43,141,401 | Visual Studio error D8016: '/ZI' and '/Gy' command-line options are incompatible | <p>I am having an issue with a project that I am working on. Despite the fact that the code is right, I can't build it because I got the following error</p>
<blockquote>
<p>Error D8016 '/ZI' and '/Gy-' command-line options are incompatible LoadReport C:\LoadReport\LoadReport\cl </p>
</blockquote>
<p>My version of the visual studio is 2015. Any idea would be appreciated.</p> | 43,141,537 | 3 | 3 | null | 2017-03-31 13:01:57.11 UTC | 10 | 2019-11-22 11:57:38.273 UTC | 2018-08-02 04:08:50.853 UTC | null | 4,284,627 | null | 3,534,844 | null | 1 | 56 | c++|visual-studio-2015 | 61,845 | <p>You are choosing "Edit and Continue" (<code>/ZI</code>) to be able to fix code during debugging, but also "Disable Function-Level Linking" (<code>/Gy-</code>). </p>
<p>Those two will not work together, as you cannot just change one function in the middle of the code. So just choose one of them, like changing <code>/Gy-</code> to <code>/Gy</code>.</p> |
61,847,231 | Question mark before dot in javascript / react | <p>I know what <a href="https://reactjs.org/docs/conditional-rendering.html" rel="noreferrer">ternary operator</a> is in React.</p>
<p>When I'm developing react native app I encounter this kind of syntax that is covered by my eslint as unexpected token</p>
<p><code>ESLint: Parsing error: Unexpected token .</code></p>
<p>It goes like this:</p>
<p><code> const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;</code></p>
<p>What does that mean? It uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_Coalescing_Operator" rel="noreferrer">null coalescing operator</a> in the end, however I can't understand what does the question mark do before a dot.</p>
<p>I know it is a correct syntax because it is a template from <a href="https://expo.io/dashboard/robertwt7" rel="noreferrer">expo</a> and they're very popular in react-native development community.</p>
<p>Can anyone help me explain?</p> | 61,847,272 | 1 | 2 | null | 2020-05-17 05:04:01.223 UTC | 19 | 2022-03-23 21:58:17.203 UTC | 2021-05-05 13:33:46.01 UTC | null | 759,866 | null | 5,047,069 | null | 1 | 66 | reactjs|react-native | 52,163 | <p>That's optional chaining: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">MDN</a></p>
<blockquote>
<p>The <strong>optional chaining</strong> operator (<code>?.</code>) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.</p>
<p>The <code>?.</code> operator is like the <code>.</code> chaining operator, except that instead of causing an error if a reference is nullish (<code>null</code> or <code>undefined</code>), the expression short-circuits with a return value of <code>undefined</code>. When used with function calls, it returns <code>undefined</code> if the given function does not exist.</p>
<p>This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.</p>
</blockquote> |
9,270,972 | Convert array of 2-element arrays into a hash, where duplicate keys append additional values | <h2>For example</h2>
<p>Given an array:</p>
<pre><code>array = [[:a,:b],[:a,:c],[:c,:b]]
</code></pre>
<p>Return the following hash:</p>
<pre><code>hash = { :a => [:b,:c] , :c => [:b] }
</code></pre>
<p><code>hash = Hash[array]</code> overwrites previous associations, producing:</p>
<pre><code>hash = { :a => :c , :c => :b }
</code></pre> | 9,271,550 | 4 | 3 | null | 2012-02-14 02:38:29.443 UTC | 11 | 2020-10-08 16:24:43.767 UTC | 2016-05-12 00:15:08.84 UTC | null | 104,219 | null | 425,760 | null | 1 | 44 | ruby|arrays|hash | 30,577 | <p>Using functional baby steps:</p>
<pre><code>irb:01.0> array = [[:a,:b],[:a,:c],[:c,:b]]
#=> [[:a, :b], [:a, :c], [:c, :b]]
irb:02.0> array.group_by(&:first)
#=> {:a=>[[:a, :b], [:a, :c]], :c=>[[:c, :b]]}
irb:03.0> array.group_by(&:first).map{ |k,a| [k,a.map(&:last)] }
#=> [[:a, [:b, :c]], [:c, [:b]]]
irb:04.0> Hash[ array.group_by(&:first).map{ |k,a| [k,a.map(&:last)] } ]
#=> {:a=>[:b, :c], :c=>[:b]}
</code></pre>
<p>Using imperative style programming:</p>
<pre><code>irb:10.0> h = Hash.new{ |h,k| h[k]=[] }
#=> {}
irb:11.0> array.each{ |k,v| h[k] << v }
#=> [[:a, :b], [:a, :c], [:c, :b]]
irb:12.0> h
#=> {:a=>[:b, :c], :c=>[:b]}
</code></pre>
<p>As an imperative one-liner:</p>
<pre><code>irb:13.0> h = Hash.new{ |h,k| h[k]=[] }.tap{ |h| array.each{ |k,v| h[k] << v } }
#=> {:a=>[:b, :c], :c=>[:b]}
</code></pre>
<p>Or using everyone's favorite <code>inject</code>:</p>
<pre><code>irb:14.0> array.inject(Hash.new{ |h,k| h[k]=[] }){ |h,(k,v)| h[k] << v; h }
#=> {:a=>[:b, :c], :c=>[:b]}
</code></pre>
<p>If you really want to have single values not collided as an array, you can either un-array them as a post-processing step, or use a different hash accumulation strategy that only creates an array upon collision. Alternatively, wrap your head around this:</p>
<pre><code>irb:17.0> hashes = array.map{ |pair| Hash[*pair] } # merge many mini hashes
#=> [{:a=>:b}, {:a=>:c}, {:c=>:b}]
irb:18.0> hashes.inject{ |h1,h2| h1.merge(h2){ |*a| a[1,2] } }
#=> {:a=>[:b, :c], :c=>:b}
</code></pre> |
9,080,135 | Twitter user id in iOS 5 | <p>I'm using the following code to get the user details from Twitter in iOS 5.</p>
<pre><code>if ([TWTweetComposeViewController canSendTweet])
{
// Create account store, followed by a Twitter account identifer
account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to use their Twitter accounts.
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
arrayOfAccounts = [account accountsWithAccountType:accountType];
[arrayOfAccounts retain];
// Populate the tableview
if ([arrayOfAccounts count] > 0)
[self performSelectorOnMainThread:@selector(updateTableview) withObject:NULL waitUntilDone:NO];
}
}];
}
//
-(void)updateTableview
{
numberOfTwitterAccounts = [arrayOfAccounts count];
NSLog(@"Twiter details-- %@",[arrayOfAccounts objectAtIndex:0]);
}
</code></pre>
<p>In my <code>NSLog</code> console, I am getting the output as follows:</p>
<pre><code>Twiter details-- type:com.apple.twitter
identifier: E8591841-2AE0-4FC3-8ED8-F286BE7A36B0
accountDescription: @Sadoo55
username: [email protected]
objectID: x-coredata://F8059811-CFB2-4E20-BD88-F4D06A43EF11/Account/p8
enabledDataclasses: {(
)}
properties: {
"user_id" = 308905856;
}
parentAccount: (null)
owningBundleID:com.apple.Preferences
</code></pre>
<p>I want to get the "user_id" from this. How can I fetch "user_id" (ie. 308905856)?</p> | 9,215,108 | 4 | 4 | 2012-02-12 21:31:06.293 UTC | 2012-01-31 13:14:25.42 UTC | 9 | 2017-07-02 02:16:31.873 UTC | 2012-02-12 21:31:06.293 UTC | null | 1,076,305 | null | 688,663 | null | 1 | 17 | iphone|objective-c|ios|twitter | 10,334 | <p>Getting the user ID &/or username is <em>much</em> easier than that. </p>
<h2>iOS 7 version</h2>
<pre><code>ACAccount *account = accountsArray[0];
NSString *userID = ((NSDictionary*)[account valueForKey:@"properties"])[@"user_id"];
</code></pre>
<p><em>or</em></p>
<pre><code>ACAccount *twitterAccount = accountsArray[0];
NSRange range = [account.description rangeOfString:@" [0-9]{7,8}"
options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSString *userID = [[account.description substringWithRange:range] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"User ID: %@", userID);
}
</code></pre>
<h2>iOS 5 version</h2>
<p>There was an undocumented method of ACAccount called accountProperties of type NSDictionary with a user_id key. </p>
<p><img src="https://i.stack.imgur.com/l4B86.png" alt="ACAccount properties"></p>
<pre><code>ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSString *userID = [[twitterAccount accountProperties] objectForKey:@"user_id"];
NSString *username = twitterAccount.username;
</code></pre>
<p>**Does not work under iOS6 because the method is no longer defined.</p> |
9,092,415 | speex support in android | <p>Can anybody help me on <strong>how to use speex or jspeex in android?</strong></p>
<p>I have searched a lot but could not able to find anywhere.There are many issues regarding this in <a href="http://code.google.com/p/android/issues/detail?can=4&q=&colspec=I&groupby=&sort=&id=354#makechanges" rel="nofollow noreferrer">code.google.com/android</a> but none have answered it. Here also this question did not got a good response as my another question regarding this is <a href="https://stackoverflow.com/questions/9029977/decoding-speex-encoded-byte-array-in-android-jniwrapper-for-speex-decodingsp">Decoding speex encoded byte array in Android</a>. So If you know something about this then Please provide me information regarding this.</p>
<p>I need to encode and decode bytearray of audio file using this codec.</p>
<p>I have tried <a href="http://andrewbrobinson.com/2011/11/28/a-jni-wrapper-for-speex-on-android/comment-page-1/#comment-1352" rel="nofollow noreferrer">Android-ndk and got encoding done,</a> but getting a <strong>problem in decoding the byte array.</strong> Is there any other alternative to achieve this?</p>
<p><strong>EDIT</strong></p>
<p>my encoding Functions in native c file are as follow:</p>
<pre><code>#include <jni.h>
#include "speex/speex.h"
#define FRAME_SIZE 320
int nbBytes;
/*Holds the state of the encoder*/
void *state;
void *decod_state;
/*Holds bits so they can be read and written to by the Speex routines*/
SpeexBits decod_bits;
SpeexBits bits;
int i, tmp;
void Java_com_mycom_speex_SpeexEncodingActivity_init(JNIEnv * env, jobject jobj) {
/*Create a new encoder state in narrowband mode*/
state = speex_encoder_init(&speex_wb_mode);
/*Set the quality to 8*/
tmp=8;
speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);
/*Initialization of the structure that holds the bits*/
speex_bits_init(&bits);
}
jbyteArray Java_com_mycom_speex_SpeexEncodingActivity_encode(JNIEnv * env, jobject jobj, jshortArray inputData) {
jbyteArray ret;
jshort * inputArrayElements = (*env)->GetShortArrayElements(env, inputData, 0);
/*Flush all the bits in the struct so we can encode a new frame*/
speex_bits_reset(&bits);
/*Encode the frame*/
speex_encode_int(state, inputArrayElements, &bits);
/*Copy the bits to an array of char that can be written*/
nbBytes = speex_bits_nbytes(&bits);
ret = (jbyteArray) ((*env)->NewByteArray(env, nbBytes));
jbyte * arrayElements = (*env)->GetByteArrayElements(env, ret, 0);
speex_bits_write(&bits, arrayElements, nbBytes);
(*env)->ReleaseShortArrayElements(env, inputData, inputArrayElements, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, ret, arrayElements, 0);
return ret;
}
</code></pre>
<p>now for decoding i am sending the converted short array to <strong>decode function as follow:</strong></p>
<pre><code>void Java_com_mycom_speex_SpeexEncodingActivity_initDecode(JNIEnv * env,
jobject jobj) {
decod_state = speex_decoder_init(&speex_wb_mode);
tmp = 1;
speex_decoder_ctl(decod_state, SPEEX_SET_ENH, &tmp);
/*Initialization of the structure that holds the bits*/
speex_bits_init(&decod_bits);
}
jshortArray Java_com_mycom_speex_SpeexEncodingActivity_decode(JNIEnv * env,
jobject jobj, jshortArray inputData) {
jshort * inputArrayElements = (*env)->GetShortArrayElements(env, inputData,
0);
/*Flush all the bits in the struct so we can decode a new frame*/
speex_bits_reset(&decod_bits);
/*Copy the bits to an array of char that can be written*/
nbBytes = speex_bits_nbytes(&decod_bits);
speex_bits_read_from(&decod_bits,inputArrayElements, nbBytes); // here it requires char * in second argument
/*Decode the frame*/
speex_decode_int(decod_state, &decod_bits, inputArrayElements);
(*env)->ReleaseShortArrayElements(env, encodedData, inputArrayElements,
JNI_ABORT);
return inputArrayElements;
}
</code></pre>
<p>my Encoding functions are working fine the example is provided on the blog <a href="http://andrewbrobinson.com/2011/11/28/a-jni-wrapper-for-speex-on-android/comment-page-1/#comment-1352" rel="nofollow noreferrer">A JNI Wrapper for Speex on Android</a></p>
<p><strong>Another attempt to decoding by passing char array and returning short array is as follow:</strong></p>
<pre><code>jshortArray Java_com_mycom_speex_SpeexEncodingActivity_decode(JNIEnv * env,
jobject jobj, jcharArray inputCharData) {
jshortArray ret;
jchar * inputArrayElements = (*env)->GetCharArrayElements(env,
inputCharData, 0);
/*Flush all the bits in the struct so we can decode a new frame*/
speex_bits_reset(&decod_bits);
/*Copy the bits to an array of char that can be written*/
nbBytes = speex_bits_nbytes(&decod_bits);
ret = (jshortArray)((*env)->NewShortArray(env, nbBytes));
jshort * arrayElements = (*env)->GetShortArrayElements(env, ret, 0);
speex_bits_read_from(&decod_bits,(char *) inputArrayElements, nbBytes);
/*Decode the frame*/
speex_decode_int(decod_state, &decod_bits, arrayElements);
(*env)->ReleaseCharArrayElements(env, inputCharData, inputArrayElements,
JNI_ABORT);
(*env)->ReleaseShortArrayElements(env, ret, arrayElements, 0);
return ret;
}
</code></pre>
<p>the result is </p>
<pre><code>Returned empty array of short if i return ret and if i return arrayElements it
gives an error Fatal signal 11 (SIGSEGV) at 0x00000018 (code=1)
</code></pre> | 9,297,583 | 3 | 5 | 2012-02-01 13:30:28.947 UTC | 2012-02-01 07:40:42.193 UTC | 10 | 2012-09-12 21:40:25.557 UTC | 2017-05-23 12:16:55.223 UTC | null | -1 | null | 786,935 | null | 1 | 13 | java|android|android-ndk|speex|jspeex | 10,719 | <p>speex_bits_reset do following in its body:</p>
<pre><code>bits->nbBits=0;
</code></pre>
<p>and speex_bits_nbytes returns ((bits->nbBits+7)>>3);
So if you call speex_bits_nbytes right after speex_bits_reset, you always receive 0. So you must call speex_bits_read_from before array allocation:</p>
<pre><code>/*Flush all the bits in the struct so we can decode a new frame*/
speex_bits_reset(&decod_bits);
/*Read bits in decod_bits struct from java array*/
speex_bits_read_from(&decod_bits,(char *) inputArrayElements, nbBytes);
/*Copy the bits to an array of char that can be written*/
nbBytes = speex_bits_nbytes(&decod_bits);
ret = (jshortArray)((*env)->NewShortArray(env, nbBytes));
jshort * arrayElements = (*env)->GetShortArrayElements(env, ret, 0);
/*Decode the frame*/
speex_decode_int(decod_state, &decod_bits, arrayElements);
(*env)->ReleaseCharArrayElements(env, inputCharData, inputArrayElements,
JNI_ABORT);
(*env)->ReleaseShortArrayElements(env, ret, arrayElements, 0);
return ret;
</code></pre> |
9,603,926 | Restart an application by itself | <p>I want to build my application with the function to restart itself. I found on codeproject</p>
<pre><code>ProcessStartInfo Info=new ProcessStartInfo();
Info.Arguments="/C choice /C Y /N /D Y /T 3 & Del "+
Application.ExecutablePath;
Info.WindowStyle=ProcessWindowStyle.Hidden;
Info.CreateNoWindow=true;
Info.FileName="cmd.exe";
Process.Start(Info);
Application.Exit();
</code></pre>
<p>This does not work at all...
And the other problem is, how to start it again like this?
Maybe there are also arguments to start applications.</p>
<p>Edit:</p>
<pre><code>http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=31454&av=58703
</code></pre> | 9,615,697 | 10 | 5 | null | 2012-03-07 15:07:49.83 UTC | 14 | 2020-11-16 22:05:20.003 UTC | 2015-08-06 06:09:46.177 UTC | null | 1,545,777 | null | 876,724 | null | 1 | 19 | c#|.net|windows|batch-file|application-restart | 97,917 | <p>I use similar code to the code you tried when restarting apps. I send a timed cmd command to restart the app for me like this:</p>
<pre><code>ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Application.Exit();
</code></pre>
<p>The command is sent to the OS, the ping pauses the script for 2-3 seconds, by which time the application has exited from <code>Application.Exit()</code>, then the next command after the ping starts it again.</p>
<p>Note: The <code>\"</code> puts quotes around the path, incase it has spaces, which cmd can't process without quotes.</p>
<p>Hope this helps!</p> |
18,406,370 | Don't create view folder on rails generate controller | <p>Is there a way with the usual generators config to turn OFF the creation of the view folders and action templates when you run a <code>rails generate controller</code>?</p>
<p>I can't find an option anywhere and the code <a href="https://github.com/rails/rails/blob/33d92bf69ec5e6f385612b69a6295f5a80332ef8/railties/lib/rails/generators/erb/controller/controller_generator.rb" rel="noreferrer">here</a> doesn't show me any pointers.</p>
<p>We are likely going to be building our own controller / resource generators at some point anyway, for our API, but I was curious if there was a way to turn off this annoyance in the meantime.</p> | 18,408,023 | 4 | 0 | null | 2013-08-23 15:18:28.887 UTC | 12 | 2019-09-10 14:03:50.907 UTC | 2019-09-10 14:03:50.907 UTC | null | 1,511,504 | null | 258,954 | null | 1 | 32 | ruby-on-rails|ruby | 20,708 | <p>It's not a well documented feature, but try to add <code>--skip-template-engine</code> (alias <code>--no-template-engine</code>) option to the command.</p>
<pre><code>rails generate controller foo bar --skip-template-engine
</code></pre>
<p>demo on a dummy app:</p>
<pre><code>rails g controller my_controller index show --no-template-engine
create app/controllers/my_controller_controller.rb
route get "my_controller/show"
route get "my_controller/index"
invoke test_unit
create test/functional/my_controller_controller_test.rb
invoke helper
create app/helpers/my_controller_helper.rb
invoke test_unit
create test/unit/helpers/my_controller_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/my_controller.js.coffee
invoke scss
create app/assets/stylesheets/my_controller.css.scss
</code></pre> |
18,465,211 | JavaScript loop variable scope | <p>Just a quick question about the scoping of JavaScript variables.</p>
<p>Why does the <code>alert()</code> function print the value of <code>i</code> instead of returning <code>undefined</code>?</p>
<pre><code>$(document).ready(function () {
for(var i = 0; i < 10; i += 1){
}
alert("What is 'i'? " + i);
});
</code></pre>
<p>I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?</p>
<p>i.e. <code>What is 'i'? 10'</code> is printed.</p> | 18,465,309 | 5 | 0 | null | 2013-08-27 12:18:22.437 UTC | 20 | 2019-05-05 15:40:35.677 UTC | 2015-05-25 09:14:09.403 UTC | null | 814,702 | null | 1,086,295 | null | 1 | 65 | javascript|variables|for-loop|scope | 70,670 | <p>See the MDN for the "<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Parameters" rel="noreferrer">initialization parameters</a>" of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Parameters" rel="noreferrer"><code>for</code>-loop</a>:</p>
<blockquote>
<p>An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. <strong>These variables are not local to the loop, i.e. they are in the same scope the for loop is in.</strong> The result of this expression is discarded.</p>
</blockquote> |
18,499,935 | Idiom for "repeat n times"? | <p>Here's a somewhat wasteful and impractical way to produce an array of 3 random numbers in JS:</p>
<pre><code>[1, 1, 1].map(Math.random) // Outputs: [0.63244645928, 0.59692098067, 0.73627558014]
</code></pre>
<p>The use of a dummy array (e.g. <code>[1, 1, 1]</code>), just so that one can call <code>map</code> on it, is -- for sufficiently large <em>n</em> -- both wasteful (of memory) and impractical.</p>
<p>What one would like, would be something like a hypothetical:</p>
<pre><code>repeat(3, Math.random) // Outputs: [0.214259553965, 0.002260502324, 0.452618881464]
</code></pre>
<p>What's the closest we can do using vanilla JavaScript?</p>
<p>I'm aware of libraries like Underscore, but I'm trying to avoid libraries here.</p>
<p>I looked at the answers to <a href="https://stackoverflow.com/questions/1877475/repeat-character-n-times">Repeat a string a number of times</a>, but it is not applicable in general. E.g.:</p>
<pre><code>Array(3).map(Math.random) // Outputs: [undefined, undefined, undefined]
Array(4).join(Math.random()) // Outputs a concatenation of a repeated number
Array(3).fill(Math.random()) // Fills with the same number
</code></pre>
<p>Several other answers propose modifying a built-in class; a practice that I consider completely unacceptable.</p> | 18,500,019 | 7 | 15 | null | 2013-08-28 23:27:29.357 UTC | 9 | 2022-03-04 13:33:10.993 UTC | 2021-04-01 13:47:43.817 UTC | null | 5,459,839 | null | 559,827 | null | 1 | 87 | javascript | 82,015 | <p>Underscore.js has a <a href="http://underscorejs.org/#times" rel="noreferrer">times</a> function that does exactly what you want:</p>
<pre><code>_.times(3, Math.random)
</code></pre>
<p>If you don't want to use Underscore, you can just write your own <code>times</code> function (copied and slightly simplified from the Underscore source):</p>
<pre><code>times = function(n, iterator) {
var accum = Array(Math.max(0, n));
for (var i = 0; i < n; i++) accum[i] = iterator.call();
return accum;
};
</code></pre> |
48,102,013 | SQL Server INSERT INTO with WHERE clause | <p>I'm trying to insert some mock payment info into a dev database with this query:</p>
<pre><code>INSERT
INTO
Payments(Amount)
VALUES(12.33)
WHERE
Payments.CustomerID = '145300';
</code></pre>
<p>How can adjust this to execute? I also tried something like this: </p>
<pre><code>IF NOT EXISTS(
SELECT
1
FROM
Payments
WHERE
Payments.CustomerID = '145300'
) INSERT
INTO
Payments(Amount)
VALUES(12.33);
</code></pre> | 48,102,108 | 8 | 4 | null | 2018-01-04 19:13:32.19 UTC | 4 | 2021-07-05 14:52:56.74 UTC | 2019-03-29 19:09:54.23 UTC | null | 7,031,230 | null | 7,986,942 | null | 1 | 12 | sql|sql-server|database|tsql|insert | 72,195 | <p>I think you are trying to do an update statement <em>(set amount = 12.33 for customer with ID = 145300)</em></p>
<pre><code>UPDATE Payments
SET Amount = 12.33
WHERE CustomerID = '145300'
</code></pre>
<p>Else if you are trying to insert a new row then you have to use</p>
<pre><code>IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
INSERT INTO Payments(CustomerID,Amount)
VALUES('145300',12.33)
</code></pre>
<p>Or if you want to combine both command <em>(if customer exists do update else insert new row)</em></p>
<pre><code>IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
INSERT INTO Payments(CustomerID,Amount)
VALUES('145300',12.33)
ELSE
UPDATE Payments
SET Amount = 12.33
WHERE CustomerID = '145300'
</code></pre> |
7,707,329 | Set Node.js environment variables in WebStorm | <p>Is there any way to set environment variables when running a Node.js app using JetBrains' official Node plugin for WebStorm (and their other IDEs as well)?</p> | 7,708,742 | 2 | 0 | null | 2011-10-09 23:41:49.833 UTC | 1 | 2021-04-29 08:47:09.717 UTC | 2014-05-19 03:07:27.333 UTC | null | 1,079,354 | null | 503,916 | null | 1 | 33 | node.js|intellij-idea|environment-variables|webstorm | 29,489 | <p>No, it's not possible from WebStorm, environment variables should be <a href="http://devnet.jetbrains.net/docs/DOC-1160" rel="noreferrer">defined in your system</a>.</p>
<p>UPDATE: in the new versions it's possible to set environment variables in the Run/Debug configuration.</p> |
8,585,184 | zz_moto_actionbar_bkg.xml resource error on Droid | <p>I am getting strange crash reports from Droid X and Droid Pro.</p>
<pre><code>android.content.res.Resources$NotFoundException:
File res/drawable/zz_moto_actionbar_bkg.xml from drawable resource ID #0x10803a8
at android.content.res.Resources.loadDrawable(Resources.java:1735)
at android.content.res.Resources.getDrawable(Resources.java:596)
at android.view.View.setBackgroundResource(View.java:7542)
at com.android.internal.app.AlertController.setBackground(AlertController.java:719)
at com.android.internal.app.AlertController.setupView(AlertController.java:424)
at com.android.internal.app.AlertController.installContent(AlertController.java:232)
at android.app.AlertDialog.onCreate(AlertDialog.java:251)
at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
at android.app.Dialog.show(Dialog.java:225)
at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
at com.*******.a(SourceFile:320)
at com.*******.onOptionsItemSelected(SourceFile:292)
at android.app.Activity.onMenuItemSelected(Activity.java:2251)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:809)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:553)
at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
at android.view.View$PerformClick.run(View.java:9089)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.graphics.drawable.LayerDrawable.addLayer(LayerDrawable.java:186)
at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:157)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:795)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:736)
at android.content.res.Resources.loadDrawable(Resources.java:1732)
... 27 more
java.lang.NullPointerException
at android.graphics.drawable.LayerDrawable.addLayer(LayerDrawable.java:186)
at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:157)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:795)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:736)
at android.content.res.Resources.loadDrawable(Resources.java:1732)
at android.content.res.Resources.getDrawable(Resources.java:596)
at android.view.View.setBackgroundResource(View.java:7542)
at com.android.internal.app.AlertController.setBackground(AlertController.java:719)
at com.android.internal.app.AlertController.setupView(AlertController.java:424)
at com.android.internal.app.AlertController.installContent(AlertController.java:232)
at android.app.AlertDialog.onCreate(AlertDialog.java:251)
at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
at android.app.Dialog.show(Dialog.java:225)
at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
at com.*******.a(SourceFile:320)
at com.*******.onOptionsItemSelected(SourceFile:292)
at android.app.Activity.onMenuItemSelected(Activity.java:2251)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:809)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:553)
at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
at android.view.View$PerformClick.run(View.java:9089)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>It happens when launching an alert dialog. Of course I am not using any resource like that, and Only resource I am using on <code>AlertDialog</code> is <code>android.R.drawable.ic_input_add</code>.</p>
<p>I tried some search on this, but the only relevant page I found was <a href="https://supportforums.motorola.com/message/513190" rel="noreferrer">https://supportforums.motorola.com/message/513190</a> and it does not help much.</p>
<p>Have anyone else had a similar problem or found a solution for this?</p> | 13,369,925 | 3 | 3 | null | 2011-12-21 04:46:42.997 UTC | 6 | 2012-11-13 22:24:17.3 UTC | null | null | null | null | 56,995 | null | 1 | 34 | android|crash-reports | 1,513 | <p>We hit this same bug and, at least in our case, it turned out to be due to running out of memory while an image associated with that layout was being loaded. The layout itself seems to be some skinning stuff Motorola is doing for the alert dialog (my assumption). The only way I found out it was an OutOfMemoryError is that our QA tester generated an adb bugreport when he hit the crash and I could see the OutOfMemoryError in the bugreport caused while attempting to decode an image (on the same thread on which the stack trace was generated).</p> |
8,844,609 | Handling Bool Value With an If Statement | <p>I am a student programmer currently designing a GUI for my company with Qt and I have a rather simple question that I just cant seem to find the answer to on the web. It seems like someone has had to of asked it before so if you know where the answer is Id be happy with a reference. My question is; can a Boolean datatype in c++ be handled using an if statement. So a bool value is either one or zero so can you do something like this</p>
<pre><code>bool trueOrFalse()
{
myclass temp;
QString tempstr;
double candidate;
bool validate;
tempstr = ui->tableWidgetInjectionLocations->item(i,9)->text();
candidate = tempstr.toDouble(&validate);
if(validate == true)
{
temp.tempProperty = candidate;
}
else
{
QMessageBox error;
error.setText("Error");
error.exec();
}
if (validate == true)
{
return true;
}
else
{
return false;
}
}
</code></pre>
<p>What I am really looking for here is in the last section of this bool function. When I use return am I actually returning a value that this function would then hold or am I using a the keyword return inappropriately? Once validation has past Id like to be able to use the function to indicate whether or not to proceed in another function Please keep my criticism constructive please. As a student I am only interested in improving. </p> | 8,844,632 | 2 | 4 | null | 2012-01-13 01:02:40.803 UTC | 1 | 2012-01-13 01:06:15.513 UTC | null | null | null | null | 1,039,044 | null | 1 | 3 | c++|qt|if-statement|boolean|return | 79,015 | <p>The value you return using the <code>return</code> statement is literally returned whenever you call the function.</p>
<p>So if you write this code somewhere else in your program:</p>
<pre><code>bool returnValue = trueOrFalse();
</code></pre>
<p>then the <code>returnValue</code> variable will contain a Boolean value equivalent to whatever was returned by the <code>trueOrFalse()</code> function.</p>
<p>The function itself doesn't "hold" the value, the caller of the function defines a variable that will hold the value after the function call has completed.</p>
<hr>
<p>As for your second question, you <em>are</em> using the <code>return</code> statement correctly, but you can simplify your code in the <code>trueOrFalse()</code> function substantially. Instead of this:</p>
<pre><code> if (validate == true)
{
return true;
}
else
{
return false;
}
</code></pre>
<p>All you need is this:</p>
<pre><code>return validate;
</code></pre>
<p>Because the <code>validate</code> local variable is already a <code>bool</code>!</p>
<p>This removes the redundancy of checking a Boolean value against a Boolean constant (<code>true</code>), which prevents strange errors from creeping in and makes the code easier to read and understand.</p>
<p>In fact, you can use this general pattern any time you're working with Boolean values (<code>bool</code>). Rather than comparing them against the literal <code>false</code> or <code>true</code>, you can just write:</p>
<pre><code>if (validate) // test for truth
{
// do whatever...
}
</code></pre>
<p>or</p>
<pre><code>if (!validate) // test for falsity
{
// do whatever...
}
</code></pre> |
8,567,743 | How to extract value from monadic action | <p>Is there a built-in function with signature <code>:: (Monad m) => m a -> a</code> ?</p>
<p>Hoogle tells that there is no such function. </p>
<p>Can you explain why?</p> | 8,567,831 | 8 | 4 | null | 2011-12-19 21:22:31.96 UTC | 11 | 2018-08-24 17:58:15.873 UTC | 2014-10-18 14:01:31.65 UTC | user1804599 | null | null | 570,689 | null | 1 | 48 | haskell|monads|comonad | 17,597 | <p>A monad only supplies two functions:</p>
<pre><code>return :: Monad m => a -> m a
(>>=) :: Monad m => m a -> (a -> m b) -> m b
</code></pre>
<p>Both of these return something of type <code>m a</code>, so there is no way to combine these in any way to get a function of type <code>Monad m => m a -> a</code>. To do that, you'll need more than these two functions, so you need to know more about <code>m</code> than that it's a monad.</p>
<p>For example, the <code>Identity</code> monad has <code>runIdentity :: Identity a -> a</code>, and several monads have similar functions, but there is no way to provide it generically. In fact, the inability to "escape" from the monad is essential for monads like <code>IO</code>.</p> |
9,009,278 | Can't push app Heroku - Failed to install gems via Bundler | <p>This is how looks my <code>Gemfile</code>:</p>
<pre><code>source 'http://rubygems.org'
gem 'rails', '3.1.2'
#gem 'sqlite3'
gem 'mysql2'
gem "rvm", "~> 1.9.2"
gem 'authlogic'
gem "taps", "~> 0.3.23"
gem "paperclip", "~> 2.4.5"
gem 'aws-s3'
gem 'actionmailer'
gem 'will_paginate'
group :assets do
gem 'sass-rails', '~> 3.1.5.rc.2'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
end
group :production do
gem 'therubyracer-heroku', '~> 0.8.1.pre3'
gem 'pg'
end
gem 'jquery-rails'
</code></pre>
<p>and this is the output from pushing the app to Heroku:</p>
<pre><code>Counting objects: 307, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (291/291), done.
Writing objects: 100% (307/307), 491.60 KiB | 47 KiB/s, done.
Total 307 (delta 43), reused 0 (delta 0)
-----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Installing dependencies using Bundler version 1.1.rc.7
Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment
Fetching gem metadata from http://rubygems.org/.......
Installing rake (0.9.2.2)
Installing multi_json (1.0.4)
Installing activesupport (3.1.2)
Installing builder (3.0.0)
Installing i18n (0.6.0)
Installing activemodel (3.1.2)
Installing erubis (2.7.0)
Installing rack (1.3.6)
Installing rack-cache (1.1)
Installing rack-mount (0.8.3)
Installing rack-test (0.6.1)
Installing hike (1.2.1)
Installing tilt (1.3.3)
Installing sprockets (2.1.2)
Installing actionpack (3.1.2)
Installing mime-types (1.17.2)
Installing polyglot (0.3.3)
Installing treetop (1.4.10)
Installing mail (2.3.0)
Installing actionmailer (3.1.2)
Installing arel (2.2.1)
Installing tzinfo (0.3.31)
Installing activerecord (3.1.2)
Installing activeresource (3.1.2)
Installing authlogic (3.1.0)
Installing xml-simple (1.1.1)
Installing aws-s3 (0.6.2)
Installing cocaine (0.2.1)
Installing coffee-script-source (1.2.0)
Installing execjs (1.3.0)
Installing coffee-script (2.2.0)
Installing rack-ssl (1.3.2)
Installing json (1.6.5) with native extensions
Installing rdoc (3.12)
Installing thor (0.14.6)
Installing railties (3.1.2)
Installing coffee-rails (3.1.1)
Installing jquery-rails (1.0.19)
Installing mysql2 (0.3.11) with native extensions
Installing paperclip (2.4.5)
Installing pg (0.12.2) with native extensions
Using bundler (1.1.rc.7)
Installing rails (3.1.2)
Installing rest-client (1.6.7)
Installing rvm (1.9.2)
Installing sass (3.1.12)
Installing sass-rails (3.1.5)
Installing sequel (3.20.0)
Installing sinatra (1.0)
Installing sqlite3 (1.3.5) with native extensions Unfortunately, a fatal error has occurred. Please report this error to the Bundler issue tracker at https://github.com/carlhuda/bundler/issues so that we can fix it. Thanks!
/usr/local/lib/ruby/1.9.1/rubygems/installer.rb:483:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)
/usr/local/bin/ruby extconf.rb
checking for sqlite3.h... no
sqlite3.h is missing. Try 'port install sqlite3 +universal'
or 'yum install sqlite-devel' and check your shared library search path (the
location where your sqlite3 shared library is located).
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/local/bin/ruby
--with-sqlite3-dir
--without-sqlite3-dir
--with-sqlite3-include
--without-sqlite3-include=${sqlite3-dir}/include
--with-sqlite3-lib
--without-sqlite3-lib=${sqlite3-dir}/lib
--enable-local
--disable-local
Gem files will remain installed in /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.5 for inspection.
Results logged to /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/sqlite3-1.3.5/ext/sqlite3/gem_make.out
from /usr/local/lib/ruby/1.9.1/rubygems/installer.rb:486:in `block in build_extensions'
from /usr/local/lib/ruby/1.9.1/rubygems/installer.rb:446:in `each'
from /usr/local/lib/ruby/1.9.1/rubygems/installer.rb:446:in `build_extensions'
from /usr/local/lib/ruby/1.9.1/rubygems/installer.rb:198:in `install'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/source.rb:90:in `block in install'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/rubygems_integration.rb:82:in `preserve_paths'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/source.rb:89:in `install'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:73:in `block in install_gem_from_spec'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/rubygems_integration.rb:97:in `with_build_args'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:72:in `install_gem_from_spec'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:56:in `block in run'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:55:in `run'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:12:in `install'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/cli.rb:220:in `install'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/task.rb:22:in `run'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor.rb:263:in `dispatch'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/base.rb:386:in `start'
from /tmp/build_14aejbvbx900f/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/bin/bundle:13:in `<top (required)>'
from vendor/bundle/ruby/1.9.1/bin/bundle:19:in `load'
from vendor/bundle/ruby/1.9.1/bin/bundle:19:in `<main>'
!
! Failed to install gems via Bundler.
!
! Detected sqlite3 gem which is not supported on Heroku.
! http://devcenter.heroku.com/articles/how-do-i-use-sqlite3-for-development
!
! Heroku push rejected, failed to compile Ruby/rails app
To [email protected]:_my_repo_.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to '[email protected]:_my_repo_.git'
</code></pre>
<p>What is wrong? I have the same set up in my else app and it works fine... I will much grateful for every help, struggling with this problem whole afternoon...</p>
<p><strong>EDIT:</strong> Also I tried remove repository and create a new one, but still the same.</p> | 9,016,279 | 7 | 5 | null | 2012-01-25 19:50:13.973 UTC | 11 | 2017-06-03 11:13:02.553 UTC | 2012-01-25 20:43:46.557 UTC | null | 984,621 | null | 984,621 | null | 1 | 12 | ruby-on-rails-3.1|heroku|bundler|git-push|pg | 16,999 | <p>So, after a little talk with Heroku suporters, the "problem" was in <code>taps</code> gem - sqlite3 has an association to it. The working solution is:</p>
<pre><code>group :development do
gem 'taps'
gem 'rvm'
end
</code></pre> |
31,201,262 | use filter to return property values in an object | <p>Trying to make a function that uses filter but not a for or while loop or foreach function, that will loop through an array of objects only to return their property values. For example, </p>
<pre class="lang-js prettyprint-override"><code>function getShortMessages(messages) {
return messages.filter(function(obj){
return obj.message
});
}
</code></pre>
<p>so if I call </p>
<pre class="lang-js prettyprint-override"><code>getShortMessages([{message:"bleh"},{message:"blah"}]);
</code></pre>
<p>I should get a return of an array = ["bleh","blah"]
I'm just not sure how to implement filter under these guidelines. Also I was thinking of using a chain function maybe .map.</p>
<p>//// Here is the entire code challenge specification/////</p>
<p>Basic: Filter
Exercise 4 of 18</p>
<h1>Task</h1>
<p>Use Array#filter to write a function called getShortMessages.</p>
<p>getShortMessages takes an array of objects with '.message' properties and returns an array of messages that are less than < 50 characters long.</p>
<p>The function should return an array containing the messages themselves, without their containing object.</p>
<h2>Arguments</h2>
<ul>
<li>messages: an Array of 10 to 100 random objects that look something like this:</li>
</ul>
<pre><code>{
message: 'Esse id amet quis eu esse aute officia ipsum.' // random
}
</code></pre>
<h2>Conditions</h2>
<ul>
<li>Do not use any for/while loops or Array#forEach.</li>
<li>Do not create any unnecessary functions e.g. helpers.</li>
</ul>
<h2>Hint</h2>
<ul>
<li>Try chaining some Array methods!</li>
</ul>
<h2>Example</h2>
<pre><code>[ 'Tempor quis esse consequat sunt ea eiusmod.',
'Id culpa ad proident ad nulla laborum incididunt.',
'Ullamco in ea et ad anim anim ullamco est.',
'Est ut irure irure nisi.' ]
</code></pre>
<h2>Resources</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map</a></li>
</ul>
<h2>Boilerplate</h2>
<pre><code>function getShortMessages(messages) {
// SOLUTION GOES HERE
}
module.exports = getShortMessages
</code></pre>
<p>» To print these instructions again, run: functional-javascript print
» To execute your program in a test environment, run: functional-javascript run program.js
» To verify your program, run: functional-javascript verify program.js
» For help run: functional-javascript help</p> | 31,201,324 | 5 | 5 | null | 2015-07-03 07:40:26.437 UTC | 21 | 2021-08-26 01:02:47.49 UTC | 2019-11-07 09:52:39.783 UTC | null | 6,592,125 | null | 3,414,374 | null | 1 | 84 | javascript|filter | 140,935 | <p>Use <code>.filter</code> when you want to get the whole object(s) that match the expected property or properties. Use <code>.map</code> when you have an array of things and want to do some operation on those things and get the result.</p>
<p>The challenge is to get all of the messages that are 50 characters or less. So you can use <code>filter</code> to get only the messages that pass that test and then <code>map</code> to get only the message text.</p>
<pre><code>function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
</code></pre>
<p>JSFiddle: <a href="http://jsfiddle.net/rbbk65sq/" rel="noreferrer">http://jsfiddle.net/rbbk65sq/</a></p>
<p>If it is possible for the input objects to not have a <code>message</code> property, you would want to test for it with <code>obj.message && obj.message.length <= 50</code> like this:</p>
<pre><code>function getShortMessages(messages) {
return messages
.filter(function(obj) {
return obj.message && obj.message.length <= 50;
})
.map(function(obj) {
return obj.message;
});
}
</code></pre>
<h3>ES6</h3>
<p>The same code samples in ES6:</p>
<pre><code>const getShortMessages = (messages) => messages
.filter(obj => obj.message.length <= 50)
.map(obj => obj.message);
</code></pre>
<p>And if the input objects might not have the <code>message</code> property:</p>
<pre><code>const getShortMessages = (messages) => messages
.filter(obj => obj.message && obj.message.length <= 50)
.map(obj => obj.message);
</code></pre>
<p>JSFiddle: <a href="http://jsfiddle.net/npfsrwjq/" rel="noreferrer">http://jsfiddle.net/npfsrwjq/</a></p> |
5,278,674 | Do redundant casts get optimized? | <p>I am updating some old code, and have found several instances where the same object is being cast repeatedly each time one of its properties or methods needs to be called. Example:</p>
<pre><code>if (recDate != null && recDate > ((System.Windows.Forms.DateTimePicker)ctrl).MinDate)
{
((System.Windows.Forms.DateTimePicker)ctrl).CustomFormat = "MM/dd/yyyy";
((System.Windows.Forms.DateTimePicker)ctrl).Value = recDate;
}
else
{
(System.Windows.Forms.DateTimePicker)ctrl).CustomFormat = " ";
}
((System.Windows.Forms.DateTimePicker)ctrl).Format = DateTimePickerFormat.Custom;
</code></pre>
<p>My inclination is to fix this monstrosity, but given my limited time I don't want to bother with anything that's not affecting functionality or performance.</p>
<p>So what I'm wondering is, are these redundant casts getting optimized away by the compiler? I tried figuring it out myself by using ildasm on a simplified example, but not being familiar with IL I only ended up more confused.</p>
<p><strong>UPDATE</strong></p>
<p>So far, the consensus seems to be that a)no, the casts are not optimized, but b)while there may possibly be some small performance hit as a result, it is not likely significant, and c)I should consider fixing them anyway. I have come down on the side of resolving to fix these someday, if I have time. Meanwhile, I won't worry about them.</p>
<p>Thanks everyone!</p> | 5,278,840 | 4 | 3 | null | 2011-03-11 21:39:28.483 UTC | 4 | 2011-03-12 07:07:06.98 UTC | 2011-03-12 07:07:06.98 UTC | null | 366,904 | null | 343,559 | null | 1 | 45 | c#|.net|casting|jit|compiler-optimization | 2,250 | <p>It is not optimized away from IL in either debug or release builds.</p>
<p>simple C# test:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RedundantCastTest
{
class Program
{
static object get()
{ return "asdf"; }
static void Main(string[] args)
{
object obj = get();
if ((string)obj == "asdf")
Console.WriteLine("Equal: {0}, len: {1}", obj, ((string)obj).Length);
}
}
}
</code></pre>
<p>Corresponding IL (note the multiple <code>castclass</code> instructions):</p>
<pre><code>.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] object obj,
[1] bool CS$4$0000)
L_0000: nop
L_0001: call object RedundantCastTest.Program::get()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: castclass string
L_000d: ldstr "asdf"
L_0012: call bool [mscorlib]System.String::op_Equality(string, string)
L_0017: ldc.i4.0
L_0018: ceq
L_001a: stloc.1
L_001b: ldloc.1
L_001c: brtrue.s L_003a
L_001e: ldstr "Equal: {0}, len: {1}"
L_0023: ldloc.0
L_0024: ldloc.0
L_0025: castclass string
L_002a: callvirt instance int32 [mscorlib]System.String::get_Length()
L_002f: box int32
L_0034: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_0039: nop
L_003a: ret
}
</code></pre>
<p>Neither is it optimized from the IL in the release build:</p>
<pre><code>.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] object obj)
L_0000: call object RedundantCastTest.Program::get()
L_0005: stloc.0
L_0006: ldloc.0
L_0007: castclass string
L_000c: ldstr "asdf"
L_0011: call bool [mscorlib]System.String::op_Equality(string, string)
L_0016: brfalse.s L_0033
L_0018: ldstr "Equal: {0}, len: {1}"
L_001d: ldloc.0
L_001e: ldloc.0
L_001f: castclass string
L_0024: callvirt instance int32 [mscorlib]System.String::get_Length()
L_0029: box int32
L_002e: call void [mscorlib]System.Console::WriteLine(string, object, object)
L_0033: ret
}
</code></pre>
<p>Neither case means that the casts don't get optimized when native code is generated - you'd need to look at the actual machine assembly there. i.e. by running ngen and disassembling. I'd be greatly surprised if it wasn't optimized away.</p>
<p>Regardless, I'll cite <a href="https://rads.stackoverflow.com/amzn/click/com/020161622X" rel="noreferrer" rel="nofollow noreferrer">The Pragmatic Programmer</a> and the broken window theorem: When you see a broken window, fix it.</p> |
5,320,525 | Regular expression to match last number in a string | <p>I need to extract the last number that is inside a string. I'm trying to do this with regex and negative lookaheads, but it's not working. This is the regex that I have: </p>
<pre><code>\d+(?!\d+)
</code></pre>
<p>And these are some strings, just to give you an idea, and what the regex should match:</p>
<pre><code>ARRAY[123] matches 123
ARRAY[123].ITEM[4] matches 4
B:1000 matches 1000
B:1000.10 matches 10
</code></pre>
<p>And so on. The regex matches the numbers, but all of them. I don't get why the negative lookahead is not working. Any one care to explain?</p> | 5,320,864 | 4 | 0 | null | 2011-03-16 02:51:23.333 UTC | 17 | 2020-09-29 19:50:37.527 UTC | 2012-10-31 14:18:37.66 UTC | null | 227,665 | null | 156,066 | null | 1 | 47 | regex|string | 76,318 | <p>Your regex <code>\d+(?!\d+)</code> says </p>
<p>match any number if it is not <strong><em>immediately followed</em></strong> by a number.</p>
<p>which is incorrect. A number is last if it is <strong><em>not followed (following it anywhere, not just immediately) by any other number.</em></strong></p>
<p>When translated to regex we have:</p>
<pre><code>(\d+)(?!.*\d)
</code></pre>
<p><a href="http://www.rubular.com/r/fQHTdkCKLI" rel="noreferrer"><strong>Rubular Link</strong></a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.