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
21,642,005
How to make responsive Android application which is used in mobile and also in tablet?
<p>I have created one Android application. </p> <p>When I run my application in <code>Mobile Phone</code> it works very well, but when I run in <code>Tablet</code> the layout of application is changed.</p> <p>So, how to make responsive Android application which is used in <code>Mobile</code> and also in <code>Tablet</code>?</p>
21,644,072
4
1
null
2014-02-08 04:43:56.487 UTC
11
2021-03-23 08:04:04.347 UTC
2018-12-20 05:28:13.96 UTC
null
3,235,048
null
3,235,048
null
1
4
android|android-layout
39,144
<p>On Android we can use <strong><em>screen size selector</em></strong>, introduced from <strong><em>Android 3.2</em></strong>, to define which layout to use. More details available at <a href="http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html" rel="noreferrer">http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html</a>. Following code snippet has been extracted from the same link :</p> <pre><code>public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(); Configuration config = getResources().getConfiguration(); if (config.smallestScreenWidthDp &gt;= 600) { setContentView(R.layout.main_activity_tablet); } else { setContentView(R.layout.main_activity); } } } </code></pre> <p>Another good reference for size configuration is keeping separator. This is explain in details at : <a href="http://www.vanteon.com/downloads/Scaling_Android_Apps_White_Paper.pdf" rel="noreferrer">http://www.vanteon.com/downloads/Scaling_Android_Apps_White_Paper.pdf</a></p>
33,172,390
How to handle SYSTEM_ALERT_WINDOW permission not being auto-granted on some pre-Marshmallow devices
<p>I've been getting reports of some Xiaomi devices (e.g. Mi 2, running API level 21) not showing overlays. My app targets API 23.</p> <p>There are <a href="http://forum.xda-developers.com/xiaomi-mi-3/help/link-bubble-playing-nice-t2857607" rel="noreferrer">several</a> <a href="http://en.miui.com/thread-30931-1-1.html" rel="noreferrer">posts</a> out there regarding this. It seems that MIUI devices do not enable this permission at install time (unlike other pre-Marshmallow devices).</p> <p>Unfortunately, <code>Settings.canDrawOverlays()</code> only works on Android 23+.</p> <ol> <li>What is the correct way to check whether this permission has not yet been enabled pre-Marshmallow?</li> <li>Is there an Intent to take the user to the relevant MUIU settings page? Maybe: <code>new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", packageName)</code> but I have no means to test this.</li> </ol>
38,283,823
5
2
null
2015-10-16 14:01:45.993 UTC
14
2018-08-14 14:08:22.273 UTC
null
null
null
null
444,761
null
1
17
android|android-overlay
23,224
<p>Checking if you have the drawOverlays permission is safer using this:</p> <pre><code>@SuppressLint("NewApi") public static boolean canDrawOverlayViews(Context con){ if(Build.VERSION.SDK_INT&lt; Build.VERSION_CODES.LOLLIPOP){return true;} try { return Settings.canDrawOverlays(con); } catch(NoSuchMethodError e){ return canDrawOverlaysUsingReflection(con); } } public static boolean canDrawOverlaysUsingReflection(Context context) { try { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); Class clazz = AppOpsManager.class; Method dispatchMethod = clazz.getMethod("checkOp", new Class[] { int.class, int.class, String.class }); //AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24 int mode = (Integer) dispatchMethod.invoke(manager, new Object[] { 24, Binder.getCallingUid(), context.getApplicationContext().getPackageName() }); return AppOpsManager.MODE_ALLOWED == mode; } catch (Exception e) { return false; } } </code></pre> <p>Custom ROMs can have altered the OS so that that Settings.canDrawOverlays() is not available. This happened to me with Xiaomi devices and the app crashed.</p> <p>Requesting the permission:</p> <pre><code>@SuppressLint("InlinedApi") public static void requestOverlayDrawPermission(Activity act, int requestCode){ Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + act.getPackageName())); act.startActivityForResult(intent, requestCode); } </code></pre>
9,047,147
What happens to TCP and UDP (with multicast) connection when an iOS Application did enter background
<p>I created couple experiments:</p> <p>Setup 1: I created a TCP Sender app and a TCP Receiver app.</p> <p>For this experiment, I started the TCP Sender on an iOS device and the TCP Receiver on another iOS device. And then both are verified to have made connection and sending and received data. I then put the TCP Receiver app into background. The TCP Sender app indicated lost of connection and crashed (yes, I intended that way).</p> <p>Setup 2: I created a UDP Sender app and a UDP Receiver app.</p> <p>Same as above, I started the UDP Sender app on an iOS device and the UDP Receiver app on another iOS device. On the UDP Receiver app I subscribed to a multicast group, etc. I verified that the UDP Receiver app is receiving the data from that multicast group sent out by UDP Sender app. I then put the UDP Receiver app into background. After 2 minutes, I get the UDP Sender app to send out another piece of data. I then quit the UDP Sender app completely and turn off that iOS device. I then wait for another 2 minutes or more, and then bring up the UDP Receiver app from background. The UDP Receiver app did receive the data that was sent out by the UDP Sender app before it was terminated.</p> <p>In setup1, my explanation is because TCP is a connection oriented.</p> <p>In setup2, I understand UDP is connectionless. Any explanation why setup2 it worked the way in my experience? (Still receiving data even in background mode)</p>
9,047,315
2
0
null
2012-01-28 17:10:36.803 UTC
9
2012-01-29 12:33:16.51 UTC
null
null
null
null
523,234
null
1
7
ios|tcp|network-programming|udp|network-protocols
7,252
<p>All that happens when you put an app into the background and then let it go suspended is that it stops getting scheduled by the kernel. It doesn't immediately break any connections or tear down any sockets (unless you force it to.)</p> <p>In your UDP case, the kernel receives the packet and puts it into a kernel buffer, waiting for your app to receive it. Since your app process exists but is effectively stopped, the data will just sit in the kernel buffer. If you get too much data, it'll overrun the kernel buffer and get dropped. Otherwise, your app can receive it when (if) it's scheduled again.</p> <p>In the TCP case, pretty much the same thing hapens.</p> <p>But (big but): the OS always has the option to tear down sockets for suspended apps if it wants to, based on memory pressure, etc. So while it won't necessarily do it gratuitously, it may do it.</p> <p>I'm not sure exactly why you're seeing the TCP connection severed quickly. It may be that the kernel heuristics for servering TCP connections is more aggressive than for UDP sockets since TCP connections require more state and more continuous processing than do UDP sockets.</p> <p>See <a href="http://developer.apple.com/library/ios/#technotes/tn2277/_index.html">Technical Note TN2277 Networking and Multitasking</a>.</p>
9,406,628
Get current Row number inside ArrayFormula
<p>In a Google Docs Spreadsheet, I would expect this formula:</p> <p><code>=ARRAYFORMULA(ROW())</code></p> <p>to fill the column like:</p> <pre><code>[ 1] [ 2] [ 3] [ 4] ... </code></pre> <p>but instead it stops at 1. What is happening here? Is there another way to get the current row number in an arrayformula?</p>
9,412,814
3
0
null
2012-02-23 03:13:37.737 UTC
3
2022-05-31 08:11:36.723 UTC
null
null
null
null
404,960
null
1
25
google-sheets
60,557
<p>You need to specify a cell-range argument for ROW() in order to have more than one value. </p> <p>Try it this way:</p> <pre><code>=ARRAYFORMULA(ROW(A1:A10)) </code></pre> <p>This will fill a column with row numbers from 1 to 10.</p>
9,232,572
Splitting a comma-separated field in Postgresql and doing a UNION ALL on all the resulting tables
<p>I have a table that contains a field of comma separated strings: </p> <pre><code>ID | fruits ----------- 1 | cherry,apple,grape 2 | apple,orange,peach </code></pre> <p>I want to create a normalized version of the table, like this: </p> <pre><code>ID | fruits ----------- 1 | cherry 1 | apple 1 | grape 2 | apple 2 | orange 2 | peach </code></pre> <p>The postgresql 8.4 documentation describes a regexp_split_to_table function that can turn a single table: </p> <pre><code>SELECT foo FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog',E'\\s+') AS foo; </code></pre> <p>which gives you this: </p> <pre><code> foo -------- the quick brown fox jumped over the lazy dog (9 rows) </code></pre> <p>But that is just for a single field. What I want to do is some kind UNION applied to all the tables generated by splitting each field. Thank you. </p>
9,232,657
1
0
null
2012-02-10 18:05:04.063 UTC
9
2012-02-10 20:02:28.443 UTC
null
null
null
null
271,844
null
1
27
sql|postgresql|csv
29,355
<p>This should give you the output you're looking for:</p> <pre><code>SELECT yourTable.ID, regexp_split_to_table(yourTable.fruits, E',') AS split_fruits FROM yourTable </code></pre> <p>EDIT: Fixed the regex.</p>
9,625,663
Calculating and printing the nth prime number
<p>I am trying to calculate prime numbers, which I've already done. But I want to calculate and print ONLY the nth prime number (User input), while calculating the rest (They won't be printed) only the nth prime number will be printed.</p> <p>Here's what I've written so far:</p> <pre><code>import java.util.Scanner; /** * Calculates the nth prime number * @author {Zyst} */ public class Prime { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n, i = 2, x = 2; System.out.printf("This program calculates the nth Prime number\n"); System.out.printf("Please enter the nth prime number you want to find: "); n = input.nextInt(); for(i = 2, x = 2; i &lt;= n; i++) { for(x = 2; x &lt; i; x++) { if(i % x == 0) { break; } } if(x == i) { System.out.printf("\n%d is prime", x); } } } } </code></pre> <p>This is the program I wrote to calculate the prime numbers from 1 to n. However, I want it to only print the nth prime number,</p> <p>What I've thought of doing is making some sort of count int and ++ing it every time it finds a prime, and when the count == n then it prints out that number, but I can't quite figure out how to land it.</p>
9,704,912
11
0
null
2012-03-08 21:58:28.86 UTC
53
2022-02-07 12:43:28.76 UTC
2014-10-29 01:39:25.263 UTC
null
1,224,232
null
1,224,232
null
1
47
java|primes
107,267
<p>To calculate the n-th prime, I know two main variants.</p> <h2>The straightforward way</h2> <p>That is to count all the primes starting from 2 as you find them until you have reached the desired n<sup>th</sup>.</p> <p>This can be done with different levels of sophistication and efficiency, and there are two conceptually different ways to do it. The first is</p> <h3>Testing the primality of all numbers in sequence</h3> <p>This would be accomplished by a driver function like</p> <pre><code>public static int nthPrime(int n) { int candidate, count; for(candidate = 2, count = 0; count &lt; n; ++candidate) { if (isPrime(candidate)) { ++count; } } // The candidate has been incremented once after the count reached n return candidate-1; } </code></pre> <p>and the interesting part that determines the efficiency is the <code>isPrime</code> function.</p> <p>The obvious way for a primality check, given the definition of a prime as a number greater than 1 that is divisible only by 1 and by itself that we learned in school¹, is</p> <h3>Trial division</h3> <p>The direct translation of the definition into code is</p> <pre><code>private static boolean isPrime(int n) { for(int i = 2; i &lt; n; ++i) { if (n % i == 0) { // We are naive, but not stupid, if // the number has a divisor other // than 1 or itself, we return immediately. return false; } } return true; } </code></pre> <p>but, as you will soon discover if you try it, its simplicity is accompanied by slowness. With that primality test, you can find the 1000<sup>th</sup> prime, 7919, in a few milliseconds (about 20 on my computer), but finding the 10000<sup>th</sup> prime, 104729, takes seconds (~2.4s), the 100000<sup>th</sup> prime,1299709, several minutes (about 5), the millionth prime, 15485863, would take about eight and a half hours, the ten-millionth prime, 179424673, weeks, and so on. The runtime complexity is worse than quadratic - Θ(n² * log n).</p> <p>So we'd like to speed the primality test up somewhat. A step that many people take is the realisation that a divisor of <code>n</code> (other than <code>n</code> itself) can be at most <code>n/2</code>. If we use that fact and let the trial division loop only run to <code>n/2</code> instead of <code>n-1</code>, how does the running time of the algorithm change? For composite numbers, the lower loop limit doesn't change anything. For primes, the number of trial divisions is halved, so overall, the running time should be reduced by a factor somewhat smaller than 2. If you try it out, you will find that the running time is almost exactly halved, so <strong>almost all the time is spent verifying the primality of primes</strong> despite there being many more composites than primes.</p> <p>Now, that didn't help much if we want to find the one-hundred-millionth prime, so we have to do better. Trying to reduce the loop limit further, let us see for what numbers the upper bound of <code>n/2</code> is actually needed. If <code>n/2</code> is a divisor of <code>n</code>, then <code>n/2</code> is an integer, in other words, <code>n</code> is divisible by 2. But then the loop doesn't go past 2, so it never (except for <code>n = 4</code>) reaches <code>n/2</code>. Jolly good, so what's the next largest possible divisor of <code>n</code>? Why, <code>n/3</code> of course. But <code>n/3</code> can only be a divisor of <code>n</code> if it is an integer, in other words, if <code>n</code> is divisible by 3. Then the loop will exit at 3 (or before, at 2) and never reach <code>n/3</code> (except for <code>n = 9</code>). The next largest possible divisor ...</p> <p>Hang on a minute! We have <code>2 &lt;-&gt; n/2</code> and <code>3 &lt;-&gt; n/3</code>. <strong>The divisors of n come in pairs.</strong></p> <p>If we consider the pair <code>(d, n/d)</code> of corresponding divisors of <code>n</code>, either <code>d = n/d</code>, i.e. <code>d = √n</code>, or one of them, say <code>d</code>, is smaller than the other. But then <code>d*d &lt; d*(n/d) = n</code> and <code>d &lt; √n</code>. Each pair of corresponding divisors of <code>n</code> contains (at least) one which does not exceed <code>√n</code>.</p> <p><strong>If</strong> <code>n</code> <strong>is composite, its smallest nontrivial divisor does not exceed</strong> <code>√n</code>.</p> <p>So we can reduce the loop limit to <code>√n</code>, and that reduces the runtime complexity of the algorithm. It should now be Θ(n<sup>1.5</sup> * √(log n)), but empirically it seems to scale a little bit better - however, there's not enough data to draw reliable conclusions from empirical results.</p> <p>That finds the millionth prime in about 16 seconds, the ten-millionth in just under nine minutes, and it would find the one-hundred-millionth in about four and a half hours. That's still slow, but a far cry from the ten years or so it would take the naive trial division.</p> <p>Since there are squares of primes and products of two close primes, like 323 = 17*19, we cannot reduce the limit for the trial division loop below <code>√n</code>. Therefore, while staying with trial division, we must look for other ways to improve the algorithm now.</p> <p>One easily seen thing is that no prime other than 2 is even, so we need only check odd numbers after we have taken care of 2. That doesn't make much of a difference, though, since the even numbers are the cheapest to find composite - and the bulk of time is still spent verifying the primality of primes. However, if we look at the even numbers as candidate divisors, we see that if <code>n</code> is divisible by an even number, <code>n</code> itself must be even, so (excepting 2) it will have been recognised as composite before division by any even number greater than 2 is attempted. So all divisions by even numbers greater than 2 that occur in the algorithm must necessarily leave a nonzero remainder. We can thus omit these divisions and check for divisibility only by 2 and the odd numbers from 3 to <code>√n</code>. This halves (not quite exactly) the number of divisions required to determine a number as prime or composite and therefore the running time. That's a good start, but can we do better?</p> <p>Another large family of numbers is the multiples of 3. Every third division we perform is by a multiple of 3, but if <code>n</code> is divisible by one of them, it is also divisible by 3, and hence no division by 9, 15, 21, ... that we perform in our algorithm will ever leave a remainder of 0. So, how can we skip these divisions? Well, the numbers divisible by neither 2 nor 3 are precisely the numbers of the form <code>6*k ± 1</code>. Starting from 5 (since we're only interested in numbers greater than 1), they are 5, 7, 11, 13, 17, 19, ..., the step from one to the next alternates between 2 and 4, which is easy enough, so we can use</p> <pre><code>private static boolean isPrime(int n) { if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int step = 4, m = (int)Math.sqrt(n) + 1; for(int i = 5; i &lt; m; step = 6-step, i += step) { if (n % i == 0) { return false; } } return true; } </code></pre> <p>This gives us another speedup by a factor of (nearly) 1.5, so we'd need about one and a half hours to the hundred-millionth prime.</p> <p>If we continue this route, the next step is the elimination of multiples of 5. The numbers coprime to 2, 3 and 5 are the numbers of the form</p> <pre><code>30*k + 1, 30*k + 7, 30*k + 11, 30*k + 13, 30*k + 17, 30*k + 19, 30*k + 23, 30*k + 29 </code></pre> <p>so we'd need only divide by eight out of every thirty numbers (plus the three smallest primes). The steps from one to the next, starting from 7, cycle through 4, 2, 4, 2, 4, 6, 2, 6. That's still easy enough to implement and yields another speedup by a factor of 1.25 (minus a bit for more complicated code). Going further, the multiples of 7 would be eliminated, leaving 48 out of every 210 numbers to divide by, then 11 (480/2310), 13 (5760/30030) and so on. Each prime <code>p</code> whose multiples are eliminated yields a speedup of (almost) <code>p/(p-1)</code>, so the return decreases while the cost (code complexity, space for the lookup table for the steps) increases with each prime.</p> <p>In general, one would stop soonish, after eliminating the multiples of maybe six or seven primes (or even fewer). Here, however, we can follow through to the very end, when the multiples of all primes have been eliminated and only the primes are left as candidate divisors. Since we are finding all primes in order, each prime is found before it is needed as a candidate divisor and can then be stored for future use. This reduces the algorithmic complexity to - if I haven't miscalculated - O(n<sup>1.5</sup> / √(log n)). At the cost of space usage for storing the primes.</p> <p>With trial division, that is as good as it gets, you have to try and divide by all primes to <code>√n</code> or the first dividing <code>n</code> to determine the primality of <code>n</code>. That finds the hundred-millionth prime in about half an hour here.</p> <p>So how about</p> <h3>Fast primality tests</h3> <p>Primes have other number-theoretic properties than the absence of nontrivial divisors which composite numbers usually don't have. Such properties, if they are fast to check, can form the basis of probabilistic or deterministic primality tests. The archetypical such property is associated with the name of Pierre de Fermat, who, in the early 17<sup>th</sup> century, found that</p> <blockquote> <p>If <code>p</code> is a prime, then <code>p</code> is a divisor of (a<sup>p</sup>-a) for all <code>a</code>.</p> </blockquote> <p>This - Fermat's so-called 'little theorem' - is, in the equivalent formulation</p> <blockquote> <p>Let <code>p</code> be a prime and <code>a</code> not divisible by <code>p</code>. Then <code>p</code> divides a<sup>p-1</sup> - 1.</p> </blockquote> <p>the basis of most of the widespread fast primality tests (for example Miller-Rabin) and variants or analogues of that appear in even more (e.g. Lucas-Selfridge).</p> <p>So if we want to know if a not too small odd number <code>n</code> is a prime (even and small numbers are efficiently treated by trial division), we can choose any number <code>a</code> (> 1) which is not a multiple of <code>n</code>, for example 2, and check whether <code>n</code> divides a<sup>n-1</sup> - 1. Since a<sup>n-1</sup> becomes huge, that is most efficiently done by checking whether <code>a^(n-1) ≡ 1 (mod n)</code>, i.e. by modular exponentiation. If that congruence doesn't hold, we know that <code>n</code> is composite. If it holds, however, we cannot conclude that <code>n</code> is prime, for example <code>2^340 ≡ 1 (mod 341)</code>, but <code>341 = 11 * 31</code> is composite. Composite numbers <code>n</code> such that <code>a^(n-1) ≡ 1 (mod n)</code> are called Fermat pseudoprimes for the base <code>a</code>.</p> <p>But such occurrences are rare. Given any base <code>a &gt; 1</code>, although there are an infinite number of Fermat pseudoprimes to base <code>a</code>, they are much rarer than actual primes. For example, there are only 78 base-2 Fermat pseudoprimes and 76 base-3 Fermat pseudoprimes below 100000, but 9592 primes. So if one chooses an arbitrary odd <code>n &gt; 1</code> and an arbitrary base <code>a &gt; 1</code> and finds <code>a^(n-1) ≡ 1 (mod n)</code>, there's a good chance that <code>n</code> is actually prime.</p> <p>However, we are in a slightly different situation, we are given <code>n</code> and can only choose <code>a</code>. So, for an odd composite <code>n</code>, for how many <code>a</code>, <code>1 &lt; a &lt; n-1</code> can <code>a^(n-1) ≡ 1 (mod n)</code> hold? Unfortunately, there are composite numbers - Carmichael numbers - such that the congruence holds for <em>every</em> <code>a</code> coprime to <code>n</code>. That means that to identify a Carmichael number as composite with the Fermat test, we have to pick a base that is a multiple of one of <code>n</code>'s prime divisors - there may not be many such multiples.</p> <p>But we can strengthen the Fermat test so that composites are more reliably detected. If <code>p</code> is an odd prime, write <code>p-1 = 2*m</code>. Then, if <code>0 &lt; a &lt; p</code>,</p> <pre><code>a^(p-1) - 1 = (a^m + 1) * (a^m - 1) </code></pre> <p>and <code>p</code> divides exactly one of the two factors (the two factors differ by 2, so their greatest common divisor is either 1 or 2). If <code>m</code> is even, we can split <code>a^m - 1</code> in the same way. Continuing, if <code>p-1 = 2^s * k</code> with <code>k</code> odd, write</p> <pre><code>a^(p-1) - 1 = (a^(2^(s-1)*k) + 1) * (a^(2^(s-2)*k) + 1) * ... * (a^k + 1) * (a^k - 1) </code></pre> <p>then <code>p</code> divides exactly one of the factors. This gives rise to the strong Fermat test,</p> <p>Let <code>n &gt; 2</code> be an odd number. Write <code>n-1 = 2^s * k</code> with <code>k</code> odd. Given any <code>a</code> with <code>1 &lt; a &lt; n-1</code>, if</p> <ol> <li><code>a^k ≡ 1 (mod n)</code> or</li> <li><code>a^((2^j)*k) ≡ -1 (mod n)</code> for any <code>j</code> with <code>0 &lt;= j &lt; s</code></li> </ol> <p>then <code>n</code> is a <em>strong (Fermat) probable prime</em> for base <code>a</code>. A composite strong base <code>a</code> (Fermat) probable prime is called a strong (Fermat) pseudoprime for the base <code>a</code>. Strong Fermat pseudoprimes are even rarer than ordinary Fermat pseudoprimes, below 1000000, there are 78498 primes, 245 base-2 Fermat pseudoprimes and only 46 base-2 strong Fermat pseudoprimes. More importantly, for any odd composite <code>n</code>, there are at most <code>(n-9)/4</code> bases <code>1 &lt; a &lt; n-1</code> for which <code>n</code> is a strong Fermat pseudoprime.</p> <p>So if <code>n</code> is an odd composite, the probability that <code>n</code> passes <code>k</code> strong Fermat tests with randomly chosen bases between 1 and <code>n-1</code> (exclusive bounds) is less than <code>1/4^k</code>.</p> <p>A strong Fermat test takes O(log n) steps, each step involves one or two multiplications of numbers with O(log n) bits, so the complexity is O((log n)^3) with naive multiplication [for huge <code>n</code>, more sophisticated multiplication algorithms can be worthwhile].</p> <p>The Miller-Rabin test is the k-fold strong Fermat test with randomly chosen bases. It is a probabilistic test, but for small enough bounds, short combinations of bases are known which give a deterministic result.</p> <p>Strong Fermat tests are part of the deterministic APRCL test.</p> <p>It is advisable to precede such tests with trial division by the first few small primes, since divisions are comparatively cheap and that weeds out most composites.</p> <p>For the problem of finding the <code>n</code><sup>th</sup> prime, in the range where testing all numbers for primality is feasible, there are known combinations of bases that make the multiple strong Fermat test correct, so that would give a faster - O(n*(log n)<sup>4</sup>) - algorithm.</p> <p>For <code>n &lt; 2^32</code>, the bases 2, 7, and 61 are sufficient to verify primality. Using that, the hundred-millionth prime is found in about six minutes.</p> <h3>Eliminating composites by prime divisors, the Sieve of Eratosthenes</h3> <p>Instead of investigating the numbers in sequence and checking whether each is prime from scratch, one can also consider the whole set of relevant numbers as one piece and eliminate the multiples of a given prime in one go. This is known as the Sieve of Eratosthenes:</p> <p>To find the prime numbers not exceeding <code>N</code></p> <ol> <li>make a list of all numbers from 2 to <code>N</code></li> <li>for each <code>k</code> from 2 to <code>N</code>: if <code>k</code> is not yet crossed off, it is prime; cross off all multiples of <code>k</code> as composites</li> </ol> <p>The primes are the numbers in the list which aren't crossed off.</p> <p>This algorithm is fundamentally different from trial division, although both directly use the divisibility characterisation of primes, in contrast to the Fermat test and similar tests which use other properties of primes.</p> <p>In trial division, each number <code>n</code> is paired with all primes not exceeding the smaller of <code>√n</code> and the smallest prime divisor of <code>n</code>. Since most composites have a very small prime divisor, detecting composites is cheap here on average. But testing primes is expensive, since there are relatively many primes below <code>√n</code>. Although there are many more composites than primes, the cost of testing primes is so high that it completely dominates the overall running time and renders trial division a relatively slow algorithm. Trial division for all numbers less than <code>N</code> takes O(N<sup>1.5</sup> / (log N)²) steps.</p> <p>In the sieve, each composite <code>n</code> is paired with all of its prime divisors, but <em>only</em> with those. Thus there the primes are the cheap numbers, they are only ever looked at once, while the composites are more expensive, they are crossed off multiple times. One might believe that since a sieve contains many more 'expensive' numbers than 'cheap' ones, it would overall be a bad algorithm. However, a composite number does not have many distinct prime divisors - the number of distinct prime divisors of <code>n</code> is bounded by <code>log n</code>, but usually it is <em>much</em> smaller, the average of the number of distinct prime divisors of the numbers <code>&lt;= n</code> is <code>log log n</code> - so even the 'expensive' numbers in the sieve are on average no more (or hardly more) expensive than the 'cheap' numbers for trial division.</p> <p>Sieving up to <code>N</code>, for each prime <code>p</code>, there are <code>Θ(N/p)</code> multiples to cross off, so the total number of crossings-off is <code>Θ(∑ (N/p)) = Θ(N * log (log N))</code>. This yields <strong>much</strong> faster algorithms for finding the primes up to <code>N</code> than trial division or sequential testing with the faster primality tests.</p> <p>There is, however, a disadvantage to the sieve, it uses <code>O(N)</code> memory. (But with a segmented sieve, that can be reduced to <code>O(√N)</code> without increasing the time complexity.)</p> <p>For finding the <code>n</code><sup>th</sup> prime, instead of the primes up to <code>N</code>, there is also the problem that it is not known beforehand how far the sieve should reach.</p> <p>The latter can be solved using the prime number theorem. The PNT says</p> <pre><code>π(x) ~ x/log x (equivalently: lim π(x)*log x/x = 1), </code></pre> <p>where <code>π(x)</code> is the number of primes not exceeding <code>x</code> (here and below, <code>log</code> must be the natural logarithm, for the algorithmic complexities it is not important which base is chosen for the logarithms). From that, it follows that <code>p(n) ~ n*log n</code>, where <code>p(n)</code> is the <code>n</code><sup>th</sup> prime, and there are good upper bounds for <code>p(n)</code> known from deeper analysis, in particular</p> <pre><code>n*(log n + log (log n) - 1) &lt; p(n) &lt; n*(log n + log (log n)), for n &gt;= 6. </code></pre> <p>So one can use that as the sieving limit, it doesn't exceed the target far.</p> <p>The <code>O(N)</code> space requirement can be overcome by using a segmented sieve. One can then record the primes below <code>√N</code> for <code>O(√N / log N)</code> memory consumption and use segments of increasing length (O(√N) when the sieve is near N).</p> <p>There are some easy improvements on the algorithm as stated above:</p> <ol> <li>start crossing off multiples of <code>p</code> only at <code>p²</code>, not at <code>2*p</code></li> <li>eliminate the even numbers from the sieve</li> <li>eliminate the multiples of further small primes from the sieve</li> </ol> <p>None of these reduce the algorithmic complexity, but they all reduce the constant factors by a significant amount (as with trial division, the elimination of multiples of <code>p</code> yields lesser speedup for larger <code>p</code> while increasing the code complexity more than for smaller <code>p</code>).</p> <p>Using the first two improvements yields</p> <pre><code>// Entry k in the array represents the number 2*k+3, so we have to do // a bit of arithmetic to get the indices right. public static int nthPrime(int n) { if (n &lt; 2) return 2; if (n == 2) return 3; int limit, root, count = 1; limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3; root = (int)Math.sqrt(limit) + 1; limit = (limit-1)/2; root = root/2 - 1; boolean[] sieve = new boolean[limit]; for(int i = 0; i &lt; root; ++i) { if (!sieve[i]) { ++count; for(int j = 2*i*(i+3)+3, p = 2*i+3; j &lt; limit; j += p) { sieve[j] = true; } } } int p; for(p = root; count &lt; n; ++p) { if (!sieve[p]) { ++count; } } return 2*p+1; } </code></pre> <p>which finds the hundred-millionth prime, 2038074743, in about 18 seconds. This time can be reduced to about 15 seconds (here, YMMV) by storing the flags packed, one bit per flag, instead of as <code>boolean</code>s, since the reduced memory usage gives better cache locality.</p> <p>Packing the flags, eliminating also multiples of 3 and using bit-twiddling for faster faster counting,</p> <pre><code>// Count number of set bits in an int public static int popCount(int n) { n -= (n &gt;&gt;&gt; 1) &amp; 0x55555555; n = ((n &gt;&gt;&gt; 2) &amp; 0x33333333) + (n &amp; 0x33333333); n = ((n &gt;&gt; 4) &amp; 0x0F0F0F0F) + (n &amp; 0x0F0F0F0F); return (n * 0x01010101) &gt;&gt; 24; } // Speed up counting by counting the primes per // array slot and not individually. This yields // another factor of about 1.24 or so. public static int nthPrime(int n) { if (n &lt; 2) return 2; if (n == 2) return 3; if (n == 3) return 5; int limit, root, count = 2; limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3; root = (int)Math.sqrt(limit); switch(limit%6) { case 0: limit = 2*(limit/6) - 1; break; case 5: limit = 2*(limit/6) + 1; break; default: limit = 2*(limit/6); } switch(root%6) { case 0: root = 2*(root/6) - 1; break; case 5: root = 2*(root/6) + 1; break; default: root = 2*(root/6); } int dim = (limit+31) &gt;&gt; 5; int[] sieve = new int[dim]; for(int i = 0; i &lt; root; ++i) { if ((sieve[i &gt;&gt; 5] &amp; (1 &lt;&lt; (i&amp;31))) == 0) { int start, s1, s2; if ((i &amp; 1) == 1) { start = i*(3*i+8)+4; s1 = 4*i+5; s2 = 2*i+3; } else { start = i*(3*i+10)+7; s1 = 2*i+3; s2 = 4*i+7; } for(int j = start; j &lt; limit; j += s2) { sieve[j &gt;&gt; 5] |= 1 &lt;&lt; (j&amp;31); j += s1; if (j &gt;= limit) break; sieve[j &gt;&gt; 5] |= 1 &lt;&lt; (j&amp;31); } } } int i; for(i = 0; count &lt; n; ++i) { count += popCount(~sieve[i]); } --i; int mask = ~sieve[i]; int p; for(p = 31; count &gt;= n; --p) { count -= (mask &gt;&gt; p) &amp; 1; } return 3*(p+(i&lt;&lt;5))+7+(p&amp;1); } </code></pre> <p>finds the hundred-millionth prime in about 9 seconds, which is not unbearably long.</p> <p>There are other types of prime sieves, of particular interest is the Sieve of Atkin, which exploits the fact that certain congruence classes of (rational) primes are composites in the ring of algebraic integers of some quadratic extensions of ℚ. Here is not the place to expand on the mathematical theory, suffice it to say that the Sieve of Atkin has lower algorithmic complexity than the Sieve of Eratosthenes and hence is preferable for large limits (for small limits, a not overly optimised Atkin sieve has higher overhead and thus can be slower than a comparably optimised Eratosthenes sieve). D. J. Bernstein's <a href="http://cr.yp.to/primegen.html" rel="noreferrer">primegen</a> library (written in C) is well optimised for numbers below 2<sup>32</sup> and finds the hundred-millionth prime (here) in about 1.1 seconds.</p> <h2>The fast way</h2> <p>If we only want to find the <code>n</code><sup>th</sup> prime, there is no intrinsic value in also finding all the smaller primes. If we can skip most of them, we can save a lot of time and work. Given a good approximation <code>a(n)</code> to the <code>n</code><sup>th</sup> prime <code>p(n)</code>, if we have a fast way to calculate the number of primes <code>π(a(n))</code> not exceeding <code>a(n)</code>, we can then sieve a small range above or below <code>a(n)</code> to identify the few missing or excess primes between <code>a(n)</code> and <code>p(n)</code>.</p> <p>We have seen an easily computed fairly good approximation to <code>p(n)</code> above, we could take</p> <pre><code>a(n) = n*(log n + log (log n)) </code></pre> <p>for example.</p> <p>A good method to compute <code>π(x)</code> is the <a href="http://en.wikipedia.org/wiki/Prime-counting_function#Algorithms_for_evaluating_.CF.80.28x.29" rel="noreferrer">Meissel-Lehmer method</a>, which computes <code>π(x)</code> in roughly <code>O(x^0.7)</code> time (the exact complexity depends on the implementation, a refinement by Lagarias, Miller, Odlyzko, Deléglise and Rivat lets one compute <code>π(x)</code> in O(x<sup>2/3</sup> / log² x) time).</p> <p>Starting with the simple approximation <code>a(n)</code>, we compute <code>e(n) = π(a(n)) - n</code>. By the prime number theorem, the density of primes near <code>a(n)</code> is about <code>1/log a(n)</code>, so we expect <code>p(n)</code> to be near <code>b(n) = a(n) - log a(n)*e(n)</code> and we would sieve a range slightly larger than <code>log a(n)*e(n)</code>. For greater confidence that <code>p(n)</code> is in the sieved range, one can increase the range by a factor of 2, say, which almost certainly will be large enough. If the range seems too large, one can iterate with the better approximation <code>b(n)</code> in place of <code>a(n)</code>, compute <code>π(b(n))</code> and <code>f(n) = π((b(n)) - n</code>. Typically, <code>|f(n)|</code> will be much smaller than <code>|e(n)|</code>. If <code>f(n)</code> is approximately <code>-e(n)</code>, <code>c(n) = (a(n) + b(n)) / 2</code> will be a better approximation to <code>p(n)</code>. Only in the very unlikely case that <code>f(n)</code> is very close to <code>e(n)</code> (and not very close to 0), finding a sufficiently good approximation to <code>p(n)</code> that the final sieving stage can be done in time comparable to computing <code>π(a(n))</code> becomes a problem.</p> <p>In general, after one or two improvements to the initial approximation, the range to be sieved is small enough for the sieving stage to have a complexity of O(n^0.75) or better.</p> <p>This method finds the hundred-millionth prime in about 40 milliseconds, and the 10<sup>12</sup>-th prime, 29996224275833, in under eight seconds.</p> <hr> <p><strong>tl;dr:</strong> Finding the <code>n</code><sup>th</sup> prime can be efficiently done, but the more efficient you want it, the more mathematics is involved.</p> <hr> <p>I have Java code for most of the discussed algorithms prepared <a href="https://bitbucket.org/dafis/javaprimes" rel="noreferrer">here</a>, in case somebody wants to play around with them.</p> <hr> <p>¹ Aside remark for overinterested souls: The definition of primes used in modern mathematics is different, applicable in much more general situations. If we adapt the school definition to include negative numbers - so a number is prime if it's neither 1 nor -1 and divisible only by 1, -1, itself and its negative - that defines (for integers) what is nowadays called an <em>irreducible</em> element of ℤ, however, for integers, the definitions of prime and irreducible elements coincide.</p>
31,091,637
How to secure the flask-admin panel with flask-security
<p>I'm looking to secure Web API made using Flask and integrated with <code>flask-admin</code> to provide an admin interface. I searched and found that flask-admin has an admin panel at <code>/admin</code> and by default anyone can have access to it. It provides no authentication system and completely open (without any security) since they didn't assume what would be used to provide security. This API has to be used in production, so we can't have an open <code>/admin</code> route for everyone hitting the url. Proper authentication is needed.</p> <p>In <code>views.py</code> I can't simply put the <code>/admin</code> route and provide authentication through decorator as that would be over-writing the existing route already created by <code>flask-admin</code> so that would cause an error. </p> <p>Further research shows that there are two modules <code>flask-admin</code> and <code>flask-security</code>. I know that <code>flask-admin</code> has <code>is_accessible</code> method to secure it, but it doesn't provide much functionality which is provided by <code>flask-security</code>.</p> <p>I've not found any method there to secure the end-point <code>/admin</code> plus all other end-points beginning with <code>/admin</code> such as <code>/admin/&lt;something&gt;</code>.</p> <p>I'm looking specifically to do this task with flask-security. If it's not possible, please suggest alternatives.</p> <p>PS: I know I can lock <code>ngnix</code> itself, but that would be the last option. If I can have an authentication system through <code>flask-security</code> that would be good.</p>
31,115,083
4
1
null
2015-06-27 17:44:06.95 UTC
9
2017-12-13 01:09:48.88 UTC
null
null
null
null
3,535,547
null
1
23
security|authentication|flask|flask-admin|flask-security
22,320
<p>You should check out the <a href="https://github.com/sasaporta/flask-security-admin-example" rel="noreferrer">Flask-Security-Admin</a> project, I think it covers pretty clearly what you are looking for. </p> <p>Taken directly from the link above:</p> <blockquote> <ul> <li>When you first visit the app's home page, you'll be prompted to log in, thanks to Flask-Security.</li> <li>If you log in with [email protected] and password=password, you'll have the "end-user" role.</li> <li>If you log in with [email protected] and password=password, you'll have the "admin" role.</li> <li>Either role is permitted to access the home page.</li> <li>Either role is permitted to access the /admin page. However, unless you have the "admin" role, you won't see the tabs for administration of users and roles on this page.</li> <li>Only the admin role is permitted to access sub-pages of /admin page such as /admin/userview. Otherwise, you'll get a "forbidden" response.</li> <li>Note that, when editing a user, the names of roles are automatically populated thanks to Flask-Admin.</li> <li>You can add and edit users and roles. The resulting users will be able to log in (unless you set active=false) and, if they have the "admin" role, will be able to perform administration.</li> </ul> </blockquote> <p>The relevant code is located in main.py, and is clearly commented to explain how to replicate the process of securing the flask-admin panel using flask-security.</p> <p>The most basic, relevant piece to you is the following (line 152-):</p> <pre><code># Prevent administration of Users unless the currently logged-in user has the "admin" role def is_accessible(self): return current_user.has_role('admin') </code></pre> <p>I hope this is helpful.</p>
47,270,324
NullInjectorError: No provider for MatDialogRef
<p>I can't inject MatDialogRef as it described in documentation: <a href="https://material.angular.io/components/dialog/overview" rel="noreferrer">https://material.angular.io/components/dialog/overview</a></p> <p>When i'm trying to do it i'v got error:</p> <p>ERROR Error: StaticInjectorError[MatDialogRef]: StaticInjectorError[MatDialogRef]: NullInjectorError: No provider for MatDialogRef!</p> <p>app.module.ts</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatInputModule, MatDialogModule, MatProgressSpinnerModule, MatButtonModule, MatDialog, MatDialogRef } from '@angular/material'; import { ApiModule } from '../api/api.module'; import { RoutingModule } from '../routing/routing.module'; import { RegistrationComponent } from './components/registration.component'; import { LoginComponent } from './components/login.component'; import { AccountService } from './services/account.service'; @NgModule({ imports: [ BrowserModule, MatInputModule, MatDialogModule, MatProgressSpinnerModule, MatButtonModule, FormsModule, RoutingModule, ApiModule ], declarations: [ RegistrationComponent, LoginComponent ], entryComponents: [ LoginComponent, RegistrationComponent ], providers: [ AccountService, MatDialog, MatDialogRef ] }) export class AccountModule {}</code></pre> </div> </div> </p> <p>home.component.ts</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core'; import { MatDialog } from '@angular/material'; import { RegistrationComponent } from '../account/components/registration.component'; @Component({ moduleId: module.id.replace('compiled', 'app'), templateUrl: 'home.component.html' }) export class HomeComponent { constructor(private modalService: MatDialog) {} public openModal() : void { let dialog = this.modalService.open(RegistrationComponent, {}); } }</code></pre> </div> </div> </p> <p>registration.component.ts</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { MatDialogRef } from '@angular/material/dialog'; import { User } from '../../../models/domain/User'; import { ApiUserService } from '../../api/entity-services/user.service'; import { AuthService } from '../../auth/auth.service'; import { AccountService } from '../services/account.service' @Component({ selector: 'registration-component', templateUrl: 'app/modules/account/templates/registration.component.html' }) export class RegistrationComponent { public user :User = new User(); public errorMessage :string; public isLoading :boolean; constructor ( private userService :ApiUserService, private authService :AuthService, private accountService :AccountService, private router :Router, public dialogRef :MatDialogRef&lt;RegistrationComponent&gt; ) { this.isLoading = false; } public onSubmit(e) :void { e.preventDefault(); this.isLoading = true; this.userService .Create(this.user) .subscribe( user =&gt; { this.user.id = user.id; this.user.login = user.login; this.authService .Login(this.user) .subscribe( token =&gt; { this.accountService.Load() .subscribe( account =&gt; { this.user = account; this.isLoading = false; this.dialogRef.close(); let redirectRoute = account.activeScopeId ? `/scope/${account.activeScopeId}` : '/scope-list/'; this.router.navigate([redirectRoute]); }, error =&gt; this.errorMessage = &lt;any&gt;error ); }, error =&gt; this.errorMessage = &lt;any&gt;error ); }, error =&gt; this.errorMessage = &lt;any&gt;error ); } }</code></pre> </div> </div> </p>
47,294,991
17
1
null
2017-11-13 17:39:59.82 UTC
6
2022-09-20 08:00:36.057 UTC
2019-04-20 14:14:44.467 UTC
null
826,983
null
2,595,716
null
1
103
angular|typescript|angular-material|angular5
152,830
<p>Thanks to the @Edric, i'v solved the problem by importing <code>MatDialogModule</code>, <code>MatDialog</code> and <code>MatDialogRef</code> from <code>@angular/material/dialog</code> instead of <code>@angular/material</code></p>
10,274,750
Java Swing - setting margins on TextArea with Line Border
<p>As the title says, I am simply trying to set the margins (provide some padding) on a TextArea with a LineBorder set. Without setting the Border, .setMargins works fine. Here is the specific chunk of code.</p> <pre><code>aboutArea = new JTextArea("program info etc....."); Border border = BorderFactory.createLineBorder(Color.BLACK); aboutArea.setSize(400, 200); aboutArea.setBorder(border); aboutArea.setEditable(false); aboutArea.setFont(new Font("Verdana", Font.BOLD, 12)); add(aboutArea); </code></pre> <p>I have tried each of these:</p> <pre><code>aboutArea.setMargins(10,10,10,10); .getBorders(aboutArea).set(10,10,10,10); UIManager.put("aboutArea.margin", new Insets(10, 10, 10, 10)); </code></pre> <p>but nothing affects the margins after I apply the border, the padding is always 0. Any ideas how to set the padding on the textArea with the border?</p>
10,275,226
1
1
null
2012-04-23 04:20:20.927 UTC
0
2012-04-23 07:18:27.84 UTC
2012-04-23 07:18:27.84 UTC
null
230,513
null
1,313,439
null
1
6
java|swing|textarea|margins|insets
39,001
<p>What if you try adding a <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html#createCompoundBorder%28javax.swing.border.Border,%20javax.swing.border.Border%29" rel="noreferrer">CompoundBorder</a> , won't this do, this will give you almost same thing</p> <pre><code>JTextArea tarea = new JTextArea("program info etc."); Border border = BorderFactory.createLineBorder(Color.BLACK); tarea.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(10, 10, 10, 10))); </code></pre> <p><img src="https://i.stack.imgur.com/iNpHM.jpg" alt="CHECK THE MIDDLE JTextArea as OUTPUT"></p>
7,126,550
Java Wait and Notify: IllegalMonitorStateException
<p>I don't completely understand how <code>wait</code> and <code>notify</code> (of <code>Object</code>) work, and as a result I'm forced to slim down my attempts into the following section of code.</p> <p>Main.java:</p> <pre><code>import java.util.ArrayList; class Main { public static Main main = null; public static int numRunners = 4; public static ArrayList&lt;Runner&gt; runners = null; public static void main(String[] args) { main = new Main(); } Main() { runners = new ArrayList&lt;Runner&gt;(numRunners); for (int i = 0; i &lt; numRunners; i++) { Runner r = new Runner(); runners.add(r); new Thread(r).start(); } System.out.println("Runners ready."); notifyAll(); } } </code></pre> <p>Runner.java:</p> <pre><code>class Runner implements Runnable { public void run() { try { Main.main.wait(); } catch (InterruptedException e) {} System.out.println("Runner away!"); } } </code></pre> <p>Currently I get an IllegalMonitorStateException when calling <code>Main.main.wait();</code>, but I don't understand why. From what I can see, I need to synchronize <code>Runner.run</code>, but in doing so I assume it would only notify one thread, when the idea is to notify them all.</p> <p>I've looked at <code>java.util.concurrent</code>, but I can't find a suitable replacement (maybe I'm just missing something).</p>
7,126,587
2
2
null
2011-08-19 19:36:56.607 UTC
20
2014-03-10 06:46:42.677 UTC
null
null
null
null
345,645
null
1
56
java|multithreading|concurrency
111,919
<p>You can't <code>wait()</code> on an object unless the current thread owns that object's monitor. To do that, you must <code>synchronize</code> on it:</p> <pre><code>class Runner implements Runnable { public void run() { try { synchronized(Main.main) { Main.main.wait(); } } catch (InterruptedException e) {} System.out.println("Runner away!"); } } </code></pre> <p>The same rule applies to <code>notify()</code>/<code>notifyAll()</code> as well.</p> <p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29" rel="noreferrer">Javadocs for <code>wait()</code></a> mention this:</p> <blockquote> <p>This method should only be called by a thread that is the owner of this object's monitor. See the <code>notify</code> method for a description of the ways in which a thread can become the owner of a monitor.</p> Throws: <p><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalMonitorStateException.html" rel="noreferrer"><code>IllegalMonitorStateException</code></a> – if the current thread is not the owner of this object's monitor.</p> </blockquote> <p>And from <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer"><code>notify()</code></a>:</p> <blockquote> <p>A thread becomes the owner of the object's monitor in one of three ways:</p> <ul> <li>By executing a synchronized instance method of that object.</li> <li>By executing the body of a <code>synchronized</code> statement that synchronizes on the object.</li> <li>For objects of type <code>Class</code>, by executing a synchronized static method of that class.</li> </ul> </blockquote>
37,093,432
Angular 2 Template Driven Form access ngForm in component
<p>I want to use template driven forms in Angular 2 and I need to access the current ngForm in my directive, as local property and I don't want to pass them as parameter.</p> <p>my form looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;form #frm="ngForm" (ngSubmit)="save(frm)"&gt; &lt;input [(ngModel)]="user.name" #name="ngForm" type="text"&gt; &lt;a (click)="showFrm()" class="btn btn-default"&gt;Show Frm&lt;/a&gt; &lt;/form&gt; </code></pre> <p>and in my component</p> <pre class="lang-js prettyprint-override"><code>@Component({ selector: 'addUser', templateUrl: `Templates/AddUser`, }) export class AddUserComponent implements CanDeactivate { public user: User; // how can I use this without defining the whole form // in my component I only want to use ngModel public frm : ngForm | ControlGroup; public showFrm() : void{ //logs undefined on the console console.log(this.frm); } } </code></pre> <p>Is this possible, because I need to check if the myFrm ist valide or was touched in a function where I can't pass the current form as parameter e.g. "routerCanDeactivate" and I don't want to use model driven forms its way too much to write in code and I love the old school ng1 model binding.</p> <p>I've updated my Example and the frm is not known in the component.</p>
37,136,597
2
2
null
2016-05-07 20:36:03.967 UTC
7
2022-08-23 15:25:35.237 UTC
2018-08-01 04:10:11.217 UTC
null
3,092,377
null
1,865,762
null
1
45
angular
43,037
<p>You need the <code>ngControl</code> attribute on the inputs you want to check.</p> <pre><code>&lt;form #frm=&quot;ngForm&quot; (ngSubmit)=&quot;save(frm)&quot;&gt; &lt;input [(ngModel)]=&quot;user.name&quot; #name=&quot;ngForm&quot; ngControl=&quot;name&quot; type=&quot;text&quot;&gt; &lt;a (click)=&quot;showFrm()&quot;&gt;Show Frm&lt;/a&gt; &lt;/form&gt; </code></pre> <p>and in the component you can access the &quot;frm&quot; variable with</p> <pre><code>import {Component, ViewChild} from 'angular2/core'; ... @ViewChild('frm') public userFrm: NgForm; ... public showFrm(): void{ console.log(this.userFrm); } </code></pre> <p>You can't access the <code>frm</code> in the constructor, it's not there at this moment, but in the ngAfterViewInit you can access it.</p> <p>since Angular 8 or so they have updated the parameters for ViewChild. Currently I need to use this syntax:</p> <pre><code>@ViewChild('frm', { static: true })userFrm: NgForm; </code></pre>
35,728,915
How to position bootstrap buttons where I want?
<p>Inside this code</p> <pre><code>&lt;div class="content"&gt; &lt;h1&gt;TraceMySteps&lt;/h1&gt; &lt;div&gt; &lt;div range-slider floor="0" ceiling="19" dragstop="true" ng-model-low="lowerValue" ng-model-high="upperValue"&gt;&lt;/div&gt; &lt;/div&gt; &lt;button type="button" class="btn btn-primary" id="right-panel-link" href="#right-panel"&gt;Visualizations Panel&lt;/button&gt; &lt;/div&gt; </code></pre> <p>I have my <code>bootstrap</code> button created. The problem here is that it is positioned on the bottom left of my div. I want to put it on the top-right/center of the div, aligned with my title (<code>h1</code>). How do I position it where I want it? I'm new to <code>bootstrap</code> so I do not know about these workarounds. Thank you.</p>
35,729,165
2
2
null
2016-03-01 17:02:35.163 UTC
null
2019-03-06 19:52:10.237 UTC
null
null
null
null
5,798,984
null
1
6
html|css|twitter-bootstrap
53,439
<h2>You can use bootstrap's classes to do this.</h2> <p>You can add <code>pull-right</code> class to float the button to the right.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="content"&gt; &lt;button type="button" class="btn btn-primary pull-right" id="right-panel-link" href="#right-panel"&gt;Visualizations Panel&lt;/button&gt; &lt;h1&gt;TraceMySteps&lt;/h1&gt; &lt;div&gt; &lt;div range-slider floor="0" ceiling="19" dragstop="true" ng-model-low="lowerValue" ng-model-high="upperValue"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Live example <a href="http://www.bootply.com/2JHCPJslHT" rel="noreferrer">here</a>.</p> <h2>As per your comments, for more precise control you can do this with absolute positioning instead.</h2> <p>You give the <code>content</code> element relative positioning and give the <code>button</code> absolute positioning. You can then use any combination of the <code>top</code>, <code>right</code>, <code>bottom</code>, and <code>left</code> properties to place it where you would like.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { position: relative; } #right-panel-link { position: absolute; top: 0; right: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="content"&gt; &lt;h1&gt;TraceMySteps&lt;/h1&gt; &lt;div&gt; &lt;div range-slider floor="0" ceiling="19" dragstop="true" ng-model-low="lowerValue" ng-model-high="upperValue"&gt;&lt;/div&gt; &lt;/div&gt; &lt;button type="button" class="btn btn-primary" id="right-panel-link" href="#right-panel"&gt;Visualizations Panel&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Live example <a href="http://www.bootply.com/4KIfkyhSgx" rel="noreferrer">here</a>.</p>
47,825,540
React-Native Invariant Violation: Element type is invalid
<p>When I going to run my react native app on my iPhone Expo this error displayed in red background area.</p> <blockquote> <p>Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in.</p> </blockquote> <p>this is the App.js inside the 'src/components/' folder <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react'; import { View, Text } from 'react-native'; export default class App extends Component { render() { return ( &lt;View&gt; &lt;Text&gt;Hello&lt;/Text&gt; &lt;/View&gt; ); } }</code></pre> </div> </div> </p> <p>This is the main App.js in react-native app folder.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import App from './src/components/App';</code></pre> </div> </div> </p> <p>I used expo app for run this code. How can I solve this error?</p>
47,871,724
5
5
null
2017-12-15 03:48:39.94 UTC
2
2022-01-22 12:14:42.947 UTC
2017-12-17 06:09:35.683 UTC
null
5,200,792
null
5,200,792
null
1
22
javascript|android|ios|reactjs|react-native
56,986
<p>Expo expects you to export a component from <code>/App.js</code>. But right now you are only importing into <code>/App.js</code>. Expo is not receiving any component to render. You need to export the component you imported like this:</p> <pre><code>export default App; </code></pre> <p><em>On side note:</em> Use a class component only if you must.</p>
8,412,834
Correct use of modules, subroutines and functions in Fortran
<p>I've recently learnt about interface blocks when adding a function to my Fortran program. Everything works nice and neatly, but now I want to add a second function into the interface block.</p> <p>Here is my interface block:</p> <pre><code>interface function correctNeighLabel (A,i,j,k) integer :: correctNeighLabel integer, intent(in) :: i,j,k integer,dimension(:,:,:),intent(inout) :: A end function function correctNeighArray (B,d,e,f) character :: correctNeighArray integer, intent(in) :: d,e,f character, dimension(:,:,:),intent(inout) :: B end function end interface </code></pre> <p>It appears to me that this may not be the best option. </p> <p>I've looked into subroutines, but I'm not very confident that it's the right solution. What I'm doing is relatively simple, and I need to pass arguments to the subroutine, but all the subroutines I've seen are a) complicated (i.e. too complicated for a function), and b) don't take arguments. They behave as though they manipulate variables without them being passed to them.</p> <p>I've not really looked into modules properly, but from what I've seen it's not the right thing to use.</p> <p>Which should I use when, and how do I go about it best?</p>
8,413,337
3
1
null
2011-12-07 09:15:17.043 UTC
19
2019-09-15 11:38:27.783 UTC
2019-09-15 11:38:27.783 UTC
null
-1
null
1,075,247
null
1
28
function|module|fortran|fortran90|subroutine
44,204
<p>Modules are always the right thing to use ;-)</p> <p>If you have a very simple F90 program you can include functions and subroutines in the 'contains' block:</p> <pre><code> program simple implicit none integer :: x, y x = ... y = myfunc(x) contains function myfunc(x) result(y) implicit none integer, intent(in) :: x integer :: y ... end function myfunc end program </code></pre> <p>Then the interface of the functions/subroutines will be known in the program and don't need to be defined in an interface block.</p> <p>For more complex programs you should keep all functions/subroutines in modules and load them when required. So you don't need to define interfaces, either:</p> <pre><code> module mymod implicit none private public :: myfunc contains function myfunc(x) result(y) implicit none integer, intent(in) :: x integer :: y ... end function myfunc end module mymod program advanced use mymod, only: myfunc implicit none integer :: x, y x = ... y = myfunc(x) end program advanced </code></pre> <p>The module and the program can (actually should) be in separate files, but the module has to be compiled before the actual program.</p>
19,386,849
Looping Through NSAttributedString Attributes to Increase Font SIze
<p>All I need is to loop through all attributes of <code>NSAttributedString</code> and increase their font size. So far I got to the point where I successfully loop through and manipulate attributes but I cannot save back to <code>NSAttributedString</code>. The line I commented out is not working for me. How to save back?</p> <pre><code>NSAttributedString *attrString = self.richTextEditor.attributedText; [attrString enumerateAttributesInRange: NSMakeRange(0, attrString.string.length) options:NSAttributedStringEnumerationReverse usingBlock: ^(NSDictionary *attributes, NSRange range, BOOL *stop) { NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes]; UIFont *font = [mutableAttributes objectForKey:NSFontAttributeName]; UIFont *newFont = [UIFont fontWithName:font.fontName size:font.pointSize*2]; [mutableAttributes setObject:newFont forKey:NSFontAttributeName]; //Error: [self.richTextEditor.attributedText setAttributes:mutableAttributes range:range]; //no interfacce for setAttributes:range: }]; </code></pre>
19,387,401
4
0
null
2013-10-15 16:59:37.267 UTC
11
2022-09-19 05:14:04.947 UTC
2013-10-15 17:31:35.397 UTC
null
1,226,963
null
634,603
null
1
33
ios|objective-c|nsattributedstring
16,382
<p>Something like this should work:</p> <pre><code>NSMutableAttributedString *res = [self.richTextEditor.attributedText mutableCopy]; [res beginEditing]; __block BOOL found = NO; [res enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, res.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { if (value) { UIFont *oldFont = (UIFont *)value; UIFont *newFont = [oldFont fontWithSize:oldFont.pointSize * 2]; [res removeAttribute:NSFontAttributeName range:range]; [res addAttribute:NSFontAttributeName value:newFont range:range]; found = YES; } }]; if (!found) { // No font was found - do something else? } [res endEditing]; self.richTextEditor.attributedText = res; </code></pre> <p>At this point <code>res</code> has a new attributed string with all fonts being twice their original size.</p>
19,814,246
R - Combining multiple columns together within a data frame, while keeping connected data
<p>So I've looked quite a lot for an answer to this question, but I can't find an answer that satisfies my needs or my understanding of R.</p> <p>First, here's some code to just give you an idea of what my data set looks like</p> <pre><code>df &lt;- data.frame("Year" = 1991:2000, "Subdiv" = 24:28, H1 = c(31.2,34,70.2,19.8,433.7,126.34,178.39,30.4,56.9,818.3), H2 = c(53.9,121.5,16.9,11.9,114.6,129.9,221.1,433.4,319.2,52.6)) &gt; df Year Subdiv H1 H2 1 1991 24 31.20 53.9 2 1992 25 34.00 121.5 3 1993 26 70.20 16.9 4 1994 27 19.80 11.9 5 1995 28 433.70 114.6 6 1996 24 126.34 129.9 7 1997 25 178.39 221.1 8 1998 26 30.40 433.4 9 1999 27 56.90 319.2 10 2000 28 818.30 52.6 </code></pre> <p>So what I've got here is a data set containing abundance of herring of different ages in different areas ("Subdiv") over time. H1 stands for herring at age 1. My real data set contains more ages as well as more areas (,and additional species of fish).</p> <p>What I would like to do is combine the abundance of different ages into one column while keeping the connected data (Year, Subdiv) as well as creating a new column for Age. Like so:</p> <pre><code> Year Subdiv Abun Age 1 1991 24 31.20 1 2 1992 25 34.00 1 3 1993 26 70.20 1 4 1994 27 19.80 1 5 1995 28 433.70 1 6 1991 24 53.9 2 7 1992 25 121.5 2 8 1993 26 16.9 2 9 1994 27 11.9 2 10 1995 28 114.6 2 </code></pre> <p>Note: Yes, I removed some rows, but only to not crowd the screen</p> <p>I hope this is enough of information for making it understandable what I need and for someone to help.</p> <p>Since I have more species of fish, if someone would like to include a description for adding a Species column as well, that would be helpful. Here's code for the same data, just duplicated for sprat (Sn):</p> <pre><code>df &lt;- data.frame("Year" = 1991:2000, "Subdiv" = 24:28, H1 = c(31.2,34,70.2,19.8,433.7,126.34,178.39,30.4,56.9,818.3), H2 = c(53.9,121.5,16.9,11.9,114.6,129.9,221.1,433.4,319.2,52.6), S1 = c(31.2,34,70.2,19.8,433.7,126.34,178.39,30.4,56.9,818.3), S2 = c(53.9,121.5,16.9,11.9,114.6,129.9,221.1,433.4,319.2,52.6)) </code></pre> <p>Cheers!</p> <p>I don't think the tags of this question should be unrelated, but if you don't find the tags fitting for my question, go a head and change.</p>
19,814,597
2
1
null
2013-11-06 14:08:53.173 UTC
3
2013-11-06 16:25:09.593 UTC
2013-11-06 16:25:09.593 UTC
null
1,270,695
null
2,885,823
null
1
1
r|dataframe|multiple-columns|reshape|calculated-columns
38,290
<p>This is a typical reshape then supplement task so you can:</p> <p>1) 'Melt' your data with reshape2</p> <pre><code>library("reshape2") df.m&lt;-melt(df,id.vars=c("Year","Subdiv")) </code></pre> <p>2) Then add additional columns based on the variable column that holds your previous df's column names</p> <pre><code>library("stringr") df.m$Fish&lt;-str_extract(df.m$variable,"[A-Z]") df.m$Age&lt;-str_extract(df.m$variable,"[0-9]") </code></pre> <p>I recommend you look up the reshape functions as these are very commonly required and learning them will save you lots of time in future <a href="http://www.statmethods.net/management/reshape.html" rel="noreferrer">http://www.statmethods.net/management/reshape.html</a></p>
62,253,289
ValueError: Data cardinality is ambiguous
<p>I'm trying to train LSTM network on data taken from a DataFrame.</p> <p>Here's the code:</p> <pre><code>x_lstm=x.to_numpy().reshape(1,x.shape[0],x.shape[1]) model = keras.models.Sequential([ keras.layers.LSTM(x.shape[1], return_sequences=True, input_shape=(x_lstm.shape[1],x_lstm.shape[2])), keras.layers.LSTM(NORMAL_LAYER_SIZE, return_sequences=True), keras.layers.LSTM(NORMAL_LAYER_SIZE), keras.layers.Dense(y.shape[1]) ]) optimizer=keras.optimizers.Adadelta() model.compile(loss="mse", optimizer=optimizer) for i in range(150): history = model.fit(x_lstm, y) save_model(model,'tmp.rnn') </code></pre> <p>This fails with </p> <pre><code>ValueError: Data cardinality is ambiguous: x sizes: 1 y sizes: 99 Please provide data which shares the same first dimension. </code></pre> <p>When I change model to</p> <pre><code>model = keras.models.Sequential([ keras.layers.LSTM(x.shape[1], return_sequences=True, input_shape=x_lstm.shape), keras.layers.LSTM(NORMAL_LAYER_SIZE, return_sequences=True), keras.layers.LSTM(NORMAL_LAYER_SIZE), keras.layers.Dense(y.shape[1]) ]) </code></pre> <p>it fails with following error:</p> <pre><code>Input 0 of layer lstm_9 is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: [None, 1, 99, 1200] </code></pre> <p>How do I get this to work?</p> <p>x has shape of <code>(99, 1200)</code> (99 items with 1200 features each, this is just sample a larger dataset), y has shape <code>(99, 1)</code></p>
62,261,086
1
1
null
2020-06-08 00:19:38.883 UTC
1
2021-12-09 05:28:47.32 UTC
null
null
null
null
847,200
null
1
12
python|tensorflow|keras|lstm
44,281
<p>As the <code>Error</code> suggests, the <code>First Dimension</code> of <code>X</code> and <code>y</code> is different. <code>First Dimension</code> indicates the <code>Batch Size</code> and it should be same.</p> <p>Please ensure that <code>Y</code> also has the <code>shape</code>, <code>(1, something)</code>.</p> <p>I could reproduce your error with the Code shown below:</p> <pre><code>from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM import tensorflow as tf import numpy as np # define sequences sequences = [ [1, 2, 3, 4], [1, 2, 3], [1] ] # pad sequence padded = pad_sequences(sequences) X = np.expand_dims(padded, axis = 0) print(X.shape) # (1, 3, 4) y = np.array([1,0,1]) #y = y.reshape(1,-1) print(y.shape) # (3,) model = Sequential() model.add(LSTM(4, return_sequences=False, input_shape=(None, X.shape[2]))) model.add(Dense(1, activation='sigmoid')) model.compile ( loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.001)) model.fit(x = X, y = y) </code></pre> <p>If we observe the <code>Print</code> Statements,</p> <pre><code>Shape of X is (1, 3, 4) Shape of y is (3,) </code></pre> <p>This Error can be fixed by uncommenting the Line, <code>y = y.reshape(1,-1)</code>, which makes the <code>First Dimension</code> (<code>Batch_Size</code>) equal (<strong><code>1</code></strong>) for both <code>X</code> and <code>y</code>.</p> <p>Now, the working code is shown below, along with the Output:</p> <pre><code>from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM import tensorflow as tf import numpy as np # define sequences sequences = [ [1, 2, 3, 4], [1, 2, 3], [1] ] # pad sequence padded = pad_sequences(sequences) X = np.expand_dims(padded, axis = 0) print('Shape of X is ', X.shape) # (1, 3, 4) y = np.array([1,0,1]) y = y.reshape(1,-1) print('Shape of y is', y.shape) # (1, 3) model = Sequential() model.add(LSTM(4, return_sequences=False, input_shape=(None, X.shape[2]))) model.add(Dense(1, activation='sigmoid')) model.compile ( loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.001)) model.fit(x = X, y = y) </code></pre> <p>The Output of above code is :</p> <pre><code>Shape of X is (1, 3, 4) Shape of y is (1, 3) 1/1 [==============================] - 0s 1ms/step - loss: 0.2588 &lt;tensorflow.python.keras.callbacks.History at 0x7f5b0d78f4a8&gt; </code></pre> <p>Hope this helps. Happy Learning!</p>
1,154,571
Scala: Abstract types vs generics
<p>I was reading <em><a href="http://www.scala-lang.org/node/105" rel="noreferrer">A Tour of Scala: Abstract Types</a></em>. When is it better to use abstract types?</p> <p>For example,</p> <pre><code>abstract class Buffer { type T val element: T } </code></pre> <p>rather that generics, for example,</p> <pre><code>abstract class Buffer[T] { val element: T } </code></pre>
1,154,727
4
0
null
2009-07-20 16:30:58.653 UTC
151
2020-03-20 14:01:14.057 UTC
2013-05-20 19:54:28.563 UTC
null
63,550
null
27,782
null
1
266
generics|scala|abstract-type
40,591
<p>You have a good point of view on this issue here: </p> <p><strong><a href="http://www.artima.com/scalazine/articles/scalas_type_system.html" rel="noreferrer">The Purpose of Scala's Type System</a></strong><br> A Conversation with Martin Odersky, Part III<br> by Bill Venners and Frank Sommers (May 18, 2009)</p> <p>Update (October2009): what follows below has actually been illustrated in this new article by Bill Venners:<br> <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=270195" rel="noreferrer">Abstract Type Members versus Generic Type Parameters in Scala</a> (see summary at the end)</p> <hr> <p>(Here is the relevant extract of the first interview, May 2009, emphasis mine)</p> <h2>General principle</h2> <p>There have always been two notions of abstraction: </p> <ul> <li>parameterization and </li> <li>abstract members. </li> </ul> <p>In Java you also have both, but it depends on what you are abstracting over.<br> In Java you have abstract methods, but you can't pass a method as a parameter.<br> You don't have abstract fields, but you can pass a value as a parameter.<br> And similarly you don't have abstract type members, but you can specify a type as a parameter.<br> So in Java you also have all three of these, but there's a distinction about what abstraction principle you can use for what kinds of things. And you could argue that this distinction is fairly arbitrary.</p> <h2>The Scala Way</h2> <p>We decided to have the <strong>same construction principles for all three sorts of members</strong>.<br> So you can have abstract fields as well as value parameters.<br> You can pass methods (or "functions") as parameters, or you can abstract over them.<br> You can specify types as parameters, or you can abstract over them.<br> And what we get conceptually is that we can model one in terms of the other. At least in principle, we can express every sort of parameterization as a form of object-oriented abstraction. So in a sense you could say Scala is a more orthogonal and complete language.</p> <h2>Why?</h2> <p>What, in particular, <strong>abstract types buy you is a nice treatment for these covariance problems</strong> we talked about before.<br> One standard problem, which has been around for a long time, is the problem of animals and foods.<br> The puzzle was to have a class <code>Animal</code> with a method, <code>eat</code>, which eats some food.<br> The problem is if we subclass Animal and have a class such as Cow, then they would eat only Grass and not arbitrary food. A Cow couldn't eat a Fish, for instance.<br> What you want is to be able to say that a Cow has an eat method that eats only Grass and not other things.<br> Actually, you can't do that in Java because it turns out you can construct unsound situations, like the problem of assigning a Fruit to an Apple variable that I talked about earlier.</p> <p>The answer is that <strong>you add an abstract type into the Animal class</strong>.<br> You say, my new Animal class has a type of <code>SuitableFood</code>, which I don't know.<br> So it's an abstract type. You don't give an implementation of the type. Then you have an <code>eat</code> method that eats only <code>SuitableFood</code>.<br> And then in the <code>Cow</code> class I would say, OK, I have a Cow, which extends class <code>Animal</code>, and for <code>Cow type SuitableFood equals Grass</code>.<br> So <strong>abstract types provide this notion of a type in a superclass that I don't know, which I then fill in later in subclasses with something I do know</strong>.</p> <h2>Same with parameterization?</h2> <p>Indeed you can. You could parameterize class Animal with the kind of food it eats.<br> But <strong>in practice, when you do that with many different things, it leads to an explosion of parameters</strong>, and usually, what's more, in <strong>bounds of parameters</strong>.<br> At the 1998 ECOOP, Kim Bruce, Phil Wadler, and I had a paper where we showed that <strong>as you increase the number of things you don't know, the typical program will grow quadratically</strong>.<br> So there are very good reasons not to do parameters, but to have these abstract members, because they don't give you this quadratic blow up. </p> <hr> <p><a href="https://stackoverflow.com/users/27782/thatismatt">thatismatt</a> asks in the comments:</p> <blockquote> <p>Do you think the following is a fair summary: </p> <ul> <li>Abstract Types are used in 'has-a' or 'uses-a' relationships (e.g. a <code>Cow eats Grass</code>) </li> <li>where as generics are usually 'of' relationships (e.g. <code>List of Ints</code>)</li> </ul> </blockquote> <p>I am not sure the relationship is that different between using abstract types or generics. What is different is:</p> <ul> <li>how they are used, and </li> <li>how parameter bounds are managed.</li> </ul> <hr> <p>To understand what Martin is speaking about when it comes to "explosion of parameters, and usually, what's more, in <strong>bounds of parameters</strong>", and its subsequent quadratically growth when abstract type are modeled using generics, you can consider the paper "<strong><a href="http://www.ist-palcom.org/publications/files/Scalable%20Component%20Abstractions.pdf" rel="noreferrer">Scalable Component Abstraction</a></strong>" written by... Martin Odersky, and Matthias Zenger for OOPSLA 2005, referenced in the <a href="http://www.ist-palcom.org/publications/" rel="noreferrer">publications of the project Palcom</a> (finished in 2007).</p> <p>Relevant extracts</p> <h2>Definition</h2> <blockquote> <p><strong>Abstract type members</strong> provide a flexible way to abstract over concrete types of components.<br> Abstract types can hide information about internals of a component, similar to their use in <a href="http://en.wikipedia.org/wiki/Standard_ML" rel="noreferrer"><strong>SML</strong></a> signatures. In an object-oriented framework where classes can be extended by inheritance, they may also be used as a flexible means of parameterization (often called family polymorphism, see this <a href="http://web.archive.org/web/20150827115928/http://www.familie-kneissl.org/Members/martin/blog/family-polymorphism-in-scala" rel="noreferrer">weblog entry for instance</a>, and the paper written by <a href="http://www.daimi.au.dk/~eernst/" rel="noreferrer">Eric Ernst</a>).</p> </blockquote> <p>(Note: Family polymorphism has been proposed for object-oriented languages as a solution to supporting reusable yet type-safe mutually recursive classes.<br> A key idea of family polymorphism is the notion of families, which are used to group mutually recursive classes)</p> <h2>bounded type abstraction</h2> <pre><code>abstract class MaxCell extends AbsCell { type T &lt;: Ordered { type O = T } def setMax(x: T) = if (get &lt; x) set(x) } </code></pre> <blockquote> <p>Here, the <strong>type declaration of T is constrained by an upper type bound</strong> which consists of a class name Ordered and a refinement <code>{ type O = T }</code>.<br> The upper bound restricts the specializations of T in subclasses to those subtypes of Ordered for which the type member <code>O</code> of <code>equals T</code>.<br> Because of this constraint, the <code>&lt;</code> method of class Ordered is guaranteed to be applicable to a receiver and an argument of type T.<br> The example shows that the bounded type member may itself appear as part of the bound.<br> (i.e. Scala supports <a href="http://www.cs.utexas.edu/~wcook/papers/FBound89/CookFBound89.pdf" rel="noreferrer">F-bounded polymorphism</a>)</p> </blockquote> <p>(Note, from Peter Canning, William Cook, Walter Hill, Walter Olthoff paper:<br> Bounded quantification was introduced by Cardelli and Wegner as a means of typing functions that operate uniformly over all subtypes of a given type.<br> They defined a simple "object" model and used bounded quantification to type-check functions that make sense on all objects having a specified set of "attributes".<br> A more realistic presentation of object-oriented languages would allow objects that are elements of <strong>recursively-defined types</strong>.<br> In this context, bounded quantification no longer serves its intended purpose. It is easy to find functions that makes sense on all objects having a specified set of methods, but which cannot be typed in the Cardelli-Wegner system.<br> To provide a basis for typed polymorphic functions in object-oriented languages, we introduce F-bounded quantification)</p> <h2>Two faces of the same coins</h2> <p>There are two principal forms of abstraction in programming languages: </p> <ul> <li>parameterization and </li> <li>abstract members. </li> </ul> <p>The first form is typical for functional languages, whereas the second form is typically used in object-oriented languages. </p> <p>Traditionally, Java supports parameterization for values, and member abstraction for operations. The more recent Java 5.0 with generics supports parameterization also for types.</p> <p>The arguments for including generics in Scala are two-fold: </p> <ul> <li><p>First, the encoding into abstract types is not that straightforward to do by hand. Besides the loss in conciseness, there is also the problem of accidental name conflicts between abstract type names that emulate type parameters.</p></li> <li><p>Second, generics and abstract types usually serve distinct roles in Scala programs. </p> <ul> <li><strong>Generics</strong> are typically used when one needs just <strong>type instantiation</strong>, whereas </li> <li><strong>abstract types</strong> are typically used when one needs to <strong>refer to the abstract type from client code</strong>.<br> The latter arises in particular in two situations: </li> <li>One might want to hide the exact definition of a type member from client code, to obtain a kind of encapsulation known from SML-style module systems. </li> <li>Or one might want to override the type covariantly in subclasses to obtain family polymorphism.</li> </ul></li> </ul> <p>In a system with bounded polymorphism, rewriting abstract type into generics might entail a <a href="http://209.85.229.132/search?q=cache:cSlnVEpYViQJ:homepages.inf.ed.ac.uk/wadler/papers/parvsvirt/parvsvirt.ps+statically+site:homepages.inf.ed.ac.uk/wadler/&amp;cd=1&amp;hl=fr&amp;ct=clnk&amp;gl=fr&amp;client=firefox-a" rel="noreferrer">quadratic expansion of type bounds</a>.</p> <hr> <h2>Update October 2009</h2> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=270195" rel="noreferrer">Abstract Type Members versus Generic Type Parameters in Scala</a> (Bill Venners)</p> <p>(emphasis mine)</p> <blockquote> <p>My observation so far about <strong>abstract type members</strong> is that they are primarily a better choice than generic type parameters when:</p> <ul> <li>you want to let people <strong>mix in definitions of those types via traits</strong>. </li> <li>you think the <strong>explicit mention of the type member name when it is being defined will help code readability</strong>. </li> </ul> </blockquote> <p>Example:</p> <blockquote> <p>if you want to pass three different fixture objects into tests, you'll be able to do so, but you'll need to specify three types, one for each parameter. Thus had I taken the type parameter approach, your suite classes could have ended up looking like this:</p> </blockquote> <pre><code>// Type parameter version class MySuite extends FixtureSuite3[StringBuilder, ListBuffer, Stack] with MyHandyFixture { // ... } </code></pre> <blockquote> <p>Whereas with the type member approach it will look like this:</p> </blockquote> <pre><code>// Type member version class MySuite extends FixtureSuite3 with MyHandyFixture { // ... } </code></pre> <blockquote> <p>One other minor difference between abstract type members and generic type parameters is that when a generic type parameter is specified, readers of the code do not see the name of the type parameter. Thus were someone to see this line of code:</p> </blockquote> <pre><code>// Type parameter version class MySuite extends FixtureSuite[StringBuilder] with StringBuilderFixture { // ... } </code></pre> <blockquote> <p>They wouldn't know what the name of the type parameter specified as StringBuilder was without looking it up. Whereas the name of the type parameter is right there in the code in the abstract type member approach:</p> </blockquote> <pre><code>// Type member version class MySuite extends FixtureSuite with StringBuilderFixture { type FixtureParam = StringBuilder // ... } </code></pre> <blockquote> <p>In the latter case, readers of the code could see that <code>StringBuilder</code> is the "fixture parameter" type.<br> They still would need to figure out what "fixture parameter" meant, but they could at least get the name of the type without looking in the documentation.</p> </blockquote>
1,299,374
What is eager loading?
<p>What is eager loading? I code in PHP/JS but a more generalised answer will be just fine. </p> <p>I saw a lot of questions regarding Java &amp; Ruby, but i don't know any of these languages, and I find it hard to read code. I don't know whats supposed to do in the first place</p>
1,299,381
4
1
null
2009-08-19 11:37:03.263 UTC
85
2020-05-22 15:03:30.1 UTC
2012-04-30 08:07:49.96 UTC
user257111
null
null
11,301
null
1
190
language-agnostic
82,153
<p>There are three levels:</p> <ol> <li><strong>Eager loading:</strong> you do everything when asked. Classic example is when you multiply two matrices. You do all the calculations. That's eager loading;</li> <li><strong>Lazy loading:</strong> you only do a calculation when required. In the previous example, you don't do any calculations until you access an element of the result matrix; and</li> <li><strong>Over-eager loading:</strong> this is where you try and anticipate what the user will ask for and preload it.</li> </ol> <p>I hope that makes sense in the context you're seeing it.</p> <p>Let me give you a "Webby" example.</p> <p>Imagine a page with rollover images like for menu items or navigation. There are three ways the image loading could work on this page:</p> <ol> <li>Load every single image required before you render the page (<strong>eager</strong>);</li> <li>Load only the displayed images on page load and load the others if/when they are required (<strong>lazy</strong>); and</li> <li>Load only the displayed images on page load. After the page has loaded preload the other images in the background <em>in case you need them</em> (<strong>over-eager</strong>).</li> </ol> <p>Make sense?</p>
39,945,881
(Java) Tic-Tac-Toe game using 2 dimensional Array
<p>In class, our assignment is to create a two-dimensional array and create a tic-tac-toe game around it. I have everything done except displaying when the whole board is full and the game is a draw. I have tried a few things but I have not found the solution and I need some help... Here is my code:</p> <pre><code>import java.util.Scanner; public class TicTacToe { public static void main(String[] args) { Scanner in = new Scanner(System.in); int row, column; char player = 'X'; //create 2 dimensional array for tic tac toe board char[][] board = new char[3][3]; char ch = '1'; for (int i = 0; i &lt; 3; i++){ for (int j = 0; j &lt; 3; j++) { board[i][j] = ch++; } } displayBoard(board); while(!winner(board) == true){ //get input for row/column System.out.println("Enter a row and column (0, 1, or 2); for player " + player + ":"); row = in.nextInt(); column = in.nextInt(); //occupied while (board[row][column] == 'X' || board[row][column] == 'O') { System.out.println("This spot is occupied. Please try again"); } //place the X board[row][column] = player; displayBoard(board); if (winner(board)){ System.out.println("Player " + player + " is the winner!"); } //time to swap players after each go. if (player == 'O') { player = 'X'; } else { player = 'O'; } if (winner(board) == false) { System.out.println("The game is a draw. Please try again."); } } private static void displayBoard(char[][] board) { for (int i = 0; i &lt; board.length; i++) { for (int j = 0; j &lt; board[i].length; j++) { if (j == board[i].length - 1) System.out.print(board[i][j]); else System.out.print( board[i][j] + " | "); } System.out.println(); } } //method to determine whether there is an x or an o in the spot public static Boolean winner(char[][] board){ for (int i = 0; i&lt; board.length; i++) { for (int j = 0; j &lt; board[0].length; j++) { if (board[i][j] == 'O' || board[i][j] == 'X') { return false; } } } return (board[0][0] == board [0][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][0] == board [1][1] &amp;&amp; board[0][0] == board [2][2]) || (board[0][0] == board [1][0] &amp;&amp; board[0][0] == board [2][0]) || (board[2][0] == board [2][1] &amp;&amp; board[2][0] == board [2][2]) || (board[2][0] == board [1][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][2] == board [1][2] &amp;&amp; board[0][2] == board [2][2]) || (board[0][1] == board [1][1] &amp;&amp; board[0][1] == board [2][1]) || (board[1][0] == board [1][1] &amp;&amp; board[1][0] == board [1][2]); } } </code></pre> <p>I want output saying that the board is full when it's full but I get nothing. This is the last line of my output and as you can see, my current strategy is not working as it continues to ask for input. --></p> <p>Enter a row and column (0, 1, or 2); for player X: 2 0 X | O | X O | O | X X | X | O Enter a row and column (0, 1, or 2); for player O: </p>
39,946,445
5
1
null
2016-10-09 16:30:12.287 UTC
2
2017-10-14 14:06:31.197 UTC
2017-10-14 14:06:31.197 UTC
null
8,679,121
null
6,791,413
null
1
2
java|arrays
40,407
<p>First off:</p> <pre><code> while (board[row][column] == 'X' || board[row][column] == 'O') { System.out.println("This spot is occupied. Please try again"); } </code></pre> <p>This will create a infinite loop because <code>row</code> and <code>column</code> shouldn't change you should ask for new input!</p> <p>Also</p> <pre><code>public static Boolean winner(char[][] board){ for (int i = 0; i&lt; board.length; i++) { for (int j = 0; j &lt; board[0].length; j++) { if (board[i][j] == 'O' || board[i][j] == 'X') { return false; } } } </code></pre> <p>As soon you hit 'O' or 'X' you will exit the Method with a false (no winner)</p> <p>What you probably want to check is if every spot is occupied</p> <pre><code>public static Boolean winner(char[][] board){ //Boolean which is true until there is a empty spot boolean occupied = true; //loop and check if there is empty space or if its a draw for (int i = 0; i&lt; board.length; i++) { for (int j = 0; j &lt; board[0].length; j++) { //Check if spot is not 'O' or not 'X' =&gt; empty if (board[i][j] != 'O' || board[i][j] != 'X') { occupied = false; } } } if(occupied) return false; //Check if someone won return (board[0][0] == board [0][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][0] == board [1][1] &amp;&amp; board[0][0] == board [2][2]) || (board[0][0] == board [1][0] &amp;&amp; board[0][0] == board [2][0]) || (board[2][0] == board [2][1] &amp;&amp; board[2][0] == board [2][2]) || (board[2][0] == board [1][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][2] == board [1][2] &amp;&amp; board[0][2] == board [2][2]) || (board[0][1] == board [1][1] &amp;&amp; board[0][1] == board [2][1]) || (board[1][0] == board [1][1] &amp;&amp; board[1][0] == board [1][2]); } </code></pre> <p>This would now check if there is a winner or its a tie</p> <pre><code>Occupied == true == tie == return false Winner == return true </code></pre> <p>But you have three states:</p> <ul> <li>Win </li> <li>Tie</li> <li>NotFinished</li> </ul> <p>With the changed Method you will NOT finish the game until you win.</p> <p>Reason:</p> <pre><code> while(!winner(board) == true) </code></pre> <p>This makes the game run as long as there is NO winner (winner() will be false because everything is occupied or there is no winner)</p> <pre><code>while(!false==true) =&gt; while(true) </code></pre> <p>You could write a method similar to winner but it only checks if the board has empty spots:</p> <pre><code>public static Boolean hasEmptySpot(char[][] board){ //loop and check if there is empty space for (int i = 0; i&lt; board.length; i++) { for (int j = 0; j &lt; board[0].length; j++) { if (board[i][j] != 'O' &amp;&amp; board[i][j] != 'X') { return true; } } } return false; } //New code while(hasEmptySpot(board) || !winner(board)){ //Your code for the game here .... } </code></pre> <p>this would end the game when there is no empty spot left After you finished the game you can call winner(board) and it will return if you tied or won!</p> <p>By creating <code>hasEmptySpot()</code> you could change your winner method to</p> <pre><code>public static Boolean winner(char[][] board){ return (board[0][0] == board [0][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][0] == board [1][1] &amp;&amp; board[0][0] == board [2][2]) || (board[0][0] == board [1][0] &amp;&amp; board[0][0] == board [2][0]) || (board[2][0] == board [2][1] &amp;&amp; board[2][0] == board [2][2]) || (board[2][0] == board [1][1] &amp;&amp; board[0][0] == board [0][2]) || (board[0][2] == board [1][2] &amp;&amp; board[0][2] == board [2][2]) || (board[0][1] == board [1][1] &amp;&amp; board[0][1] == board [2][1]) || (board[1][0] == board [1][1] &amp;&amp; board[1][0] == board [1][2]); } </code></pre> <p>Why? Because you finished the game and you know there are only two possible outcomes Win or Tie.</p> <p>I hope this helped you a little bit.</p> <p><strong>EDIT</strong> Had a logic error myself!</p> <p><strong>First mistake:</strong> you still need to check if there is a winner while the game is running forgot that point!</p> <pre><code>while(hasEmptySpot(board) || !winner(board)){ } </code></pre> <p>Now this will quit the game loop when there is a winner or no empty spots is left</p> <p><strong>Second mistake:</strong> In hasEmptySpot()</p> <pre><code> if (board[i][j] != 'O' &amp;&amp; board[i][j] != 'X') { return true; </code></pre> <p>not </p> <pre><code> if (board[i][j] != 'O' || board[i][j] != 'X') { return true; </code></pre> <p>Fixed it in the upper examples.</p> <p>I'm sorry for the inconvenience!</p>
42,980,663
FFmpeg: high quality animated GIF?
<p>I'm generating animated a GIF from a video on my server.</p> <p>The generated GIF is not really high quality and it looks like the pixels are huge.</p> <p>Example:</p> <p><a href="https://i.stack.imgur.com/aXnUl.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/aXnUl.gif" alt="example GIF"></a></p> <p>This is how I generate the GIF:</p> <pre><code>shell_exec("/usr/bin/ffmpeg -i video.mkv -vf scale=500:-1 -t 10 -r 10 image.gif"); </code></pre> <p>I did a search on Google and came across this:</p> <pre><code>shell_exec("/usr/bin/ffmpeg -i video.mkv -r 20 -f image2pipe -vcodec ppm - | convert -delay 5 - output.gif"); </code></pre> <p>But the command above doesn't do anything and no <em>output.gif</em> is being generated at all.</p> <p>There are some tutorials that I came across but none of them worked for me and some of them involve using ImageMagick which I dont have access to.</p> <p>Could someone please let me know if there is a clear way to generate a high-quality GIF using FFmpeg?</p>
47,486,545
3
5
null
2017-03-23 15:37:59.893 UTC
17
2020-06-09 09:12:07.85 UTC
2020-06-09 09:12:07.85 UTC
null
775,954
null
7,186,963
null
1
31
animation|ffmpeg
36,137
<p>I've written a tool specifically for maximum quality:</p> <p><a href="https://gif.ski" rel="noreferrer">https://gif.ski</a></p> <pre><code>ffmpeg -i video.mp4 frame%04d.png gifski -o clip.gif frame*.png </code></pre> <p>It generates good per-frame palettes, but also combines palettes across frames, achieving even thousands of colors per frame.</p> <p><img src="https://i.stack.imgur.com/OPjCq.gif" width="480"></p> <p>If you want to reduce the video dimensions, add a scaling filter:</p> <pre><code>ffmpeg -i video.mp4 -vf scale=400:240 frame%04d.png </code></pre> <p>If you want to reduce the frame rate, add the <code>fps</code> filter:</p> <pre><code>ffmpeg -i video.mp4 -vf fps=12 frame%04d.png </code></pre> <p>You can combine the filters with <code>-vf scale=400:240,fps=12</code></p>
52,980,064
Maven + Spring Boot: Found multiple occurrences of org.json.JSONObject on the class path:
<p>When I run <code>mvn test</code> I get this warning. How can I fix it? </p> <pre><code>Found multiple occurrences of org.json.JSONObject on the class path: jar:file:/C:/Users/Chloe/.m2/repository/org/json/json/20140107/json-20140107.jar!/org/json/JSONObject.class jar:file:/C:/Users/Chloe/.m2/repository/com/vaadin/external/google/android-json/0.0.20131108.vaadin1/android-json-0.0.20131108.vaadin1.jar!/org/json/JSONObject.class You may wish to exclude one of them to ensure predictable runtime behavior </code></pre> <p>Here is my <a href="https://gist.github.com/starrychloe/a3f3c85c09c0f70e1c698b8b00c6a42c" rel="noreferrer">pom.xml</a>. The only reference to JSON is </p> <pre><code> &lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt; &lt;dependency&gt; &lt;groupId&gt;org.json&lt;/groupId&gt; &lt;artifactId&gt;json&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>Apache Maven 3.5.3</p>
52,980,523
6
1
null
2018-10-25 01:28:25.14 UTC
15
2020-11-20 11:06:20.627 UTC
2018-11-25 08:28:58.727 UTC
null
7,294,900
null
148,844
null
1
75
java|spring|maven|spring-boot|build-dependencies
38,117
<p>Add under</p> <pre><code> &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; </code></pre> <p>The following exclusion:</p> <pre><code> &lt;scope&gt;test&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;com.vaadin.external.google&lt;/groupId&gt; &lt;artifactId&gt;android-json&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; </code></pre> <p>Similarly, for Gradle projects:</p> <pre><code>testCompile("org.springframework.boot:spring-boot-starter-test") { exclude group: "com.vaadin.external.google", module:"android-json" } </code></pre>
37,441,140
How to use tf.while_loop() in tensorflow
<p>This is a generic question. I found that in the tensorflow, after we build the graph, fetch data into the graph, the output from graph is a tensor. but in many cases, we need to do some computation based on this output (which is a <code>tensor</code>), which is not allowed in tensorflow. </p> <p>for example, I'm trying to implement a RNN, which loops times based on data self property. That is, I need use a <code>tensor</code> to judge whether I should stop (I am not using dynamic_rnn since in my design, the rnn is highly customized). I find <code>tf.while_loop(cond,body.....)</code> might be a candidate for my implementation. But the official tutorial is too simple. I don't know how to add more functionalities into the 'body'. Can anyone give me few more complex example? </p> <p>Also, in such case that if the future computation is based on the tensor output (ex: the RNN stop based on the output criterion), which is very common case. Is there an elegant way or better way instead of dynamic graph?</p>
37,444,810
1
1
null
2016-05-25 15:09:35.937 UTC
19
2018-12-28 13:54:14.003 UTC
null
null
null
null
4,524,141
null
1
37
python|tensorflow
39,014
<p>What is stopping you from adding more functionality to the body? You can build whatever complex computational graph you like in the body and take whatever inputs you like from the enclosing graph. Also, outside of the loop, you can then do whatever you want with whatever outputs you return. As you can see from the amount of 'whatevers', TensorFlow's control flow primitives were built with much generality in mind. Below is another 'simple' example, in case it helps.</p> <pre><code>import tensorflow as tf import numpy as np def body(x): a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100) b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32) c = a + b return tf.nn.relu(x + c) def condition(x): return tf.reduce_sum(x) &lt; 100 x = tf.Variable(tf.constant(0, shape=[2, 2])) with tf.Session(): tf.global_variables_initializer().run() result = tf.while_loop(condition, body, [x]) print(result.eval()) </code></pre>
25,121,067
onvif vs rtsp - difference
<p>i have just started to delve into streaming libraries and the underlying protocols. I understand rtsp/rtp streaming and what these 2 protocols are for. But if we need the ip address, codec and the rtsp/rtp protocols to stream the video and audio from any cameras then why do we have onvif standard which essentially also aims to standardize the communication between IP network devices. I have seen the definitions of onvif so thats not what I am looking for. I want to know why at all we need onvif when we already have rtsp/rtp and what additional benefits it can provide.</p>
25,186,692
1
0
null
2014-08-04 14:29:42.707 UTC
2
2015-07-09 09:18:38.937 UTC
null
null
null
null
2,611,292
null
1
8
rtsp|rtp|onvif
40,060
<p>ONVIF is much more than just video streaming. It's an attempt to standardize all remote protocols for network communication between security devices. This includes things like PTZ control video analytics and is much more than just digital camera devices. </p>
35,733,917
TensorFlow: Restoring variables from from multiple checkpoints
<p>I have the following situation:</p> <ul> <li><p>I have 2 models written in 2 separate scripts:</p></li> <li><p>Model A consists of variables <code>a1</code>, <code>a2</code>, and <code>a3</code>, and is written in <code>A.py</code></p></li> <li><p>Model B consists of variables <code>b1</code>, <code>b2</code>, and <code>b3</code>, and is written in B.py</p></li> </ul> <p>In each of <code>A.py</code> and <code>B.py</code>, I have a <code>tf.train.Saver</code> that saves the checkpoint of all the local variables, and let's call the checkpoint files <code>ckptA</code> and <code>ckptB</code> respectively.</p> <p>I now want to make a model C that uses <code>a1</code> and <code>b1</code>. I can make it so that the exact same variable name for <code>a1</code> is used in both A and C by using the var_scope (and the same for <code>b1</code>).</p> <p>The question is how might I load <code>a1</code> and <code>b1</code> from <code>ckptA</code> and <code>ckptB</code> into model C? For example, would the following work?</p> <pre><code>saver.restore(session, ckptA_location) saver.restore(session, ckptB_location) </code></pre> <p>Would an error be raised if you are try to restore the same session twice? Would it complain that there are no allocated "slots" for the extra variables (<code>b2</code>, <code>b3</code>, <code>a2</code>, <code>a3</code>), or would it simply restore the variables it can, and only complain if there are some other variables in C that are uninitialized?</p> <p>I'm trying to write some code to test this now but I would love to see a canonical approach to this problem, because one encounters this often when trying to re-use some pre-trained weights.</p> <p>Thanks!</p>
35,734,473
1
0
null
2016-03-01 21:29:49.333 UTC
8
2016-03-01 22:39:17.473 UTC
2016-03-01 22:37:56.847 UTC
null
3,574,081
null
1,002,035
null
1
11
tensorflow
7,550
<p>You would get a <code>tf.errors.NotFoundError</code> if you tried to use a saver (by default representing all six variables) to restore from a checkpoint that does not contain all of the variables that the saver represents. (Note however that you are free to call <code>Saver.restore()</code> multiple times in the same session, for any subset of the variables, as long as all of the requested variables are present in the corresponding file.)</p> <p>The canonical approach is to define <strong>two separate <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/state_ops.html#Saver" rel="noreferrer"><code>tf.train.Saver</code></a> instances</strong> covering each subset of variables that is entirely contained in a single checkpoint. For example:</p> <pre><code>saver_a = tf.train.Saver([a1]) saver_b = tf.train.Saver([b1]) saver_a.restore(session, ckptA_location) saver_b.restore(session, ckptB_location) </code></pre> <p>Depending on how your code is built, if you have pointers to <code>tf.Variable</code> objects called <code>a1</code> and <code>b1</code> in the local scope, you can stop reading here.</p> <p>On the other hand, if variables <code>a1</code> and <code>b1</code> are defined in separate files, you might need to do something creative to retrieve pointers to those variables. Although it's not ideal, what people typically do is to use a common prefix, for example as follows (assuming the variable names are <code>"a1:0"</code> and <code>"b1:0"</code> respectively):</p> <pre><code>saver_a = tf.train.Saver([v for v in tf.all_variables() if v.name == "a1:0"]) saver_b = tf.train.Saver([v for v in tf.all_variables() if v.name == "b1:0"]) </code></pre> <p>One final note: you don't have to make heroic efforts to ensure that the variables have the same names in A and C. You can pass a name-to-<code>Variable</code> dictionary as the first argument to the <code>tf.train.Saver</code> constructor, and thereby remap names in the checkpoint file to <code>Variable</code> objects in your code. This helps if <code>A.py</code> and <code>B.py</code> have similarly-named variables, or if in <code>C.py</code> you want to organize the model code from those files in a <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/framework.html#name_scope" rel="noreferrer"><code>tf.name_scope()</code></a>.</p>
43,042,262
Left & right align modal footer buttons in Bootstrap 4
<p>Bootstrap 4 uses flex-box for it's modal footers. If I want two buttons, one on the left and one on the right, how do I get it to work properly? </p> <p>The code below tries to use a <code>div.row</code> with <code>col-sm-6</code> but doesn't work.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;!-- Button trigger modal --&gt; &lt;button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"&gt; Launch demo modal &lt;/button&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLabel"&gt;Modal title&lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; ... &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6 text-left"&gt; &lt;button type="button" class="btn btn-primary"&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;div class="col-sm-6 text-right"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
43,044,647
11
0
null
2017-03-27 09:10:14.733 UTC
13
2022-02-16 12:43:58.447 UTC
2017-03-27 11:07:42.94 UTC
null
171,456
null
214,980
null
1
95
twitter-bootstrap|bootstrap-4|twitter-bootstrap-4
132,248
<p>Now that the <code>modal-footer</code> is "display:flex" in Bootstrap 4, it would be easiest to use the auto-margins. Use <code>mr-auto</code> on the left button.</p> <pre><code>&lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-primary mr-auto"&gt;Save changes&lt;/button&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; </code></pre> <p><a href="http://www.codeply.com/go/D7lspW0mto" rel="noreferrer">Demo</a></p> <p>Also see: <a href="https://stackoverflow.com/questions/18672452/left-align-and-right-align-within-div-in-bootstrap/18672475">Left align and right align within div in Bootstrap</a></p> <hr/> <p>Follow-up to comment "What if I need the button on the right to occupy all the space left?" - Use the <code>btn-block</code> class:</p> <pre><code>&lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-primary text-nowrap"&gt;Save changes&lt;/button&gt; &lt;button type="button" class="btn btn-secondary btn-block ml-1" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; </code></pre>
54,212,220
how to fix 'Access to XMLHttpRequest has been blocked by CORS policy' Redirect is not allowed for a preflight request only one route
<p><a href="https://i.stack.imgur.com/8BpwB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8BpwB.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/FAz9Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FAz9Q.png" alt="enter image description here"></a>i'm setting a laravel and vuejs.</p> <p>CORS plugin for laravel and frontend side i use Axios to call REST api</p> <p>i got this ERROR Access to XMLHttpRequest at '<a href="https://xx.xxxx.xx" rel="noreferrer">https://xx.xxxx.xx</a>' from origin '<a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. </p> <pre><code>this is for a vuejs axios setup **main.js** axios.defaults.baseURL = process.env.BASE_URL; axios.defaults.headers.get['Accepts'] = 'application/json'; axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'; axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'; **content.vue file** this.loading = true; var companyId = this.$route.params.cid; var userId = this.$route.params.uid; const thisVue = this; var formData = new FormData(); let data = {}; formData.append("subject", this.title); formData.append("content", this.content); formData.append("posting_article_url", this.blog_link); formData.append("recruitment_tension", this.sel_recruitment_tension); formData.append("why_hire_engineer", this.sel_company_hire_engineer); formData.append("technique_skill", this.requiredTechniqueSkill); formData.append("better_technique_skill",this.betterTechniqueSkillIfThereIs); formData.append("personality", this.requiredPersonality); formData.append("any_request", this.anyRequest); formData.append("location", this.location); formData.append("supplement_time", this.supplement_time); formData.append("supplement_contract", this.supplement_contract); formData.append("en_benefits", this.en_benefits); formData.append("recruit_role", this.recruit_role); formData.append("how_to_proceed", this.how_to_proceed); formData.append("current_structure", this.current_structure); if (this.selectedSkill.length &gt; 0) { let selectedSkills = this.selectedSkill .filter(obj =&gt; { return obj.id; }) .map(item =&gt; { return item.id; }); formData.append("skill_keyword", selectedSkills); } if (this.imageBlob != "") { formData.append("image", this.imageBlob, "temp.png"); } for (var i = 0; i &lt; this.sel_schedule.length; i++) { formData.append("freelance_type[" + i + "]", this.sel_schedule[i]) } for (var i = 0; i &lt; this.sel_type_of_contract.length; i++) { formData.append("contract_type[" + i + "]", this.sel_type_of_contract[i]) } this.loading = false; $('html, body').animate({scrollTop:300}, 'slow'); } else { axios .post( "/xx/xxx/?token=" + localStorage.getItem("token"), formData, { headers: [ { "X-localization": localStorage.getItem("lan") }, { "Access-Control-Allow-Origin": '*' }, { "Access-Control-Allow-Headers": 'Origin, X-Requested-With, Content-Type, Accept '}, { "Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE" }, { "Access-Control-Max-Age": 3600 } ] } ) .then(res =&gt; { if (!res.data.result) { if (res.data[0]) { this.$toaster.error(res.data[0]); this.$store.dispatch("logout"); } if (res.data.errors) { for (var i = 0; i &lt; res.data.errors.length; i++) { this.$toaster.error(res.data.errors[i].message); } } this.loading = false; } else { this.$toaster.success(thisVue.$t("success_recruit_add")); } }) .catch(() =&gt; { this.$toaster.error(thisVue.$t("err_network")); }); } </code></pre> <p>the error occur only one route rest all are working. also working on <strong>Postman</strong> </p>
54,901,498
10
3
null
2019-01-16 07:29:19.697 UTC
7
2022-09-17 16:46:12.14 UTC
2019-01-17 05:30:28.983 UTC
null
10,841,607
null
10,841,607
null
1
29
javascript|laravel|vue.js|vuejs2
256,963
<h2>Permanent solution from server side:</h2> <p>The best and secure solution is to allow access control from server end. For laravel you can follow the following steps:</p> <p>In <code>App\Http\Middleware\Cors.php</code>:</p> <pre><code>public function handle($request, Closure $next) { return $next($request)-&gt;header('Access-Control-Allow-Origin', '*') -&gt;header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'); } </code></pre> <p>In <code>App\Http\Kernel.php</code>:</p> <pre><code>protected $middleware = [ ... \App\Http\Middleware\Cors::class, ]; </code></pre> <h2>Temporary solution from browser side:</h2> <p>If you want to disable CORS from browser-end then follow one of the following steps:</p> <p><strong>Safari:</strong> Enable the develop menu from <code>Preferences &gt; Advanced</code>. Then select “Disable Cross-Origin Restrictions” from the develop menu.</p> <p><strong>Chrome (Extension):</strong> Use the Chrome extension <a href="https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf" rel="nofollow noreferrer">Allow CORS: Access-Control-Allow-Origin</a></p> <p><strong>Chrome (CMD):</strong> Close all your Chrome browser and services. Then run the following command:</p> <p>Windows:</p> <pre><code>“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” –-allow-file-access-from-files --disable-web-security --user-data-dir --disable-features=CrossSiteDocumentBlockingIfIsolating </code></pre> <p>Mac:</p> <pre><code>open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome — args — user-data-dir=”/tmp/chrome_dev_test” — disable-web-security </code></pre>
29,421,781
How are the Event Loop, Callback Queue, and Javascript’s single thread connected?
<h1>GENERAL GOAL</h1> <p>I’d like to know how the following pieces of a javascript environment <strong>interconnect as a system</strong>. </p> <ul> <li>Javascript Engine</li> <li>Event Loop</li> <li>Event Queue</li> </ul> <p>We can limit this to a <strong>browser environment</strong> since node has been covered in another article (<a href="https://stackoverflow.com/questions/21607692/understanding-the-event-loop">here</a>)</p> <h1>THINGS I (believe to) UNDERSTAND:</h1> <ul> <li><p>Javascript is single threaded and therefore only has one callstack.</p></li> <li><p>Javascript environments provide only a few functions that are truly asynchronous. These may include setTimeout(), setInterval(), and I/O function(s).</p></li> <li>A developer cannot create their own asynchronous functions without using one of these. </li> <li>Javascript itself runs synchronously but through it’s async functions can callback the would-be blocking functions once the current callstack is clear. </li> </ul> <h3>EXAMPLE:</h3> <pre><code> console.log(‘Sync code started…’); setTimeout(function asyncLog() { console.log(‘Async function has completed’) }, 2000); console.log(‘Sync code finished…') </code></pre> <h3>EXAMPLE STEPS:</h3> <p>( Please correct steps if I’m wrong ) </p> <ol> <li>‘Sync code started…’ is logged </li> <li>setTimeout is added to stack but immediately returns control </li> <li>setTimeout is sent to a different ‘thread’…’worker’? outside of javascript’s single thread to count the 2000 milliseconds </li> <li>‘Sync code finished…’ is logged </li> <li>After 2000 milliseconds asyncLog() is pushed to the Event Queue </li> <li>Because the callstack is clear the Event Loop checks the Event Queue for pending callbacks </li> <li>asyncLog() is removed from the queue and pushed to the stack by the Event Loop</li> <li>'Async function has completed’ is logged</li> <li>callstack is now clear</li> </ol> <h1>QUESTIONS</h1> <p>These don’t need to be answered one by one if someone could produce an overview of the steps of how and where async functions (such as setTimeout) go from the time they first hit the callstack to when they are called back to the callstack.</p> <ol> <li>On step 3, who produces this new thread? Is it the browser? <ul> <li>This new thread is being blocked correct?</li> <li>What happens if you have a loop that creates 1000 setTimeouts. Are 1000 ‘threads’ created?</li> <li>Is there a limit to how many threads can be spawned at a time?</li> <li>When new thread finishes executing, how does it end up on the queue?</li> </ul></li> <li>Who supplies the Event Queue?</li> <li>Who supplies the Event Loop? <ul> <li>Does the event loop poll the Event Queue?</li> <li>Is the javascript’s thread aware of an event loop? Or does the Event loop just push things onto the stack?</li> <li>How does the Event loop know when the stack is clear?</li> </ul></li> </ol>
29,422,900
1
0
null
2015-04-02 20:22:13.36 UTC
16
2019-09-26 10:19:48.487 UTC
null
null
null
null
3,880,954
null
1
24
javascript|asynchronous|event-loop|single-threaded|event-queue
7,053
<p>Your understanding and your example seem to be basically correct. Now, to your questions:</p> <blockquote> <p>On step 3, who produces this new thread? Is it the browser?</p> </blockquote> <p>Yes. It is basically the thing that supplies the implementation for those "truly asynchronous" functions. IIRC, <code>setTimeout</code> is implemented in JS engines directly, while networking IO would be definitely the browser's responsibility - but it doesn't really matter who creates them. In the end, in your "browser environment" it's always some part of the browser. </p> <blockquote> <p>This new thread is being blocked correct?</p> </blockquote> <p>Yes. No. It depends on the work that needs to be done, i.e. which async function you called. Some may require spinning of a new thread, but for simple timeouts I'm pretty sure that a non-blocking system call is used.</p> <blockquote> <p>What happens if you have a loop that creates 1000 setTimeouts. Are 1000 ‘threads’ created?</p> </blockquote> <p>Possible. Unlikely, though. I'd assume for those async actions that really require their own thread, a thread pool is used, and requests are queued. The size of this pool might be hidden in the bowels of your browser's configuration.</p> <blockquote> <p>Is there a limit to how many threads can be spawned at a time?</p> </blockquote> <p>That would be controlled by the OS.</p> <blockquote> <p>When new thread finishes executing, how does it end up on the queue? Who supplies the Event Queue?</p> </blockquote> <p>Basically, the last action of each such thread is to put its result in the event queue.</p> <blockquote> <p>Who supplies the Event Loop? Does the event loop poll the Event Queue?</p> </blockquote> <p>I'd say that's an implementation detail, whether the loop polls the queue or the queue drives the loop iterations.</p> <blockquote> <p>Is the javascript’s thread aware of an event loop? Or does the Event loop just push things onto the stack?</p> </blockquote> <p>I'd say that the javascript runs <em>in</em> the event loop thread. The event loop just repeatedly pops events from the queue and executes their javascript.</p> <blockquote> <p>How does the Event loop know when the stack is clear?</p> </blockquote> <p>The event loop <em>calls</em> the javascript execution - so the stack is clear when the javascript returns.</p>
4,572,193
How to reload img every 5 second using javascript?
<p>How to reload img every 5 second using javascript ?</p> <pre><code>&lt;img src="screen.jpg" alt="" /&gt; </code></pre>
4,572,383
1
2
null
2010-12-31 20:32:17.463 UTC
7
2011-01-01 03:18:11.467 UTC
2011-01-01 03:18:11.467 UTC
null
423,903
null
423,903
null
1
22
javascript
38,683
<p>Every time you want to reload the image, you must change the image url like so: "screen.jpg?rand=123456789" where "123456789" is a randomly generated number, which is regenerated every time you want to reload the image. The browser will think that it is a different image, and actually download it again, instead of retrieve it from the cache. The web server will most likely ignore and discard everything after the question mark.</p> <p>To cause the reload in the first place, your would have to use Javascript to get the image element and change the source. The easiest option I can see is to give the image element an <code>id</code> attribute, like so:</p> <pre><code>&lt;img src="screen.jpg" id="myImage" /&gt; </code></pre> <p>Then you may change the source of the image:</p> <pre><code>var myImageElement = document.getElementById('myImage'); myImageElement.src = 'screen.jpg?rand=' + Math.random(); </code></pre> <p>To do this on a set timer, then use the top-level Javascript function <code>setInterval</code>:</p> <pre><code>setInterval(function() { var myImageElement = document.getElementById('myImage'); myImageElement.src = 'screen.jpg?rand=' + Math.random(); }, 5000); </code></pre> <p>The second argument specifies 5000 milliseconds, which equates to 5 seconds.</p>
14,015,073
server-side fallback rendering
<p>Is there any way to have three.js running server-side on a headless server (standalone server, Amazon AWS or similar)?</p> <p>Currently I fall back to canvas rendering (wireframe only for performance reasons) when user's browser does not support WebGL. This is good enough for realtime interaction, but for the app to make sense, users would really need to somehow be able to see a properly rendered version with lights, shadows, post processing etc. even if it comes with great latency.</p> <p>So... would it be possible to create a server-side service with functional three.js instance? The client would still use tree.js canvas wireframe rendering, but after say... a second of inactivity, it would request via AJAX a full render from the server-side service, and overlay it simply as an image.</p> <p>Are there currently any applications, libraries or anything that would allow such a thing (functional javascript+webgl+three.js on a headless, preferably linux server, and GPU-less at that)?</p> <p>PhantomJS comes to mind, but apparently it does not yet support WebGL: <a href="http://code.google.com/p/phantomjs/issues/detail?id=273" rel="noreferrer">http://code.google.com/p/phantomjs/issues/detail?id=273</a></p> <p>Or any alternative approaches to the problem? Going the route of programmatically controlling a full desktop machine with a GPU and standard chrome/firefox instance feels possible, while fragile, and I really really wouldn't want to go there if there are any software-only solutions.</p>
14,083,984
3
0
null
2012-12-23 22:05:02.247 UTC
11
2015-02-21 17:03:11.9 UTC
null
null
null
null
1,858,208
null
1
6
three.js
4,172
<p>In its QA infrastructure, Google can run Chromium testing using Mesa (see issue <a href="http://code.google.com/p/chromium/issues/detail?id=97675">97675</a>, via the switch <code>--use-gl=osmesa</code>). The software rasterizer in the latest edition of Mesa is pretty advanced, involving the use of LLVM to convert the shaders and emulate the execution on the CPU. Your first adventure could be building Mesa, building Chromium, and then try to tie them together.</p> <p>As a side note, this is also what I plan (in the near future) for PhantomJS itself, in particular since Qt is also moving in that direction, i.e. using Mesa/LLVMpipe instead of its own raster engine only. <a href="http://blog.qt.digia.com/blog/2011/05/31/qml-scene-graph-in-master/">The numbers</a> actually look good. Even better, for an offline, non-animated single-shot capture, the performance would be more than satisfactory.</p>
25,284,011
How to autowire an object in spring in an object created with new
<p>all I want to do is autowire the field backgroundGray in the NotesPanel class, but all I get is the exception below.</p> <p>So, question is, how to autowire it correctly ? It really drives me crazy because it's probably something very stupid I'm doing wrong... </p> <p>thanks for any help! Thorsten</p> <pre><code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'notepad' defined in class path resource [Beans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [notepad.Notepad]: Constructor threw exception; nested exception is java.lang.NullPointerException Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [notepad.Notepad]: Constructor threw exception; nested exception is java.lang.NullPointerException Caused by: java.lang.NullPointerException at notepad.NotesPanel.&lt;init&gt;(NotesPanel.java:23) at notepad.Notepad.&lt;init&gt;(Notepad.java:18) </code></pre> <p>Class Notepad:</p> <pre><code>package notepad; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JFrame; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Notepad { public Notepad() { JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.add(new NotesPanel(), BorderLayout.CENTER); frame.setPreferredSize(new Dimension(1024, 768)); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); context.getBean("notepad"); } } </code></pre> <p>Class Notespanel:</p> <pre><code>package notepad; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JTextPane; import org.springframework.beans.factory.annotation.Autowired; public class NotesPanel extends JPanel { JTextPane tPane = new JTextPane(); @Autowired private BackgroundGray backgroundgray; public NotesPanel() { // backgroundgray = new BackgroundGray(); // backgroundgray.setGray("200"); setLayout(new BorderLayout()); tPane.setBackground(backgroundgray.getGrayObject()); add(tPane, BorderLayout.CENTER); tPane.setText("Fill me with notes... "); } } </code></pre> <p>Class BackgroundGray:</p> <pre><code>package notepad; import java.awt.Color; public class BackgroundGray { String gray; public BackgroundGray() { System.out.println("Background Gray Constructor."); } public String getGray() { return gray; } public void setGray(String gray) { this.gray = gray; } public Color getGrayObject() { int val = Integer.parseInt(gray); return new Color(val, val, val); } } </code></pre> <p>Beans.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"&gt; &lt;context:annotation-config /&gt; &lt;bean id="notepad" class="notepad.Notepad"/&gt; &lt;bean id="backgroundgray" class="notepad.BackgroundGray" autowire="byName"&gt; &lt;property name="gray" value="120"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
25,284,157
5
2
null
2014-08-13 10:38:45.223 UTC
6
2019-10-14 16:58:35.287 UTC
null
null
null
null
1,119,859
null
1
14
java|spring|autowired
40,320
<p>Spring support <code>@Autowire</code>, ... only for Spring Beans. Normally a Java Class become a Spring Bean when it is created by Spring, but not by <code>new</code>.</p> <p>One workarround is to annotate the class with <code>@Configurable</code> but you must use AspectJ (compile time or loadtime waving)!</p> <p>@see <a href="http://olivergierke.de/2009/05/using-springs-configurable-in-three-easy-steps/">Using Spring's <code>@Configurable</code> in three easy steps</a> for an short step by step instruction.</p>
48,878,629
Why is const required for 'operator>' but not for 'operator<'?
<p>Consider this piece of code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; using namespace std; struct MyStruct { int key; std::string stringValue; MyStruct(int k, const std::string&amp; s) : key(k), stringValue(s) {} bool operator &lt; (const MyStruct&amp; other) { return (key &lt; other.key); } }; int main() { std::vector &lt; MyStruct &gt; vec; vec.push_back(MyStruct(2, "is")); vec.push_back(MyStruct(1, "this")); vec.push_back(MyStruct(4, "test")); vec.push_back(MyStruct(3, "a")); std::sort(vec.begin(), vec.end()); for (const MyStruct&amp; a : vec) { cout &lt;&lt; a.key &lt;&lt; ": " &lt;&lt; a.stringValue &lt;&lt; endl; } } </code></pre> <p>It compiles fine and gives the output one would expect. But if I try to sort the structures in descending order:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; using namespace std; struct MyStruct { int key; std::string stringValue; MyStruct(int k, const std::string&amp; s) : key(k), stringValue(s) {} bool operator &gt; (const MyStruct&amp; other) { return (key &gt; other.key); } }; int main() { std::vector &lt; MyStruct &gt; vec; vec.push_back(MyStruct(2, "is")); vec.push_back(MyStruct(1, "this")); vec.push_back(MyStruct(4, "test")); vec.push_back(MyStruct(3, "a")); std::sort(vec.begin(), vec.end(), greater&lt;MyStruct&gt;()); for (const MyStruct&amp; a : vec) { cout &lt;&lt; a.key &lt;&lt; ": " &lt;&lt; a.stringValue &lt;&lt; endl; } } </code></pre> <p>This gives me an error. <a href="https://bitbucket.org/snippets/Rockstar5645/Le4A48" rel="noreferrer">Here is the full message</a>:</p> <blockquote> <p>/usr/include/c++/7.2.0/bits/stl_function.h: In instantiation of 'constexpr bool std::greater&lt;_Tp>::operator()(const _Tp&amp;, const _Tp&amp;) const [with _Tp = MyStruct]':<br> /usr/include/c++/7.2.0/bits/stl_function.h:376:20: error: no match for 'operator>' (operand types are 'const MyStruct' and 'const MyStruct')<br> { return __x > __y; }</p> </blockquote> <p>It seems to be because this function right here doesn't have a <code>const</code> qualifier:</p> <pre><code>bool operator &gt; (const MyStruct&amp; other) { return (key &gt; other.key); } </code></pre> <p>If I add it, </p> <pre><code>bool operator &gt; (const MyStruct&amp; other) const { return (key &gt; other.key); } </code></pre> <p>Then everything is fine again. Why is this so? I'm not too familiar with operator overloading, so I've just put it in memory that we need to add the <code>const</code> but it's still weird why it works for <code>operator&lt;</code> without the <code>const</code>.</p>
48,878,701
2
3
null
2018-02-20 05:45:31.79 UTC
4
2018-02-21 01:31:33.473 UTC
2018-02-21 01:31:33.473 UTC
null
4,143,855
null
4,944,292
null
1
60
c++|sorting|operator-overloading
5,525
<p>You get different behaviors because you are in fact calling two different (overloaded) <a href="http://en.cppreference.com/w/cpp/algorithm/sort" rel="noreferrer">sort</a> functions. </p> <p>In the first case you call the two parameter <code>std::sort</code>, which uses <code>operator&lt;</code> directly. Since the iterators to your vector elements produce non-const references, it can apply <code>operator&lt;</code> just fine.</p> <p>In the second case, you are using the three parameter version of <code>std::sort</code>. The one that accepts a functor. You pass <code>std::greater</code>. And that functor has an <code>operator()</code> declared as follows:</p> <pre><code>constexpr bool operator()( const T&amp; lhs, const T&amp; rhs ) const; </code></pre> <p>Note the const references. It binds the elements it needs to compare to const references. So your own <code>operator&gt;</code> must be const correct as well.</p> <p>If you were to call <code>std::sort</code> with <a href="http://en.cppreference.com/w/cpp/utility/functional/less" rel="noreferrer"><code>std::less</code></a>, your <code>operator&lt;</code> will produce the same error, because it's not const-correct.</p>
48,760,542
Time complexity of the includes method in JavaScript
<p>I have an array that contains some hash values of certain strings, I don't want duplicate values in my array so I use <code>if</code> logic like this:</p> <pre class="lang-js prettyprint-override"><code>if(!arrayOfHash.includes(hash_value)){ arrayOfHash.push(hash_value); } </code></pre> <p>I want to know the complexity of the <code>includes</code> method in JavaScript. Is it a <strong>linear search</strong> function or is it a modified search function?</p>
48,761,894
2
5
null
2018-02-13 06:15:13.223 UTC
4
2021-08-01 17:05:18.5 UTC
2021-08-01 17:05:18.5 UTC
null
11,407,695
null
5,974,810
null
1
29
javascript|arrays|time-complexity
27,965
<p>Spec describes this function as linear search. <a href="https://tc39.github.io/ecma262/#sec-array.prototype.includes" rel="noreferrer">Array.prototype.includes</a></p> <blockquote> <ol> <li><p>Let O be ? ToObject(this value).</p></li> <li><p>Let len be ? ToLength(? Get(O, "length")).</p></li> <li>If len is 0, return false.</li> <li>Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.)</li> <li>If n ≥ 0, then Let k be n.</li> <li>Else n &lt; 0, Let k be len + n. If k &lt; 0, let k be 0.</li> <li><strong>Repeat, while k &lt; len</strong> ... <strong>Increase k by 1.</strong></li> </ol> </blockquote> <p>Which is quite a reasonable choice in general case (list is not sorted, list is not uniform, you do not maintain additional datastructures along with the list itself). </p>
26,867,775
Google SpreadSheet Query: Can I remove column header?
<p>I'm doing this query at my google spreadsheet:</p> <pre><code>=QUERY(H4:L35;"select sum(L) where H='First Week'"; -1) </code></pre> <p>But it returns a little table with "sum" as header and result below it. What I want is just the result! How I remove header? Can I?</p>
26,897,291
7
1
null
2014-11-11 14:58:32.373 UTC
17
2022-04-29 14:38:53.08 UTC
2018-08-23 03:06:04.103 UTC
null
9,337,071
null
1,735,077
null
1
132
google-sheets|formulas|google-sheets-query|google-query-language
117,526
<p>Try this:</p> <pre><code>=QUERY(H4:L35,&quot;select sum(L) where H='First Week' label sum(L) ''&quot;) </code></pre>
7,053,608
How do I use Git Extensions with a Bitbucket repository?
<p>I have repository on both github.com and bitbucket.org, and I am very familiar using Git Extensions for all repository functions... But when I started using bitbucket.org repositories I have to use TortoiseHg SVN for it ... so I want to ask that is there a way I can use Git Extensions for Bitbucket repositories?</p>
7,757,318
3
2
null
2011-08-13 22:10:25.67 UTC
28
2022-06-22 09:30:09.56 UTC
2018-06-27 20:11:34.48 UTC
null
63,550
null
690,873
null
1
40
repository|bitbucket|git-extensions
34,194
<p>I haven't fully tested it, but these steps allowed me to clone a Bitbucket repository in Git Extensions.</p> <p>You can use PuTTY to generate a public/private SSH key, then add that key to Bitbucket.</p> <ol> <li><p>Run <code>GitExtensions\PuTTY\puttygen.exe</code></p> </li> <li><p>Click Generate</p> </li> <li><p>Click Save public key (as a text file)</p> </li> <li><p>Click Save private key (as a ppk file)</p> </li> <li><p>Run <code>GitExtensions\PuTTY\pageant.exe C:\path\to\ppk-file.ppk</code></p> </li> <li><p>Log into Bitbucket</p> </li> <li><p>Go into Account settings (<em>Settings</em> → <em>Security</em> → SSH keys*)</p> </li> <li><p>Paste your public key into the SSH keys text input as (spaces are important, <strong>do not</strong> include square brackets around the public key):</p> <p><code>ssh-rsa [AA-YOUR-PUBLIC-KEY-ALL-ONE-LINE-SPACES-REMOVED-==] [email protected]</code></p> </li> <li><p>Click <kbd>Add key</kbd></p> </li> <li><p>In Git Extensions, click <kbd>Clone repository</kbd></p> </li> <li><p>Use the SSH repository link on Bitbucket as the repository to clone</p> </li> <li><p>Click <kbd>Load SSH key</kbd></p> </li> <li><p>Browse to and load the ppk file</p> </li> <li><p>Click <kbd>Clone</kbd></p> </li> </ol>
8,239,356
Can a cast operator be explicit?
<p>When it comes to constructors, adding the keyword <code>explicit</code> prevents an enthusiastic compiler from creating an object when it was not the programmer’s first intention. Is such mechanism available for casting operators too?</p> <pre><code>struct Foo { operator std::string() const; }; </code></pre> <p>Here, for instance, I would like to be able to cast <code>Foo</code> into a <code>std::string</code>, but I don’t want such cast to happen implicitly.</p>
8,239,402
1
0
null
2011-11-23 08:51:57.09 UTC
17
2016-10-12 07:42:38.603 UTC
null
null
null
null
748,175
null
1
86
c++|casting|operator-keyword|explicit
26,334
<p>Yes and No. </p> <p>It depends on which version of C++, you're using.</p> <ul> <li>C++98 and C++03 do not support <code>explicit</code> type conversion operators</li> <li>But C++11 does.</li> </ul> <p>Example,</p> <pre><code>struct A { //implicit conversion to int operator int() { return 100; } //explicit conversion to std::string explicit operator std::string() { return "explicit"; } }; int main() { A a; int i = a; //ok - implicit conversion std::string s = a; //error - requires explicit conversion } </code></pre> <p>Compile it with <code>g++ -std=c++0x</code>, you will get this error:</p> <blockquote> <p>prog.cpp:13:20: error: conversion from 'A' to non-scalar type 'std::string' requested</p> </blockquote> <p>Online demo : <a href="http://ideone.com/DJut1" rel="noreferrer">http://ideone.com/DJut1</a></p> <p>But as soon as you write:</p> <pre><code>std::string s = static_cast&lt;std::string&gt;(a); //ok - explicit conversion </code></pre> <p>The error goes away : <a href="http://ideone.com/LhuFd" rel="noreferrer">http://ideone.com/LhuFd</a></p> <p>BTW, in C++11, the explicit conversion operator is referred to as <em>"contextual conversion operator"</em> if it converts to <em>boolean</em>. Also, if you want to know more about implicit and explicit conversions, read this topic:</p> <ul> <li><a href="https://stackoverflow.com/questions/7099957/implicit-vs-explicit-conversion">Implicit VS Explicit Conversion</a></li> </ul> <p>Hope that helps.</p>
1,835,532
Building a Contact Database - Need a little schema inspiration
<p>I've been working on laying out the data structure for an application I'm working on. One of the things it will need to handle is storing customer / contact information. I've been studying the interface of a few different contact information programs like Address Book, gmail contacts, etc. </p> <p>I have basically boiled the contact down to an "entity" (individual, company, role, etc). </p> <ul> <li>Each <strong>Entity</strong> can have multiple <strong>Address</strong>, <strong>Phone</strong>, <strong>E-Mail</strong> entries. <ul> <li>Each of these defines a "relationship" (home/work/assistant, etc)</li> <li><strong>Entity</strong> {1} --{relationship}--> {0..*} <strong>Data</strong></li> </ul></li> <li>An <strong>Entity</strong> can have multiple <strong>fields</strong> that are freeform data storage for other "generic" data (birthdays, AIM account, etc) <ul> <li><strong>Entity</strong> {1} --{fieldName}--> {0..*} <strong>Field Data</strong></li> </ul></li> <li>An <strong>Entity</strong> can link to another <strong>Entity</strong> for instance as a <em>employee</em>, <em>spouse</em> <ul> <li><strong>Entity</strong> {0..<em>} &lt;--{relationship}--> {0..</em>} <strong>Entity</strong></li> </ul></li> </ul> <p>Has anyone done any SQL implementations of similar contact databases? Any insight/suggestions/pitfalls to avoid that you could share with someone trying to work on a project by themselves here? Does what I have described seem reasonable or overcomplicated?</p> <p>One question, lets say you have 4 people who all work for the same company. They all have the same "work" phone number (perhaps with a different extension) - If the number or address for "work" changes, I'd like to be able to update the contacts fairly easily. Now a lot of this comes down to how you would use the database. I'm thinking that this becomes a matter of linking employee's to their respective company entities, but then the address/phone number is no longer directly connected to the employee. I'm kind of debating making the Entity/data relationship many to many allowing you to attach the same mailing address/phone number to multiple people, and updating it in one place can update it in all places. Am I just over thinking this? <em>pulls out hair</em> </p>
1,835,559
4
0
null
2009-12-02 20:21:01.697 UTC
11
2019-05-16 22:08:39.943 UTC
2013-07-03 17:07:13.2 UTC
null
1,048,862
null
91,914
null
1
14
database-design|street-address
30,443
<p>It's a bit trite, but you need to know your data and what you're going to do with it before you start thinking tables.</p> <p>I'd suggest looking at <a href="http://en.wikipedia.org/wiki/Object-Role_Modeling" rel="nofollow noreferrer">Object Role Modeling</a> (or <a href="http://www.orm.net/" rel="nofollow noreferrer">this</a> too) to define the model in plain English before you actually implement any tables. I use this VS plugin: <a href="http://sourceforge.net/projects/orm/" rel="nofollow noreferrer">NORMA</a> that will also generate a schema for you too.</p> <p>Alternatively, there are a bunch of <a href="http://www.databaseanswers.org/data_models/" rel="nofollow noreferrer">data models here</a> that may inspire you. This is "Contact Management" but there are others, such as the "Customers" section</p> <p>(I just wanted to post an image..) <a href="https://i.stack.imgur.com/sZIkS.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sZIkS.gif" alt="Contact Management"></a><br> <sub>(source: <a href="http://www.databaseanswers.org/data_models/contact_management/images/contact_management_model.gif" rel="nofollow noreferrer">databaseanswers.org</a>)</sub> </p>
36,475,736
Exclude with pattern in tsconfig.json
<p>Is there any way to add a pattern in the exclude property of a tsconfig file or is it only able to support directories?</p> <p>I'm trying to exclude all my test files from compilation so I was wondering if I can use something like this :</p> <pre><code>src/**/*.spec.ts </code></pre> <p>Seems like it doesn't work though.</p>
36,489,073
2
7
null
2016-04-07 12:08:29.11 UTC
7
2022-09-13 23:59:44.14 UTC
2019-05-03 12:54:54.913 UTC
null
542,251
null
385,692
null
1
66
typescript|tsconfig
43,599
<p>Globs work in Typescript 2.0+. You would do <code>&quot;exclude&quot; : [&quot;src/**/*.spec.ts&quot;]</code> in your <code>tsconfig.json</code>.</p> <p><strong>More</strong></p> <p><a href="https://basarat.gitbook.io/typescript/content/docs/project/files.html" rel="nofollow noreferrer">https://basarat.gitbook.io/typescript/content/docs/project/files.html</a></p>
49,035,732
Are nested structured bindings possible?
<p>Assume I have an object of type</p> <pre><code>std::map&lt;std::string, std::tuple&lt;int, float&gt;&gt; data; </code></pre> <p>Is it possible to access the element types in a nested way (i.e. when used in ranged for loop) like this</p> <pre><code>for (auto [str, [my_int, my_float]] : data) /* do something */ </code></pre>
49,035,851
2
3
null
2018-02-28 17:53:20.293 UTC
5
2019-08-09 17:13:33.673 UTC
2019-08-09 17:13:33.673 UTC
null
6,205,379
null
6,205,379
null
1
65
c++|c++17|structured-bindings
6,779
<p>No, it is not possible.</p> <p>I distinctly remember reading somewhere that nested structured bindings are not allowed for C++17, but they are considering allowing it in a future standard. Can't find the source though.</p>
48,919,320
React - How to pass props to a component passed as prop
<p>I have a React component (React v15.5.4) that you can pass other components to:</p> <pre><code>class CustomForm extends React.Component { ... render() { return ( &lt;div&gt; {this.props.component} &lt;/div&gt; ); } } </code></pre> <p>And I have a different component that uses it:</p> <pre><code>class SomeContainer extends React.Component { ... render() { let someObjectVariable = {someProperty: 'someValue'}; return ( &lt;CustomForm component={&lt;SomeInnerComponent someProp={'someInnerComponentOwnProp'}/&gt;} object={someObjectVariable} /&gt; ); } } </code></pre> <p>Everything renders fine, but I want to pass <strong>someObjectVariable</strong> prop to the child component inside <strong>CustomForm</strong> (in this case that'll be <strong>SomeInnerComponent</strong>), since in the actual code you can pass several components to it instead of just one like the example.</p> <p>Mind you, I also need to pass <strong>SomeInnerComponent</strong> its own props.</p> <p>Is there a way to do that?</p>
48,919,396
5
4
null
2018-02-22 03:46:14.83 UTC
5
2020-05-04 22:36:02.443 UTC
2018-02-22 04:05:12.363 UTC
null
1,274,923
null
1,274,923
null
1
55
javascript|reactjs
42,187
<p>You can achieve that by using <a href="https://reactjs.org/docs/react-api.html#cloneelement" rel="noreferrer">React.cloneElement</a>.</p> <p>Like this:</p> <pre><code>class CustomForm extends React.Component { ... render() { return ( &lt;div&gt; {React.cloneElement(this.props.component,{ customProps: this.props.object })} &lt;/div&gt; ); } } </code></pre> <p>Working Code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Parent extends React.Component{ render() { return( &lt;Child a={1} comp={&lt;GChild/&gt;} /&gt; ) } } class Child extends React.Component{ constructor(){ super(); this.state = {b: 1}; this.updateB = this.updateB.bind(this); } updateB(){ this.setState(prevState =&gt; ({b: prevState.b+1})) } render(){ var Comp = this.props.comp; return ( &lt;div&gt; {React.cloneElement(Comp, {b: this.state.b})} &lt;button onClick={this.updateB}&gt;Click to update b&lt;/button&gt; &lt;/div&gt; ); } } const GChild = props =&gt; &lt;div&gt;{JSON.stringify(props)}&lt;/div&gt;; ReactDOM.render( &lt;Parent /&gt;, document.getElementById('container') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id='container' /&gt;</code></pre> </div> </div> </p>
7,030,699
Oracle SQL: Update a table with data from another table
<p>Table 1:</p> <pre><code>id name desc ----------------------- 1 a abc 2 b def 3 c adf </code></pre> <p>Table 2:</p> <pre><code>id name desc ----------------------- 1 x 123 2 y 345 </code></pre> <p>In oracle SQL, how do I run an <strong>sql update</strong> query that can update Table 1 with Table 2's <code>name</code> and <code>desc</code> using the same <code>id</code>? So the end result I would get is</p> <p>Table 1:</p> <pre><code>id name desc ----------------------- 1 x 123 2 y 345 3 c adf </code></pre> <p>Question is taken from <a href="https://stackoverflow.com/questions/5036918/sql-update-query-with-data-from-another-table">update one table with data from another</a>, but specifically for oracle SQL.</p>
7,031,405
7
5
null
2011-08-11 18:05:54.983 UTC
111
2021-02-09 11:17:40.957 UTC
2017-12-22 05:10:50.03 UTC
null
6,755,093
null
446,921
null
1
308
sql|oracle|sql-update
1,220,497
<p>This is called a correlated update</p> <pre><code>UPDATE table1 t1 SET (name, desc) = (SELECT t2.name, t2.desc FROM table2 t2 WHERE t1.id = t2.id) WHERE EXISTS ( SELECT 1 FROM table2 t2 WHERE t1.id = t2.id ) </code></pre> <p>Assuming the join results in a key-preserved view, you could also</p> <pre><code>UPDATE (SELECT t1.id, t1.name name1, t1.desc desc1, t2.name name2, t2.desc desc2 FROM table1 t1, table2 t2 WHERE t1.id = t2.id) SET name1 = name2, desc1 = desc2 </code></pre>
7,608,632
How do I get the current version of my iOS project in code?
<p>I would like to be able to get the current version of my iOS project/app as an <code>NSString</code> object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places.</p> <p>The value needs to be updated when I bump my version in the Project target summary.</p>
7,608,711
8
0
null
2011-09-30 09:46:31.467 UTC
41
2020-08-04 16:03:23.867 UTC
2017-08-15 14:32:23.1 UTC
null
3,151,675
null
956,593
null
1
162
ios|objective-c|iphone|swift
72,577
<p>You can get the version and build numbers as follows:</p> <pre><code>let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String </code></pre> <p>or in Objective-C</p> <pre><code>NSString * version = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]; NSString * build = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey]; </code></pre> <p>I have the following methods in a category on <code>UIApplication</code>:</p> <pre><code>extension UIApplication { static var appVersion: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } static var appBuild: String { return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String } static var versionBuild: String { let version = appVersion, build = appBuild return version == build ? "v\(version)" : "v\(version)(\(build))" } } </code></pre> <p><strong>Gist:</strong> <a href="https://gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b" rel="noreferrer">https://gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b</a></p> <hr> <p>Here's the equivalent in Objective-C:</p> <pre><code>+ (NSString *) appVersion { return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]; } + (NSString *) build { return [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey]; } + (NSString *) versionBuild { NSString * version = [self appVersion]; NSString * build = [self build]; NSString * versionBuild = [NSString stringWithFormat: @"v%@", version]; if (![version isEqualToString: build]) { versionBuild = [NSString stringWithFormat: @"%@(%@)", versionBuild, build]; } return versionBuild; } </code></pre> <p><strong>Gist:</strong> <a href="https://gist.github.com/ashleymills/c37efb46c9dbef73d5dd" rel="noreferrer">https://gist.github.com/ashleymills/c37efb46c9dbef73d5dd</a></p>
7,642,456
IntelliJ - Convert a Java project/module into a Maven project/module
<p>I have a project on Bitbucket. Only the sources are committed. To retrieve the project onto a new machine, I used Version Control > Checkout from Version Control from within IntelliJ.</p> <p>It then asks whether I would like to create a new project from this source, to which I reply Yes. So far, so good. It creates a nice little Java project for me, consisting of a single module.</p> <p>However, my goal in pulling this project into IntelliJ was to turn it into a Maven project. I cannot find any option anywhere that will let me do this!</p> <p>Is there a way to have IntelliJ just generate a basic empty pom.xml for me, with a name and an artifactId and a repository? Or, is there a way to import the project as a Maven project in the first place? (Whenever I try to create a project from existing source, it only gives me the option of a Java project.)</p>
7,642,607
11
0
null
2011-10-04 01:36:46.083 UTC
92
2022-04-26 10:13:29.437 UTC
null
null
null
null
213,525
null
1
437
java|maven|intellij-idea|pom.xml
243,176
<p>Right-click on the module, select &quot;Add framework support...&quot;, and check the &quot;Maven&quot; technology.</p> <p><a href="https://i.stack.imgur.com/sC2ix.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sC2ix.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/RK3xx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RK3xx.png" alt="enter image description here" /></a></p> <p><em>(This also creates a <code>pom.xml</code> for you to modify.)</em></p> <p>If you mean adding source repository elements, I think you need to do that manually–not sure.</p> <p>Pre-IntelliJ 13 this won't convert the project to the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="noreferrer">Maven Standard Directory Layout</a>, 13+ it will.</p>
14,113,187
How do you set a conditional in python based on datatypes?
<p>This question seems mind-boggling simple, yet I can't figure it out. I know you can check datatypes in python, but how can you set a conditional based on the datatype? For instance, if I have to write a code that sorts through a dictionary/list and adds up all the integers, how do I isolate the search to look for only integers? </p> <p>I guess a quick example would look something like this:</p> <pre><code>y = [] for x in somelist: if type(x) == &lt;type 'int'&gt;: ### &lt;--- psuedo-code line y.append(x) print sum(int(z) for z in y) </code></pre> <p>So for line 3, how would I set such a conditional?</p>
14,113,197
6
3
null
2013-01-01 18:45:00.237 UTC
10
2020-12-02 09:23:12.523 UTC
null
null
null
null
1,715,000
null
1
44
python|types|conditional
98,313
<p>How about, </p> <pre><code>if isinstance(x, int): </code></pre> <p>but a cleaner way would simply be</p> <pre><code>sum(z for z in y if isinstance(z, int)) </code></pre>
13,865,842
Does static constexpr variable inside a function make sense?
<p>If I have a variable inside a function (say, a large array), does it make sense to declare it both <code>static</code> and <code>constexpr</code>? <code>constexpr</code> guarantees that the array is created at compile time, so would the <code>static</code> be useless?</p> <pre><code>void f() { static constexpr int x [] = { // a few thousand elements }; // do something with the array } </code></pre> <p>Is the <code>static</code> actually doing anything there in terms of generated code or semantics?</p>
13,867,690
3
0
null
2012-12-13 18:08:39.893 UTC
80
2021-07-23 18:51:52.14 UTC
2019-08-08 10:13:00.703 UTC
null
895,245
null
852,254
null
1
254
c++|static|c++11|constexpr
139,302
<p>The short answer is that not only is <code>static</code> useful, it is pretty well always going to be desired.</p> <p>First, note that <code>static</code> and <code>constexpr</code> are completely independent of each other. <code>static</code> defines the object's lifetime during execution; <code>constexpr</code> specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, <code>constexpr</code> is no longer relevant.</p> <p>Every variable declared <code>constexpr</code> is implicitly <code>const</code> but <code>const</code> and <code>static</code> are almost orthogonal (except for the interaction with <code>static const</code> integers.)</p> <p>The <code>C++</code> object model (&sect;1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the <code>as-if</code> principle provided it can prove that no other such object can be observed.</p> <p>That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static <code>const(expr)</code> array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.</p> <p>On the other hand, a local <code>static const</code> object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.</p> <p>So you should definitely use <code>static constexpr</code> in your example.</p> <p>However, there is one case where you wouldn't want to use <code>static constexpr</code>. Unless a <code>constexpr</code> declared object is either <a href="https://en.cppreference.com/w/cpp/language/definition#ODR-use" rel="noreferrer">ODR-used</a> or declared <code>static</code>, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary <code>constexpr</code> arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use <code>static</code>, since <code>static</code> is likely to force the object to exist at runtime.</p>
29,066,117
Streaming a file from server to client with socket.io-stream
<p>I've managed to upload files in chunk from a client to a server, but now i want to achieve the opposite way. Unfortunately the documentation on the offical module page lacks for this part.</p> <p>I want to do the following:</p> <ul> <li>emit a stream and 'download'-event with the filename to the server</li> <li>the server should create a readstream and pipe it to the stream emitted from the client</li> <li>when the client reaches the stream, a download-popup should appear and ask where to save the file</li> </ul> <p>The reason why i don't wanna use simple file-hyperlinks is obfuscating: the files on the server are encrpted and renamed, so i have to decrypt and rename them for each download request.</p> <p>Any code snippets around to get me started with this?</p>
30,965,486
2
2
null
2015-03-15 21:00:01.867 UTC
8
2021-10-16 17:13:38.857 UTC
null
null
null
null
804,743
null
1
9
node.js|stream|socket.io
13,753
<p>This is a working example I'm using. But somehow (maybe only in my case) this can be very slow.</p> <pre><code>//== Server Side ss(socket).on('filedownload', function (stream, name, callback) { //== Do stuff to find your file callback({ name : "filename", size : 500 }); var MyFileStream = fs.createReadStream(name); MyFileStream.pipe(stream); }); //== Client Side /** Download a file from the object store * @param {string} name Name of the file to download * @param {string} originalFilename Overrules the file's originalFilename * @returns {$.Deferred} */ function downloadFile(name, originalFilename) { var deferred = $.Deferred(); //== Create stream for file to be streamed to and buffer to save chunks var stream = ss.createStream(), fileBuffer = [], fileLength = 0; //== Emit/Request ss(mysocket).emit('filedownload', stream, name, function (fileError, fileInfo) { if (fileError) { deferred.reject(fileError); } else { console.log(['File Found!', fileInfo]); //== Receive data stream.on('data', function (chunk) { fileLength += chunk.length; var progress = Math.floor((fileLength / fileInfo.size) * 100); progress = Math.max(progress - 2, 1); deferred.notify(progress); fileBuffer.push(chunk); }); stream.on('end', function () { var filedata = new Uint8Array(fileLength), i = 0; //== Loop to fill the final array fileBuffer.forEach(function (buff) { for (var j = 0; j &lt; buff.length; j++) { filedata[i] = buff[j]; i++; } }); deferred.notify(100); //== Download file in browser downloadFileFromBlob([filedata], originalFilename); deferred.resolve(); }); } }); //== Return return deferred; } var downloadFileFromBlob = (function () { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (data, fileName) { var blob = new Blob(data, { type : "octet/stream" }), url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; }()); </code></pre>
43,873,546
React-native textAlign justify
<h2>Android</h2> <p>I tried to use <code>textAlign</code> to make the text justified but it doesn't work.</p> <pre class="lang-js prettyprint-override"><code>&lt;Text style={{textAlign: 'justify',color:'#1B3D6C', margin: 20}}&gt; Lorem ipsum dolor sit amet, et usu congue vocibus, ei sea alienum repudiandae, intellegam quaerendum an nam. Vocibus apeirian no vis, eos cu conguemoo scaevola accusamus. Et sea placerat persecutii oinn &lt;/Text&gt; </code></pre> <p><a href="https://i.stack.imgur.com/WctNe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WctNe.png" alt="enter image description here" /></a></p> <p>Edit : Ok , <code>textAlign</code> justify doesnt work on Android , so what im asking now if there is some solution to this? I really need!</p>
43,874,011
2
2
null
2017-05-09 15:09:46.733 UTC
null
2022-07-01 12:44:34.343 UTC
2022-07-01 10:24:06.967 UTC
null
9,521,512
null
6,832,877
null
1
28
react-native
50,077
<p>Android does not support text justification. The docs of <a href="https://facebook.github.io/react-native/docs/text.html#style" rel="nofollow noreferrer">React Native Text component</a> about the style attribute says:</p> <blockquote> <p><strong>textAlign</strong> enum('auto', 'left', 'right', 'center', 'justify') : Specifies text alignment. <strong>The value 'justify' is only supported on iOS and fallbacks to left on Android</strong>.</p> </blockquote> <p>A workaround for this limitation is to use a <a href="https://facebook.github.io/react-native/docs/webview.html" rel="nofollow noreferrer">React Native WebView</a> component. The content of the WebView can be an HTML code with the justified text. Like this:</p> <pre class="lang-js prettyprint-override"><code>&lt;View style={{flex: 1}}&gt; &lt;WebView source={{ html: &quot;&lt;p style='text-align: justify;'&gt;Justified text here&lt;/p&gt;&quot; }} /&gt; &lt;/View&gt; </code></pre>
43,209,666
React-router v4 - cannot GET *url*
<p>I started to use react-router v4. I have a simple <code>&lt;Router&gt;</code> in my app.js with some navigation links (see code below). If I navigate to <code>localhost/vocabulary</code>, router redirects me to the right page. However, when I press reload (F5) afterwards (<code>localhost/vocabulary</code>), all content disappear and browser report <code>Cannot GET /vocabulary</code>. How is that possible? Can somebody gives me any clue how to solve that (reload the page correctly)?</p> <p>App.js:</p> <pre><code>import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' import { Switch, Redirect } from 'react-router' import Login from './pages/Login' import Vocabulary from './pages/Vocabulary' const appContainer = document.getElementById('app') ReactDOM.render( &lt;Router&gt; &lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;Link to="/"&gt;Home&lt;/Link&gt;&lt;/li&gt; &lt;li&gt;&lt;Link to="/vocabulary"&gt;Vocabulary&lt;/Link&gt;&lt;/li&gt; &lt;/ul&gt; &lt;Switch&gt; &lt;Route exact path="/" component={Login} /&gt; &lt;Route exact path="/vocabulary" component={Vocabulary} /&gt; &lt;/Switch&gt; &lt;/div&gt; &lt;/Router&gt;, appContainer) </code></pre>
43,212,553
11
1
null
2017-04-04 14:09:18.403 UTC
31
2022-08-11 22:32:28.043 UTC
null
null
null
null
3,384,562
null
1
105
javascript|reactjs|routes|localhost|react-router
68,511
<p>I'm assuming you're using Webpack. If so, adding a few things to your webpack config should solve the issue. Specifically, <code>output.publicPath = '/'</code> and <code>devServer.historyApiFallback = true</code>. Here's an example webpack config below which uses both of ^ and fixes the refresh issue for me. If you're curious "why", <a href="https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writting-manually">this</a> will help.</p> <pre><code>var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './app/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'index_bundle.js', publicPath: '/' }, module: { rules: [ { test: /\.(js)$/, use: 'babel-loader' }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]} ] }, devServer: { historyApiFallback: true, }, plugins: [ new HtmlWebpackPlugin({ template: 'app/index.html' }) ] }; </code></pre> <p>I wrote more about this here - <a href="https://tylermcginnis.com/react-router-cannot-get-url-refresh/" rel="noreferrer">Fixing the "cannot GET /URL" error on refresh with React Router (or how client side routers work)</a></p>
9,575,409
Calling parent class __init__ with multiple inheritance, what's the right way?
<p>Say I have a multiple inheritance scenario:</p> <pre><code>class A(object): # code for A here class B(object): # code for B here class C(A, B): def __init__(self): # What's the right code to write here to ensure # A.__init__ and B.__init__ get called? </code></pre> <p>There's two typical approaches to writing <code>C</code>'s <code>__init__</code>:</p> <ol> <li>(old-style) <code>ParentClass.__init__(self)</code></li> <li>(newer-style) <code>super(DerivedClass, self).__init__()</code></li> </ol> <p>However, in either case, if the parent classes (<code>A</code> and <code>B</code>) <a href="http://fuhm.org/super-harmful/" rel="noreferrer">don't follow the same convention, then the code will not work correctly</a> (some may be missed, or get called multiple times).</p> <p>So what's the correct way again? It's easy to say "just be consistent, follow one or the other", but if <code>A</code> or <code>B</code> are from a 3rd party library, what then? Is there an approach that can ensure that all parent class constructors get called (and in the correct order, and only once)?</p> <p>Edit: to see what I mean, if I do:</p> <pre><code>class A(object): def __init__(self): print("Entering A") super(A, self).__init__() print("Leaving A") class B(object): def __init__(self): print("Entering B") super(B, self).__init__() print("Leaving B") class C(A, B): def __init__(self): print("Entering C") A.__init__(self) B.__init__(self) print("Leaving C") </code></pre> <p>Then I get:</p> <pre><code>Entering C Entering A Entering B Leaving B Leaving A Entering B Leaving B Leaving C </code></pre> <p>Note that <code>B</code>'s init gets called twice. If I do: </p> <pre><code>class A(object): def __init__(self): print("Entering A") print("Leaving A") class B(object): def __init__(self): print("Entering B") super(B, self).__init__() print("Leaving B") class C(A, B): def __init__(self): print("Entering C") super(C, self).__init__() print("Leaving C") </code></pre> <p>Then I get: </p> <pre><code>Entering C Entering A Leaving A Leaving C </code></pre> <p>Note that <code>B</code>'s init never gets called. So it seems that unless I know/control the init's of the classes I inherit from (<code>A</code> and <code>B</code>) I cannot make a safe choice for the class I'm writing (<code>C</code>).</p>
9,575,426
11
1
null
2012-03-05 23:00:31.537 UTC
95
2021-08-03 07:11:42.063 UTC
2018-09-24 01:14:52.88 UTC
null
1,944,335
null
808,804
null
1
301
python|oop|inheritance|multiple-inheritance|super
144,364
<p>Both ways work fine. The approach using <code>super()</code> leads to greater flexibility for subclasses. </p> <p>In the direct call approach, <code>C.__init__</code> can call both <code>A.__init__</code> and <code>B.__init__</code>.</p> <p>When using <code>super()</code>, the classes need to be designed for cooperative multiple inheritance where <code>C</code> calls <code>super</code>, which invokes <code>A</code>'s code which will also call <code>super</code> which invokes <code>B</code>'s code. See <a href="http://rhettinger.wordpress.com/2011/05/26/super-considered-super" rel="noreferrer">http://rhettinger.wordpress.com/2011/05/26/super-considered-super</a> for more detail on what can be done with <code>super</code>.</p> <p>[Response question as later edited]</p> <blockquote> <p>So it seems that unless I know/control the init's of the classes I inherit from (A and B) I cannot make a safe choice for the class I'm writing (C).</p> </blockquote> <p>The referenced article shows how to handle this situation by adding a wrapper class around <code>A</code> and <code>B</code>. There is a worked-out example in the section titled "How to Incorporate a Non-cooperative Class".</p> <p>One might wish that multiple inheritance were easier, letting you effortlessly compose Car and Airplane classes to get a FlyingCar, but the reality is that separately designed components often need adapters or wrappers before fitting together as seamlessly as we would like :-)</p> <p>One other thought: if you're unhappy with composing functionality using multiple inheritance, you can use composition for complete control over which methods get called on which occasions.</p>
58,901,288
SpringRunner vs SpringBootTest
<p>In unit test, what are the differences between <code>@Runwith(SpringRunner.class)</code> &amp; <code>@SpringBootTest</code>? </p> <p>Can you explain to me the use cases of each one?</p>
58,902,051
3
4
null
2019-11-17 14:08:38.537 UTC
23
2020-04-15 06:02:44.35 UTC
2019-11-17 14:12:03.447 UTC
null
3,001,761
null
12,367,005
null
1
62
java|spring-boot|junit|spring-boot-test
47,282
<p><strong>@RunWith(SpringRunner.class) :</strong> You need this annotation to just enable spring boot features like <code>@Autowire</code>, <code>@MockBean</code> etc.. during junit testing</p> <blockquote> <p>is used to provide a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.</p> </blockquote> <p><strong>@SpringBootTest :</strong> This annotation is used to load complete application context for end to end integration testing </p> <blockquote> <p>The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.</p> </blockquote> <p>Here is the article with clear examples on both scenarios <a href="https://www.baeldung.com/spring-boot-testing" rel="noreferrer">Baeldung</a> </p>
62,644,070
Differences between std::is_convertible and std::convertible_to (in practice)?
<p>According to <a href="https://en.cppreference.com/" rel="noreferrer">en.cppreference.com</a> (from what I can gather):</p> <ul> <li><a href="https://en.cppreference.com/w/cpp/types/is_convertible" rel="noreferrer"><code>std::is_convertible</code></a> is a trait class requiring types <code>From</code> &amp; <code>To</code> to be such that a function with return type <code>To</code> that returns a <code>From</code> value can compile.</li> <li><a href="https://en.cppreference.com/w/cpp/concepts/convertible_to" rel="noreferrer"><code>std::convertible_to</code></a> is a concept requiring types <code>From</code> &amp; <code>To</code> to be as explained above, <strong>AND</strong> such that an <em>r-value reference</em> of type <code>From</code> can be converted with <code>static_cast&lt;To&gt;</code>.</li> </ul> <p>The requirement imposed by <a href="https://en.cppreference.com/w/cpp/types/is_convertible" rel="noreferrer"><code>std::is_convertible</code></a> seems relatively straight-forward. Conversely, the <em>r-value reference</em> casting requirement of <a href="https://en.cppreference.com/w/cpp/concepts/convertible_to" rel="noreferrer"><code>std::convertible_to</code></a> seems oddly specific for such a generic concept that is shown in simple examples for C++20 features.</p> <p>Being a novice in C++, I could not quite understand some terminology and parts of the supplementary descriptions provided in both webpages and I cannot imagine the exact difference between the requirements of either.</p> <p>Some inter-related questions:</p> <ul> <li>What are the practical implications for types <code>From</code> &amp; <code>To</code> of not only being constrained by <a href="https://en.cppreference.com/w/cpp/types/is_convertible" rel="noreferrer"><code>std::is_convertible</code></a> but also by the strange r-value reference casting requirement?</li> <li>What kind of candidate types for <code>From</code> &amp; <code>To</code> are <em>additionally</em> rejected by the r-value reference casting requirement?</li> <li>Why might a programmer want to use either of <a href="https://en.cppreference.com/w/cpp/types/is_convertible" rel="noreferrer"><code>std::is_convertible</code></a> or <a href="https://en.cppreference.com/w/cpp/concepts/convertible_to" rel="noreferrer"><code>std::convertible_to</code></a>, instead of the other, as constraints for their function return types or parameter types (<strong>aside from just the convenience of concepts</strong>)?</li> </ul> <p>A simpler explanation or an example would help. Thank you!</p>
62,644,127
1
0
null
2020-06-29 17:58:34.363 UTC
2
2020-06-29 18:02:42.62 UTC
null
null
null
null
3,842,561
null
1
36
c++|stl|rvalue-reference|c++20|c++-concepts
2,707
<p><code>std::is_convertible&lt;From, To&gt;</code> (the type trait) checks is type <code>From</code> is <em>implicitly</em> convertible to type <code>To</code>.</p> <p><code>std::convertible_to&lt;From, To&gt;</code> (the concept) checks that <code>From</code> is both <em>implicitly and explicitly</em> convertible to <code>To</code>. It's rare that this is not the case, such types are ridiculous, but it's nice in generic code to just <em>not</em> have to worry about that case.</p> <p>One example:</p> <pre><code>struct From; struct To { explicit To(From) = delete; }; struct From { operator To(); }; static_assert(std::is_convertible_v&lt;From, To&gt;); static_assert(not std::convertible_to&lt;From, To&gt;); </code></pre>
44,731,221
How integrate jQuery plugin in React
<p>I want to use <a href="https://github.com/t1m0n/air-datepicker" rel="noreferrer">https://github.com/t1m0n/air-datepicker</a> with in a React app, but it doesn't work.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react'; import AirDatepicker from 'air-datepicker'; class Datepicker extends React.Component { render() { return( &lt;AirDatepicker /&gt; ) } } export default Datepicker; `</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="./../bower_components/jquery/dist/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>This produces:</p> <pre><code>error($ is not defined) </code></pre> <p>Another approach:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react'; import $ from 'jquery'; import AirDatepicker from 'air-datepicker'; class Datepicker extends React.Component { render() { return( &lt;AirDatepicker /&gt; ) } } export default Datepicker;</code></pre> </div> </div> </p> <p>Same error.</p> <p>How can I integrate a jQuery plugin with React?</p>
44,734,500
3
5
null
2017-06-23 23:28:30.29 UTC
6
2021-10-17 05:11:24.903 UTC
2021-10-17 05:11:24.903 UTC
null
10,248,678
null
7,852,453
null
1
6
javascript|jquery|reactjs|webpack
40,374
<p>First of all <code>air-datepicker</code> <strong>is not React component</strong>, it's jQuery plugin, so it won't work like in your examples. </p> <p>Secondly, for proper work, jQuery should be availabel in global context, the most esiest ways to do this is to include it into page via <code>&lt;script&gt;</code> tag. It should be included <strong>before</strong> plugin script.</p> <p>To check if its really included and it available globally, just type in Chrome console <code>window.jQuery</code>and press <strong>Enter</strong> it should return something like <code>function (a,b){...}</code>. If not, when you doing something wrong, check <code>src</code> attribute of <code>&lt;script&gt;</code> tag, maybe it pointing to wrong destination</p> <p><strong>How to get it worked in React?</strong></p> <p>Well, the most simpliest way is just to initialize plugin on any DOM element in your component, like in regular JavaScript.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class MyComponent extends React.Component { componentDidMount(){ this.initDatepicker(); } initDatepicker(){ $(this.refs.datepicker).datepicker(); } render(){ return ( &lt;div&gt; &lt;h3&gt;Choose date!&lt;/h3&gt; &lt;input type='text' ref='datepicker' /&gt; &lt;/div&gt; ) } } ReactDOM.render( &lt;MyComponent /&gt;, document.getElementById('app') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"&gt;&lt;/script&gt; &lt;link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet"/&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>As separate component</strong></p> <p>Very simple datepicker React component example</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Datepicker extends React.Component { componentDidMount(){ this.initDatepicker(); } initDatepicker(){ $(this.refs.datepicker).datepicker(this.props); } render(){ return ( &lt;input type='text' ref='datepicker'/&gt; ) } } class MyComponent extends React.Component { render(){ return ( &lt;div&gt; &lt;h3&gt;Choose date from React Datepicker!&lt;/h3&gt; &lt;Datepicker range={true} /&gt; &lt;/div&gt; ) } } ReactDOM.render( &lt;MyComponent /&gt;, document.getElementById('app') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"&gt;&lt;/script&gt; &lt;link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet"/&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Also don't forget to include <strong>css</strong> files.</p>
24,750,395
Reload Express.js routes changes without manually restarting server
<p>I tried <code>express-livereload</code>, but it just reloaded view files.</p> <p>Should I use another tool, or this one can be configured to watch for my <code>index.js</code> file which runs the server?</p> <p>I read that options are the same as <code>node-livereload</code>, and default for watched files include <code>.js</code> files.</p> <p>Any URL you know with a simple configuration?</p> <p>My main problem is how to setup good development environment for Express.js, and I would like to inspect the variables when I am making a request, is painful to restart each time I make a change in a route.</p> <p>PS I tried <code>node-inspector</code> to inspect variables when server handles a request, but it seems <code>node-inspector</code> is not intended for that, right?</p>
24,750,584
3
3
null
2014-07-15 05:24:54.997 UTC
4
2022-01-26 06:25:29.777 UTC
2018-11-13 04:02:55.8 UTC
null
977,931
null
1,197,775
null
1
59
javascript|node.js|express
44,558
<p>I think <a href="http://nodemon.io/" rel="noreferrer">Nodemon</a> has what you're looking for.</p> <blockquote> <p><a href="http://nodemon.io/" rel="noreferrer">Nodemon</a> is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. </p> </blockquote> <p>Example invocation: </p> <pre><code>nodemon index.js </code></pre>
1,198,701
Storing and displaying unicode string (हिन्दी) using PHP and MySQL
<p>I have to store hindi text in a MySQL database, fetch it using a PHP script and display it on a webpage. I did the following:</p> <p>I created a database and set its encoding to UTF-8 and also the collation to <code>utf8_bin</code>. I added a varchar field in the table and set it to accept UTF-8 text in the charset property.</p> <p>Then I set about adding data to it. Here I had to copy data from an <a href="http://www.mypanchang.com/2009/hi/Jammu-Kashmir-India/0/july.html" rel="noreferrer">existing site</a>. The hindi text looks like this: सूर्योदय:05:30 </p> <p>I directly copied this text into my database and used the PHP code <code>echo(utf8_encode($string))</code> to display the data. Upon doing so the browser showed me "??????".</p> <p>When I inserted the UTF equivalent of the text by going to "view source" in the browser, however, सूर्योदय translates into <code>&amp;#2360;&amp;#2370;&amp;#2352;&amp;#2381;&amp;#2351;&amp;#2379;&amp;#2342;&amp;#2351;</code>.</p> <p>If I enter and store <code>&amp;#2360;&amp;#2370;&amp;#2352;&amp;#2381;&amp;#2351;&amp;#2379;&amp;#2342;&amp;#2351;</code> in the database, it converts perfectly.</p> <p>So what I want to know is how I can directly store सूर्योदय into my database and fetch it and display it in my webpage using PHP.</p> <p>Also, can anyone help me understand if there's a script which when I type in सूर्योदय, gives me <code>&amp;#2360;&amp;#2370;&amp;#2352;&amp;#2381;&amp;#2351;&amp;#2379;&amp;#2342;&amp;#2351;</code>?</p> <p><strong>Solution Found</strong></p> <p>I wrote the following sample script which worked for me. Hope it helps someone else too</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Hindi&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;?php include("connection.php"); //simple connection setting $result = mysql_query("SET NAMES utf8"); //the main trick $cmd = "select * from hindi"; $result = mysql_query($cmd); while ($myrow = mysql_fetch_row($result)) { echo ($myrow[0]); } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The dump for my database storing hindi utf strings is</p> <pre><code>CREATE TABLE `hindi` ( `data` varchar(1000) character set utf8 collate utf8_bin default NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `hindi` VALUES ('सूर्योदय'); </code></pre> <p>Now my question is, how did it work without specifying "META" or header info?</p> <p>Thanks!</p>
1,198,713
5
0
null
2009-07-29 08:05:39.547 UTC
28
2019-09-02 06:34:11.69 UTC
2009-12-04 11:57:54.797 UTC
null
31,615
null
70,826
null
1
49
php|mysql|unicode|utf-8|internationalization
127,913
<p>Did you set proper charset in the HTML Head section?</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html;charset=UTF-8"&gt; </code></pre> <p>or you can set content type in your php script using - </p> <pre><code> header( 'Content-Type: text/html; charset=utf-8' ); </code></pre> <p>There are already some discussions here on StackOverflow - please have a look</p> <p><a href="https://stackoverflow.com/questions/202205/how-to-make-mysql-handle-utf-8-properly/202246">How to make MySQL handle UTF-8 properly</a> <a href="https://stackoverflow.com/questions/624301/setting-utf8-with-mysql-through-php">setting utf8 with mysql through php</a></p> <p><a href="https://stackoverflow.com/questions/405684/php-mysql-with-encoding-problems">PHP/MySQL with encoding problems</a></p> <blockquote> <p>So what i want to know is how can i directly store सूर्योदय into my database and fetch it and display in my webpage using PHP.</p> </blockquote> <p>I am not sure what you mean by "directly storing in the database" .. did you mean entering data using PhpMyAdmin or any other similar tool? If yes, I have tried using PhpMyAdmin to input unicode data, so it has worked fine for me - You could try inputting data using phpmyadmin and retrieve it using a php script to confirm. If you need to submit data via a Php script just set the NAMES and CHARACTER SET when you create mysql connection, before execute insert queries, and when you select data. Have a look at the above posts to find the syntax. Hope it helps.</p> <p>** UPDATE ** Just fixed some typos etc</p>
646,217
How to run a bash script from C++ program
<p>Bash scripts are very useful and can save a lot of programming time. So how do you start a bash script in a C++ program? Also if you know how to make user become the super-user that would be nice also. Thanks!</p>
646,222
5
0
null
2009-03-14 16:43:07.807 UTC
25
2021-08-06 12:15:10.18 UTC
2009-03-14 16:47:15.893 UTC
dmckee
2,509
Lucas Aardvark
56,555
null
1
63
c++|linux|bash|shell
150,439
<p>Use the <code>system</code> function.</p> <pre><code>system("myfile.sh"); // myfile.sh should be chmod +x </code></pre>
1,085,749
Google Map Route Draw on IPhone
<p>I am developing an application that has two versions. One for web and another for iPhone. </p> <p>In the web app, I am able to draw a route on the road (drawing the route automatically that follows roads/highways) and off road (draw direct line between two specific points).</p> <p>Is there an API, for iPhone, that can be used to draw a route on the map? I am able to draw a straight line on the map between two nodes, but i am not able to draw a road map route in iPhone.</p> <p>I am using iPhone 3.0 and SDK 3.0</p> <p>Thanks.</p>
1,089,645
6
4
null
2009-07-06 07:03:26.157 UTC
20
2012-08-12 09:00:41.317 UTC
2011-12-02 11:06:33.71 UTC
null
363,363
null
131,483
null
1
19
iphone|google-maps|routes
31,463
<p>Maybe you want to take a look at Craig Spitzkoff's <a href="http://spitzkoff.com/craig/wp-content/uploads/2009/05/maplinesandannotations1.zip" rel="noreferrer">MapLinesAndAnnotations</a> sample that he recently wrote: </p> <ol> <li><a href="http://spitzkoff.com/craig/?p=65" rel="noreferrer">Drawing polyines or routes on a MKMapView (Using Map Kit on the iPhone)</a></li> <li><a href="http://spitzkoff.com/craig/?p=81" rel="noreferrer">Using MKAnnotation, MKPinAnnotationView and creating a custom MKAnnotationView in an MKMapView</a></li> </ol>
886,692
Automatically stop/restart ASP.NET Development Server on Build
<p>Is there a way to automatically stop the ASP.NET Development Server (Cassini) whenever I do a build/rebuild in VS2008 (and then obviously have it start again when required)? Maybe there's some hidden configuration setting somewhere? Or at least some way to do it as a post-build event maybe?</p> <p>For some background, the issue is that I'm using Spring.NET for dependency injection, etc, but it loads its singletons on Application Start, meaning that if I change any spring related code/configuration I have to stop the Development Server, so that it starts again next debug/run ensuring the Application Start event is triggered again. In other words, even if you change a bunch of code/config &amp; then start debugging again, it doesn't actually <em>start</em> again, since its already running, so your new code isn't being used.</p>
891,363
6
2
null
2009-05-20 07:58:26.67 UTC
12
2016-02-11 15:26:44.08 UTC
null
null
null
null
68,727
null
1
32
asp.net|visual-studio|cassini
29,254
<p>So I ended up with a workaround based off Magnus' answer, but using the following relatively simple macro (why do they force you to use VB for macros? I feel all dirty):</p> <pre><code>Imports System Imports System.Diagnostics Public Module KillCassini Sub RestartDebug() If (DTE.Debugger.DebuggedProcesses.Count &gt; 0) Then DTE.Debugger.Stop(True) End If KillCassini() DTE.Debugger.Go(False) End Sub Sub KillCassini() Dim name As String = "WebDev.WebServer" Dim proc As Process For Each proc In Process.GetProcesses If (proc.ProcessName.StartsWith(name)) Then proc.Kill() End If Next End Sub End Module </code></pre> <p>Basically if the debugger is currently running, it will stop it &amp; then kill any processes named "WebDev.WebServer" which should be all the Cassini instances and then starts the debugger again (which will implicitly start Cassini again). I'm using <code>proc.Kill()</code> because neither <code>proc.CloseMainWindow()</code> or <code>proc.WaitForExit(1000)</code> seemed to work...</p> <p>Anyway, once you've got your macro you can assign it to keyboard shortcuts, or create custom toolbar buttons to run it.</p>
42,385,099
#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’
<p>I have a WordPress website on my local <strong>WAMP</strong> server. But when I upload its database to live server, I get error </p> <pre><code>#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ </code></pre> <p>Any help would be appreciated!</p>
42,385,164
17
5
null
2017-02-22 07:23:15.593 UTC
92
2021-10-30 19:17:40.14 UTC
2018-11-20 18:33:45.59 UTC
null
1,766,831
null
4,543,797
null
1
271
mysql|sql|wordpress|collation
494,279
<p>You can solve this by finding</p> <pre><code>ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; </code></pre> <p>in your <code>.sql</code> file, and swapping it with </p> <pre><code>ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci; </code></pre>
32,367,469
Unable to create converter for my class in Android Retrofit library
<p>Im migrating from using Volley to Retrofit, I already have gson class that I used before for converting JSONObject reponse to a object that implements gson annotations. When I'm trying to make http get request using retrofit but then my app crashes with this error :</p> <pre><code> Unable to start activity ComponentInfo{com.lightbulb.pawesome/com.example.sample.retrofit.SampleActivity}: java.lang.IllegalArgumentException: Unable to create converter for class com.lightbulb.pawesome.model.Pet for method GitHubService.getResponse </code></pre> <p>Im following the guide in <a href="http://square.github.io/retrofit/">retrofit</a> site and I come up with these implementations :</p> <p>This is my activity where I am trying to execute the retro http request:</p> <pre><code>public class SampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample); Retrofit retrofit = new Retrofit.Builder() .baseUrl("**sample base url here**") .build(); GitHubService service = retrofit.create(GitHubService.class); Call&lt;Pet&gt; callPet = service.getResponse("41", "40"); callPet.enqueue(new Callback&lt;Pet&gt;() { @Override public void onResponse(Response&lt;Pet&gt; response) { Log.i("Response", response.toString()); } @Override public void onFailure(Throwable t) { Log.i("Failure", t.toString()); } }); try{ callPet.execute(); } catch (IOException e){ e.printStackTrace(); } } } </code></pre> <p>My interface which turned to be my API</p> <pre><code>public interface GitHubService { @GET("/ **sample here** /{petId}/{otherPet}") Call&lt;Pet&gt; getResponse(@Path("petId") String userId, @Path("otherPet") String otherPet); } </code></pre> <p>And finally the Pet class which should be the reponse:</p> <pre><code>public class Pet implements Parcelable { public static final String ACTIVE = "1"; public static final String NOT_ACTIVE = "0"; @SerializedName("is_active") @Expose private String isActive; @SerializedName("pet_id") @Expose private String petId; @Expose private String name; @Expose private String gender; @Expose private String age; @Expose private String breed; @SerializedName("profile_picture") @Expose private String profilePicture; @SerializedName("confirmation_status") @Expose private String confirmationStatus; /** * * @return * The confirmationStatus */ public String getConfirmationStatus() { return confirmationStatus; } /** * * @param confirmationStatus * The confirmation_status */ public void setConfirmationStatus(String confirmationStatus) { this.confirmationStatus = confirmationStatus; } /** * * @return * The isActive */ public String getIsActive() { return isActive; } /** * * @param isActive * The is_active */ public void setIsActive(String isActive) { this.isActive = isActive; } /** * * @return * The petId */ public String getPetId() { return petId; } /** * * @param petId * The pet_id */ public void setPetId(String petId) { this.petId = petId; } /** * * @return * The name */ public String getName() { return name; } /** * * @param name * The name */ public void setName(String name) { this.name = name; } /** * * @return * The gender */ public String getGender() { return gender; } /** * * @param gender * The gender */ public void setGender(String gender) { this.gender = gender; } /** * * @return * The age */ public String getAge() { return age; } /** * * @param age * The age */ public void setAge(String age) { this.age = age; } /** * * @return * The breed */ public String getBreed() { return breed; } /** * * @param breed * The breed */ public void setBreed(String breed) { this.breed = breed; } /** * * @return * The profilePicture */ public String getProfilePicture() { return profilePicture; } /** * * @param profilePicture * The profile_picture */ public void setProfilePicture(String profilePicture) { this.profilePicture = profilePicture; } protected Pet(Parcel in) { isActive = in.readString(); petId = in.readString(); name = in.readString(); gender = in.readString(); age = in.readString(); breed = in.readString(); profilePicture = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(isActive); dest.writeString(petId); dest.writeString(name); dest.writeString(gender); dest.writeString(age); dest.writeString(breed); dest.writeString(profilePicture); } @SuppressWarnings("unused") public static final Parcelable.Creator&lt;Pet&gt; CREATOR = new Parcelable.Creator&lt;Pet&gt;() { @Override public Pet createFromParcel(Parcel in) { return new Pet(in); } @Override public Pet[] newArray(int size) { return new Pet[size]; } }; } </code></pre>
32,390,665
14
5
null
2015-09-03 05:17:22.97 UTC
27
2022-03-19 06:19:21.71 UTC
2015-09-03 06:24:41.667 UTC
null
4,998,335
null
4,998,335
null
1
169
android|gson|retrofit
123,380
<p>Prior to <code>2.0.0</code>, the default converter was a gson converter, but in <code>2.0.0</code> and later the default converter is <code>ResponseBody</code>. From the docs:</p> <blockquote> <p>By default, Retrofit can only deserialize HTTP bodies into OkHttp's <code>ResponseBody</code> type and it can only accept its <code>RequestBody</code> type for <code>@Body</code>.</p> </blockquote> <p>In <code>2.0.0+</code>, you need to explicitly specify you want a Gson converter:</p> <pre><code>Retrofit retrofit = new Retrofit.Builder() .baseUrl("**sample base url here**") .addConverterFactory(GsonConverterFactory.create()) .build(); </code></pre> <p>You will also need to add the following dependency to your gradle file:</p> <pre><code>compile 'com.squareup.retrofit2:converter-gson:2.1.0' </code></pre> <p>Use the same version for the converter as you do for your retrofit. The above matches this retrofit dependency: </p> <pre><code>compile ('com.squareup.retrofit2:retrofit:2.1.0') </code></pre> <p>Also, note as of writing this, the retrofit docs are not completely updated, which is why that example got you into trouble. From the docs: </p> <blockquote> <p>Note: This site is still in the process of being expanded for the new 2.0 APIs. </p> </blockquote>
21,114,784
R error type "Subscript out of bounds"
<p>I am simulating a correlation matrix, where the 60 variables correlate in the following way:</p> <ul> <li>more highly (0.6) for every two variables (1-2, 3-4... 59-60)</li> <li><p>moderate (0.3) for every group of 12 variables (1-12,13-24...)</p> <pre><code>mc &lt;- matrix(0,60,60) diag(mc) &lt;- 1 for (c in seq(1,59,2)){ # every pair of variables in order are given 0.6 correlation mc[c,c+1] &lt;- 0.6 mc[c+1,c] &lt;- 0.6 } for (n in seq(1,51,10)){ # every group of 12 are given correlation of 0.3 for (w in seq(12,60,12)){ # these are variables 11-12, 21-22 and such. mc[n:n+1,c(n+2,w)] &lt;- 0.2 mc[c(n+2,w),n:n+1] &lt;- 0.2 } } for (m in seq(3,9,2)){ # every group of 12 are given correlation of 0.3 for (w in seq(12,60,12)){ # these variables are the rest. mc[m:m+1,c(1:m-1,m+2:w)] &lt;- 0.2 mc[c(1:m-1,m+2:w),m:m+1] &lt;- 0.2 } } </code></pre></li> </ul> <p>The first loop works well, but not the second and third ones. I get this error message:</p> <pre><code>Error in `[&lt;-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : subscript out of bounds Error in `[&lt;-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : subscript out of bounds </code></pre> <p>I would really appreciate any hints, since I don't see the loop commands get to exceed the matrix dimensions. Thanks a lot in advance!</p>
21,115,535
1
4
null
2014-01-14 13:29:30.437 UTC
2
2014-01-14 14:05:25.143 UTC
2014-01-14 13:48:28.83 UTC
null
2,674,353
null
2,674,353
null
1
2
r|loops
42,605
<p>Note that <code>:</code> takes precedence over <code>+</code>. E.g., <code>n:n+1</code> is the same as <code>n+1</code>. I guess you want <code>n:(n+1)</code>.</p> <p>The maximal value of <code>w</code> is 60:</p> <pre><code>w &lt;- 60 m &lt;- 1 m+2:w #[1] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 #[49] 51 52 53 54 55 56 57 58 59 60 61 </code></pre> <p>And 61 is out of bounds. You need to add a lot of parentheses.</p>
1,700,062
change link text in HTML using JavaScript
<p>I have an html page which has a link called "open". Once the link is clicked the text "open" should change to "close". How do I do this?</p>
1,700,093
5
0
null
2009-11-09 09:55:21.19 UTC
2
2021-02-02 19:51:40.663 UTC
2009-11-09 10:37:51.82 UTC
null
114,672
null
167,114
null
1
12
javascript|html
72,340
<p>Script </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function open_fun() { document.getElementById('link').innerHTML = "&lt;a href='javascript:clo_fun()'&gt;CLOSE&lt;/a&gt;"; } function clo_fun() { document.getElementById('link').innerHTML = "&lt;a href='javascript:open_fun()'&gt;OPEN&lt;/a&gt;"; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='link'&gt;&lt;a href='javascript:open_fun()'&gt;OPEN&lt;/a&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1,356,232
C#: How to get a user control to properly auto size itself
<p>I have a <code>UserControl</code> which consists of a <code>Label</code> (Top), a <code>FlowLayoutPanel</code> (Fill, TopDown flow and no wrap) and a <code>Panel</code> (Bottom). The user control creates a number of controls, based on a list of stuff it gets, and adds them to the <code>FlowLayoutPanel</code>.</p> <p>How can I get this <code>UserControl</code> to properly resize itself so that the <code>FlowLayoutPanel</code> does not have any scroll bars? I have tried to use various combinations of <code>AutoSize</code> and <code>AutoSizeMode</code> on the <code>FlowLayoutPanel</code> and the <code>UserControl</code> itself, but I can't seem to get it working. Either I end up with something that doesn't resize itself at all, or it doesn't become big enough or it is squished down to almost nothing.</p>
1,356,997
5
0
null
2009-08-31 07:24:56.523 UTC
5
2013-03-11 08:46:00.887 UTC
null
null
null
null
39,321
null
1
23
c#|winforms|dynamic|user-controls
75,766
<p>Thanks for all the suggestions. The solution this time seemed to set <code>AutoSize</code> to <code>true</code> for both the <code>FlowLayoutPanel</code> <em>and</em> the <code>UserControl</code> itself.</p> <p><em>Now, how to get the form which will contain this <code>UserControl</code> as well as some other controls, that I can't quite figure out at the moment, but I guess that should be a separate question...</em></p>
1,535,246
Format date from database?
<p>When I pull the date out of the db, it comes back like this:</p> <p>2009-10-14T19:00:00</p> <p>I want to format it in two different ways...</p> <p>The first: F d, Y The second h:m (12 hour format)</p> <p>Everything I try returns December 1969... Help?! I feel so confused... </p>
1,535,259
5
0
null
2009-10-08 02:07:05.213 UTC
11
2015-12-01 07:30:14.73 UTC
2013-02-12 16:42:11.033 UTC
null
560,648
null
183,819
null
1
26
php|date|format
95,223
<p>Normally the code is just:</p> <pre><code>echo date('F d, Y h:mA', strtotime('2009-10-14 19:00:00')); </code></pre> <p>Note that if <code>strtotime()</code> can't figure out the date, it returns the time as <a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">1/1/1970 00:00:00 GMT</a>.</p>
1,897,458
Parallel Sort Algorithm
<p>I'm looking for a simple implementation of a parallelized (multi-threaded) sort algorithm in C# that can operate on <code>List&lt;T&gt;</code> or Arrays, and possibly using Parallel Extensions but that part isn't strictly necessary.</p> <p>Edit: Frank Krueger provides a good answer, however I wish to convert that example to one that doesn't use LINQ. Also note that <code>Parallel.Do()</code> seems to have been superceded by <code>Parallel.Invoke()</code>.</p> <p>Thanks.</p>
1,897,484
5
1
null
2009-12-13 19:29:22.897 UTC
19
2018-01-18 22:56:14.233 UTC
2010-05-11 12:24:42.513 UTC
null
182,467
null
15,703
null
1
26
c#|.net|sorting|parallel-processing|parallel-extensions
25,884
<p>From "The Darkside" in his article <a href="http://www.darkside.co.za/archive/2008/03/14/microsoft-parallel-extensions-.net-framework.aspx" rel="noreferrer">Parallel Extensions to the .Net Framework</a> we have this parallel extensions version of quicksort:</p> <p>(Edit: Since the link is now dead, interested readers may find an archive of it at <a href="https://web.archive.org/web/20120201062954/http://www.darkside.co.za/archive/2008/03/14/microsoft-parallel-extensions-.net-framework.aspx" rel="noreferrer">the Wayback Machine</a>)</p> <pre><code>private void QuicksortSequential&lt;T&gt;(T[] arr, int left, int right) where T : IComparable&lt;T&gt; { if (right &gt; left) { int pivot = Partition(arr, left, right); QuicksortSequential(arr, left, pivot - 1); QuicksortSequential(arr, pivot + 1, right); } } private void QuicksortParallelOptimised&lt;T&gt;(T[] arr, int left, int right) where T : IComparable&lt;T&gt; { const int SEQUENTIAL_THRESHOLD = 2048; if (right &gt; left) { if (right - left &lt; SEQUENTIAL_THRESHOLD) { QuicksortSequential(arr, left, right); } else { int pivot = Partition(arr, left, right); Parallel.Do( () =&gt; QuicksortParallelOptimised(arr, left, pivot - 1), () =&gt; QuicksortParallelOptimised(arr, pivot + 1, right)); } } } </code></pre> <p>Notice that he reverts to a sequential sort once the number of items is less than 2048.</p>
1,770,209
Run child processes as different user from a long running Python process
<p>I've got a long running, daemonized Python process that uses subprocess to spawn new child processes when certain events occur. The long running process is started by a user with super user privileges. I need the child processes it spawns to run as a different user (e.g., "nobody") while retaining the super user privileges for the parent process.</p> <p>I'm currently using</p> <pre><code>su -m nobody -c &lt;program to execute as a child&gt; </code></pre> <p>but this seems heavyweight and doesn't die very cleanly.</p> <p>Is there a way to accomplish this programmatically instead of using su? I'm looking at the os.set*uid methods, but the doc in the Python std lib is quite sparse in that area. </p>
6,037,494
5
0
null
2009-11-20 12:39:09.63 UTC
25
2021-10-13 17:52:21.02 UTC
2019-02-22 01:47:25.663 UTC
null
1,003,746
null
165,224
null
1
54
python|fork|subprocess|setuid
60,979
<p>Since you mentioned a daemon, I can conclude that you are running on a Unix-like operating system. This matters, because how to do this depends on the kind operating system. This answer applies <em>only</em> to <strong>Unix</strong>, including Linux, and Mac OS X.</p> <ol> <li>Define a function that will set the gid and uid of the running process.</li> <li>Pass this function as the preexec_fn parameter to subprocess.Popen</li> </ol> <p>subprocess.Popen will use the fork/exec model to use your preexec_fn. That is equivalent to calling os.fork(), preexec_fn() (in the child process), and os.exec() (in the child process) in that order. Since os.setuid, os.setgid, and preexec_fn are all only supported on Unix, this solution is not portable to other kinds of operating systems.</p> <p>The following code is a script (Python 2.4+) that demonstrates how to do this:</p> <pre><code>import os import pwd import subprocess import sys def main(my_args=None): if my_args is None: my_args = sys.argv[1:] user_name, cwd = my_args[:2] args = my_args[2:] pw_record = pwd.getpwnam(user_name) user_name = pw_record.pw_name user_home_dir = pw_record.pw_dir user_uid = pw_record.pw_uid user_gid = pw_record.pw_gid env = os.environ.copy() env[ 'HOME' ] = user_home_dir env[ 'LOGNAME' ] = user_name env[ 'PWD' ] = cwd env[ 'USER' ] = user_name report_ids('starting ' + str(args)) process = subprocess.Popen( args, preexec_fn=demote(user_uid, user_gid), cwd=cwd, env=env ) result = process.wait() report_ids('finished ' + str(args)) print 'result', result def demote(user_uid, user_gid): def result(): report_ids('starting demotion') os.setgid(user_gid) os.setuid(user_uid) report_ids('finished demotion') return result def report_ids(msg): print 'uid, gid = %d, %d; %s' % (os.getuid(), os.getgid(), msg) if __name__ == '__main__': main() </code></pre> <p>You can invoke this script like this:</p> <p>Start as root...</p> <pre><code>(hale)/tmp/demo$ sudo bash --norc (root)/tmp/demo$ ls -l total 8 drwxr-xr-x 2 hale wheel 68 May 17 16:26 inner -rw-r--r-- 1 hale staff 1836 May 17 15:25 test-child.py </code></pre> <p>Become non-root in a child process...</p> <pre><code>(root)/tmp/demo$ python test-child.py hale inner /bin/bash --norc uid, gid = 0, 0; starting ['/bin/bash', '--norc'] uid, gid = 0, 0; starting demotion uid, gid = 501, 20; finished demotion (hale)/tmp/demo/inner$ pwd /tmp/demo/inner (hale)/tmp/demo/inner$ whoami hale </code></pre> <p>When the child process exits, we go back to root in parent ...</p> <pre><code>(hale)/tmp/demo/inner$ exit exit uid, gid = 0, 0; finished ['/bin/bash', '--norc'] result 0 (root)/tmp/demo$ pwd /tmp/demo (root)/tmp/demo$ whoami root </code></pre> <p><strong>Note</strong> that having the parent process wait around for the child process to exit is for <em>demonstration purposes only</em>. I did this so that the parent and child could share a terminal. A daemon would have no terminal and would seldom wait around for a child process to exit.</p>
2,033,711
How can I attach "meta data" to a DOM node?
<p>Sometimes I want to attach some kind of meta data to a HTML node and I wondered, what's the best way to do this. </p> <p>I can imagine the following:</p> <ul> <li>Non-standard attributes: <code>&lt;div myattr1="myvalue1" myattr2="myvalue2" &gt;</code> (Breaks validation)</li> <li>Re-use an existing attribute <code>&lt;div class="myattr1-myvalue2-myattr2-myvalue2"&gt;</code> (Requires parsing and some level of escaping)</li> </ul> <p>Both solutions are really ugly!</p> <p>Is there any way to do this more elegantly? I'm already using jQuery so any good Javascript solution, if any, is appreciated, too.</p>
2,033,951
6
0
null
2010-01-09 14:48:29.017 UTC
10
2018-02-21 02:42:12.61 UTC
2011-02-24 04:25:14.733 UTC
null
17,174
null
23,368
null
1
26
javascript|jquery|html
10,737
<p>HTML5 introduces the notion of <a href="https://html.spec.whatwg.org/#embedding-custom-non-visible-data-with-the-data-*-attributes" rel="noreferrer">custom data attributes</a>, that anyone can create in order to attach custom, hidden data to elements for scripting purposes. Just create an attribute using a <code>data-</code> prefix, such as <code>data-myattr1</code> or <code>data-myattr2</code>, and fill it with your data.</p> <pre><code>&lt;div data-myattr1="myvalue1" data-myattr2="myvalue2"&gt;Content&lt;/div&gt; </code></pre> <p>The nice thing about this solution is that it already works in all major browsers; they will all parse unknown attributes, and expose them in the DOM for access by JavaScript. HTML5 adds a few convenience mechanisms for accessing them, which haven't been implemented yet, but you can just use the standard <a href="https://developer.mozilla.org/En/DOM/Element.getAttribute" rel="noreferrer"><code>getAttribute</code></a> to access them for now. And the fact that they are allowed in HTML5 means that your code will validate, as long as you're willing to use a draft standard as opposed to an accepted one (I don't believe the <code>data-</code> attributes are particularly controversial, however, so I'd be surprised if they were removed from the standard).</p> <p>The advantage this has over namespaced attributes in XHTML is the IE doesn't support XHTML, so you would have to implement something that pretends to use namespace attributes but actually just uses invalid attributes with a <code>:</code> in their name, which is how IE would parse them. It's nicer than using <code>class</code>, because putting lots of data into a <code>class</code> attribute overloads it quite a lot, and involves having to do extra parsing to pull out different pieces of data. And it's better than just making up your own (which will work in current browsers), because it's well defined that these attributes prefixed with <code>data-</code> are private pieces of data for scripting, and so your code will validate in HTML5 and won't ever conflict with future standards.</p> <p>Another little-known technique for adding custom data to HTML, which is valid even in HTML 4, is adding <code>script</code> elements with <code>type</code> attributes of something other than <code>text/javascript</code> (or one of the couple of other types that can be used to specify JavaScript). These script blocks will be ignored by browsers that don't know what to with them, and you can access them via the DOM and do what you want with them. HTML5 <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#script" rel="noreferrer">explicitly discusses this usage</a>, but there's nothing that makes it invalid in older versions, and it works in all modern browsers as far as I know. For example, if you would like to use CSV to define a table of data:</p> <pre><code>&lt;div&gt; &lt;script type="text/csv;header=present"&gt; id,myattr1,myattr2 something,1,2 another,2,4 &lt;/script&gt; Content &lt;/div&gt; </code></pre> <p>This is the technique used by <a href="http://code.google.com/p/svgweb/" rel="noreferrer">SVG Web</a> to allow embedding of SVG in HTML, with emulation via Flash if the browser doesn't support native SVG. Currently, even browsers that do support SVG (Firefox, Safari, Chrome, Opera) don't support it directly inline in HTML, they only support it directly inline in XHTML (because the SVG elements are in a different namespace). SVG Web allows you to put SVG inline in HTML, using a script tag, and it then transforms those elements into the appropriate namespace and adds them to the DOM, so they can be rendered as XHTML. In browsers that don't support SVG, it then also emulates the function of the elements using Flash.</p>
2,016,669
Getting execute permission to xp_cmdshell
<p>I am seeing an error message when trying to execute xp_cmdshell from within a stored procedure.</p> <p>xp_cmdshell <strong>is enabled</strong> on the instance. And <strong>the execute permission was granted</strong> to my user, but I am still seeing the exception.</p> <p>The EXECUTE permission was denied on the object ‘xp_cmdshell’, database ‘mssqlsystemresource’, schema ‘sys’</p> <p>Part of the issue is that this is a shared cluster, and we have a single database on the instance, so we don't have a full range of admin permissions. So I can't go in and grant permissions, and what-not.</p>
2,028,996
6
8
null
2010-01-06 22:13:51.247 UTC
13
2022-03-28 13:46:24.253 UTC
null
null
null
null
245,097
null
1
35
sql-server|database|xp-cmdshell
214,586
<p>For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.</p> <ol> <li><p><strong>Enable the xp_cmdshell procedure</strong></p> <blockquote> <p>Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see &quot;Surface Area Configuration&quot; in SQL Server Books Online.*</p> </blockquote> </li> <li><p><strong>Create a login for the non-sysadmin user that has public access to the master database</strong></p> <blockquote> <p>Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*</p> </blockquote> </li> <li><p><strong>Grant EXEC permission on the xp_cmdshell stored procedure</strong></p> <blockquote> <p>Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*</p> </blockquote> </li> <li><p><strong>Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account</strong></p> <blockquote> <p>Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*</p> </blockquote> </li> </ol> <p>It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.</p>
1,484,143
Scope Chain in Javascript
<p>I've reading scope chain in Javascript but it didn't make any sense to me, could any one tell me what is scope chain and how it works with a graphic or something even an idiot can understand. I googled it but I didn't find something comprehensible :(</p>
1,484,230
6
0
null
2009-09-27 18:38:09.607 UTC
42
2019-07-25 19:34:58.893 UTC
2019-07-25 19:34:58.893 UTC
null
5,291,477
null
44,852
null
1
67
javascript|scope-chain
35,267
<p>To understand the scope chain you must know how closures work.</p> <p>A closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.</p> <p>JavaScript resolves identifiers within a particular context by traversing up the scope chain, moving from locally to globally.</p> <p>Consider this example with three nested functions:</p> <pre><code>var currentScope = 0; // global scope (function () { var currentScope = 1, one = 'scope1'; alert(currentScope); (function () { var currentScope = 2, two = 'scope2'; alert(currentScope); (function () { var currentScope = 3, three = 'scope3'; alert(currentScope); alert(one + two + three); // climb up the scope chain to get one and two }()); }()); }()); </code></pre> <p>Recommended reads:</p> <ul> <li><a href="http://jibbering.com/faq/faq_notes/closures.html" rel="noreferrer">JavaScript Closures</a></li> <li><a href="http://ejohn.org/apps/learn/#48" rel="noreferrer">Closures</a></li> </ul>
2,152,742
Java swing: Multiline labels?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/685521/multiline-text-in-jlabel">Multiline text in JLabel</a> </p> </blockquote> <p>I want to do this:</p> <pre><code>JLabel myLabel = new JLabel(); myLabel.setText("This is\na multi-line string"); </code></pre> <p>Currently this results in a label that displays</p> <pre><code>This isa multi-line string </code></pre> <p>I want it to do this instead:</p> <pre><code>This is a multi-line string </code></pre> <p>Any suggestions?</p> <p>Thank you</p> <hr> <p>EDIT: Implemented solution</p> <p>In body of method:</p> <pre><code>myLabel.setText(convertToMultiline("This is\na multi-line string")); </code></pre> <p>Helper method:</p> <pre><code>public static String convertToMultiline(String orig) { return "&lt;html&gt;" + orig.replaceAll("\n", "&lt;br&gt;"); } </code></pre>
2,152,787
7
1
null
2010-01-28 06:33:55.73 UTC
7
2022-07-15 14:55:04.623 UTC
2017-05-23 12:10:19.847 UTC
null
-1
null
194,982
null
1
56
java|string|swing|multiline|jlabel
70,432
<p>You can use <code>HTML</code> in <code>JLabels</code>. To use it, your text has to start with <code>&lt;html&gt;</code>.</p> <p>Set your text to <code>"&lt;html&gt;This is&lt;br&gt;a multi-line string"</code> and it should work.</p> <p>See <a href="http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JLabel.html" rel="noreferrer">Swing Tutorial: JLabel</a> and <a href="http://www.java2s.com/Tutorial/Java/0240__Swing/MultilinelabelHTML.htm" rel="noreferrer">Multiline label (HTML)</a> for more information.</p>
1,635,080
Terminate a multi-thread python program
<p>How to make a multi-thread python program response to Ctrl+C key event?</p> <p><strong>Edit:</strong> The code is like this:</p> <pre><code>import threading current = 0 class MyThread(threading.Thread): def __init__(self, total): threading.Thread.__init__(self) self.total = total def stop(self): self._Thread__stop() def run(self): global current while current&lt;self.total: lock = threading.Lock() lock.acquire() current+=1 lock.release() print current if __name__=='__main__': threads = [] thread_count = 10 total = 10000 for i in range(0, thread_count): t = MyThread(total) t.setDaemon(True) threads.append(t) for i in range(0, thread_count): threads[i].start() </code></pre> <p>I tried to remove join() on all threads but it still doesn't work. Is it because the lock segment inside each thread's run() procedure?</p> <p><strong>Edit:</strong> The above code is supposed to work but it always interrupted when current variable was in 5,000-6,000 range and through out the errors as below</p> <pre><code>Exception in thread Thread-4 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner File "test.py", line 20, in run &lt;type 'exceptions.TypeError'&gt;: unsupported operand type(s) for +=: 'NoneType' and 'int' Exception in thread Thread-2 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner File "test.py", line 22, in run </code></pre>
1,635,084
7
1
null
2009-10-28 03:41:20.99 UTC
13
2022-05-16 07:47:09.17 UTC
2009-10-29 07:09:12.837 UTC
null
192,767
null
192,767
null
1
73
python|multithreading
91,469
<p>Make every thread except the main one a daemon (<code>t.daemon = True</code> in 2.6 or better, <code>t.setDaemon(True)</code> in 2.6 or less, for every thread object <code>t</code> before you start it). That way, when the main thread receives the KeyboardInterrupt, if it doesn't catch it or catches it but decided to terminate anyway, the whole process will terminate. See <a href="http://docs.python.org/library/threading.html?highlight=daemon#threading.Thread.daemon" rel="noreferrer">the docs</a>.</p> <p><strong>edit</strong>: having just seen the OP's code (not originally posted) and the claim that "it doesn't work", it appears I have to add...:</p> <p>Of course, if you want your main thread to stay responsive (e.g. to control-C), don't mire it into blocking calls, such as <code>join</code>ing another thread -- especially not totally <em>useless</em> blocking calls, such as <code>join</code>ing <strong>daemon</strong> threads. For example, just change the final loop in the main thread from the current (utterless and damaging):</p> <pre><code>for i in range(0, thread_count): threads[i].join() </code></pre> <p>to something more sensible like:</p> <pre><code>while threading.active_count() &gt; 0: time.sleep(0.1) </code></pre> <p>if your main has nothing better to do than either for all threads to terminate on their own, or for a control-C (or other signal) to be received.</p> <p>Of course, there are many other usable patterns if you'd rather have your threads not terminate abruptly (as daemonic threads may) -- unless <em>they</em>, too, are mired forever in unconditionally-blocking calls, deadlocks, and the like;-).</p>
2,095,520
Fighting client-side caching in Django
<p>I'm using the render_to_response shortcut and don't want to craft a specific Response object to add additional headers to prevent client-side caching.</p> <p>I'd like to have a response that contains: </p> <ul> <li>Pragma: no-cache</li> <li>Cache-control : no-cache</li> <li>Cache-control: must-revalidate</li> </ul> <p>And all the other nifty ways that browsers will hopefully interpret as directives to avoid caching.</p> <p>Is there a no-cache middleware or something similar that can do the trick with minimal code intrusion?</p>
2,095,648
7
0
null
2010-01-19 17:29:51.777 UTC
22
2020-04-15 09:30:48.613 UTC
null
null
null
null
192,337
null
1
77
django|caching
38,627
<p>You can achieve this using the cache_control decorator. Example from the <a href="https://docs.djangoproject.com/en/3.0/topics/cache/#controlling-cache-using-other-headers" rel="noreferrer">documentation</a>:</p> <pre><code>from django.views.decorators.cache import never_cache @never_cache def myview(request): # ... </code></pre>
1,388,072
Disable Enable Trigger SQL server for a table
<p>I want to create one proc like below but it has error on syntax. Could anyone pointing out the problem?</p> <pre><code>Create PROCEDURE [dbo].[my_proc] AS BEGIN DISABLE TRIGGER dbo.tr_name ON dbo.table_name -- some update statement ENABLE TRIGGER dbo.tr_name ON dbo.table_name END ** Error Message : Incorrect syntax near 'ENABLE'. </code></pre>
1,388,097
9
0
null
2009-09-07 07:47:36.763 UTC
24
2021-05-24 22:07:43.48 UTC
2018-10-29 20:11:01.527 UTC
null
2,862
null
52,727
null
1
140
sql-server|triggers
215,873
<p>use the following commands instead:</p> <pre><code>ALTER TABLE table_name DISABLE TRIGGER tr_name ALTER TABLE table_name ENABLE TRIGGER tr_name </code></pre>
2,205,353
Why doesn't this reinterpret_cast compile?
<p>I understand that <code>reinterpret_cast</code> is dangerous, I'm just doing this to test it. I have the following code:</p> <pre><code>int x = 0; double y = reinterpret_cast&lt;double&gt;(x); </code></pre> <p>When I try to compile the program, it gives me an error saying</p> <blockquote> <p>invalid cast from type 'float' to type 'double</p> </blockquote> <p>What's going on? I thought <code>reinterpret_cast</code> was the rogue cast that you could use to convert apples to submarines, why won't this simple cast compile?</p>
2,205,394
11
4
null
2010-02-05 06:10:04.383 UTC
20
2021-03-07 09:22:30.097 UTC
2018-10-12 12:59:01.907 UTC
null
1,671,066
null
139,117
null
1
79
c++|casting|reinterpret-cast
50,965
<p>Perhaps a better way of thinking of <code>reinterpret_cast</code> is the rouge operator that can &quot;convert&quot; <em>pointers</em> to apples as <em>pointers</em> to submarines.</p> <p>By assigning y to the value returned by the cast you're not really casting the value <code>x</code>, you're converting it. That is, <code>y</code> doesn't point to <code>x</code> and pretend that it points to a float. Conversion constructs a new value of type <code>float</code> and assigns it the value from <code>x</code>. There are several ways to do this conversion in C++, among them:</p> <pre><code>int main() { int x = 42; float f = static_cast&lt;float&gt;(x); float f2 = (float)x; float f3 = float(x); float f4 = x; return 0; } </code></pre> <p>The only real difference being the last one (an implicit conversion) will generate a compiler diagnostic on higher warning levels. But they all do functionally the same thing -- and in many case <em>actually</em> the same thing, as in the same machine code.</p> <p>Now if you really do want to pretend that <code>x</code> is a float, then you really do want to cast <code>x</code>, by doing this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int x = 42; float* pf = reinterpret_cast&lt;float*&gt;(&amp;x); (*pf)++; cout &lt;&lt; *pf; return 0; } </code></pre> <p>You can see how dangerous this is. In fact, the output when I run this on my machine is <code>1</code>, which is decidedly not 42+1.</p>
1,344,015
What is a predicate?
<p>Being a hobbyist coder, I'm lacking some fundamental knowledge. For the last couple days I've been reading some stuff and the word "predicate" keeps reappearing. I'd very much appreciate an explanation on the subject.</p>
1,344,021
12
3
null
2009-08-27 22:09:59.537 UTC
21
2021-08-02 16:34:01.49 UTC
2016-07-25 12:35:42.633 UTC
null
759,866
null
142,168
null
1
83
language-agnostic
27,122
<p>The definition of a predicate, which can be found online in various sources such as <a href="https://books.google.co.uk/books?id=nT8ABwAAQBAJ&amp;pg=PT60&amp;lpg=PT60" rel="noreferrer">here</a>, is:</p> <blockquote> <p>A logical expression which evaluates to TRUE or FALSE, normally to direct the execution path in code.</p> </blockquote> <p>Referencing: <a href="https://books.google.co.uk/books?id=nT8ABwAAQBAJ" rel="noreferrer">Software Testing. By Mathew Hayden</a></p>
1,526,794
Rename master branch for both local and remote Git repositories
<p>I have the branch <code>master</code> which tracks the remote branch <code>origin/master</code>.</p> <p>I want to rename them to <code>master-old</code> both locally and on the remote. Is this possible? </p> <p>For other users who tracked <code>origin/master</code> (and who always updated their local <code>master</code> branch via <code>git pull</code>), what would happen after I renamed the remote branch?<br> Would their <code>git pull</code> still work or would it throw an error that it couldn't find <code>origin/master</code> anymore?</p> <p>Then, further on, I want to create a new <code>master</code> branch (both locally and remote). Again, after I did this, what would happen now if the other users do <code>git pull</code>?</p> <p>I guess all this would result in a lot of trouble. Is there a clean way to get what I want? Or should I just leave <code>master</code> as it is and create a new branch <code>master-new</code> and just work there further on?</p>
1,527,004
16
7
null
2009-10-06 16:51:57.323 UTC
287
2021-05-28 15:48:47.387 UTC
2020-04-17 18:24:58.373 UTC
user456814
806,202
null
133,374
null
1
873
git|git-branch|git-pull
313,826
<p>The closest thing to renaming is deleting and then recreating on the remote. For example:</p> <pre class="lang-bash prettyprint-override"><code>git branch -m master master-old git push remote :master # Delete master git push remote master-old # Create master-old on remote git checkout -b master some-ref # Create a new local master git push remote master # Create master on remote </code></pre> <p>However, this has a lot of caveats. First, no existing checkouts will know about the rename - Git does <em>not</em> attempt to track branch renames. If the new <code>master</code> doesn't exist yet, <em>git pull</em> will error out. If the new <code>master</code> has been created. the pull will attempt to merge <code>master</code> and <code>master-old</code>. So it's generally a bad idea unless you have the cooperation of everyone who has checked out the repository previously.</p> <p>Note: Newer versions of Git will not allow you to delete the master branch remotely by default. You can override this by setting the <code>receive.denyDeleteCurrent</code> configuration value to <code>warn</code> or <code>ignore</code> on the <em>remote</em> repository. Otherwise, if you're ready to create a new master right away, skip the <code>git push remote :master</code> step, and pass <code>--force</code> to the <code>git push remote master</code> step. Note that if you're not able to change the remote's configuration, you won't be able to completely delete the master branch!</p> <p>This caveat only applies to the current branch (usually the <code>master</code> branch); any other branch can be deleted and recreated as above.</p>
17,818,099
How to check if a file exists before creating a new file
<p>I want to input some contents to a file, but I'd like to check first if a file with the name I wish to create exists. If so, I don't want to create any file, even if the file is empty. </p> <p><strong>My attempt</strong></p> <pre><code>bool CreateFile(char name[], char content[]){ std::ofstream file(name); if(file){ std::cout &lt;&lt; "This account already exists" &lt;&lt; std::endl; return false; } file &lt;&lt; content; file.close(); return true; } </code></pre> <p><strong>Is there any way to do what I want?</strong></p>
17,818,217
9
4
null
2013-07-23 18:24:59.933 UTC
3
2020-11-28 02:54:53.103 UTC
2014-12-21 13:18:25.187 UTC
null
4,172,861
null
459,943
null
1
27
c++|file
107,583
<p>Assuming it is OK that the operation is not atomic, you can do:</p> <pre><code>if (std::ifstream(name)) { std::cout &lt;&lt; "File already exists" &lt;&lt; std::endl; return false; } std::ofstream file(name); if (!file) { std::cout &lt;&lt; "File could not be created" &lt;&lt; std::endl; return false; } ... </code></pre> <p>Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have <a href="http://en.wikipedia.org/wiki/Time_of_check_to_time_of_use">TOCTUI</a> problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable]. </p> <p>A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file. </p> <p>In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach. </p>
18,091,324
Regex to match all us phone number formats
<p>First of all i would say i have seen many example here and googled but none found that matches all the condition i am looking for some match top 3 not below some inbetween. Kindly let me know how to put all of them in one place.</p> <pre><code>(xxx)xxxxxxx (xxx) xxxxxxx (xxx)xxx-xxxx (xxx) xxx-xxxx xxxxxxxxxx xxx-xxx-xxxxx </code></pre> <p>Using as :</p> <pre><code> const string MatchPhonePattern = @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}"; Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); // Find matches. MatchCollection matches = rx.Matches(text); // Report the number of matches found. int noOfMatches = matches.Count; // Report on each match. foreach (Match match in matches) { tempPhoneNumbers= match.Value.ToString(); ; } </code></pre> <p>SAMPLE OUTPUT:</p> <pre><code>3087774825 (281)388-0388 (281)388-0300 (979) 778-0978 (281)934-2479 (281)934-2447 (979)826-3273 (979)826-3255 1334714149 (281)356-2530 (281)356-5264 (936)825-2081 (832)595-9500 (832)595-9501 281-342-2452 1334431660 </code></pre>
18,091,377
9
0
null
2013-08-06 22:03:10.973 UTC
10
2022-03-28 04:42:46.027 UTC
2013-08-06 23:01:49.61 UTC
null
1,133,359
null
1,133,359
null
1
23
c#|regex|visual-studio
103,331
<p><code>\(?\d{3}\)?-? *\d{3}-? *-?\d{4}</code></p>
6,397,817
Color spaces, gamma and image enhancement
<p><em>Color space</em>. Well, everybody knows about RGB: three values normalized in the range [0.0,1.0], which have the meaning of the intensity of the color components Red Green Blue; this intensity is meant as linear, isn't?</p> <p><em>Gamma</em>. As far I can understand, gamma is a function which maps RGB color components to another value. Googling on this, I've seen linear functions and non linear functions... Linear functions seems to scale RGB components, so it seems to tune image brightness; non linear functions seems to "decompress" darker/lighter components.</p> <p>Now, I'm starting to implement an image viewer, which shall display different image formats as texture. I'd like to modify the gamma of these images, so I should build up a fragment shader and run over the textured quad. Fine, but how do I determine the right gamma correction?</p> <p>OpenGL works using linear RGB color space, using floating point components. Indeed, I could compute gamma-corrected values starting from those values (with special floating point precision), so they are displayed after having clamped the gamma-corrected value.</p> <p>First, I shall determine the gamma ramp. How could I determine it? (analitically or using lookup tables)</p> <p>Then, I came up to investigate on the OpenGL extension EXT_framebuffer_sRGB, which seems very related with the extension <a href="http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt" rel="noreferrer">EXT_texture_sRGB</a>.</p> <p>EXT_texture_sRGB introduce a new texture format which is used to linearize textel values into RGB linear space. (footnote 1) In this way, I'm aware of sRGB color space and use it as linear RGB color space.</p> <p>Instead, EXT_framebuffer_sRGB extension allows me to encode linear RGB values onto the sRGB framebuffer, without worrying about it.</p> <p>...</p> <p>Wait, all this information for what? If I can use sRGB framebuffer and load sRGB textures, process that textures without sRGB conversions... why should I correct gamma?</p> <p>Maybe can I correct gamma all the same, even on a sRGB buffer? Or I better not? And brightness and contrast: shall they applied before or after gamma correction?</p> <p>That's a lot of information, I'm getting confused now. Hope that someone of you can explain me more all these concepts! Thank you.</p> <p>...</p> <p>There's another question. In the case the device gamma is different from the "standard" 2.2, how do I "accumulate" different gamma corrections? I don't know if it is clear: in the case image RGB values are already corrected for a monitor with a gamma value of 2.2, but the monitor has a gamma of value 2.8, how to I correct gamma?</p> <hr> <p>(1) Here is some extract to highlight what I mean:</p> <blockquote> <p>The sRGB color space is based on typical (non-linear) monitor characteristics expected in a dimly lit office. It has been standardized by the International Electrotechnical Commission (IEC) as IEC 61966-2-1. The sRGB color space roughly corresponds to 2.2 gamma correction.</p> </blockquote> <p><br></p> <blockquote> <p>Does this extension provide any sort of sRGB framebuffer formats or guarantee images rendered with sRGB textures will "look good" when output to a device supporting an sRGB color space?</p> <pre><code> RESOLVED: No. Whether the displayed framebuffer is displayed to a monitor that faithfully reproduces the sRGB color space is beyond the scope of this extension. This involves the gamma correction and color calibration of the physical display device. With this extension, artists can author content in an sRGB color space and provide that sRGB content for use as texture imagery that can be properly converted to linear RGB and filtered as part of texturing in a way that preserves the sRGB distribution of precision, but that does NOT mean sRGB pixels are output to the framebuffer. Indeed, this extension provides texture formats that convert sRGB to linear RGB as part of filtering. With programmable shading, an application could perform a linear RGB to sRGB conversion just prior to emitting color values from the shader. Even so, OpenGL blending (other than simple modulation) will perform linear math operations on values stored in a non-linear space which is technically incorrect for sRGB-encoded colors. One way to think about these sRGB texture formats is that they simply provide color components with a distribution of values distributed to favor precision towards 0 rather than evenly distributing the precision with conventional non-sRGB formats such as GL_RGB8. </code></pre> </blockquote>
6,397,924
3
1
null
2011-06-18 17:52:35.113 UTC
13
2019-06-21 10:06:20 UTC
2011-06-18 17:58:04.117 UTC
null
161,554
null
161,554
null
1
14
opengl|rgb|gamma|srgb|gamma-distribution
10,980
<p>Unfortunately OpenGL by itself doesn't define a colour space. It's just defined that the RGB values passed to OpenGL form a linear vector space. The values of the rendered framebuffer are then sent to the display device as they are. OpenGL just passes through the value.</p> <p>Gamma services two purposes:</p> <ul> <li>Sensory perception is nonlinear</li> <li>In the old days, display devices had a nonlinear response</li> </ul> <p>The gamma correction is used to compensate for both.</p> <p>The transformation is just "linear value V to some power Gamma", i.e. y(v) = v^gamma</p> <p>Colorspace transformations involve the complete chain from input values to whats sent to the display, so this includes the gamma correction. This also implies that you should not manipulate the gamma ramp youself.</p> <p>For a long time the typical Gamma value used to be 2.2. However this caused some undesireable quantisation of low values, so Adobe introduced a new colour space, called sRGB which has a linear part for low values and a powerfunction with exponential ~2.3 for the higher values. Most display devices these days use sRGB. Also most image files these days are in sRGB.</p> <p>So if you have a sRGB image, and display it as-is on a sRGB display device with a linear gamma ramp configured on the device (i.e. video driver gamma=1) you're good by simply using sRGB texturing and framebuffer and not doing anything else.</p> <p><em>EDIT due to comments</em></p> <p>Just to summarize:</p> <ul> <li><p>Use a ARB_framebuffer_sRGB framebuffer, so that the results of the linear OpenGL processing are properly color transformed by the driver <a href="http://www.opengl.org/registry/specs/ARB/framebuffer_sRGB.txt" rel="noreferrer">http://www.opengl.org/registry/specs/ARB/framebuffer_sRGB.txt</a></p></li> <li><p>Linearize all colour inputs to OpenGL</p></li> <li><p>Textures in sRGB colour space should be passed through EXT_texture_sRGB <a href="http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt" rel="noreferrer">http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt</a></p></li> <li><p>Don't gamma correct the output values (the sRGB format framebuffer will take care of this)</p></li> </ul> <p>If your system does not support sRGB framebuffers:</p> <ul> <li><p>Set a linear colour ramp on your display device. </p> <ul> <li>Windows <a href="http://msdn.microsoft.com/en-us/library/ms536529(v=vs.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms536529(v=vs.85).aspx</a> </li> <li>X11 can be done though xgamma <a href="http://www.xfree86.org/current/xgamma.1.html" rel="noreferrer">http://www.xfree86.org/current/xgamma.1.html</a></li> </ul></li> <li><p>create (linear) framebuffer objects, to linear rendering in the framebuffer object. The use of a FBO is, to properly to blending, which only works in linear colour space.</p></li> <li><p>draw the final render result from the FBO to the window using a fragment shader that applies the desired colour (gamma and other) corrections.</p></li> </ul>
6,363,154
What is the difference between numpy.fft and scipy.fftpack?
<p>Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better?</p>
6,363,572
3
2
null
2011-06-15 19:28:04.247 UTC
14
2011-12-12 22:37:44.737 UTC
null
null
null
null
621,944
null
1
68
python|numpy|scipy|fft
45,234
<p>SciPy does more:</p> <ul> <li><a href="http://docs.scipy.org/doc/numpy/reference/routines.fft.html">http://docs.scipy.org/doc/numpy/reference/routines.fft.html</a></li> <li><a href="http://docs.scipy.org/doc/scipy/reference/fftpack.html#">http://docs.scipy.org/doc/scipy/reference/fftpack.html#</a></li> </ul> <p>In addition, SciPy exports some of the NumPy features through its own interface, for example if you execute <em>scipy.fftpack.helper.fftfreq</em> and <em>numpy.fft.helper.fftfreq</em> you're actually running the same code.</p> <p>However, SciPy has its own implementations of much functionality. The source has performance benchmarks that compare the original NumPy and new SciPy versions. My archaic laptop shows something like this:</p> <pre><code> Fast Fourier Transform ================================================= | real input | complex input ------------------------------------------------- size | scipy | numpy | scipy | numpy ------------------------------------------------- 100 | 0.07 | 0.06 | 0.06 | 0.07 (secs for 7000 calls) 1000 | 0.06 | 0.09 | 0.09 | 0.09 (secs for 2000 calls) 256 | 0.11 | 0.11 | 0.12 | 0.11 (secs for 10000 calls) 512 | 0.16 | 0.21 | 0.20 | 0.21 (secs for 10000 calls) 1024 | 0.03 | 0.04 | 0.04 | 0.04 (secs for 1000 calls) 2048 | 0.05 | 0.09 | 0.08 | 0.08 (secs for 1000 calls) 4096 | 0.05 | 0.08 | 0.07 | 0.09 (secs for 500 calls) 8192 | 0.10 | 0.20 | 0.19 | 0.21 (secs for 500 calls) </code></pre> <p>It does seem that SciPy runs significantly faster as the array increases in size, though these are just contrived examples and it would be worth experimenting with both for your particular project.</p> <p>It's worth checking out the source code <a href="http://www.scipy.org/Download#head-312ad78cdf85a9ca6fa17a266752069d23f785d1">http://www.scipy.org/Download#head-312ad78cdf85a9ca6fa17a266752069d23f785d1</a> . Yes those .f files really are Fortran! :-D</p>
6,368,967
Duck typing in the C# compiler
<p><strong>Note</strong> This is <em>not</em> a question about how to implement or emulate duck typing in C#...</p> <p>For several years I was under the impression that certain C# language features were depdendent on data structures defined in the language itself (which always seemed like an odd chicken &amp; egg scenario to me). For example, I was under the impression that the <code>foreach</code> loop was only available to use with types that implemented <code>IEnumerable</code>.</p> <p>Since then I've come to understand that the C# compiler uses duck typing to determine whether an object can be used in a foreach loop, looking for a <code>GetEnumerator</code> method rather than <code>IEnumerable</code>. This makes a lot of sense as it removes the chicken &amp; egg conundrum.</p> <p>I'm a little confused as to why this doesn't seem to be the case with the <code>using</code> block and <code>IDisposable</code>. Is there any particular reason the compiler can't use duck typing and look for a <code>Dispose</code> method? What's the reason for this inconsistency?</p> <p>Perhaps there's something else going on under the hood with IDisposable?</p> <p><em>Discussing why you would <strong>ever</strong> have an object with a Dispose method that didn't implement IDisposable is outside the scope of this question :)</em></p>
6,369,023
3
5
null
2011-06-16 08:18:26.597 UTC
8
2022-06-13 09:12:01.797 UTC
2022-06-13 09:12:01.797 UTC
null
1,879,699
null
522,374
null
1
68
c#|compiler-construction|idisposable|duck-typing
6,809
<p>There's nothing special about <code>IDisposable</code> here - but there <em>is</em> something special about iterators.</p> <p>Before C# 2, using this duck type on <code>foreach</code> was the <em>only</em> way you could implement a strongly-typed iterator, and also the only way of iterating over value types without boxing. I <em>suspect</em> that if C# and .NET had had generics to start with, <code>foreach</code> would have <em>required</em> <code>IEnumerable&lt;T&gt;</code> instead, and not had the duck typing.</p> <p>Now the compiler uses this sort of duck typing in a couple of other places I can think of:</p> <ul> <li>Collection initializers look for a suitable <code>Add</code> overload (as well as the type having to implement <code>IEnumerable</code>, just to show that it really is a collection of some kind); this allows for flexible adding of single items, key/value pairs etc</li> <li>LINQ (<code>Select</code> etc) - this is how LINQ achieves its flexibility, allowing the same query expression format against multiple types, without having to change <code>IEnumerable&lt;T&gt;</code> itself</li> <li>The C# 5 await expressions require <code>GetAwaiter</code> to return an awaiter type which has <code>IsCompleted</code> / <code>OnCompleted</code> / <code>GetResult</code></li> </ul> <p>In both cases this makes it easier to add the feature to existing types and interfaces, where the concept didn't exist earlier on.</p> <p>Given that <code>IDisposable</code> has been in the framework since the very first version, I don't think there would be any benefit in duck typing the <code>using</code> statement. I know you explicitly tried to discount the reasons for having <code>Dispose</code> without implementing <code>IDisposable</code> from the discussion, but I think it's a crucial point. There need to be good reasons to implement a feature in the language, and I would argue that duck typing is a feature above-and-beyond supporting a known interface. If there's no clear benefit in doing so, it won't end up in the language.</p>
18,509,358
How to iterate through XML in Powershell?
<p>I have this XML document in a text file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;Objects&gt; &lt;Object Type="System.Management.Automation.PSCustomObject"&gt; &lt;Property Name="DisplayName" Type="System.String"&gt;SQL Server (MSSQLSERVER)&lt;/Property&gt; &lt;Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState"&gt;Running&lt;/Property&gt; &lt;/Object&gt; &lt;Object Type="System.Management.Automation.PSCustomObject"&gt; &lt;Property Name="DisplayName" Type="System.String"&gt;SQL Server Agent (MSSQLSERVER)&lt;/Property&gt; &lt;Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState"&gt;Stopped&lt;/Property&gt; &lt;/Object&gt; &lt;/Objects&gt; </code></pre> <p>I want to iterate through each object and find the <code>DisplayName</code> and <code>ServiceState</code>. How would I do that? I've tried all kinds of combinations and am struggling to work it out.</p> <p>I'm doing this to get the XML into a variable:</p> <p><code>[xml]$priorServiceStates = Get-Content $serviceStatePath;</code></p> <p>where <code>$serviceStatePath</code> is the xml file name shown above. I then thought I could do something like:</p> <pre><code>foreach ($obj in $priorServiceStates.Objects.Object) { if($obj.ServiceState -eq "Running") { $obj.DisplayName; } } </code></pre> <p>And in this example I would want a string outputted with <code>SQL Server (MSSQLSERVER)</code></p>
18,509,715
2
1
null
2013-08-29 11:10:58.533 UTC
7
2019-01-22 18:18:57.117 UTC
2017-08-11 07:00:52.227 UTC
null
1,772,150
null
38,211
null
1
42
xml|powershell
121,173
<p>PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.</p> <pre class="lang-sh prettyprint-override"><code>[xml]$xml = Get-Content $serviceStatePath $nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml $nodes | ForEach-Object {$_.Node.'#text'} </code></pre> <p>Or shorter</p> <pre class="lang-sh prettyprint-override"><code>[xml]$xml = Get-Content $serviceStatePath Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml | % {$_.Node.'#text'} </code></pre>
5,587,485
Dynamically loading partial view
<p>For a project I need a dynamic way of loading partial views, preferably by jquery / ajax.</p> <p>Here's the functionality I require:</p> <ul> <li>User enters form. A dropdownlist is shown and a generic partial view is rendered with some input controls.</li> <li>User selects a different value in the dropdown</li> <li>The partial view refreshes. Based on the value of the dropdown, it should load the partial view. Some values have custom views associated with them (I could name them with the primary key for instance), others don't. When there's no custom view; it should load the default. When there is one, it should of course load the custom one.</li> </ul> <p>And this should all be ajaxified when possible.</p> <p>I have read some things about dynamically loading partials, but I wanted to repost the complete case so I can find the best solution for this specific case.</p>
5,587,580
2
0
null
2011-04-07 20:50:35.387 UTC
10
2013-02-14 20:28:01.027 UTC
null
null
null
null
122,036
null
1
12
asp.net-mvc|asp.net-mvc-3
15,722
<p>Assuming you have a dropdown:</p> <pre><code>@Html.DropDownListFor( x =&gt; x.ItemId, new SelectList(Model.Items, "Value", "Text"), new { id = "myddl", data_url = Url.Action("Foo", "SomeController") } ) </code></pre> <p>you could subscribe for the <code>.change()</code> event of this dropdown and send an AJAX request to a controller action which will return a partial and inject the result into the DOM:</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $('#myddl').change(function() { var url = $(this).data('url'); var value = $(this).val(); $('#result').load(url, { value: value }) }); }); &lt;/script&gt; </code></pre> <p>And place a DIV tag where you want the partial view to render in your host view:</p> <pre><code>&lt;div id="result"&gt;&lt;/div&gt; </code></pre> <p>and inside the Foo action you could return a partial view:</p> <pre><code>public ActionResult Foo(string value) { SomeModel model = ... return PartialView(model); } </code></pre>
5,157,853
Hibernate: How to use cascade in annotation?
<h2>How can I use cascade and annotations in hibernate?</h2> <p>But I stay with a doubt:</p> <p>I have this situation:</p> <pre><code>public class Package(){ @OneToOne(cascade=CascadeType.PERSIST) private Product product; @OneToOne(cascade=CascadeType.PERSIST) private User user; .. } </code></pre> <p>When I try to <code>session.save(package)</code>, an error occurs. I don't want to save product and package. I just want to initialize and set them into my package object.</p> <p>Is that possible?</p>
5,157,891
2
6
null
2011-03-01 17:12:35.413 UTC
4
2018-09-27 19:45:02.883 UTC
2018-09-27 19:45:02.883 UTC
null
7,109,437
null
523,168
null
1
13
java|hibernate|cascade
67,994
<p>See the <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-cascade">hibernate documentation</a> which is very clear on this issue. For instance you could use e.g., </p> <pre><code>@Cascade(CascadeType.PERSIST) private List&lt;Object&gt; obj; </code></pre> <p>or</p> <pre><code>@OneToMany(cascade = CascadeType.PERSIST) private List&lt;Object&gt; obj; </code></pre>
5,224,827
Generate a migration file from schema.rb
<p>I'm looking to generate a migration file from the schema.rb. is it possible? </p> <p>I have many migration files at the moment and would like to combine everything into one master migration file.</p> <p>I also think i may have accidentally deleted a migration file at some point.</p> <p>thanks for any help</p>
5,224,939
2
1
null
2011-03-07 20:24:30.55 UTC
9
2011-10-02 23:08:00.12 UTC
null
null
null
null
388,458
null
1
34
ruby-on-rails|ruby|ruby-on-rails-3|migration
15,707
<p>There's no need to do this. For new installations you should be running <code>rake db:schema:load</code>, not <code>rake db:migrate</code>, this will load the schema into the database, which is faster than running all the migrations.</p> <p>You should never delete migrations, and certainly not combine them. As for accidentally deleting one, you should be using a <a href="http://en.wikipedia.org/wiki/Revision_control" rel="noreferrer">version control system</a>, such as <a href="http://git-scm.org" rel="noreferrer">Git</a>.</p>
5,453,366
create dll file in c#
<p>How can I create a dll file in C#?</p>
5,453,406
2
4
null
2011-03-27 23:59:50.16 UTC
12
2015-06-22 06:52:23.55 UTC
2015-06-22 06:52:23.55 UTC
null
1,670,729
null
616,493
null
1
39
c#|dll
60,324
<p>File menu -> New Project -> choose your Programing language (Visual C#/VB etc.) -> Windows -> Class Library.</p> <p>After the project has been created, make use of Build menu -> Build Solution (or Build [Project Name]) to compile the project.</p> <p>You may find out the dll in the folder: project folder\bin\debug(or release)</p>
104,380
Tips on refactoring an outdated database schema
<p>Being stuck with a legacy database schema that no longer reflects your data model is every developer's nightmare. Yet with all the talk of refactoring code for maintainability I have not heard much of refactoring outdated database schemas. </p> <p>What are some tips on how to transition to a better schema without breaking all the code that relies on the old one? I will propose a specific problem I am having to illustrate my point but feel free to give advice on other techniques that have proven helpful - those will likely come in handy as well.</p> <hr> <p>My example:</p> <p>My company receives and ships products. Now a product receipt and a product shipment have some very different data associated with them so the original database designers created a separate table for receipts and for shipments. </p> <p>In my one year working with this system I have come to the realization that the current schema doesn't make a lick of sense. After all, both a receipt and a shipment are basically a transaction, they each involve changing the amount of a product, at heart only the +/- sign is different. Indeed, we frequently need to find the total amount that the product has changed over a period of time, a problem for which this design is downright intractable. </p> <p>Obviously the appropriate design would be to have a single Transactions table with the Id being a foreign key of either a ReceiptInfo or a ShipmentInfo table. Unfortunately, the wrong schema has already been in production for some years and has hundreds of stored procedures, and thousands of lines of code written off of it. How then can I transition the schema to work correctly?</p>
104,431
8
0
null
2008-09-19 18:36:14.39 UTC
9
2013-01-20 15:38:41.22 UTC
2013-01-20 15:38:41.22 UTC
George Mauer
698,179
George Mauer
5,056
null
1
14
database|refactoring|schema
2,976
<p>Here's a whole catalogue of database refactorings:</p> <p><a href="http://databaserefactoring.com/" rel="noreferrer">http://databaserefactoring.com/</a></p>
870,919
Why are Haskell algebraic data types "closed"?
<p>Correct me if I'm wrong, but it seems like algebraic data types in Haskell are useful in many of the cases where you would use classes and inheritance in OO languages. But there is a big difference: once an algebraic data type is declared, it can not be extended elsewhere. It is "closed". In OO, you can extend already defined classes. For example:</p> <pre><code>data Maybe a = Nothing | Just a </code></pre> <p>There is no way that I can somehow add another option to this type later on without modifying this declaration. So what are the benefits of this system? It seems like the OO way would be much more extensible.</p>
871,002
8
3
null
2009-05-15 21:17:04.267 UTC
22
2015-03-24 19:10:25.603 UTC
2011-04-16 19:42:52.347 UTC
null
83,805
null
83,871
null
1
58
oop|haskell|types|functional-programming|type-systems
8,048
<p>The fact that ADT are closed makes it a lot easier to write total functions. That are functions that always produce a result, for all possible values of its type, eg.</p> <pre><code>maybeToList :: Maybe a -&gt; [a] maybeToList Nothing = [] maybeToList (Just x) = [x] </code></pre> <p>If <code>Maybe</code> were open, someone could add a extra constructor and the <code>maybeToList</code> function would suddenly break.</p> <p>In OO this isn't an issue, when you're using inheritance to extend a type, because when you call a function for which there is no specific overload, it can just use the implementation for a superclass. I.e., you can call <code>printPerson(Person p)</code> just fine with a <code>Student</code> object if <code>Student</code> is a subclass of <code>Person</code>.</p> <p>In Haskell, you would usually use encapsulation and type classes when you need to extent your types. For example:</p> <pre><code>class Eq a where (==) :: a -&gt; a -&gt; Bool instance Eq Bool where False == False = True False == True = False True == False = False True == True = True instance Eq a =&gt; Eq [a] where [] == [] = True (x:xs) == (y:ys) = x == y &amp;&amp; xs == ys _ == _ = False </code></pre> <p>Now, the <code>==</code> function is completely open, you can add your own types by making it an instance of the <code>Eq</code> class.</p> <hr> <p>Note that there has been work on the idea of <a href="http://www.haskell.org/haskellwiki/Extensible_datatypes" rel="noreferrer">extensible datatypes</a>, but that is definitely not part of Haskell yet.</p>
594,852
What is the default height of UITableViewCell?
<p>I thought this information would have been easier to find :-)</p> <p>What is the default height of a UITableViewCell? It looks like 44 pixels, but I'd prefer to be sure.</p>
595,185
8
0
null
2009-02-27 13:57:07.897 UTC
30
2019-05-21 09:55:45.767 UTC
2019-05-15 14:04:13.42 UTC
null
2,272,431
unforgiven3
18,505
null
1
168
ios|iphone|uitableview
61,302
<p>It's 44 pixels. Definitely. I'll never forget that number.</p> <p>44px is also the default height for UIToolbar and UINavigationBar. (Both switch to 32px when autorotated to landscape orientation.)</p>
505,747
Best way to do nested case statement logic in SQL Server
<p>I'm writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.</p> <p>I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?</p> <p>(I am using Microsoft SQL Server, 2005)</p> <hr> <p>A simplified example:</p> <pre><code>SELECT col1, col2, col3, CASE WHEN condition THEN CASE WHEN condition1 THEN CASE WHEN condition2 THEN calculation1 ELSE calculation2 END ELSE CASE WHEN condition2 THEN calculation3 ELSE calculation4 END END ELSE CASE WHEN condition1 THEN CASE WHEN condition2 THEN calculation5 ELSE calculation6 END ELSE CASE WHEN condition2 THEN calculation7 ELSE calculation8 END END END AS 'calculatedcol1', col4, col5 -- etc FROM table </code></pre>
505,760
9
3
null
2009-02-03 01:39:04.123 UTC
69
2022-08-18 06:03:58.003 UTC
2019-07-23 13:26:45.263 UTC
null
13,860
smb
59,587
null
1
217
sql|sql-server|sql-server-2005|select|nested
883,487
<p>You could try some sort of COALESCE trick, eg:</p> <pre> SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... ) </pre>
402,980
How to find the next record after a specified one in SQL?
<p>I'd like to use a single SQL query (in MySQL) to find the record which comes after one that I specify.</p> <p>I.e., if the table has:</p> <pre><code>id, fruit -- ----- 1 apples 2 pears 3 oranges </code></pre> <p>I'd like to be able to do a query like:</p> <pre><code>SELECT * FROM table where previous_record has id=1 order by id; </code></pre> <p>(clearly that's not real SQL syntax, I'm just using pseudo-SQL to illustrate what I'm trying to achieve)</p> <p>which would return:</p> <pre><code>2, pears </code></pre> <p>My current solution is just to fetch all the records, and look through them in PHP, but that's slower than I'd like. Is there a quicker way to do it?</p> <p>I'd be happy with something that returned two rows -- i.e. the one with the specified value and the following row.</p> <p>EDIT: Sorry, my question was badly worded. Unfortunately, my definition of "next" is not based on ID, but on alphabetical order of fruit name. Hence, my example above is wrong, and should return oranges, as it comes alphabetically next after apples. Is there a way to do the comparison on strings instead of ids?</p>
402,985
10
0
null
2008-12-31 13:46:19.88 UTC
6
2018-11-22 01:05:02.16 UTC
2015-11-29 05:24:51.157 UTC
user212218
5,441
Ben
11,522
null
1
21
mysql
71,894
<p>After the question's edit and the simplification below, we can change it to</p> <pre><code>SELECT id FROM table WHERE fruit &gt; 'apples' ORDER BY fruit LIMIT 1 </code></pre>
333,995
How to detect that Python code is being executed through the debugger?
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be passed debug options too.</p>
338,391
10
0
null
2008-12-02 13:58:30.39 UTC
11
2022-04-20 21:38:11.72 UTC
2021-10-06 07:32:42.903 UTC
Ned Batchelder
10,761,353
Steph
11,618
null
1
35
python|debugging
10,077
<p>A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev:</p> <pre><code>import inspect def isdebugging(): for frame in inspect.stack(): if frame[1].endswith("pydevd.py"): return True return False </code></pre> <p>The same should work with pdb by simply replacing <code>pydevd.py</code> with <code>pdb.py</code>. As do3cc suggested, it tries to find the debugger within the stack of the caller.</p> <p>Useful links:</p> <ul> <li><a href="https://docs.python.org/library/pdb.html" rel="noreferrer">The Python Debugger</a></li> <li><a href="https://docs.python.org/library/inspect.html#the-interpreter-stack" rel="noreferrer">The interpreter stack</a></li> </ul>
1,080,556
How can I test Apple Push Notification Service without an iPhone?
<p>Is it possible test the Apple Push Notification Services without an iPhone application? (Creating an emulator on windows?)</p> <p>If isn't, how could I test that? Is there a free sample application compiled to do that?</p> <p>I created the Server provider, but I need test the functionallity.</p>
60,085,404
13
2
null
2009-07-03 19:26:42.343 UTC
28
2022-09-23 14:12:00.96 UTC
2020-10-27 20:46:21.117 UTC
null
5,175,709
null
116,838
null
1
94
ios|testing|apple-push-notifications|ios-simulator
90,896
<h1>Testing push notifications using the Xcode 11.4 iOS Simulator</h1> <p>As of <strong>Xcode 11.4</strong>, it is now possible to simulate push notifications by <strong>dragging and dropping</strong> an <code>.apns</code> file onto the iOS simulator. The <a href="https://developer.apple.com/documentation/xcode_release_notes/xcode_11_4_beta_release_notes/" rel="noreferrer">Xcode 11.4 release notes</a> have the following to say about the new feature:</p> <blockquote> <p>Simulator supports simulating remote push notifications, including background content fetch notifications. In Simulator, <strong>drag and drop an APNs file onto the target simulator</strong>. The file must be a JSON file with a valid Apple Push Notification Service payload, including the <strong>“aps” key</strong>. It must also contain a top-level <strong>“Simulator Target Bundle”</strong> with a string value matching the target application‘s bundle identifier.</p> <p><code>simctl</code> also supports sending simulated push notifications. If the file contains “Simulator Target Bundle” the bundle identifier is not required, otherwise you must provide it as an argument (8164566):</p> <p><code>xcrun simctl push &lt;device&gt; com.example.my-app ExamplePush.apns</code></p> </blockquote> <h2>Example</h2> <p>Here is an example for such an <code>.apns</code> file, targeted towards the system settings app:</p> <pre><code>{ "Simulator Target Bundle": "com.apple.Preferences", "aps": { "alert": "This is a simulated notification!", "badge": 3, "sound": "default" } } </code></pre> <p>Dragging and dropping this onto the target simulator will present the notification and set the badge:</p> <p><a href="https://i.stack.imgur.com/tghUX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/tghUX.jpg" alt="Notification on the iOS simulator"></a></p> <p>Now, to use this for debugging purposes, you only have to <strong>change the <code>Simulator Target Bundle</code> to your own app's identifier</strong> and <strong>adjust the payload</strong> to your debugging needs!</p>
604,864
Print a file, skipping the first X lines, in Bash
<p>I have a very long file which I want to print, skipping the first 1,000,000 lines, for example.</p> <p>I looked into the cat man page, but I did not see any option to do this. I am looking for a command to do this or a simple Bash program.</p>
604,871
13
0
null
2009-03-03 02:19:54.09 UTC
124
2021-12-07 15:37:38.473 UTC
2020-07-23 15:16:26.837 UTC
Chas. Owens
775,954
Eduardo
39,160
null
1
712
linux|bash|printing|skip
567,247
<p>You'll need tail. Some examples: </p> <pre><code>$ tail great-big-file.log &lt; Last 10 lines of great-big-file.log &gt; </code></pre> <p>If you really need to SKIP a particular number of "first" lines, use</p> <pre><code>$ tail -n +&lt;N+1&gt; &lt;filename&gt; &lt; filename, excluding first N lines. &gt; </code></pre> <p>That is, if you want to skip N lines, you start printing line N+1. Example:</p> <pre><code>$ tail -n +11 /tmp/myfile &lt; /tmp/myfile, starting at line 11, or skipping the first 10 lines. &gt; </code></pre> <p>If you want to just see the last so many lines, omit the "+":</p> <pre><code>$ tail -n &lt;N&gt; &lt;filename&gt; &lt; last N lines of file. &gt; </code></pre>
977,105
Ever done a total rewrite of a large C++ application in C#?
<p>I know <a href="http://www.joelonsoftware.com/articles/fog0000000069.html" rel="nofollow noreferrer">Joel says to never do it</a>, and I agree with this in most cases. I do think there are cases where it is justified.</p> <p>We have a large C++ application (around 250,000 total lines of code) that uses a MFC front end and a Windows service as the core components. We are thinking about moving the project to C#.</p> <p>The reasons we are thinking about rewriting are:</p> <ol> <li>Faster development time</li> <li>Use of WCF and other .NET built-in features</li> <li>More consistent operation on various systems</li> <li>Easier 64 bit support</li> <li>Many nice .NET libraries and components out there</li> </ol> <p>Has anyone done a rewrite like this? Was it successful?</p> <hr> <p><strong>EDIT:</strong></p> <p>The project is almost 10 years old now, and we are getting to the point that adding new features we want would be writing significant functionality that .NET already has built-in. </p>
977,138
15
7
null
2009-06-10 17:38:02.853 UTC
18
2019-01-17 15:37:35.173 UTC
2013-08-16 15:42:06.907 UTC
null
1,743,811
null
67,386
null
1
30
c#|c++|mfc
5,587
<p>Have you thought about instead of re writing from scratch you should start to separate out the GUI and back end layer if it is not already, then you can start to write pieces of it in C#.</p> <p>the 250,000 lines were not written overnight they contains hundreds of thousands of man years of effort, so nobody sane enough would suggest to rewrite it all from scratch all at once.</p> <p>The best approach if you guys are intend on doing it is piece by piece. otherwise ask for several years of development effort from your management while no new features are implemented in your existing product (basically stagnating in front of competition)</p>
977,796
Why does Math.Round(2.5) return 2 instead of 3?
<p>In C#, the result of <code>Math.Round(2.5)</code> is 2.</p> <p>It is supposed to be 3, isn't it? Why is it 2 instead in C#?</p>
977,807
15
11
null
2009-06-10 19:51:05.797 UTC
95
2022-03-04 02:23:06.833 UTC
2016-05-18 06:03:59.36 UTC
null
17,034
null
111,265
null
1
463
.net|rounding
320,593
<p>Firstly, this wouldn't be a C# bug anyway - it would be a .NET bug. C# is the language - it doesn't decide how <code>Math.Round</code> is implemented.</p> <p>And secondly, no - if you read <a href="http://msdn.microsoft.com/en-us/library/wyk4d9cy.aspx" rel="noreferrer">the docs</a>, you'll see that the default rounding is "round to even" (banker's rounding):</p> <blockquote> <p><strong>Return Value</strong><br />Type: System.Double<br/>The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. Note that this method returns a <code>Double</code> instead of an integral type.</p> <p><strong>Remarks</strong><br />The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.</p> </blockquote> <p>You can specify how <code>Math.Round</code> should round mid-points using <a href="http://msdn.microsoft.com/en-us/library/ef48waz8.aspx" rel="noreferrer">an overload</a> which takes a <a href="http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx" rel="noreferrer"><code>MidpointRounding</code></a> value. There's one overload with a <code>MidpointRounding</code> corresponding to each of the overloads which doesn't have one:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx" rel="noreferrer"><code>Round(Decimal)</code></a> / <a href="http://msdn.microsoft.com/en-us/library/ms131274.aspx" rel="noreferrer"><code>Round(Decimal, MidpointRounding)</code></a></li> <li><a href="http://msdn.microsoft.com/en-us/library/wyk4d9cy.aspx" rel="noreferrer"><code>Round(Double)</code></a> / <a href="http://msdn.microsoft.com/en-us/library/ef48waz8.aspx" rel="noreferrer"><code>Round(Double, MidpointRounding)</code></a></li> <li><a href="http://msdn.microsoft.com/en-us/library/zy06z30k.aspx" rel="noreferrer"><code>Round(Decimal, Int32)</code></a> / <a href="http://msdn.microsoft.com/en-us/library/ms131275.aspx" rel="noreferrer"><code>Round(Decimal, Int32, MidpointRounding)</code></a></li> <li><a href="http://msdn.microsoft.com/en-us/library/75ks3aby.aspx" rel="noreferrer"><code>Round(Double, Int32)</code></a> / <a href="http://msdn.microsoft.com/en-us/library/f5898377.aspx" rel="noreferrer"><code>Round(Double, Int32, MidpointRounding)</code></a></li> </ul> <p>Whether this default was well chosen or not is a different matter. (<code>MidpointRounding</code> was only introduced in .NET 2.0. Before then I'm not sure there was any easy way of implementing the desired behaviour without doing it yourself.) In particular, history has shown that it's not the <em>expected</em> behaviour - and in most cases that's a cardinal sin in API design. I can see <em>why</em> Banker's Rounding is useful... but it's still a surprise to many.</p> <p>You may be interested to take a look at the nearest Java equivalent enum (<a href="http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html" rel="noreferrer"><code>RoundingMode</code></a>) which offers even more options. (It doesn't just deal with midpoints.)</p>
1,147,359
How to decode HTML entities using jQuery?
<p>How do I use jQuery to decode HTML entities in a string?</p>
2,419,664
20
1
null
2009-07-18 11:58:48.007 UTC
105
2021-06-20 13:18:29.11 UTC
2015-07-10 19:56:10.457 UTC
null
1,709,587
null
87,921
null
1
353
javascript|jquery|html
358,755
<blockquote> <p><strong>Security note:</strong> using this answer (preserved in its original form below) may introduce an <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)" rel="noreferrer">XSS vulnerability</a> into your application. <strong>You should not use this answer.</strong> Read <a href="https://stackoverflow.com/a/1395954/1709587">lucascaro's answer</a> for an explanation of the vulnerabilities in this answer, and use the approach from either that answer or <a href="https://stackoverflow.com/a/23596964/1709587">Mark Amery's answer</a> instead.</p> </blockquote> <p>Actually, try</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var encodedStr = "This is fun &amp;amp; stuff"; var decoded = $("&lt;div/&gt;").html(encodedStr).text(); console.log(decoded);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div/&gt;</code></pre> </div> </div> </p>
6,689,876
string.Empty vs null.Which one do you use?
<p>Recently a colleague at work told me not to use <code>string.Empty</code> when setting a string variable but use <code>null</code> as it pollutes the stack?</p> <p>He says don't do </p> <p><code>string myString=string.Empty;</code> but do <code>string mystring=null;</code></p> <p>Does it really matter? I know string is an object so it sort of makes sense.</p> <p>I know is a silly question but what is your view?</p>
6,689,898
5
6
null
2011-07-14 07:33:59.5 UTC
20
2021-01-21 15:00:42.76 UTC
2011-07-14 07:45:23.03 UTC
null
366,904
null
712,923
null
1
86
c#|.net|null|string
72,707
<p><code>null</code> and <code>Empty</code> are very different, and I don't suggest arbitrarily switching between them. But neither has any extra "cost", since <code>Empty</code> is a single fixed reference (you can use it any number of times).</p> <p>There is no "pollution" on the stack caused by a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldsfld.aspx" rel="noreferrer">ldsfld</a> - that concern is.... crazy. Loading a <code>null</code> is arguably <strong><em>marginally</em></strong> cheaper, but could cause null-reference exceptions if you aren't careful about checking the value.</p> <p>Personally, I use neither... If I want an empty string I use <code>""</code> - simple and obvious. Interning means this <em>also</em> has no per-usage overhead.</p> <hr> <p>At the IL level, the difference here between "" and Empty is just ldstr vs ldsfld - but both give the same single interned string reference. Furthermore, in more recent .NET versions the JIT has direct interception of these, yielding the empty string reference <em>without</em> actually doing a static field lookup. Basically, there is exactly no reason to care either way, except readability. I just use "".</p>
6,783,788
button inside href
<p>Is it ok to write like this?</p> <pre><code>&lt;a href="add-lead-new.php" target="rightframe"&gt;&lt;input type="button" value="New booking" /&gt;&lt;/a&gt; </code></pre> <p>The link should look like a button but it should open in the right part of the page. If its wrong, is there any other way to do it? The above code works fine. i just don't know if its the correct way to do it. Thanks</p>
6,783,830
6
1
null
2011-07-21 22:52:20.283 UTC
1
2017-06-24 14:58:12.477 UTC
null
null
null
null
724,584
null
1
3
php|html|button|href
42,507
<p>No, this is not allowed according to the <a href="http://www.w3.org/TR/html5/" rel="noreferrer">HTML5 specification</a>.</p> <ul> <li><a href="http://www.w3.org/TR/html5/the-button-element.html#the-button-element" rel="noreferrer">The <code>&lt;button&gt;</code> element</a> is considered "interactive content".</li> <li><a href="http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element" rel="noreferrer">The <code>&lt;a&gt;</code> element</a> must contain "no interactive content".</li> </ul> <p>The button will probably show up, but since you're violating the specification it may not behave as you want. You should avoid doing this.</p> <hr> <p>The most reliable to way to make a button bring the user to a page is to create a <code>&lt;form&gt;</code> that <code>target</code>s that page, and make the button submit that form.</p> <pre><code>&lt;form action="add-lead-new.php"&gt;&lt;input type="submit" value="New Booking" /&gt;&lt;/form&gt; </code></pre>
6,635,851
Real-world use of X-Macros
<p>I just learned of <a href="http://en.wikibooks.org/wiki/C_Programming/Preprocessor#X-Macros" rel="noreferrer">X-Macros</a>. What real-world uses of X-Macros have you seen? When are they the right tool for the job?</p>
9,384,467
7
2
null
2011-07-09 15:56:16.387 UTC
66
2020-07-16 14:20:05.737 UTC
2016-03-14 23:39:48.243 UTC
null
4,370,109
null
380,331
null
1
83
c|macros|c-preprocessor|x-macros
29,805
<p>I discovered X-macros a couple of years ago when I started making use of function pointers in my code. I am an embedded programmer and I use state machines frequently. Often I would write code like this:</p> <pre><code>/* declare an enumeration of state codes */ enum{ STATE0, STATE1, STATE2, ... , STATEX, NUM_STATES}; /* declare a table of function pointers */ p_func_t jumptable[NUM_STATES] = {func0, func1, func2, ... , funcX}; </code></pre> <p>The problem was that I considered it very error prone to have to maintain the ordering of my function pointer table such that it matched the ordering of my enumeration of states.</p> <p>A friend of mine introduced me to X-macros and it was like a light-bulb went off in my head. Seriously, where have you been all my life x-macros!</p> <p>So now I define the following table:</p> <pre><code>#define STATE_TABLE \ ENTRY(STATE0, func0) \ ENTRY(STATE1, func1) \ ENTRY(STATE2, func2) \ ... ENTRY(STATEX, funcX) \ </code></pre> <p>And I can use it as follows:</p> <pre><code>enum { #define ENTRY(a,b) a, STATE_TABLE #undef ENTRY NUM_STATES }; </code></pre> <p>and</p> <pre><code>p_func_t jumptable[NUM_STATES] = { #define ENTRY(a,b) b, STATE_TABLE #undef ENTRY }; </code></pre> <p>as a bonus, I can also have the pre-processor build my function prototypes as follows:</p> <pre><code>#define ENTRY(a,b) static void b(void); STATE_TABLE #undef ENTRY </code></pre> <p>Another usage is to declare and initialize registers</p> <pre><code>#define IO_ADDRESS_OFFSET (0x8000) #define REGISTER_TABLE\ ENTRY(reg0, IO_ADDRESS_OFFSET + 0, 0x11)\ ENTRY(reg1, IO_ADDRESS_OFFSET + 1, 0x55)\ ENTRY(reg2, IO_ADDRESS_OFFSET + 2, 0x1b)\ ... ENTRY(regX, IO_ADDRESS_OFFSET + X, 0x33)\ /* declare the registers (where _at_ is a compiler specific directive) */ #define ENTRY(a, b, c) volatile uint8_t a _at_ b: REGISTER_TABLE #undef ENTRY /* initialize registers */ #define ENTRY(a, b, c) a = c; REGISTER_TABLE #undef ENTRY </code></pre> <p>My favourite usage however is when it comes to communication handlers</p> <p>First I create a comms table, containing each command name and code:</p> <pre><code>#define COMMAND_TABLE \ ENTRY(RESERVED, reserved, 0x00) \ ENTRY(COMMAND1, command1, 0x01) \ ENTRY(COMMAND2, command2, 0x02) \ ... ENTRY(COMMANDX, commandX, 0x0X) \ </code></pre> <p>I have both the uppercase and lowercase names in the table, because the upper case will be used for enums and the lowercase for function names.</p> <p>Then I also define structs for each command to define what each command looks like:</p> <pre><code>typedef struct {...}command1_cmd_t; typedef struct {...}command2_cmd_t; etc. </code></pre> <p>Likewise I define structs for each command response:</p> <pre><code>typedef struct {...}command1_resp_t; typedef struct {...}command2_resp_t; etc. </code></pre> <p>Then I can define my command code enumeration:</p> <pre><code>enum { #define ENTRY(a,b,c) a##_CMD = c, COMMAND_TABLE #undef ENTRY }; </code></pre> <p>I can define my command length enumeration:</p> <pre><code>enum { #define ENTRY(a,b,c) a##_CMD_LENGTH = sizeof(b##_cmd_t); COMMAND_TABLE #undef ENTRY }; </code></pre> <p>I can define my response length enumeration:</p> <pre><code>enum { #define ENTRY(a,b,c) a##_RESP_LENGTH = sizeof(b##_resp_t); COMMAND_TABLE #undef ENTRY }; </code></pre> <p>I can determine how many commands there are as follows:</p> <pre><code>typedef struct { #define ENTRY(a,b,c) uint8_t b; COMMAND_TABLE #undef ENTRY } offset_struct_t; #define NUMBER_OF_COMMANDS sizeof(offset_struct_t) </code></pre> <p>NOTE: I never actually instantiate the offset_struct_t, I just use it as a way for the compiler to generate for me my number of commands definition.</p> <p>Note then I can generate my table of function pointers as follows:</p> <pre><code>p_func_t jump_table[NUMBER_OF_COMMANDS] = { #define ENTRY(a,b,c) process_##b, COMMAND_TABLE #undef ENTRY } </code></pre> <p>And my function prototypes:</p> <pre><code>#define ENTRY(a,b,c) void process_##b(void); COMMAND_TABLE #undef ENTRY </code></pre> <p>Now lastly for the coolest use ever, I can have the compiler calculate how big my transmit buffer should be.</p> <pre><code>/* reminder the sizeof a union is the size of its largest member */ typedef union { #define ENTRY(a,b,c) uint8_t b##_buf[sizeof(b##_cmd_t)]; COMMAND_TABLE #undef ENTRY }tx_buf_t </code></pre> <p>Again this union is like my offset struct, it is not instantiated, instead I can use the sizeof operator to declare my transmit buffer size.</p> <pre><code>uint8_t tx_buf[sizeof(tx_buf_t)]; </code></pre> <p>Now my transmit buffer tx_buf is the optimal size and as I add commands to this comms handler, my buffer will always be the optimal size. Cool!</p> <p>One other use is to create offset tables: Since memory is often a constraint on embedded systems, I don't want to use 512 bytes for my jump table (2 bytes per pointer X 256 possible commands) when it is a sparse array. Instead I will have a table of 8bit offsets for each possible command. This offset is then used to index into my actual jump table which now only needs to be NUM_COMMANDS * sizeof(pointer). In my case with 10 commands defined. My jump table is 20bytes long and I have an offset table that is 256 bytes long, which is a total of 276bytes instead of 512bytes. I then call my functions like so:</p> <pre><code>jump_table[offset_table[command]](); </code></pre> <p>instead of</p> <pre><code>jump_table[command](); </code></pre> <p>I can create an offset table like so:</p> <pre><code>/* initialize every offset to 0 */ static uint8_t offset_table[256] = {0}; /* for each valid command, initialize the corresponding offset */ #define ENTRY(a,b,c) offset_table[c] = offsetof(offset_struct_t, b); COMMAND_TABLE #undef ENTRY </code></pre> <p>where offsetof is a standard library macro defined in "stddef.h"</p> <p>As a side benefit, there is a very easy way to determine if a command code is supported or not:</p> <pre><code>bool command_is_valid(uint8_t command) { /* return false if not valid, or true (non 0) if valid */ return offset_table[command]; } </code></pre> <p>This is also why in my COMMAND_TABLE I reserved command byte 0. I can create one function called "process_reserved()" which will be called if any invalid command byte is used to index into my offset table.</p>
6,499,012
get the second to last item of an array?
<p>How can I get the last second item in an array?</p> <p>For instance,</p> <pre><code>var fragment = '/news/article-1/' var array_fragment = fragment.split('/'); var pg_url = $(array_fragment).last()[0]; </code></pre> <p>This returns an empty value. But I want to get <code>article-1</code></p> <p>Thanks.</p>
6,499,033
11
1
null
2011-06-27 21:13:04.133 UTC
11
2021-08-02 08:11:51.117 UTC
2011-06-27 21:19:57.783 UTC
null
717,383
null
413,225
null
1
79
javascript|jquery|arrays
127,586
<p>Not everything has to be done using jQuery. </p> <p>In plain old javascript you can do:</p> <pre><code>var pg_url = array_fragment[array_fragment.length - 2] </code></pre> <p>Easier and faster :)</p>