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
4,246,744
Java - How to check value of 'ThreadLocal' variables in Eclipse?
<p>I have couple of <code>ThreadLocal</code>s populated in my web app. And, while remote debugging the webapp, I want to see the value of these <code>ThreadLocal</code> variables in <code>Eclipse</code> (just like the way <code>Eclipse</code> shows other variables in the variables tab in Debug perspective).</p> <p><strong>Any idea how can I view the value of <code>ThreadLocal</code> variables during debugging in <code>Eclipse</code>?</strong></p> <p>Thanks!</p>
4,247,031
3
0
null
2010-11-22 14:59:57.847 UTC
9
2019-03-05 07:06:13.703 UTC
2011-11-19 23:56:01.927 UTC
null
1,502,059
null
133,830
null
1
16
java|eclipse|debugging|thread-local
3,607
<p>In your code you have to place the values into a local variable, which you can see. You should be able to breakpoint where the ThreadLocal is used.</p> <p>The problem is that the debugger's connection is on a different thread to the one you are interested in. Eclipse could have a solution for this, but I don't know what it is.</p>
4,161,175
How do I get the count of attributes that an object has?
<p>I've got a class with a number of attributes, and I need to find a way to get a count of the number of attributes it has. I want to do this because the class reads a CSV file, and if the number of attributes (csvcolumns) is less than the number of columns in the file, special things will need to happen. Here is a sample of what my class looks like:</p> <pre><code> public class StaffRosterEntry : RosterEntry { [CsvColumn(FieldIndex = 0, Name = "Role")] public string Role { get; set; } [CsvColumn(FieldIndex = 1, Name = "SchoolID")] public string SchoolID { get; set; } [CsvColumn(FieldIndex = 2, Name = "StaffID")] public string StaffID { get; set; } } </code></pre> <p>I tried doing this:</p> <pre><code>var a = Attribute.GetCustomAttributes(typeof(StaffRosterEntry)); var attributeCount = a.Count(); </code></pre> <p>But this failed miserably. Any help you could give (links to some docs, or other answers, or simply suggestions) is greatly appreciated!</p>
4,161,224
4
0
null
2010-11-12 02:43:57.28 UTC
5
2014-02-26 10:55:07.197 UTC
null
null
null
null
182,992
null
1
10
c#|.net|attributes
42,415
<p>Since the attributes are on the properties, you would have to get the attributes on each property:</p> <pre><code>Type type = typeof(StaffRosterEntry); int attributeCount = 0; foreach(PropertyInfo property in type.GetProperties()) { attributeCount += property.GetCustomAttributes(false).Length; } </code></pre>
14,564,641
Drop a table in a procedure
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1799128/oracle-if-table-exists">Oracle: If Table Exists</a><br> <a href="https://stackoverflow.com/questions/10838558/drop-table-if-it-exists">Drop table if it exists</a> </p> </blockquote> <p>I'm trying to create this procedure but I get an error.</p> <pre><code>CREATE OR REPLACE PROCEDURE SP_VEXISTABLA(NOMBRE IN VARCHAR2) IS CANTIDAD NUMBER(3); BEGIN SELECT COUNT(*) INTO CANTIDAD FROM ALL_OBJECTS WHERE OBJECT_NAME = NOMBRE; IF (CANTIDAD &gt;0) THEN DROP TABLE NOMBRE; END IF; END; </code></pre> <p>The error is:</p> <blockquote> <p>Error(8,1): PLS-00103: Encountered the symbol "END" when expecting one of the following: ( begin case declare exit for goto if loop mod null pragma raise return select update while with &lt;&lt; continue close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe purge.</p> </blockquote> <p>Do you know what am I doing wrong? </p>
14,565,068
3
4
null
2013-01-28 14:52:25.037 UTC
1
2018-02-26 15:02:32.34 UTC
2017-05-23 12:09:52.14 UTC
null
-1
null
1,981,790
null
1
7
oracle|plsql|oracle11g
45,672
<p>you'd need to change your procedure to:</p> <pre><code>CREATE OR REPLACE PROCEDURE SP_VEXISTABLA(NOMBRE IN VARCHAR2) IS CANTIDAD NUMBER(3); BEGIN SELECT COUNT(*) INTO CANTIDAD FROM USER_TABLES WHERE TABLE_NAME = NOMBRE; IF (CANTIDAD &gt;0) THEN execute immediate 'DROP TABLE ' || NOMBRE; END IF; END; </code></pre>
4,527,213
How to register a legacy typelib (.tlb) on Windows 7?
<p>I have a new PC running Windows 7 and Visual Studio 2010, and need to register a legacy typelib (.tlb) to interface with an existing legacy application. However, regtlib.exe does not seem to be part of Windows 7 (I don't think it was part of Vista either), and regtlibv12.exe, available as part of Visual Studio 2005, seems to have disappeared with Visual Studio 2008 (and certainly Visual Studio 2010).</p> <p>Microsoft forums and knowledge base articles refer to RegAsm.exe. I've tried RegAsm.exe, but that will only create and register a typelib from an existing dll or assembly (which I do not have). I can't believe there is no way to register an existing typelib on Windows 7. Any help would be most appreciated.</p>
4,627,062
4
0
null
2010-12-24 16:10:26.727 UTC
14
2019-01-08 14:26:41.52 UTC
2019-01-08 14:26:41.52 UTC
null
3,195,477
null
553,414
null
1
39
windows-7|typelib|regtlib
102,868
<p>Well, I guess I can answer my own question (and for anyone else who has the same problem):</p> <p>Apparently, regtlibv12.exe is part of Visual Studio 2010 (contrary to what I read on various Microsoft forums), but it is located in the Windows\Microsoft.NET\Framework\v4.0.30139 folder (not the v2.0.50727 folder). Using that executable I was able to successfully register the legacy typelib (.tlb). </p>
4,724,701
RegExp.exec() returns NULL sporadically
<p>I am seriously going crazy over this and I've already spent an unproportionate amount of time on trying to figure out what's going on here. So please give me a hand =)</p> <p>I need to do some RegExp matching of strings in JavaScript. Unfortunately it behaves very strangely. This code:</p> <pre><code>var rx = /(cat|dog)/gi; var w = new Array(&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;, &quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;,&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;,&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;,&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;,&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;,&quot;I have a cat and a dog too.&quot;, &quot;There once was a dog and a cat.&quot;); for (var i in w) { var m = null; m = rx.exec(w[i]); if(m){ document.writeln(&quot;&lt;pre&gt;&quot; + i + &quot;\nINPUT: &quot; + w[i] + &quot;\nMATCHES: &quot; + m.slice(1) + &quot;&lt;/pre&gt;&quot;); }else{ document.writeln(&quot;&lt;pre&gt;&quot; + i + &quot;\n'&quot; + w[i] + &quot;' FAILED.&lt;/pre&gt;&quot;); } } </code></pre> <p>Returns &quot;cat&quot; and &quot;dog&quot; for the first two elements, as it should be, but then some <code>exec()</code>-calls start returning <code>null</code>. I don't understand why.</p> <p>I posted a Fiddle <a href="http://jsfiddle.net/cpak/Wgnns/3/" rel="noreferrer">here</a>, where you can run and edit the code.</p> <p>And so far I've tried this in Chrome and Firefox.</p>
4,724,837
4
2
null
2011-01-18 13:37:46.607 UTC
22
2021-07-03 13:31:24.047 UTC
2021-07-03 13:31:24.047 UTC
null
50,776
null
266,319
null
1
106
javascript|regex
24,497
<p>Oh, here it is. Because you're defining your regex global, it matches first <code>cat</code>, and on the second pass of the loop <code>dog</code>. So, basically you just need to reset your regex (it's internal pointer) as well. Cf. this:</p> <pre><code>var w = new Array("I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too."); for (var i in w) { var rx = /(cat|dog)/gi; var m = null; m = rx.exec(w[i]); if(m){ document.writeln("&lt;p&gt;" + i + "&lt;br/&gt;INPUT: " + w[i] + "&lt;br/&gt;MATCHES: " + w[i].length + "&lt;/p&gt;"); }else{ document.writeln("&lt;p&gt;&lt;b&gt;" + i + "&lt;br/&gt;'" + w[i] + "' FAILED.&lt;/b&gt;&lt;br/&gt;" + w[i].length + "&lt;/p&gt;"); } document.writeln(m); } </code></pre>
4,449,935
integer array static initialization
<p>Which two code fragments correctly create and initialize a static array of int elements? (Choose two.)</p> <p>A.</p> <pre><code>static final int[] a = { 100,200 }; </code></pre> <p>B. </p> <pre><code>static final int[] a; static { a=new int[2]; a[0]=100; a[1]=200; } </code></pre> <p>C.</p> <pre><code>static final int[] a = new int[2]{ 100,200 }; </code></pre> <p>D.</p> <pre><code>static final int[] a; static void init() { a = new int[3]; a[0]=100; a[1]=200; } </code></pre> <p>Answer: A, B</p> <p>here even D seems true, can anyone let me know why D is false.</p>
4,450,001
5
2
null
2010-12-15 12:38:04.363 UTC
2
2015-07-20 14:21:41.433 UTC
2012-11-16 21:18:22.877 UTC
null
992,687
null
516,108
null
1
19
java|arrays|static
63,559
<p>The correct answers are 1 and 2 (or A and B with your notation), and an also correct solution would be:</p> <pre><code>static final int[] a = new int[]{ 100,200 }; </code></pre> <p>Solution D doesn't initalize the array automatically, as the class gets loaded by the runtime. It just defines a static method (init), which you have to call before using the array field.</p>
4,106,764
What is a good way to read line-by-line in R?
<p>I have a file where each line is a set of results collected in specific replicate of an experiment. The number of results in each experiment (i.e. number of columns in each row) may differ. There's also no importance to the order of the results in each row (the first result in row 1 and the first result 2 are not more related than any other pair; these are <em>sets</em> of results).</p> <p>The file looks something like this:</p> <pre><code>2141 0 5328 5180 357 5335 1 5453 5325 5226 7 4880 5486 0 2650 0 5280 4980 5243 5301 4244 5106 5228 5068 5448 3915 4971 5585 4818 4388 5497 4914 5364 4849 4820 4370 2069 2595 2478 4941 2627 3319 5192 5106 32 4666 3999 5503 5085 4855 4135 4383 4770 2005 2117 2803 2722 2281 2248 2580 2697 2897 4417 4094 4722 5138 5004 4551 5758 5468 17361 1914 1977 2414 100 2711 2171 3041 5561 4870 4281 4691 4461 5298 3849 5166 5578 5520 4634 4836 4905 5105 5089 2539 2326 0 4617 3735 0 5122 5439 5238 1 25 5316 21173 4492 5038 5944 5576 5424 5139 5184 5 5096 4963 2771 2808 2592 2 4963 9428 17152 5467 5202 6038 5094 5221 5469 5079 3753 5080 5141 4097 5173 11338 4693 5273 5283 5110 4503 51 2024 2 2822 5097 5239 5296 4561 </code></pre> <p>except each line is much longer (up to a few thousand values). As can be seen, all values are non-negative integers.</p> <p>To put it short - this is not a normal table, where the columns have meanings. Its just a bunch of results - each set in a line.</p> <p>I would like to read all the results, then do some operations on each experiment (row), such as calculating the ecdf. I would also like to calculate the average ecdf over all the replicates.</p> <p>My problem - how should I read this strange looking file? I'm so use to <code>read.table</code> that I'm not sure I ever tried anything else... Do I have to use some low-level like <code>readlines</code>? I guess the preferred output would be a list (or vector?) of vectors. I looked at <code>scan</code> but it seems all vectors must be of the same length there.</p> <p>Any suggestions will be appreciated.</p> <p><strong>UPDATE</strong> Following the suggestions below, I now do something like this:</p> <pre><code>con &lt;- file('myfile') open(con); results.list &lt;- list(); current.line &lt;- 1 while (length(line &lt;- readLines(con, n = 1, warn = FALSE)) &gt; 0) { results.list[[current.line]] &lt;- as.integer(unlist(strsplit(line, split=" "))) current.line &lt;- current.line + 1 } close(con) </code></pre> <p>Seems to work. Does it looks OK?</p> <p>When I <code>summary(results.list)</code> I get:Length Class Mode </p> <pre><code> Length Class Mode [1,] 1091 -none- numeric [2,] 1070 -none- numeric .... </code></pre> <p>Shouldn't the class be integer? And what is the mode?</p>
4,106,976
6
2
null
2010-11-05 14:24:08.813 UTC
27
2015-07-23 13:52:53.19 UTC
2015-07-23 13:52:53.19 UTC
null
24,108
null
377,031
null
1
43
r|input|format
57,246
<p>The example Josh linked to is one that I use all the time. </p> <pre><code>inputFile &lt;- "/home/jal/myFile.txt" con &lt;- file(inputFile, open = "r") dataList &lt;- list() ecdfList &lt;- list() while (length(oneLine &lt;- readLines(con, n = 1, warn = FALSE)) &gt; 0) { myVector &lt;- (strsplit(oneLine, " ")) myVector &lt;- list(as.numeric(myVector[[1]])) dataList &lt;- c(dataList,myVector) myEcdf &lt;- ecdf(myVector[[1]]) ecdfList &lt;- c(ecdfList,myEcdf) } close(con) </code></pre> <p>I edited the example to create two lists from your example data. dataList is a list where each item in the list is a vector of numeric values from each line in your text file. ecdfList is a list where each element is an ecdf for each line in your text file. </p> <p>You should probably add some try() or trycatch() logic in there to properly handle situations where the ecdf can't be created because of nulls or some such. But the above example should get you pretty close. Good luck! </p>
4,281,910
What's the purpose of using & before a function's argument?
<p>I saw some function declarations like this:</p> <pre><code>function boo(&amp;$var){ ... } </code></pre> <p>what does the <code>&amp;</code> character do?</p>
4,281,919
7
0
null
2010-11-26 01:11:33.483 UTC
5
2018-02-23 17:55:46.08 UTC
2016-07-18 10:16:46.853 UTC
null
3,924,118
null
376,947
null
1
38
php|function|variables|reference
16,702
<p>It's a pass by reference. The variable inside the function "points" to the same data as the variable from the calling context.</p> <pre><code>function foo(&amp;$bar) { $bar = 1; } $x = 0; foo($x); echo $x; // 1 </code></pre>
4,228,161
Comparing arrays in JUnit assertions, concise built-in way?
<p>Is there a concise, built-in way to do equals assertions on two like-typed arrays in JUnit? By default (at least in JUnit 4) it seems to do an instance compare on the array object itself.</p> <p>EG, doesn't work:</p> <pre><code>int[] expectedResult = new int[] { 116800, 116800 }; int[] result = new GraphixMask().sortedAreas(rectangles); assertEquals(expectedResult, result); </code></pre> <p>Of course, I can do it manually with:</p> <pre><code>assertEquals(expectedResult.length, result.length); for (int i = 0; i &lt; expectedResult.length; i++) assertEquals("mismatch at " + i, expectedResult[i], result[i]); </code></pre> <p>..but is there a better way?</p>
4,228,468
8
0
null
2010-11-19 18:26:46.343 UTC
17
2021-06-20 09:09:54.79 UTC
2010-11-19 18:59:50.21 UTC
null
63,562
null
63,562
null
1
201
java|arrays|junit|assertions
166,397
<p>Use <a href="http://junit.sourceforge.net/javadoc/org/junit/Assert.html" rel="noreferrer">org.junit.Assert</a>'s method <code>assertArrayEquals</code>:</p> <pre><code>import org.junit.Assert; ... Assert.assertArrayEquals( expectedResult, result ); </code></pre> <p>If this method is not available, you may have accidentally imported the Assert class from <code>junit.framework</code>. </p>
4,189,807
Select rows with min value by group
<p>I got a problems that bugs me for some time… hopefully anybody here can help me.</p> <p>I got the following data frame</p> <pre><code>f &lt;- c('a','a','b','b','b','c','d','d','d','d') v1 &lt;- c(1.3,10,2,10,10,1.1,10,3.1,10,10) v2 &lt;- c(1:10) df &lt;- data.frame(f,v1,v2) </code></pre> <p>f is a factor; v1 and v2 are values. For each level of f, I want only want to keep one row: the one that has the lowest value of v1 in this factor level.</p> <pre><code>f v1 v2 a 1.3 1 b 2 3 c 1.1 6 d 3.1 8 </code></pre> <p>I tried various things with aggregate, ddply, by, tapply… but nothing seems to work. For any suggestions, I would be very thankful. </p>
4,190,259
10
0
null
2010-11-15 23:15:10.967 UTC
12
2021-09-15 18:51:04.983 UTC
2020-05-20 21:01:08.033 UTC
null
1,851,712
null
415,697
null
1
28
r|dataframe
10,481
<p>Using DWin's solution, <code>tapply</code> can be avoided using <code>ave</code>. </p> <pre><code>df[ df$v1 == ave(df$v1, df$f, FUN=min), ] </code></pre> <p>This gives another speed-up, as shown below. Mind you, this is also dependent on the number of levels. I give this as I notice that <code>ave</code> is far too often forgotten about, although it is one of the more powerful functions in R.</p> <pre><code>f &lt;- rep(letters[1:20],10000) v1 &lt;- rnorm(20*10000) v2 &lt;- 1:(20*10000) df &lt;- data.frame(f,v1,v2) &gt; system.time(df[ df$v1 == ave(df$v1, df$f, FUN=min), ]) user system elapsed 0.05 0.00 0.05 &gt; system.time(df[ df$v1 %in% tapply(df$v1, df$f, min), ]) user system elapsed 0.25 0.03 0.29 &gt; system.time(lapply(split(df, df$f), FUN = function(x) { + vec &lt;- which(x[3] == min(x[3])) + return(x[vec, ]) + }) + .... [TRUNCATED] user system elapsed 0.56 0.00 0.58 &gt; system.time(df[tapply(1:nrow(df),df$f,function(i) i[which.min(df$v1[i])]),] + ) user system elapsed 0.17 0.00 0.19 &gt; system.time( ddply(df, .var = "f", .fun = function(x) { + return(subset(x, v1 %in% min(v1))) + } + ) + ) user system elapsed 0.28 0.00 0.28 </code></pre>
4,253,728
Performance cost of 'new' in C#?
<p>In C# what is the performance cost of using the new keyword? I ask specifically in relation to games development, I know in C++ it is a definite no-no to be newing things every update cycle. Does the same apply to C#? I'm using XNA and developing for mobile. Just asking as an optimization question really.</p>
4,253,750
10
3
null
2010-11-23 07:33:03.493 UTC
8
2022-07-18 20:03:50.61 UTC
2013-09-14 19:19:52.093 UTC
null
234,175
null
79,891
null
1
42
c#|performance|xna|new-operator
16,141
<p>There are three parts to the cost of <code>new</code>:</p> <ul> <li>Allocating the memory (may not be required if it's a value type)</li> <li>Running the constructor (depending on what you're doing)</li> <li>Garbage collection cost (again, this may not apply if it's a value type, depending on context)</li> </ul> <p>It's hard to use C# idiomatically without ever creating <em>any</em> new objects in your main code... although I dare say it's feasible by reusing objects as heavily as possible. Try to get hold of some real devices, and see how your game performs.</p> <p>I'd certainly agree that micro-optimization like this is <em>usually</em> to be avoided in programming, but it's more likely to be appropriate for game loops than elsewhere - as obviously games are very sensitive to even small pauses. It can be quite hard to judge the cost of using more objects though, as it's spread out over time due to GC costs.</p> <p>The allocator and garbage collector is pretty good in .NET, although it's likely to be simpler on a device (Windows Phone 7, I assume)? In particular, I'm not sure whether the Compact Framework CLR (which is the one WP7 uses) has a generational GC.</p>
14,479,981
How do I check, if bitmask contains bit?
<p>I don't quite understand this whole bitmask concept.</p> <p>Let's say I have a mask:</p> <pre><code>var bitMask = 8 | 524288; </code></pre> <p>I undestand that this is how I would combine <code>8</code> and <code>524288</code>, and get <code>524296</code>.</p> <p>BUT, how do I go the other way? How do I check my bitmask, to see if it contains <code>8</code> and/or <code>524288</code>?</p> <p>To make it a bit more complex, let's say the bitmask I have is <code>18358536</code> and I need to check if <code>8</code> and <code>524288</code> are in that bitmask. How on earth would I do that?</p>
14,480,058
3
0
null
2013-01-23 12:40:09.23 UTC
3
2019-08-15 20:44:01.41 UTC
null
null
null
null
587,153
null
1
22
c#|bit-manipulation|bitmask
41,457
<p>well</p> <pre><code>if (8 &amp; bitmask == 8 ) { } </code></pre> <p>will check if the bitmask contains 8.</p> <p>more complex</p> <pre><code>int mask = 8 | 12345; if (mask &amp; bitmask == mask) { //true if, and only if, bitmask contains 8 | 12345 } if (mask &amp; bitmask != 0) { //true if bitmask contains 8 or 12345 or (8 | 12345) } </code></pre> <p>may be interested by enum and more particularly <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/system.flagsattribute.aspx" rel="noreferrer">FlagsAttibute</a>.</p>
2,438,396
Asterisk auto Call recording
<p>We are running asterisk with 8 port FXO. FXO connects to our old PBX (Samsung Office Serv 100).</p> <p>Now we want to record all calls routed through FXO (if it was dialed to outside or comming from outside).</p> <p>Is there a simple way to do this?</p>
2,440,144
3
0
null
2010-03-13 12:59:34.087 UTC
9
2022-06-01 16:04:27.593 UTC
2022-06-01 16:04:27.593 UTC
null
1,255,289
null
150,174
null
1
15
asterisk
50,210
<p>Are you running plain Asterisk? If so you can modify your dial plan to start 'monitoring' the channel, which will record the call.</p> <p>The monitor command's documentation: <a href="http://www.voip-info.org/wiki/view/Asterisk+cmd+monitor" rel="noreferrer">http://www.voip-info.org/wiki/view/Asterisk+cmd+monitor</a></p> <p>Just for the sake of completion, here's the documentation:</p> <pre><code>[root@localhost ~]# asterisk -rx 'core show application monitor' -= Info about application 'Monitor' =- [Synopsis] Monitor a channel [Description] Monitor([file_format[:urlbase],[fname_base],[options]]): Used to start monitoring a channel. The channel's input and output voice packets are logged to files until the channel hangs up or monitoring is stopped by the StopMonitor application. file_format optional, if not set, defaults to "wav" fname_base if set, changes the filename used to the one specified. options: m - when the recording ends mix the two leg files into one and delete the two leg files. If the variable MONITOR_EXEC is set, the application referenced in it will be executed instead of soxmix and the raw leg files will NOT be deleted automatically. soxmix or MONITOR_EXEC is handed 3 arguments, the two leg files and a target mixed file name which is the same as the leg file names only without the in/out designator. If MONITOR_EXEC_ARGS is set, the contents will be passed on as additional arguments to MONITOR_EXEC Both MONITOR_EXEC and the Mix flag can be set from the administrator interface b - Don't begin recording unless a call is bridged to another channel i - Skip recording of input stream (disables m option) o - Skip recording of output stream (disables m option) By default, files are stored to /var/spool/asterisk/monitor/. Returns -1 if monitor files can't be opened or if the channel is already monitored, otherwise 0. </code></pre> <p>And here's a sample way you can use it:</p> <pre><code>; This fake context records all outgoing calls to /var/spool/asterisk/monitor in wav format. [fake-outgoing-context] exten =&gt; s,1,Answer() exten =&gt; s,n,Monitor(wav,,b) exten =&gt; s,n,Dial(DAHDI/g0/${EXTEN}) exten =&gt; s,n,Hangup() </code></pre> <p>Obviously you'd have to make changes to my code, but hopefully that gives you a good idea.</p>
2,523,397
Error creating a table : "There is already an object named ... in the database", but not object with that name
<p>I'm trying to create a table on a Microsoft SQL Server 2005 (Express).</p> <p>When i run this query</p> <pre><code>USE [QSWeb] GO /****** Object: Table [dbo].[QSW_RFQ_Log] Script Date: 03/26/2010 08:30:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[QSW_RFQ_Log]( [RFQ_ID] [int] NOT NULL, [Action_Time] [datetime] NOT NULL, [Quote_ID] [int] NULL, [UserName] [nvarchar](256) NOT NULL, [Action] [int] NOT NULL, [Parameter] [int] NULL, [Note] [varchar](255) NULL, CONSTRAINT [QSW_RFQ_Log] PRIMARY KEY CLUSTERED ( [RFQ_ID] ASC, [Action_Time] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre> <p>I got this error message</p> <blockquote> <p>Msg 2714, Level 16, State 4, Line 2 There is already an object named 'QSW_RFQ_Log' in the database. Msg 1750, Level 16, State 0, Line 2 Could not create constraint. See previous errors.</p> </blockquote> <p>but if i try to find the object in question using this query:</p> <pre><code>SELECT * FROM QSWEB.sys.all_objects WHERE upper(name) like upper('QSW_RFQ_%') </code></pre> <p>I got this</p> <blockquote> <p>(0 row(s) affected)</p> </blockquote> <p>What is going on????</p>
2,523,412
3
0
null
2010-03-26 13:08:13.463 UTC
1
2010-03-26 13:13:30.957 UTC
null
null
null
null
275,404
null
1
15
sql|sql-server|sql-server-2005|tsql
44,009
<p>You are trying to create a table with the same name as a constraint (QSW_RFQ_Log). Your query doesn't find the object because the table creation fails so the object doesn't exist after the error. Pick a new name for the constraint and it will work, e.g.:</p> <pre><code>CONSTRAINT [QSW_RFQ_Log_PK] PRIMARY KEY CLUSTERED </code></pre>
2,975,248
How to handle a SIGTERM
<p>Is there a way in Java to handle a received SIGTERM?</p>
2,975,265
3
0
null
2010-06-04 14:53:41.44 UTC
19
2018-07-09 19:38:31.317 UTC
2016-10-11 14:33:50.403 UTC
null
179,850
null
155,137
null
1
87
java|exit|sigterm
53,096
<p>Yes, you can register a shutdown hook with <a href="http://java.sun.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29" rel="noreferrer"><code>Runtime.addShutdownHook()</code></a>.</p>
2,607,067
Can you access the iPhone camera from Mobile Safari?
<p>Is there a JavaScript API for accessing the the iPhone's camera from Mobile Safari?</p>
14,295,860
4
2
null
2010-04-09 11:44:50.34 UTC
13
2020-08-04 15:17:55.463 UTC
null
null
null
null
110,010
null
1
39
javascript|iphone|camera|mobile-safari
56,494
<p>Since <strong>iOS6</strong>, you can use</p> <pre><code>&lt;input type="file" accept="image/*" capture="camera"&gt; &lt;input type="file" accept="video/*" capture="camera"&gt; </code></pre> <p>It will act like a regular file upload, but instead, it will open the iPhone camera and upload a picture or a video.</p> <p>Hope this help someone.</p>
3,183,707
Stripping off the seconds in datetime python
<p>now() gives me </p> <pre><code>datetime.datetime(2010, 7, 6, 5, 27, 23, 662390) </code></pre> <p>How do I get just <code>datetime.datetime(2010, 7, 6, 5, 27, 0, 0)</code> (the datetime object) where everything after minutes is zero?</p>
3,183,720
4
0
null
2010-07-06 05:30:00.95 UTC
13
2021-01-05 06:29:11.833 UTC
2010-07-06 05:35:53.793 UTC
null
197,473
null
197,473
null
1
71
python
75,626
<pre><code>dtwithoutseconds = dt.replace(second=0, microsecond=0) </code></pre> <p><a href="http://docs.python.org/library/datetime.html#datetime.datetime.replace" rel="noreferrer">http://docs.python.org/library/datetime.html#datetime.datetime.replace</a></p>
3,018,633
Insert a datetime value with GetDate() function to a SQL server (2005) table?
<p>I am working (or fixing bugs) on an application which was developed in VS 2005 C#. The application saves data to a SQL server 2005. One of insert SQL statement tries to insert a time-stamp value to a field with GetDate() TSQL function as date time value.</p> <pre><code>Insert into table1 (field1, ... fieldDt) values ('value1', ... GetDate()); </code></pre> <p>The reason to use GetDate() function is that the SQL server may be at a remove site, and the date time may be in a difference time zone. Therefore, GetDate() will always get a date from the server. As the function can be verified in SQL Management Studio, this is what I get:</p> <pre><code>SELECT GetDate(), LEN(GetDate()); -- 2010-06-10 14:04:48.293 19 </code></pre> <p>One thing I realize is that the length is not up to the milliseconds, i.e., 19 is actually for '2010-06-10 14:04:48'. Anyway, the issue I have right now is that after the insert, the fieldDt actually has a date time value up to minutes, for example, '2010-06-10 14:04:00'. I am not sure why. I don't have permission to update or change the table with a trigger to update the field. </p> <p>My question is that how I can use a INSERT T-SQL to add a new row with a date time value ( SQL server's local date time) with a precision up to milliseconds?</p>
3,018,738
5
0
null
2010-06-10 21:22:07.933 UTC
null
2017-01-25 07:21:24.357 UTC
null
null
null
null
62,776
null
1
3
visual-studio|tsql
73,005
<p>Check your table. My guess is that the FieldDT column has a data type of SmallDateTime which stores date and time, but with a precision to the nearest minute. If my guess is correct, you will not be able to store seconds or milliseconds unless you change the data type of the column.</p>
29,652,538
sequelize.js TIMESTAMP not DATETIME
<p>In my node.js app I have several models in which I want to define <code>TIMESTAMP</code> type columns, including the default timestamps <code>created_at</code> and <code>updated_at</code>. </p> <p>According to <a href="http://docs.sequelizejs.com/en/latest/api/datatypes/">sequelize.js' documentation</a>, there is only a <code>DATE</code> data type. It creates <code>DATETIME</code> columns in MySQL.</p> <p>Example:</p> <pre><code>var User = sequelize.define('User', { ... // columns last_login: { type: DataTypes.DATE, allowNull: false }, ... }, { // options timestamps: true }); </code></pre> <p>Is it possible to generate <code>TIMESTAMP</code> columns instead?</p>
39,628,784
6
0
null
2015-04-15 14:09:00.507 UTC
10
2020-05-06 15:14:27.213 UTC
2015-04-15 14:49:07.063 UTC
null
350,478
null
350,478
null
1
39
mysql|node.js|datetime|timestamp|sequelize.js
84,545
<p>Just pass in 'TIMESTAMP' string to your type</p> <pre><code>module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.createTable('users', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, created_at: { type: 'TIMESTAMP', defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false }, updated_at: { type: 'TIMESTAMP', defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: false } }); } }; </code></pre>
32,057,636
How to get a list of all the blobs in a container in Azure?
<p>I have the account name and account key of a storage account in Azure. I need to get a list of all the blobs in a container in that account. (The "$logs" container).</p> <p>I am able to get the information of a specific blob using the CloudBlobClient class but can't figure out how to get a list of all the blobs within the $logs container. </p>
32,057,883
6
0
null
2015-08-17 18:53:13.97 UTC
0
2022-06-25 12:27:14.027 UTC
null
null
null
null
1,647,763
null
1
18
c#|azure|cloud
42,091
<p>There is a sample of how to list all of the blobs in a container at <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/#list-the-blobs-in-a-container" rel="noreferrer">https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/#list-the-blobs-in-a-container</a>:</p> <pre><code>// Retrieve the connection string for use with the application. The storage // connection string is stored in an environment variable on the machine // running the application called AZURE_STORAGE_CONNECTION_STRING. If the // environment variable is created after the application is launched in a // console or with Visual Studio, the shell or application needs to be closed // and reloaded to take the environment variable into account. string connectionString = Environment.GetEnvironmentVariable(&quot;AZURE_STORAGE_CONNECTION_STRING&quot;); // Create a BlobServiceClient object which will be used to create a container client BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); // Get the container client object BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(&quot;yourContainerName&quot;); // List all blobs in the container await foreach (BlobItem blobItem in containerClient.GetBlobsAsync()) { Console.WriteLine(&quot;\t&quot; + blobItem.Name); } </code></pre>
22,738,470
Chrome Extension js: Sharing functions between background.js and popup.js
<p>Suppose I have a JavaScript function <code>foo()</code> which I want to execute in both the background and in <code>popup.html</code>.</p> <p>For example: it is executed every hour in the background of my Chrome extension, but can also be activated by the user from the popup menu (<code>popup.html</code>) on a button click.</p> <p>I currently have a <code>global.js</code> script which defines <code>foo()</code> and when I include calls to <code>foo()</code> in my <code>popup.js</code> document, they execute without issue. (If I include both scripts in <code>popup.html</code>)</p> <p>However, when I try to access <code>foo()</code> inside <code>background.js</code>, the calls do not execute (even if <code>global.js</code> is included in the "background" "manifest.json" extension file:</p> <pre><code>"background": { "persistent": true, "scripts": ["background.js", "global.js"] }, </code></pre> <p>Is there a convenient way to share functions between <code>background.js</code> and <code>popup.js</code> (without copying the entire function into each)?</p>
22,741,922
3
0
null
2014-03-29 23:53:43.23 UTC
9
2016-12-02 19:42:25.49 UTC
2014-03-30 00:03:35.44 UTC
null
2,319,844
null
3,476,946
null
1
14
javascript|google-chrome-extension
7,702
<p>The background scripts are loaded in the order specified in the manifest file. Simply load the file with common code before your background script as follows:</p> <pre><code>"background": { "persistent": true, "scripts": ["global.js", "background.js"] }, </code></pre> <p>Instead of duplicating the code in the popup, you can also use <a href="https://developer.chrome.com/extensions/extension#method-getBackgroundPage" rel="noreferrer"><code>chrome.extension.getBackgroundPage()</code></a> from the popup to access functions/variables of the <a href="https://developer.chrome.com/extensions/background_pages" rel="noreferrer">background page</a>, e.g. <code>chrome.extension.getBackgroundPage().myFunction();</code>.</p>
40,775,709
Avoiding "Too broad exception clause" warning in PyCharm
<p>I'm writing an exception clause at the top level of a script, and I just want it to log whatever errors occur. Annoyingly, PyCharm complains if I just catch <code>Exception</code>.</p> <pre><code>import logging logging.basicConfig() try: raise RuntimeError('Bad stuff happened.') except Exception: # &lt;= causes warning: Too broad exception clause logging.error('Failed.', exc_info=True) </code></pre> <p>Is there something wrong with this handler? If not, how can I tell PyCharm to shut up about it?</p>
40,776,385
4
3
null
2016-11-23 23:16:58.33 UTC
5
2021-08-11 09:31:38.997 UTC
null
null
null
null
4,794
null
1
45
python|exception-handling|pycharm
42,132
<p>From a comment by <a href="https://stackoverflow.com/a/40775710/4794#comment68775868_40775710">Joran</a>: you can use <code># noinspection PyBroadException</code> to tell PyCharm that you're OK with this exception clause. This is what I was originally looking for, but I missed the option to <a href="https://www.jetbrains.com/help/pycharm/2016.1/suppressing-inspections.html" rel="noreferrer">suppress the inspection</a> in the suggestions menu.</p> <pre><code>import logging logging.basicConfig() # noinspection PyBroadException try: raise RuntimeError('Bad stuff happened.') except Exception: logging.error('Failed.', exc_info=True) </code></pre> <p>If you don't even want to log the exception, and you just want to suppress it without PyCharm complaining, there's a new feature in Python 3.4: <a href="https://docs.python.org/3/library/contextlib.html#contextlib.suppress" rel="noreferrer"><code>contextlib.suppress()</code></a>.</p> <pre><code>import contextlib with contextlib.suppress(Exception): raise RuntimeError('Bad stuff happened.') </code></pre> <p>That's equivalent to this:</p> <pre><code>try: raise RuntimeError('Bad stuff happened.') except Exception: pass </code></pre>
2,474,429
Does throw inside a catch ellipsis (...) rethrow the original error in C++?
<p>If in my code I have the following snippet:</p> <pre><code>try { doSomething(); } catch (...) { doSomethingElse(); throw; } </code></pre> <p>Will the throw rethrow the specific exception caught by the default ellipsis handler?</p>
2,474,436
1
0
null
2010-03-19 01:22:44.273 UTC
6
2014-12-15 19:13:36.683 UTC
2014-12-15 19:13:36.683 UTC
null
1,223,693
null
115,751
null
1
36
c++|exception|throw|ellipsis
16,016
<p>Yes. The exception is active until it's caught, where it becomes inactive. But <em>it lives until the scope of the handler ends</em>. From the standard, emphasis mine:</p> <blockquote> <p>§15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. <em>The temporary persists as long as there is a handler being executed for that exception.</em></p> </blockquote> <p>That is:</p> <pre><code>catch(...) { // &lt;-- /* ... */ } // &lt;-- </code></pre> <p>Between those arrows, you can re-throw the exception. Only when the handlers scope ends does the exception cease to exist.</p> <p>In fact, in §15.1/6 the example given is nearly the same as your code:</p> <pre><code>try { // ... } catch (...) { // catch all exceptions // respond (partially) to exception &lt;-- ! :D throw; //pass the exception to some // other handler } </code></pre> <p>Keep in mind if you <code>throw</code> without an active exception, <code>terminate</code> will be called. This cannot be the case for you, being in a handler.</p> <hr> <p>If <code>doSomethingElse()</code> throws and the exception has no corresponding handler, because the original exception is considered handled the new exception will replace it. (As if it had just thrown, begins stack unwinding, etc.)</p> <p>That is:</p> <pre><code>void doSomethingElse(void) { try { throw "this is fine"; } catch(...) { // the previous exception dies, back to // using the original exception } try { // rethrow the exception that was // active when doSomethingElse was called throw; } catch (...) { throw; // and let it go again } throw "this replaces the old exception"; // this new one takes over, begins stack unwinding // leaves the catch's scope, old exception is done living, // and now back to normal exception stuff } try { throw "original exception"; } catch (...) { doSomethingElse(); throw; // this won't actually be reached, // the new exception has begun propagating } </code></pre> <p>Of course if nothing throws, <code>throw;</code> will be reached and you'll throw your caught exception as expected.</p>
37,253,568
DispatcherServlet and ContextLoaderListener in Spring
<p>What is the difference between <code>DispatcherServlet</code> and <code>ContextLoaderListener</code> in Spring framework? Do we need to configure both of them in <strong>web.xml</strong> when we are using spring framework? </p>
41,994,252
3
0
null
2016-05-16 12:07:05.057 UTC
10
2020-08-06 07:14:31.723 UTC
2018-08-09 13:57:14.17 UTC
null
3,151,210
null
4,316,933
null
1
9
spring|configuration
7,967
<p>The root WebApplicationContext is a Spring Application Context shared across the application. </p> <blockquote> <p>A DispatcherServlet instance actually has its own WebApplicationContext.</p> </blockquote> <p>One can have multiple DispatcherServlet instances in an application, and each will have its own WebApplicationContext.</p> <blockquote> <p>The root WebApplicationContext is shared across the application, so if you have a root WebApplicationContext and multiple DispatcherServlets, the DispatcherServlets will share the root WebApplicationContext.</p> </blockquote> <p>However, for a simple Spring MVC application, one can even have a situation where <em>there is no need to have a root WebApplicationContext</em>. A DispatcherServlet would still have its own WebApplicationContext, but it doesn’t actually need to have a parent root WebApplicationContext.</p> <p>So, which beans should go in the root Web Application Context and which beans should go in the DispatcherServlet’s Web Application Context? Well, general beans such as services and DAOs make their way in root Web Application Context, and more web-specific beans such as controllers are included in DispatcherServlet’s Web Application Context.</p>
37,358,340
Should I add the google-services.json (from Firebase) to my repository?
<p>I just signed up with Firebase and I created a new project. Firebase asked me for my app domain and a SHA1 debug key. I input these details and it generated a google-services.json file for me to add in the root of my app module.</p> <p>My question is, should this .json file be added to a public (open source) repo. Is it something that should be secret, like an API key?</p>
37,359,108
5
0
null
2016-05-21 02:37:33.693 UTC
22
2022-08-09 19:59:37.7 UTC
null
null
null
null
1,386,289
null
1
147
git|version-control|firebase
42,307
<p>A <a href="https://firebase.google.com/docs/admob/android/google-services.json" rel="nofollow noreferrer"><code>google-services.json</code></a> file is, <a href="https://firebase.google.com/support/guides/google-android#migrate_your_console_project" rel="nofollow noreferrer">from the Firebase doc</a>:</p> <blockquote> <p>Firebase manages all of your API settings and credentials through a single configuration file.<br /> The file is named <code>google-services.json</code> on Android and <code>GoogleService-Info.plist</code> on iOS.</p> </blockquote> <p>It seems to make sense to add it to a <code>.gitignore</code> and not include it in a public repo.<br /> This was discussed in <a href="https://github.com/googlesamples/google-services/issues/26#issuecomment-168869043" rel="nofollow noreferrer">issue 26</a>, with more details on what <a href="https://developers.google.com/android/guides/google-services-plugin#processing_the_json_file" rel="nofollow noreferrer"><code>google-services.json</code></a> contains.</p> <p>A project like <a href="https://github.com/googlesamples/google-services/" rel="nofollow noreferrer"><code>googlesamples/google-services</code></a> does have it <a href="https://github.com/googlesamples/google-services/blob/0edda8fe963a9baf78f67de4e78311c33e38c397/.gitignore" rel="nofollow noreferrer">in its <code>.gitignore</code></a> for instance.<br /> Although, as <a href="https://stackoverflow.com/questions/37358340/should-i-add-the-google-services-json-from-firebase-to-my-repository/37359108?noredirect=1#comment77979395_42750187">commented</a> by <a href="https://stackoverflow.com/users/3873192/stepheaw">stepheaw</a>, this <a href="https://groups.google.com/forum/#!msg/firebase-talk/bamCgTDajkw/uVEJXjtiBwAJ" rel="nofollow noreferrer">thread does mention</a></p> <blockquote> <p>For a library or open-source sample we do not include the JSON file because the intention is that users insert their own to point the code to their own backend.<br /> That's why you won't see JSON files in most of our firebase repos on GitHub.</p> </blockquote> <p>If the &quot;database URL, Android API key, and storage bucket&quot; are not secret for you, then you could consider adding the file to your repo.<br /> As mentioned in &quot;<a href="https://stackoverflow.com/a/45508703/6309">Is google-services.json safe from hackers?</a>&quot;, this isn't that simple though.</p> <p><a href="https://stackoverflow.com/users/2847310/baueric">baueric</a> asks in <a href="https://stackoverflow.com/questions/37358340/should-i-add-the-google-services-json-from-firebase-to-my-repository/37359108?noredirect=1#comment112734236_37359108">the comments</a>:</p> <blockquote> <p>In that post he says:</p> <blockquote> <p>The JSON file does not contain any super-sensitive information (like a server API key)</p> </blockquote> <p>But the <code>google-services.json</code> does have entry called <code>api_key</code>.<br /> Is that a different api key than a &quot;<code>server api key</code>&quot;?</p> </blockquote> <p><a href="https://stackoverflow.com/users/5742625/willie-chalmers-iii">Willie Chalmers III</a> points to &quot;<a href="https://stackoverflow.com/a/45508703/6309">Is google-services.json safe from hackers?</a>&quot;, and adds:</p> <blockquote> <p>Yes, that API key isn't a server API key which should never be public, so it's fine if your <code>google-services.json</code> is visible by others.</p> <p>In any case, you should still restrict how your client API key can be used in the Google Cloud console.</p> </blockquote> <hr /> <p>As noted by <a href="https://stackoverflow.com/users/8841562/puzz">Puzz</a> in <a href="https://stackoverflow.com/questions/37358340/should-i-add-the-google-services-json-from-firebase-to-my-repository/37359108?noredirect=1#comment129376469_37359108">the comments</a>, see also &quot;<strong><a href="https://stackoverflow.com/a/37484053/6309">Is it safe to expose Firebase apiKey to the public?</a></strong>&quot;</p> <p>In that answer, <a href="https://stackoverflow.com/users/209103/frank-van-puffelen">Frank Van Puffelen</a> mentions:</p> <p>Update (May 2021): Thanks to the new feature called <strong><a href="https://firebase.google.com/docs/app-check" rel="nofollow noreferrer">Firebase App Check</a></strong>, it is now actually possible to limit access to the backend services in your Firebase project to only those coming from iOS, Android and Web apps that are registered in that specific project.</p>
38,709,923
Why is requestAnimationFrame better than setInterval or setTimeout
<p>Why should I use requestAnimationFrame rather than setTimeout or setInterval?</p> <p>This self-answered question is a documentation example.</p>
38,709,924
1
1
null
2016-08-02 00:15:56.933 UTC
49
2019-10-30 16:25:13.77 UTC
2017-09-26 16:25:59.787 UTC
null
641,914
null
3,877,726
null
1
111
javascript|animation|canvas|html5-canvas
57,295
<h2>High quality animation.</h2> <p>The question is most simply answered with. <code>requestAnimationFrame</code> produces higher quality animation completely eliminating flicker and shear that can happen when using <code>setTimeout</code> or <code>setInterval</code>, and reduce or completely remove frame skips.</p> <em>Shear</em> <p>is when a new canvas buffer is presented to the display buffer midway through the display scan resulting in a shear line caused by the mismatched animation positions.</p> <em>Flicker</em> <p>is caused when the canvas buffer is presented to the display buffer before the canvas has been fully rendered.</p> <em>Frame skip</em> <p>is caused when the time between rendering frames is not in precise sync with the display hardware. Every so many frames a frame will be skipped producing inconsistent animation. (There are method to reduce this but personally I think these methods produce worse overall results) As most devices use 60 frames per second (or multiple of) resulting in a new frame every 16.666...ms and the timers <code>setTimeout</code> and <code>setInterval</code> use integers values they can never perfectly match the framerate (rounding up to 17ms if you have <code>interval = 1000/60</code>)</p> <hr> <h3>A demo is worth a thousand words.</h3> <p><strong>Update</strong> The answer to the question <a href="https://stackoverflow.com/a/43381828/3877726">requestAnimationFrame loop not correct fps</a> shows how setTimeout's frame time is inconsistent and compares it to requestAnimationFrame.</p> <p>The demo shows a simple animation (stripes moving across the screen) clicking the mouse button will switch between the rendering update methods used.</p> <p>There are several update methods used. It will depend on the hardware setup you are running as to what the exact appearance of the animation artifacts will be. You will be looking for little twitches in the movement of the stripes</p> <blockquote> <p>Note. You may have display sync turned off, or hardware acceleration off which will affect the quality of all the timing methods. Low end devices may also have trouble with the animation</p> </blockquote> <ul> <li><strong>Timer</strong> Uses setTimeout to animate. Time is 1000/60</li> <li><strong>RAF Best Quality</strong>, Uses requestAnimationFrame to animate</li> <li><p><strong>Dual Timers</strong>, <strike> Uses two timers, one called every 1000/60 clears and another to render.</strike></p> <p><strong>UPDATE OCT 2019</strong> There have been some changes in how timers present content. To show that <code>setInterval</code> does not correctly sync with the display refresh I have changed the Dual timers example to show that using more than one <code>setInterval</code> can still cause serious flicker The extent of the flickering this will produce depends on hardware set up.</p></li> <li><p><strong>RAF with timed animation</strong>, Uses requestAnimationFrame but animates using frame elapsed time. This technique is very common in animations. I believe it is flawed but I leave that up to the viewer</p></li> <li><strong>Timer with timed animation</strong>. As "RAF with timed animation" and is used in this case to overcome frame skip seen in "Timer" method. Again I think it suks, but the gaming community swear it is the best method to use when you don't have access to display refresh</li> </ul> <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>/** SimpleFullCanvasMouse.js begin **/ var backBuff; var bctx; const STRIPE_WIDTH = 250; var textWidth; const helpText = "Click mouse to change render update method."; var onResize = function(){ if(backBuff === undefined){ backBuff = document.createElement("canvas") ; bctx = backBuff.getContext("2d"); } backBuff.width = canvas.width; backBuff.height = canvas.height; bctx.fillStyle = "White" bctx.fillRect(0,0,w,h); bctx.fillStyle = "Black"; for(var i = 0; i &lt; w; i += STRIPE_WIDTH){ bctx.fillRect(i,0,STRIPE_WIDTH/2,h) ; } ctx.font = "20px arial"; ctx.textAlign = "center"; ctx.font = "20px arial"; textWidth = ctx.measureText(helpText).width; }; var tick = 0; var displayMethod = 0; var methods = "Timer,RAF Best Quality,Dual Timers,RAF with timed animation,Timer with timed animation".split(","); var dualTimersActive = false; var hdl1, hdl2 function display(timeAdvance){ // put code in here tick += timeAdvance; tick %= w; ctx.drawImage(backBuff,tick-w,0); ctx.drawImage(backBuff,tick,0); if(textWidth !== undefined){ ctx.fillStyle = "rgba(255,255,255,0.7)"; ctx.fillRect(w /2 - textWidth/2, 0,textWidth,40); ctx.fillStyle = "black"; ctx.fillText(helpText,w/2, 14); ctx.fillText("Display method : " + methods[displayMethod],w/2, 34); } if(mouse.buttonRaw&amp;1){ displayMethod += 1; displayMethod %= methods.length; mouse.buttonRaw = 0; lastTime = null; tick = 0; if(dualTimersActive) { dualTimersActive = false; clearInterval(hdl1); clearInterval(hdl2); updateMethods[displayMethod]() } } } //================================================================================================== // The following code is support code that provides me with a standard interface to various forums. // It provides a mouse interface, a full screen canvas, and some global often used variable // like canvas, ctx, mouse, w, h (width and height), globalTime // This code is not intended to be part of the answer unless specified and has been formated to reduce // display size. It should not be used as an example of how to write a canvas interface. // By Blindman67 const U = undefined;const RESIZE_DEBOUNCE_TIME = 100; var w,h,cw,ch,canvas,ctx,mouse,createCanvas,resizeCanvas,setGlobals,globalTime=0,resizeCount = 0; var L = typeof log === "function" ? log : function(d){ console.log(d); } createCanvas = function () { var c,cs; cs = (c = document.createElement("canvas")).style; cs.position = "absolute"; cs.top = cs.left = "0px"; cs.zIndex = 1000; document.body.appendChild(c); return c;} resizeCanvas = function () { if (canvas === U) { canvas = createCanvas(); } canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx = canvas.getContext("2d"); if (typeof setGlobals === "function") { setGlobals(); } if (typeof onResize === "function"){ resizeCount += 1; setTimeout(debounceResize,RESIZE_DEBOUNCE_TIME);} } function debounceResize(){ resizeCount -= 1; if(resizeCount &lt;= 0){ onResize();}} setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; mouse.updateBounds(); } mouse = (function(){ function preventDefault(e) { e.preventDefault(); } var mouse = { x : 0, y : 0, w : 0, alt : false, shift : false, ctrl : false, buttonRaw : 0, over : false, bm : [1, 2, 4, 6, 5, 3], active : false,bounds : null, crashRecover : null, mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",") }; var m = mouse; function mouseMove(e) { var t = e.type; m.x = e.clientX - m.bounds.left; m.y = e.clientY - m.bounds.top; m.alt = e.altKey; m.shift = e.shiftKey; m.ctrl = e.ctrlKey; if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1]; } else if (t === "mouseup") { m.buttonRaw &amp;= m.bm[e.which + 2]; } else if (t === "mouseout") { m.buttonRaw = 0; m.over = false; } else if (t === "mouseover") { m.over = true; } else if (t === "mousewheel") { m.w = e.wheelDelta; } else if (t === "DOMMouseScroll") { m.w = -e.detail; } if (m.callbacks) { m.callbacks.forEach(c =&gt; c(e)); } if((m.buttonRaw &amp; 2) &amp;&amp; m.crashRecover !== null){ if(typeof m.crashRecover === "function"){ setTimeout(m.crashRecover,0);}} e.preventDefault(); } m.updateBounds = function(){ if(m.active){ m.bounds = m.element.getBoundingClientRect(); } } m.addCallback = function (callback) { if (typeof callback === "function") { if (m.callbacks === U) { m.callbacks = [callback]; } else { m.callbacks.push(callback); } } else { throw new TypeError("mouse.addCallback argument must be a function"); } } m.start = function (element, blockContextMenu) { if (m.element !== U) { m.removeMouse(); } m.element = element === U ? document : element; m.blockContextMenu = blockContextMenu === U ? false : blockContextMenu; m.mouseEvents.forEach( n =&gt; { m.element.addEventListener(n, mouseMove); } ); if (m.blockContextMenu === true) { m.element.addEventListener("contextmenu", preventDefault, false); } m.active = true; m.updateBounds(); } m.remove = function () { if (m.element !== U) { m.mouseEvents.forEach(n =&gt; { m.element.removeEventListener(n, mouseMove); } ); if (m.contextMenuBlocked === true) { m.element.removeEventListener("contextmenu", preventDefault);} m.element = m.callbacks = m.contextMenuBlocked = U; m.active = false; } } return mouse; })(); resizeCanvas(); mouse.start(canvas,true); onResize() var lastTime = null; window.addEventListener("resize",resizeCanvas); function clearCTX(){ ctx.setTransform(1,0,0,1,0,0); // reset transform ctx.globalAlpha = 1; // reset alpha ctx.clearRect(0,0,w,h); // though not needed this is here to be fair across methods and demonstrat flicker } function dualUpdate(){ if(!dualTimersActive) { dualTimersActive = true; hdl1 = setInterval( clearCTX, 1000/60); hdl2 = setInterval(() =&gt; display(10), 1000/60); } } function timerUpdate(){ timer = performance.now(); if(!lastTime){ lastTime = timer; } var time = (timer-lastTime) / (1000/60); lastTime = timer; setTimeout(updateMethods[displayMethod],1000/60); clearCTX(); display(10*time); } function updateRAF(){ clearCTX(); requestAnimationFrame(updateMethods[displayMethod]); display(10); } function updateRAFTimer(timer){ // Main update loop clearCTX(); requestAnimationFrame(updateMethods[displayMethod]); if(!timer){ timer = 0; } if(!lastTime){ lastTime = timer; } var time = (timer-lastTime) / (1000/60); display(10 * time); lastTime = timer; } displayMethod = 1; var updateMethods = [timerUpdate,updateRAF,dualUpdate,updateRAFTimer,timerUpdate] updateMethods[displayMethod](); /** SimpleFullCanvasMouse.js end **/</code></pre> </div> </div> </p>
5,645,104
ANDROID - ExpandableListView
<p>Im trying to figure out how to build a view that contains (many of):</p> <ul> <li>PARENT1 (checkable, expandable)</li> <li>CHILD1 (RADIO BUTTON)</li> <li>CHILD2 (RADIO BUTTON)</li> </ul> <p>...</p> <ul> <li>PARENT2 (checkable, expandable)</li> <li>CHILD1 (CHECKABLE)</li> <li>CHILD2 (CHECKABLE)</li> </ul> <p>...</p> <p>The point is that parent has to be checkable and based on that children have to change the icon. Can some1 point me into the right direction, because from what i found nothing seems to work for me.</p>
5,645,596
1
0
null
2011-04-13 06:10:34.157 UTC
10
2016-05-15 03:11:19.45 UTC
2012-05-31 19:46:35.883 UTC
null
506,879
null
281,092
null
1
9
android|checkbox|radio-button|expandablelistview|itemrenderer
12,371
<p>I assume, you have your data structured somehow, like: ArrayList where </p> <ul> <li>Parent {name:String, checked:boolean, children:ArrayList} and</li> <li>Child {name:String}</li> </ul> <p>If so, you only have to do two things: </p> <ol> <li>create proper layouts for your parent item renderer and child item renderer</li> <li>expand BaseExpandableListAdapter to build up the list yourself.</li> </ol> <p>Here is a small sample about what's in my mind: <br /> <strong>layout/grouprow.xml</strong>: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout android:orientation="horizontal" android:gravity="fill" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;!-- PARENT --&gt; &lt;TextView android:id="@+id/parentname" android:paddingLeft="5px" android:paddingRight="5px" android:paddingTop="3px" android:paddingBottom="3px" android:textStyle="bold" android:textSize="18px" android:layout_gravity="fill_horizontal" android:gravity="left" android:layout_height="wrap_content" android:layout_width="wrap_content" /&gt; &lt;CheckBox android:id="@+id/checkbox" android:focusable="false" android:layout_alignParentRight="true" android:freezesText="false" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5px" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>layout/childrow.xml</strong>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="0px"&gt; &lt;!-- CHILD --&gt; &lt;TextView android:id="@+id/childname" android:paddingLeft="15px" android:paddingRight="5px" android:focusable="false" android:textSize="14px" android:layout_marginLeft="10px" android:layout_marginRight="3px" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>MyELAdapter class</strong>: I've declared this as an inner class of MyExpandableList, so i could reach the list of parents directly, without having to pass it as parameter.</p> <pre><code>private class MyELAdapter extends BaseExpandableListAdapter { private LayoutInflater inflater; public MyELAdapter() { inflater = LayoutInflater.from(MyExpandableList.this); } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView) { final Parent parent = parents.get(groupPosition); convertView = inflater.inflate(R.layout.grouprow, parentView, false); ((TextView) convertView.findViewById(R.id.parentname)).setText(parent.getName()); CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkbox); checkbox.setChecked(parent.isChecked()); checkbox.setOnCheckedChangeListener(new CheckUpdateListener(parent)); if (parent.isChecked()) convertView.setBackgroundResource(R.color.red); else convertView.setBackgroundResource(R.color.blue); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView) { final Parent parent = parents.get(groupPosition); final Child child = parent.getChildren().get(childPosition); convertView = inflater.inflate(R.layout.childrow, parentView, false); ((TextView) convertView.findViewById(R.id.childname)).setText(child.getName()); return convertView; } @Override public Object getChild(int groupPosition, int childPosition) { return parents.get(groupPosition).getChildren().get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public int getChildrenCount(int groupPosition) { return parents.get(groupPosition).getChildren().size(); } @Override public Object getGroup(int groupPosition) { return parents.get(groupPosition); } @Override public int getGroupCount() { return parents.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); } @Override public boolean isEmpty() { return ((parents == null) || parents.isEmpty()); } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public boolean hasStableIds() { return true; } @Override public boolean areAllItemsEnabled() { return true; } } </code></pre> <p>You must already have a public class <code>MyExpandableList extends ExpandableListActivity</code> which has a member:</p> <pre><code>private ArrayList&lt;Parent&gt; parents; </code></pre> <p>after you assign a value to this member / load the list of parents, you should also attach your adapter to this view: </p> <pre><code>this.setListAdapter(new MyELAdapter()); </code></pre> <p>and that's it. You have a checkable-expandable list, and in the <code>CheckUpdateListener</code>'s <code>onCheckedChanged(CompoundButton buttonView, boolean isChecked)</code> method you can update your parent object's checked state. </p> <p>Note, that the background color is determined in the getGroupView method, so you don't have to change it anywhere, just call the adapter's <code>notifyDataSetChanged()</code> method if needed. </p> <p><strong>Update</strong></p> <p>you can download the sample source code from <a href="http://tordai.rekaszeru.ro/expandablelist_sample.zip" rel="noreferrer">this link</a>. It is an eclipse project, but if you are using other developer environment, just simply copy the necessary source files (java + xml). </p>
6,286,127
Why is my windows service launching instances of csc.exe?
<p>I've written a multi-threaded windows service in C#. For some reason, csc.exe is being launched each time a thread is spawned. I doubt it's related to threading per se, but the fact that it is occurring on a per-thread basis, and that these threads are short-lived, makes the problem very visible: lots of csc.exe processes constantly starting and stopping.</p> <p>Performance is still pretty good, but I expect it would improve if I could eliminate this. However, what concerns me even more is that McAfee is attempting to scan the csc.exe instances and eventually kills the service, apparently when one the instances exits in mid-scan. I need to deploy this service commercially, so changing McAfee settings is not a solution.</p> <p>I assume that something in my code is triggering dynamic compilation, but I'm not sure what. Anyone else encounter this problem? Any ideas for resolving it?</p> <p><strong>Update 1:</strong></p> <p>After further research based on the suggestion and links from @sixlettervariables, the problem appears to stem from the implementation of XML serialization, as indicated in <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="noreferrer">Microsoft's documentation on XmlSerializer:</a></p> <blockquote> <p>To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types.</p> </blockquote> <p>Microsoft notes an optimization further on in the same doc:</p> <blockquote> <p>The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:</p> <p>XmlSerializer.XmlSerializer(Type)</p> <p>XmlSerializer.XmlSerializer(Type, String)</p> </blockquote> <p>which appears to indicate that the codegen and compilation would occur only once, at first use, as long as one of the two specified constructors are used. However, I don't benefit from this optimization because I am using another form of the constructor, specifically:</p> <blockquote> <p>public XmlSerializer(Type type, Type[] extraTypes)</p> </blockquote> <p>Reading a bit further, it turns out that this also happens to be a likely explanation for a memory leak that I have been observing when my code executes. Again, from the same doc:</p> <blockquote> <p>If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable.</p> </blockquote> <p>The two workarounds that Microsoft suggests above are a last resort for me. Going to another form of the constructor is not preferred (I am using the &quot;extratypes&quot; form for serialization of derived classes, which is a supported use per Microsoft's docs), and I'm not sure I like the idea of managing a cache of assemblies for use across multiple threads.</p> <p>So, I have <a href="http://msdn.microsoft.com/en-us/library/bk3w6240%28v=VS.100%29.aspx" rel="noreferrer">sgen</a>'d, and see the resulting assembly of serializers for my types produced as expected, but when my code executes the sgen-produced assembly is not loaded (per observation in the fusion log viewer and process monitor). I'm currently exploring why this is the case.</p> <p><strong>Update 2:</strong></p> <p>The sgen'd assembly loads fine when I use one of the two &quot;friendlier&quot; XmlSerializer constructors (see Update 1, above). When I use <code>XmlSerializer(Type)</code>, for example, the sgen'd assembly loads and no run-time codegen/compilation is performed. However, when I use <code>XmlSerializer(Type, Type[])</code>, the assembly does not load. Can't find any reasonable explanation for this.</p> <p>So I'm reverting to using one of the supported constructors and sgen'ing. This combination eliminates my original problem (the launching of csc.exe), plus one other related problem (the XmlSerializer-induced memory leak mentioned in Update 1 above). It does mean, however, that I have to revert to a less optimal form of of serialization for derived types (the use of <code>XmlInclude</code> on the base type) until something changes in the framework to address this situation.</p>
6,286,253
1
2
null
2011-06-08 22:38:24.04 UTC
9
2011-06-13 22:13:51.33 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
509,891
null
1
14
c#|.net
6,251
<p>Psychic debugging:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="noreferrer">Your Windows Service does XML serialization/deserialization</a> <blockquote> <p>To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types.</p> </blockquote></li> </ul> <p><a href="http://msdn.microsoft.com/en-us/library/bk3w6240%28v=VS.100%29.aspx" rel="noreferrer">If this is the case you can build these XML Serializer Assemblies a-priori.</a></p>
37,683,143
Extract passphrase from Jenkins' credentials.xml
<p>I have added an SSH credential to Jenkins.</p> <p>Unfortunately, I have forgotten the SSH passphrase and would now like to obtain it from Jenkins' credential archive, which is located at <code>${JENKINS_HOME}/credentials.xml</code>.</p> <p>That XML document seems to have credentials encrypted in XML tags <code>&lt;passphrase&gt;</code> or <code>&lt;password&gt;</code>.</p> <p>How can I retrieve the plaintext passphrase?</p>
37,683,492
5
0
null
2016-06-07 15:12:12.043 UTC
27
2019-04-22 19:02:11.923 UTC
null
null
null
null
923,560
null
1
80
jenkins
81,723
<p>Open your Jenkins' installation's script console by visiting <code>http(s)://${JENKINS_ADDRESS}/script</code>.</p> <p>There, execute the following Groovy script:</p> <pre><code>println( hudson.util.Secret.decrypt("${ENCRYPTED_PASSPHRASE_OR_PASSWORD}") ) </code></pre> <p>where <code>${ENCRYPTED_PASSPHRASE_OR_PASSWORD}</code> is the encrypted content of the <code>&lt;password&gt;</code> or <code>&lt;passphrase&gt;</code> XML element that you are looking for.</p>
784,549
Using Dictionary.app’s thesaurus function programmatically on OSX (preferably via Ruby)
<p>I need to write a Ruby method that takes a word, runs it through OS 10.5’s Dictionary.app’s thesaurus function, and returns alternative words.</p> <p>If the Ruby method ends up calling the command-line, that’s fine; I just need to be able to do it programmatically from Ruby.</p> <p>After looking through Ruby OSA, I realize that the Dictionary is accessible through some Dictionary Service [<a href="http://discussions.apple.com/thread.jspa?threadID=1561332]" rel="noreferrer">http://discussions.apple.com/thread.jspa?threadID=1561332]</a>, but I don’t really get it.</p> <p>Anyone see a simple solution?</p> <p>I was also up for making an Automator workflow and calling it from the command line, but I wasn’t able to properly feed the "Get Definition" function a word from the shell for some reason (it kept saying that it couldn’t find the word, but when looking manually it worked).</p>
784,669
2
0
null
2009-04-24 04:44:10.427 UTC
10
2013-10-22 14:47:17.043 UTC
null
null
null
Edward Ocampo-Gooding
null
null
1
10
ruby|macos|scripting|dictionary
3,080
<p>Unfortunately the only programmatic interface to this (Dictionary Services) doesn't support setting a dictionary.</p> <p>However, it does consult the dictionary preferences to use the first dictionary specified, so you could potentially, in very ugly fashion, reset the preferences so the thesaurus is the only dictionary available.</p> <p>This is really disgusting and likely to break if breathed upon, but it should work:</p> <pre><code>/* compile with: gcc -o thesaurus -framework CoreServices -framework Foundation thesaurus.m */ #import &lt;Foundation/Foundation.h&gt; #include &lt;CoreServices/CoreServices.h&gt; int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSMutableDictionary *dictionaryPrefs = [[userDefaults persistentDomainForName:@"com.apple.DictionaryServices"] mutableCopy]; NSArray *activeDictionaries = [dictionaryPrefs objectForKey:@"DCSActiveDictionaries"]; [dictionaryPrefs setObject: [NSArray arrayWithObject:@"/Library/Dictionaries/Oxford American Writer's Thesaurus.dictionary"] forKey:@"DCSActiveDictionaries"]; [userDefaults setPersistentDomain:dictionaryPrefs forName:@"com.apple.DictionaryServices"]; NSString *word = [NSString stringWithUTF8String:argv[1]]; puts([(NSString *)DCSCopyTextDefinition(NULL, (CFStringRef)word, CFRangeMake(0, [word length])) UTF8String]); [dictionaryPrefs setObject:activeDictionaries forKey: @"DCSActiveDictionaries"]; [userDefaults setPersistentDomain:dictionaryPrefs forName:@"com.apple.DictionaryServices"]; } </code></pre> <p>And use it as:</p> <pre><code>% ./thesaurus string noun 1 twine, cord, yarn, thread, strand. 2 chain, group, firm, company. 3 series, succession, chain, sequence, run, streak. 4 line, train, procession, queue, file, column, convoy, cavalcade. [...] </code></pre>
2,947,675
int value under 10 convert to string two digit number
<pre><code>string strI; for (int i = 1; i &lt; 100; i++) strI = i.ToString(); </code></pre> <p>in here, if <code>i = 1</code> then <code>ToString</code> yields <code>"1"</code></p> <p>But I want to get <code>"01"</code> or <code>"001"</code></p> <p>It looks quite easy, but there's only article about </p> <pre><code>datetime.ToString("yyyy-MM-dd")` </code></pre>
2,947,687
7
3
null
2010-06-01 06:28:40.073 UTC
3
2020-10-06 12:52:11.85 UTC
2017-10-06 09:55:21.74 UTC
null
2,249,175
null
278,235
null
1
137
c#|string
155,851
<pre><code>i.ToString("00") </code></pre> <p>or </p> <pre><code>i.ToString("000") </code></pre> <p>depending on what you want</p> <p>Look at the MSDN article on custom numeric format strings for more options: <a href="http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx</a></p>
3,176,962
jQuery object equality
<p>How do I determine if two jQuery objects are equal? I would like to be able to search an array for a particular jQuery object.</p> <pre><code>$.inArray(jqobj, my_array);//-1 alert($("#deviceTypeRoot") == $("#deviceTypeRoot"));//False alert($("#deviceTypeRoot") === $("#deviceTypeRoot"));//False </code></pre>
3,177,083
7
0
null
2010-07-05 02:22:42.86 UTC
26
2018-08-04 14:27:33.767 UTC
null
null
null
null
165,495
null
1
158
equality|jquery
164,490
<p>Since jQuery 1.6, you can use <a href="http://api.jquery.com/is/" rel="noreferrer"><code>.is</code></a>. Below is the answer from over a year ago...</p> <pre><code>var a = $('#foo'); var b = a; if (a.is(b)) { // the same object! } </code></pre> <hr> <p>If you want to see if two variables are actually the same object, eg:</p> <pre><code>var a = $('#foo'); var b = a; </code></pre> <p>...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.</p> <pre><code>if ($.data(a) == $.data(b)) { // the same object! } </code></pre> <p>Though, the same could be achieved with a simple <code>a === b</code>, the above might at least show the next developer exactly what you're testing for.</p> <p>In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:</p> <pre><code>$.fn.equals = function(compareTo) { if (!compareTo || this.length != compareTo.length) { return false; } for (var i = 0; i &lt; this.length; ++i) { if (this[i] !== compareTo[i]) { return false; } } return true; }; </code></pre> <p><sub><a href="http://groups.google.com/group/jquery-dev/browse_thread/thread/86504e9660e893ef?pli=1" rel="noreferrer">Source</a></sub></p> <pre><code>var a = $('p'); var b = $('p'); if (a.equals(b)) { // same set } </code></pre>
2,560,368
What is the use of printStackTrace() method in Java?
<p>I am going through a socket program. In it, <code>printStackTrace</code> is called on the <code>IOException</code> object in the catch block.<br> What does <code>printStackTrace()</code> actually do?</p> <pre><code>catch(IOException ioe) { ioe.printStackTrace(); } </code></pre> <p>I am unaware of its purpose. What is it used for? </p>
2,560,378
9
8
null
2010-04-01 12:46:11.773 UTC
32
2021-10-12 09:23:07.057 UTC
2015-06-02 03:35:20.923 UTC
null
4,099,598
null
277,516
null
1
106
java|exception-handling|printstacktrace
461,483
<p>It's a method on <code>Exception</code> instances that <a href="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace()" rel="nofollow noreferrer">prints the stack trace of the instance to <code>System.err</code></a>.</p> <p>It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.</p> <p>Here's an example of how it might be used in practice:</p> <pre><code>try { // ... } catch (SomeException e) { e.printStackTrace(); } </code></pre> <p>Note that in &quot;serious production code&quot; you usually don't want to do this, for various reasons (such as <code>System.out</code> being less useful and not thread safe). In those cases you usually use some log framework that provides the same (or very similar) output using a command like <code>log.error(&quot;Error during frobnication&quot;, e);</code>.</p>
2,751,227
How to download source in ZIP format from GitHub?
<p>I see something strange like: </p> <p><a href="http://github.com/zoul/Finch.git" rel="noreferrer">http://github.com/zoul/Finch.git</a></p> <p>Now I'm not that CVS, SVN, etc. dude. When I open that in the browser it tells me that I did something wrong. So I bet I need some hacker-style tool? Some client?</p> <p>(I mean... why not just provide a ZIP file? Isn't the world complex enough?)</p>
2,751,270
15
0
null
2010-05-01 19:06:51.65 UTC
60
2022-09-07 08:48:21.12 UTC
2015-02-20 23:18:37.037 UTC
null
63,550
null
268,733
null
1
279
git|github
787,682
<p>To clone that repository via a <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URL</a> like that: yes, you do need a client, and that client is <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a>. That will let you make changes, your own branches, merge back in sync with other developers, maintain your own source that you can easily keep up to date without downloading the whole thing each time and writing over your own changes etc. A ZIP file won't let you do that.</p> <p>It is mostly meant for people who want to develop the source rather than people who just want to get the source one off and not make changes.</p> <p>But it just so happens you can get a ZIP file as well:</p> <p>Click on <a href="http://github.com/zoul/Finch/" rel="noreferrer">http://github.com/zoul/Finch/</a> and then click on the green <kbd>Clone or Download</kbd> button. See here:</p> <p><a href="https://i.stack.imgur.com/TYzwW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TYzwW.png" alt="enter image description here"></a></p>
25,342,587
Chef 'cookbook' in Berksfile vs 'depends' in metadata.rb
<p>What's the difference between adding cookbooks to Berksfile using 'cookbook' and adding cookbooks to metadata.rb using 'depends'? For example, if I add to metadata.rb</p> <pre><code>depends 'nginx' </code></pre> <p>do I need to add it to Berksfile using</p> <pre><code>cookbook 'nginx' </code></pre> <p>?</p>
25,342,713
3
0
null
2014-08-16 18:20:48.607 UTC
16
2020-06-15 18:06:20.57 UTC
2016-10-05 05:38:11.037 UTC
null
3,885,376
null
1,575,245
null
1
63
chef-infra|berkshelf|berksfile
18,416
<p>The Berksfile is Berkshelf specific, while the metadata file is built into Chef.</p> <p>Adding your dependencies to the metadata file allows other applications, like librarian-chef or the supermarket, to read your dependencies as well.</p> <p>Note that Berkshelf reads the dependencies from metadata as well, as long as you add the <code>metadata</code> line to the Berksfile.</p> <p>I strongly recommend specifying all dependencies in your metadata file, and using your Berksfile to point to where specific cookbooks are stored if they're not available in the supermarket (like Github, or a local path).</p>
23,777,337
Can I select a particular Android Device Emulator from AVD using Apache Cordova?
<p>Is there a way when using Cordova CLI to select a particular emulated device from the Android Device Manager (AVD)?</p> <p>I am working on a tablet app and a smartphone app at the same time and need to switch to different types of emulators because of the different form factors and screen resolutions?</p> <p>I know it's not a particular coding question but perhaps there is some Cordova code I can run in terminal to make the emulation more specific rather than:</p> <pre><code>cordova emulate android </code></pre> <p>Which seems to pick the first emulator off the stack.</p>
23,787,449
4
0
null
2014-05-21 07:58:25.943 UTC
8
2020-06-08 09:15:30.343 UTC
2015-10-17 15:46:48.257 UTC
null
65,775
null
2,006,447
null
1
33
android|cordova|android-emulator|avd
26,297
<p>Use the <code>target</code> parameter like this:</p> <pre><code>cordova emulate --target=emulator-5554 android </code></pre> <p>To get the device name of your emulator ("emulator-5554" in this example), run <code>/platforms/android/cordova/lib/list-started-emulators.bat</code></p>
23,870,801
go run: cannot run non-main package
<p>here the simple go application. I am getting "go run: cannot run non-main package" error, if I run following code.</p> <pre><code>package zsdfsdf import ( "fmt" ) func Main() { fmt.Println("sddddddd") } </code></pre> <p>To fix it, I just need to name the package to <code>main</code>. But I don't understand why I need to do that. I should be able to name the package whatever I want.</p> <p>Another question, I know main function is the entry point of the program, you need it. otherwise it will not work. But I see some codes that didn't have main function still works.</p> <p>Click on this link, the example at the bottom of the page didn't use package main and main function, and it still works. just curious why.</p> <p><a href="https://developers.google.com/appengine/docs/go/gettingstarted/usingdatastore" rel="noreferrer">https://developers.google.com/appengine/docs/go/gettingstarted/usingdatastore</a></p>
23,870,944
5
0
null
2014-05-26 13:02:24.543 UTC
3
2021-02-20 04:22:37.29 UTC
2020-06-08 13:40:41.56 UTC
null
1,480,391
null
817,314
null
1
91
go|google-app-engine-go
101,049
<p>You need to specify in your app.yaml file what your app access point is. Take a look <a href="https://developers.google.com/appengine/docs/go/gettingstarted/helloworld">here</a>. You need to specify:</p> <pre><code>application: zsdfsdf </code></pre> <p>Also see from that above link:</p> <blockquote> <p>"Note: When writing a stand-alone Go program we would place this code in package main. The Go App Engine Runtime provides a special main package, so you should put HTTP handler code in a package of your choice (in this case, hello)."</p> </blockquote> <p>You are correct that all Go programs need the <code>Main</code> method. But it is provided by Google App Engine. That is why your provided example works. Your example would not work locally (not on GAE).</p>
10,353,173
How can I make ThreadPoolExecutor command wait if there's too much data it needs to work on?
<p>I am getting data from a queue server and I need to process it and send an acknowledgement. Something like this:</p> <pre><code>while (true) { queueserver.get.data ThreadPoolExecutor //send data to thread queueserver.acknowledgement </code></pre> <p>I don't fully understand what happens in threads but I think this program gets the data, sends it the thread and then immediately acknowledges it. So even if I have a limit of each queue can only have 200 unacknowledged items, it will just pull as fast as it can receive it. This is good when I write a program on a single server, but if I'm using multiple workers then this becomes an issue because the amount of items in the thread queue are not a reflection of the work its done but instead of how fast it can get items from the queue server. </p> <p>Is there anything I can do to somehow make the program wait if the thread queue is full of work?</p>
10,353,250
4
0
null
2012-04-27 15:10:38.537 UTC
9
2022-02-25 16:54:21.787 UTC
2012-04-27 15:12:58.793 UTC
null
179,850
null
640,558
null
1
12
java|multithreading
4,982
<blockquote> <p>How can I make ThreadPoolExecutor command wait if there's too much data it needs to work on?</p> </blockquote> <p>Instead of an open-ended queue, you can use a <code>BlockingQueue</code> with a limit on it:</p> <pre><code>BlockingQueue&lt;Date&gt; queue = new ArrayBlockingQueue&lt;Date&gt;(200); </code></pre> <p>In terms of jobs submitted to an <code>ExecutorService</code>, instead of using the default <code>ExecutorService</code>s created using <code>Executors</code>, which use an unbounded queue, you can create your own:</p> <pre><code>return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue&lt;Runnable&gt;(200)); </code></pre> <p>Once the queue fills up, it will cause it to reject any new tasks that are submitted. You will need to set a <code>RejectedExecutionHandler</code> that submits to the queue. Something like:</p> <pre><code>final BlockingQueue queue = new ArrayBlockingQueue&lt;Runnable&gt;(200); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue); // by default (unfortunately) the ThreadPoolExecutor will throw an exception // when you submit the 201st job, to have it block you do: threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // this will block if the queue is full executor.getQueue().put(r); // check afterwards and throw if pool shutdown if (executor.isShutdown()) { throw new RejectedExecutionException( &quot;Task &quot; + r + &quot; rejected from &quot; + e); } } }); </code></pre> <p>I think it's a major miss that Java doesn't have a <code>ThreadPoolExecutor.CallerBlocksPolicy</code>.</p>
10,351,565
How do I fit long title?
<p>There's a <a href="https://stackoverflow.com/questions/8802918/my-matplotlib-title-gets-cropped">similar question</a> - but I can't make the solution proposed there work.</p> <p>Here's an example plot with a long title:</p> <pre><code>#!/usr/bin/env python import matplotlib import matplotlib.pyplot import textwrap x = [1,2,3] y = [4,5,6] # initialization: fig = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # lines: fig.add_subplot(111).plot(x, y) # title: myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all." fig.add_subplot(111).set_title("\n".join(textwrap.wrap(myTitle, 80))) # tight: (matplotlib.pyplot).tight_layout() # saving: fig.savefig("fig.png") </code></pre> <p>it gives a</p> <pre class="lang-rb prettyprint-override"><code> AttributeError: 'module' object has no attribute 'tight_layout' </code></pre> <p>and if I replace <code>(matplotlib.pyplot).tight_layout()</code> with <code>fig.tight_layout()</code> it gives:</p> <pre class="lang-rb prettyprint-override"><code> AttributeError: 'Figure' object has no attribute 'tight_layout' </code></pre> <p>So my question is - how do I fit the title to the plot?</p>
10,634,897
5
0
null
2012-04-27 13:30:31.947 UTC
8
2022-05-04 21:44:07.993 UTC
2017-05-23 11:46:33.49 UTC
null
-1
null
788,700
null
1
36
matplotlib
45,330
<p>Here's what I've finally used:</p> <pre><code>#!/usr/bin/env python3 import matplotlib from matplotlib import pyplot as plt from textwrap import wrap data = range(5) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data, data) title = ax.set_title("\n".join(wrap("Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all.", 60))) fig.tight_layout() title.set_y(1.05) fig.subplots_adjust(top=0.8) fig.savefig("1.png") </code></pre> <p><img src="https://i.stack.imgur.com/Q3Uog.png" alt="enter image description here"></p>
10,605,730
Remove an attribute from a Backbone.js model
<p>Is there a way to remove an attribute from a <a href="http://documentcloud.github.com/backbone/" rel="noreferrer">Backbone</a> model?</p> <p>Reason being is I pass up extra data on save to perform certain actions, but then that data gets automatically added to my model</p> <p>The documentation says to not edit the model.attributes directly, so the only other method I see to do this would be to use the <a href="http://documentcloud.github.com/backbone/#Model-set" rel="noreferrer">set</a> method and set the attribute to null, but that is not ideal</p> <pre><code>var myModel = new Model() myModel.save({name:'Holla', specialAttr:'Please Remove me'}) myModel.set({tempAttr:null}) if(myModel.attributes['specialAttr'] == null){ alert("Model does not have a specialAttr") } </code></pre> <p>I've also tried removing it from the attributes property, but it doesn't really remove it.</p>
10,605,833
1
0
null
2012-05-15 17:17:09.5 UTC
2
2014-08-29 10:07:12.003 UTC
2012-05-15 17:23:15.673 UTC
null
443,722
null
443,722
null
1
40
javascript|backbone.js
28,609
<p>Are you looking for <code>model.unset</code> ?</p> <blockquote> <p>Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.</p> </blockquote> <p>You can find the documentation <a href="http://backbonejs.org/#Model-unset" rel="noreferrer">here</a>.</p>
5,743,099
Looping through GridView rows and Checking Checkbox Control
<p>I currently have a GridView which displays data from a Student Table, here is my Grid and associated SQLDataSource;</p> <pre><code> &lt;asp:GridView ID="GridView2" style="position:absolute; top: 232px; left: 311px;" AutoGenerateColumns="false" runat="server" DataSourceID="SqlDataSource4"&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate &gt; &lt;asp:CheckBox runat="server" ID="AttendanceCheckBox" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="studentIDLabel" Text='&lt;%# Eval("StudentID") %&gt;' runat="server"&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:BoundField DataField="Name" HeaderText="Name" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="&lt;%$ ConnectionStrings:RegisterConnectionString %&gt;" SelectCommand="SELECT [StudentID], [Name] FROM [Student] WHERE CourseID = @CourseID "&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="CourseDropDownList" Name="CourseID" PropertyName="SelectedValue" Type="Int32" /&gt; &lt;/SelectParameters&gt; &lt;/asp:SqlDataSource&gt; </code></pre> <p>I have a button on the page which when the user clicks the button I need to loop through each row in the GridView, then find the CheckBox then I need to check if the checkbox is checked or not. If the checkbox is checked I need to add the value in the Label Template Field to a different table in the database. I am using C# Code. Any help is much appreciated, thanks in advance!</p>
5,743,161
2
0
null
2011-04-21 10:52:28.27 UTC
0
2017-03-09 01:07:35.323 UTC
2017-03-09 01:07:35.323 UTC
null
1,313,642
null
715,115
null
1
13
c#|asp.net|gridview
104,645
<p>Loop like</p> <pre><code>foreach (GridViewRow row in grid.Rows) { if (((CheckBox)row.FindControl("chkboxid")).Checked) { //read the label } } </code></pre>
23,210,828
asp.net identity 2.0 unity not resolving default user store
<p>i get the following exception when trying to configure Unity using Unity.Mvc5 with an MVC 5 application using Identity 2.0 and the Identity 2.0 Samples boilerplate. i have read this SO <a href="https://stackoverflow.com/questions/21927785/configure-unity-di-for-asp-net-identity">Configure Unity DI for ASP.NET Identity</a> and i'm still not clear on what i'm missing. What am i doing wrong here?</p> <p>The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping? </p> <p>[ResolutionFailedException: Resolution of the dependency failed, type = "myApp.Web.Controllers.AccountController", name = "(none)". Exception occurred while: while resolving.</p> <h2>Exception is: InvalidOperationException - The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?</h2> <p>At the time of the exception, the container was:</p> <p>Resolving myApp.Web.Controllers.AccountController,(none) Resolving parameter "userManager" of constructor myApp.Web.Controllers.AccountController(myApp.Web.Models.ApplicationUserManager userManager) Resolving myApp.Web.Models.ApplicationUserManager,(none) Resolving parameter "store" of constructor myApp.Web.Models.ApplicationUserManager(Microsoft.AspNet.Identity.IUserStore<code>1[[myApp.Web.DAL.Profiles.ApplicationUser, myApp.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] store) Resolving Microsoft.AspNet.Identity.EntityFramework.UserStore</code>1[myApp.Web.DAL.Profiles.ApplicationUser],(none) (mapped from Microsoft.AspNet.Identity.IUserStore<code>1[myApp.Web.DAL.Profiles.ApplicationUser], (none)) Resolving parameter "context" of constructor Microsoft.AspNet.Identity.EntityFramework.UserStore</code>1[[myApp.Web.DAL.Profiles.ApplicationUser, myApp.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](System.Data.Entity.DbContext context) Resolving System.Data.Entity.DbContext,(none) Resolving parameter "existingConnection" of constructor System.Data.Entity.DbContext(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Boolean contextOwnsConnection) Resolving System.Data.Common.DbConnection,(none)</p> <p>account controller as i have modified it</p> <pre><code> public AccountController(ApplicationUserManager userManager) { _userManager = userManager; } private ApplicationUserManager _userManager; </code></pre> <p>containers i have registered</p> <pre><code>container.RegisterType&lt;ApplicationUserManager&gt;(new HierarchicalLifetimeManager()); container.RegisterType&lt;IUserStore&lt;ApplicationUser&gt;, UserStore&lt;ApplicationUser&gt;&gt;(new HierarchicalLifetimeManager()); </code></pre>
23,245,631
2
0
null
2014-04-22 05:08:19.943 UTC
8
2014-04-23 13:19:48.343 UTC
2017-05-23 12:33:29.757 UTC
null
-1
null
289,980
null
1
10
asp.net-mvc|dependency-injection|unity-container|asp.net-identity|asp.net-identity-2
12,679
<p>I see you found a solution, but I think I have a simpler one.</p> <p>You're using Entity Framework, right? So your application almost certainly has something inheriting from <code>DbContext</code> (probably inheriting from <code>IdentityContext&lt;TUser&gt;</code>, which in turn inherits from <code>DbContext</code> in this case). In the default template it's ApplicationDbContext.</p> <p>In your composition root you can just add <code>container.RegisterType&lt;DbContext, ApplicationDbContext&gt;(new HierarchicalLifetimeManager());</code> (obviously edit this if yours isn't called ApplicationDbContext).</p>
21,221,581
InteractivePopGestureRecognizer causing app freezing
<p>In my app I have different controllers. When I push controller1 to navigation controller and swipe to back, all works good. But, if I push navigation controller1, and into controller1 push controller2 and try to swipe to back I get a frozen application. If go back through back button all works fine.</p> <p>How can I catch the problem?</p>
21,424,580
9
2
null
2014-01-19 19:33:47.507 UTC
14
2019-03-29 20:20:50.053 UTC
2018-03-26 10:34:40.32 UTC
null
3,547,788
null
1,542,514
null
1
26
ios|objective-c|interactivepopgesture
12,068
<p>I had similar problem with freezing interface when using swipe-to-pop gesture. In my case the problem was in controller1.viewDidAppear I was disabling swipe gesture: <code>self.navigationController.interactivePopGestureRecognizer.enabled = NO</code>. So when user started to swipe back from contorller2, controller1.viewDidAppear was triggered and gesture was disabled, right during it's work.</p> <p>I solved this by setting <code>self.navigationController.interactivePopGestureRecognizer.delegate = self</code> in controller1 and implementing <code>gestureRecognizerShouldBegin:</code>, instead of disabling gesture recognizer:</p> <pre><code>- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)] &amp;&amp; gestureRecognizer == self.navigationController.interactivePopGestureRecognizer) { return NO; } return YES; } </code></pre>
18,873,066
Pretty JSON Formatting in IPython Notebook
<p>Is there an existing way to get <code>json.dumps()</code> output to appear as "pretty" formatted JSON inside ipython notebook? </p>
18,873,131
7
0
null
2013-09-18 13:05:04.053 UTC
11
2022-09-10 14:13:38.127 UTC
2013-09-18 13:23:45.657 UTC
null
1,673,391
null
107,156
null
1
65
python|json|ipython-notebook
59,792
<p><code>json.dumps</code> has an <code>indent</code> argument, printing the result should be enough:</p> <pre><code>print(json.dumps(obj, indent=2)) </code></pre>
43,195,143
Is there a way to export a BigQuery table's schema as JSON?
<p>A BigQuery <a href="https://cloud.google.com/bigquery/docs/tables" rel="noreferrer">table</a> has schema which can be viewed in the web UI, <a href="https://cloud.google.com/bigquery/docs/tables#updateschema" rel="noreferrer">updated</a>, or used to <a href="https://cloud.google.com/bigquery/loading-data" rel="noreferrer">load data</a> with the <code>bq</code> tool as a JSON file. However, I can't find a way to dump this schema from an existing table to a JSON file (preferably from the command-line). Is that possible?</p>
43,195,210
5
0
null
2017-04-03 22:08:35.537 UTC
24
2022-05-15 06:50:34.613 UTC
null
null
null
null
9,760
null
1
98
json|google-bigquery
101,878
<blockquote> <p>a way to dump schema from an existing table to a JSON file (preferably from the command-line). Is that possible?</p> </blockquote> <p>try below </p> <pre><code>bq show bigquery-public-data:samples.wikipedia </code></pre> <p>You can use –format flag to prettify output</p> <p>--format: none|json|prettyjson|csv|sparse|pretty: </p> <p>Format for command output. Options include: </p> <pre><code>none: ... pretty: formatted table output sparse: simpler table output prettyjson: easy-to-read JSON format json: maximally compact JSON csv: csv format with header </code></pre> <p>The first three are intended to be human-readable, and the latter three are for passing to another program. If no format is selected, one will be chosen based on the command run. </p> <p>Realized I provided partial answer :o) </p> <p>Below does what PO wanted </p> <pre><code>bq show --format=prettyjson bigquery-public-data:samples.wikipedia | jq '.schema.fields' </code></pre>
8,500,185
How to make a div onload function?
<p>I want to load an HTML page as a div inside my webpage by removing its HTML and body tags. But the HTML page has a <code>&lt;body onload=" ... " &gt;</code> , I need this function to continue working. Seems <code>&lt;div onload=" ... " &gt;</code> is not working. How can I insert this onload function into my website's body (on this page only) without directly editing my original website code (php)?</p>
8,500,209
5
0
null
2011-12-14 06:11:23.79 UTC
2
2018-02-15 19:04:29.49 UTC
2011-12-14 06:15:57.66 UTC
null
540,162
null
775,698
null
1
5
javascript
55,995
<p>you can use <a href="http://api.jquery.com/load/" rel="nofollow">jQuery.load</a> to load the contents of the page into your div</p> <pre><code>$(document).ready(function() { $("#containing-div").load("[url of page with onload function]"); }); </code></pre> <p>the code above goes in the page that contains the div. the page with the onload function doesn't get changed.</p>
8,552,192
Select distinct column along with some other columns in MySQL
<p>I can't seem to find a suitable solution for the following (probably an age old) problem so hoping someone can shed some light. I need to return 1 distinct column along with other non distinct columns in mySQL.</p> <p>I have the following table in mySQL:</p> <pre><code>id name destination rating country ---------------------------------------------------- 1 James Barbados 5 WI 2 Andrew Antigua 6 WI 3 James Barbados 3 WI 4 Declan Trinidad 2 WI 5 Steve Barbados 4 WI 6 Declan Trinidad 3 WI </code></pre> <p>I would like SQL statement to return the DISTINCT name along with the destination, rating based on country.</p> <pre><code>id name destination rating country ---------------------------------------------------- 1 James Barbados 5 WI 2 Andrew Antigua 6 WI 4 Declan Trinidad 2 WI 5 Steve Barbados 4 WI </code></pre> <p>As you can see, James and Declan have different ratings, but the same name, so they are returned only once. </p> <p>The following query returns all rows because the ratings are different. Is there anyway I can return the above result set?</p> <pre><code>SELECT (distinct name), destination, rating FROM table WHERE country = 'WI' ORDER BY id </code></pre>
8,552,203
4
0
null
2011-12-18 13:56:44.743 UTC
10
2013-02-12 00:32:54.13 UTC
2011-12-18 14:31:48.61 UTC
null
458,741
null
1,038,814
null
1
34
mysql|select|distinct
64,645
<p>Using a subquery, you can get the highest <code>id</code> for each name, then select the rest of the rows based on that:</p> <pre><code>SELECT * FROM table WHERE id IN ( SELECT MAX(id) FROM table GROUP BY name ) </code></pre> <p>If you'd prefer, use <code>MIN(id)</code> to get the first record for each name instead of the last.</p> <p>It can also be done with an <code>INNER JOIN</code> against the subquery. For this purpose the performance should be similar, and sometimes you need to join on <em>two</em> columns from the subquery.</p> <pre><code>SELECT table.* FROM table INNER JOIN ( SELECT MAX(id) AS id FROM table GROUP BY name ) maxid ON table.id = maxid.id </code></pre>
8,369,640
ListView: setItemChecked only works with standard ArrayAdapter - does NOT work when using customized ArrayAdapter?
<p>This is really weird.</p> <p>When I use the standard ArrayAdapter for a ListView calling setItemChecked works OK</p> <p>But when using a custom made ArrayAdapter it does not.</p> <p>What would be the reason? Is this a bug? Or am I missing something?</p> <pre><code>public class Test_Activity extends Activity { /** Called when the activity is first created. */ private List&lt;Model&gt; list; private ListView lView; public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity setContentView(R.layout.main); lView = (ListView) findViewById(R.id.ListView01); lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); list = getModel(); //with this adapter setItemChecked works OK lView.setAdapter(new ArrayAdapter&lt;Model&gt;(this, android.R.layout.simple_list_item_multiple_choice, list)); //************************** //PROBLEM: with this adapter it does not check any items on the screen // ArrayAdapter&lt;Model&gt; adapter = new Test_Class1(this, list); // lView.setAdapter(adapter); } private List&lt;Model&gt; getModel() { List&lt;Model&gt; list = new ArrayList&lt;Model&gt;(); list.add(get("0")); list.add(get("1")); list.add(get("2")); list.get(1).setSelected(true); Model m = list.get(1); list.add(get("3")); list.add(get("4")); list.add(get("5")); list.add(get("6")); list.add(get("7")); // Initially select one of the items return list; } private Model get(String s) { return new Model(s); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.results_screen_option_menu, menu); return true; } /** * @category OptionsMenu */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.select_all: { int size = lView.getAdapter().getCount(); for (int i = 0; i &lt;= size; i++) { //************************** PROBLEM lView.setItemChecked(i, true); // selects the item only for standard ArrayAdapter Log.i("xxx", "looping " + i); } } return true; case R.id.select_none: return true; } return false; } } </code></pre> <p>//------------------------------------------------------------</p> <pre><code>public class Test_Class1 extends ArrayAdapter&lt;Model&gt; { private final List&lt;Model&gt; list; private final Activity context; public Test_Class1(Activity context, List&lt;Model&gt; list) { super(context, R.layout.rowbuttonlayout2, list); this.context = context; this.list = list; } static class ViewHolder { protected TextView text; protected CheckBox checkbox; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; Log.i("xxx", "-&gt; getView " + position); if (convertView == null) { LayoutInflater inflator = context.getLayoutInflater(); view = inflator.inflate(R.layout.rowbuttonlayout, null); final ViewHolder viewHolder = new ViewHolder(); viewHolder.text = (TextView) view.findViewById(R.id.label); viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check); viewHolder.checkbox .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Model element = (Model) viewHolder.checkbox .getTag(); Log.i("xxx", "-&gt; onCheckedChanged"); element.setSelected(buttonView.isChecked()); Log.i("xxx", "&lt;- onCheckedChanged"); } }); view.setTag(viewHolder); viewHolder.checkbox.setTag(list.get(position)); } else { view = convertView; ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position)); } ViewHolder holder = (ViewHolder) view.getTag(); holder.text.setText(list.get(position).getName()); Log.i("xxx", "holder.checkbox.setChecked: " + position); holder.checkbox.setChecked(list.get(position).isSelected()); Log.i("xxx", "&lt;- getView " + position); return view; } } </code></pre>
8,369,927
4
0
null
2011-12-03 17:49:54.22 UTC
15
2017-12-15 23:13:08.95 UTC
2013-05-28 12:50:40.06 UTC
null
444,705
null
387,184
null
1
39
android|listview|android-arrayadapter
42,372
<p>Your row layout needs to be <code>Checkable</code> for <code>setItemChecked()</code> to work, in which case Android will manage calling <code>setChecked()</code> on your <code>Checkable</code> as the user clicks on the row. You would not need to be setting up your own <code>OnCheckedChangeListener</code>.</p> <p>For more, see:</p> <ul> <li><a href="https://stackoverflow.com/questions/5612600/listview-with-choice-mode-multiple-using-checkedtext-in-a-custom-view">ListView with CHOICE_MODE_MULTIPLE using CheckedText in a custom view</a></li> <li><a href="https://stackoverflow.com/questions/2652109/multiple-choice-list-with-custom-view">Multiple choice list with custom view?</a></li> <li><a href="http://www.marvinlabs.com/2010/10/custom-listview-ability-check-items/" rel="nofollow noreferrer">http://www.marvinlabs.com/2010/10/custom-listview-ability-check-items/</a></li> <li><a href="http://tokudu.com/2010/android-checkable-linear-layout/" rel="nofollow noreferrer">http://tokudu.com/2010/android-checkable-linear-layout/</a></li> <li><a href="http://alvinalexander.com/java/jwarehouse/apps-for-android/RingsExtended/src/com/example/android/rings_extended/CheckableRelativeLayout.java.shtml" rel="nofollow noreferrer">http://alvinalexander.com/java/jwarehouse/apps-for-android/RingsExtended/src/com/example/android/rings_extended/CheckableRelativeLayout.java.shtml</a></li> </ul>
8,936,397
How to change the Grid.Row and Grid.Column of the control from code behind in wpf
<p>I have the control placed in <code>DataGrid</code> like this:</p> <pre><code>&lt;Label Name="lblDescription" HorizontalAlignment="Left" Margin="0,5,0,0" Grid.Row="2" Grid.Column="2" /&gt; &lt;TextBox Name="txtDescription" HorizontalAlignment="Left" Width="200" Margin="0,5,0,0" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" AcceptsReturn="True" Grid.RowSpan="2" Grid.Row="2" Grid.Column="3" /&gt; </code></pre> <p>How can I change the <code>Grid.Row</code> and <code>Grid.Column</code> of the control in code behind?</p>
8,936,592
2
0
null
2012-01-20 03:26:11.173 UTC
4
2018-09-02 11:25:47.71 UTC
2018-09-02 11:25:47.71 UTC
null
893,863
null
769,091
null
1
46
c#|wpf
39,607
<p>There is also a static method to do this (analogous to using the property in code to set a non-attached property rather than using the DP there).</p> <pre><code>Grid.SetRow(txtDescription, 1); </code></pre> <p>You may find this more readable.</p>
48,339,829
Async programming and Azure functions
<p>In the Azure functions "Performance considerations" part, <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-best-practices" rel="noreferrer">Functions Best Practices</a>, under "Use async code but avoid blocking calls", <code>async</code> programming is the suggested practice for performance improvement. However, what is the best way to use it? For example, in my scenario, I have the following Service Bus Trigger:</p> <pre><code>public static void Run( [ServiceBusTrigger("topicname", "subname", AccessRights.Manage, Connection = "TopicConnection")]string message, TraceWriter log) { try { log.Info($"C# ServiceBus topic trigger function processed message: {message}"); Task.Run(() =&gt; PushToDb(message, log)); } catch(Exception ex) { log.Info($"Exception found {ex.Message}"); } } </code></pre> <p>In the above code, I call <code>PushToDb</code> method <code>async</code>. However, since it runs in the background, Function runtime assumes that the messages are consumed successfully and completes it. What if the <code>PushToDb</code> method throws an exception? How can I make sure runtime knows that it's not complete, but rather should be abandoned?</p> <p>Looking to use <code>async</code> as much as possible for performance.</p>
48,339,873
1
1
null
2018-01-19 11:13:22.98 UTC
10
2020-04-08 22:24:13.513 UTC
2020-04-08 22:24:13.513 UTC
null
1,454,879
null
945,175
null
1
44
c#|azure|azure-functions
34,817
<p>You can make the function async:</p> <pre><code>public static async Task Run( [ServiceBusTrigger("topicname", "subname", AccessRights.Manage, Connection = "TopicConnection")]string message, TraceWriter log) { try { log.Info($"C# ServiceBus topic trigger function processed message: {message}"); await PushToDb(message, log); } catch(Exception ex) { log.Info($"Exception found {ex.Message}"); } } </code></pre> <p>The Functions runtime allows you to make your function async and return a Task.</p> <p>In this case we can just await the call so we can handle exceptions normally.</p>
57,697,664
What is the benefit of using withStyles over makeStyles?
<p>Are there different use cases for each? When should one use withStyles over makeStyles?</p>
57,702,612
2
0
null
2019-08-28 17:48:59.943 UTC
8
2021-08-06 15:16:29.413 UTC
null
null
null
null
11,302,328
null
1
30
css|reactjs|material-ui
29,251
<p><strong>UPDATE</strong> This question/answer is geared towards v4 of Material-UI. I have added some v5 info/links at the end.</p> <hr /> <p>The <a href="https://material-ui.com/styles/basics/#hook-api" rel="noreferrer">Hook API</a> (<code>makeStyles/useStyles</code>) can only be used with function components.</p> <p>The <a href="https://material-ui.com/styles/basics/#higher-order-component-api" rel="noreferrer">Higher-order component API</a> (<code>withStyles</code>) can be used with either class components or function components.</p> <p>They both provide the same functionality and there is no difference in the <code>styles</code> parameter for <code>withStyles</code> and <code>makeStyles</code>.</p> <p>If you are using it with a function component, then I would recommend using the Hook API (<code>makeStyles</code>). <code>withStyles</code> has a little bit of extra overhead compared to <code>makeStyles</code> (and internally delegates to <code>makeStyles</code>).</p> <p>If you are customizing the styles of a Material-UI component, using <code>withStyles</code> is preferable to wrapping it with your own component solely for the purpose of calling <code>makeStyles/useStyles</code> since then you would just be re-implementing <code>withStyles</code>.</p> <p>So wrapping a Material-UI component might look like the following example (from <a href="https://stackoverflow.com/questions/36759985/how-to-style-material-uis-tooltip/54606987#54606987">How to style Material-UI&#39;s tooltip?</a>):</p> <pre><code>const BlueOnGreenTooltip = withStyles({ tooltip: { color: &quot;lightblue&quot;, backgroundColor: &quot;green&quot; } })(Tooltip); </code></pre> <p><a href="https://codesandbox.io/s/tooltip-customization-9fle8?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Tooltip customization" /></a></p> <hr /> <p>For v5 of Material-UI, <code>styled</code> replaces <code>withStyles</code> and <code>makeStyles</code>. <a href="https://stackoverflow.com/questions/36759985/how-to-style-material-uis-tooltip/54606987#54606987">How to style Material-UI&#39;s tooltip?</a> contains v5 examples. I also have further discussion of v5 styling options in <a href="https://stackoverflow.com/questions/68674848/using-conditional-styles-in-material-ui-with-styled-vs-jss/68675923#68675923">Using conditional styles in Material-UI with styled vs JSS</a>.</p>
2,668,574
onchange on dropdownlist
<p>my question is continuation of what i have asked see the link. <a href="https://stackoverflow.com/questions/2640001/load-country-state-city">Load Country/State/City</a></p> <p>i have expand to load my drop downs list from db and i just need a way to wire onchange method in my first dropdownlist and second, please see the code. appreciate any help.</p> <p><strong><em>Append latest code:</em></strong></p> <pre><code>&lt;select id="country" onchange="getStateByCountryId()"&gt;&lt;/select&gt; &lt;br /&gt; &lt;select id="state"&gt;&lt;/select&gt; &lt;br /&gt; $(document).ready(function() { var options = { type: "POST", url: "SearchPage.aspx/LoadCountry", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { var returnedArray = msg.d; country = $("#country"); country.append('&lt;option&gt;Select a Country&lt;/option&gt;'); for (i = 0; i &lt; returnedArray.length; i++) { country.append("&lt;option value='" + returnedArray[i].Id + "'&gt;" + returnedArray[i].Name + "&lt;/option&gt;"); } } }; $.ajax(options); }); function getStateByCountryId() { $("#country").change(function() { var _selected = $("#country").val(); var options = { type: "POST", url: "SearchPage.aspx/StateBy", data: "{'countryId':'" + _selected + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { $('#state').empty(); var returnedArray = msg.d; state = $("#state"); for (var i = 0; i &lt; returnedArray.length; ++i) { state.append("&lt;option value='" + returnedArray[i].Id + "'&gt;" + returnedArray[i].Name + "&lt;/option&gt;"); } } }; $.ajax(options); }); } </code></pre> <p>but does not populate? the way i am doing is that how you suppose to do? </p> <p>thanks.</p>
2,668,629
2
0
null
2010-04-19 15:18:31.123 UTC
3
2014-03-20 11:25:10.703 UTC
2017-05-23 12:18:20.913 UTC
null
-1
null
275,390
null
1
20
jquery|ajax
60,507
<pre><code>$("#state").change(function(){ //on-change code goes in here. //variable "this" references the state dropdown element }); </code></pre>
33,641,663
Why isn't this an instance of map of google.maps.Map? InvalidValueError: setMap: not an instance of Map;
<p>I am getting the error <code>Assertion failed: InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama</code> on a google map web page. I then read <a href="https://stackoverflow.com/questions/20003952/uncaught-invalidvalueerror-setmap-not-an-instance-of-map">this question</a> elsewhere here on Stack Overflow which told me I need an instance of the <code>google.maps.MAP</code> object. I thought that by calling that object in order to initialize the map that I would be calling that object. </p> <p>Previously, I got the error <code>i is not defined</code> so I moved the <code>createMarker</code> function into the <code>$.getJSON</code> function where it has local scope.</p> <p>Do I need to call <code>google.mapsMap</code> somewhere else?</p> <p>What am I doing wrong?</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;h1 style="text-align: center;"&gt;Hello World&lt;/h1&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;ul id="list"&gt;&lt;/ul&gt; &lt;/body&gt; </code></pre> <p>CSS:</p> <pre><code>#map { height: 300px; width: 600px; border: 1px solid black; margin: 0 auto; } </code></pre> <p>JavaScript:</p> <pre><code>function initialize(){ var mapProp = { center: new google.maps.LatLng(38, -78), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('map'), mapProp); }; $(document).ready(function(){ var url = 'https://opendata.howardcountymd.gov/resource/96q9-qbh7.json'; initialize(); $.getJSON(url, function (data){ $.each(data, function(i, field) { $('#list').append("&lt;li&gt;" + data[i].location.longitude + " &amp; " + data[i].location.latitude + "&lt;/li&gt;"); createMarker(data); function createMarker (data) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude), map: map, title: field.crossroad }); }; }); }); }); </code></pre>
33,641,784
3
0
null
2015-11-10 23:32:06.517 UTC
2
2020-04-11 12:02:36.967 UTC
2017-05-23 12:16:25.81 UTC
null
-1
null
5,194,667
null
1
13
javascript|google-maps|object|google-maps-api-3
41,350
<p>The map variable that is an instance of a <code>google.maps.Map</code> is local to the <code>initialize</code> function. The map variable in the <code>createMarker</code> function is undefined. One option: define the variable in the global scope:</p> <pre><code>var map; </code></pre> <p>then just initialize it in the <code>initialize</code> function:</p> <pre><code>function initialize(){ var mapProp = { center: new google.maps.LatLng(38, -78), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map'), mapProp); }; </code></pre> <p><a href="http://jsfiddle.net/geocodezip/9zy1zd61/2/" rel="noreferrer">proof of concept fiddle</a></p> <p><strong>code snippet:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var map; function initialize() { var mapProp = { center: new google.maps.LatLng(38, -78), zoom: 6, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map'), mapProp); }; $(document).ready(function() { var url = 'https://opendata.howardcountymd.gov/resource/96q9-qbh7.json'; initialize(); $.getJSON(url, function(data) { $.each(data, function(i, field) { $('#list').append("&lt;li&gt;" + data[i].location.longitude + " &amp; " + data[i].location.latitude + "&lt;/li&gt;"); createMarker(data); function createMarker(data) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude), map: map, title: field.crossroad }); }; }); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#map { height: 300px; width: 600px; border: 1px solid black; margin: 0 auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"&gt;&lt;/script&gt; &lt;h1 style="text-align: center;"&gt;Hello World&lt;/h1&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;ul id="list"&gt;&lt;/ul&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/geocodezip/9zy1zd61/3/" rel="noreferrer">Another option would be to return the <code>map</code> from the initialize function</a></p>
21,505,956
authentication from json api on Rails with Devise
<p>I use devise and rails app for authenticate users from mobile; so the user sign up/sign in/ sign out from their mobile devices, the problem is for (sign up/sign in) so that the user send his plain text password over the wire, how can I encrypt the plain text password and decrypt it on the server side? I am very new to RoR and Devise.</p>
21,540,395
1
0
null
2014-02-02 01:28:43.587 UTC
10
2014-02-04 00:02:00.04 UTC
2014-02-03 05:56:28.947 UTC
null
631,400
null
631,400
null
1
5
ruby-on-rails|json|devise|passwords|restful-authentication
6,400
<p>I'm not sure what you are trying to accomplish when you say "send plaint text password over wire" but below [1] is a good tutorial for creating a json api with devise. It uses the old token_authenticable module which has been removed from devise so follow this gist [2] to make modifications.</p> <p>[1]<a href="http://lucatironi.github.io/tutorial/2012/10/15/ruby_rails_android_app_authentication_devise_tutorial_part_one/">http://lucatironi.github.io/tutorial/2012/10/15/ruby_rails_android_app_authentication_devise_tutorial_part_one/</a></p> <p>[2]<a href="https://gist.github.com/josevalim/fb706b1e933ef01e4fb6">https://gist.github.com/josevalim/fb706b1e933ef01e4fb6</a></p>
30,231,187
List only stopped Docker containers
<p>Docker gives you a way of listing running containers or all containers including stopped ones.</p> <p>This can be done by:</p> <pre><code>$ docker ps # To list running containers </code></pre> <p>Or by</p> <pre><code>$ docker ps -a # To list running and stopped containers </code></pre> <p>Do we have a way of only listing containers that have been stopped?</p>
30,231,188
3
0
null
2015-05-14 06:56:21.87 UTC
41
2021-10-21 06:40:33.317 UTC
2018-07-23 17:11:10.41 UTC
null
63,550
null
1,747,018
null
1
267
docker|containers
210,662
<p>Only stopped containers can be listed using:</p> <pre><code>docker ps --filter "status=exited" </code></pre> <p>or</p> <pre><code>docker ps -f "status=exited" </code></pre>
29,876,342
How to get (only) author name or email in git given SHA1?
<p>I would like to check for author's e-mail and name, surname to verify who's pushing to my repo.</p> <p>Is there any way that I can come up with a command in git to show commiter's name/e-mail given only SHA1 of the commit?</p> <p>This is what I came up with but it's far from ideal solution (the first solution is for git hook that's why it's using 2 SHA1s with <code>rev-list</code>. The second one simply uses <code>git show</code>):</p> <pre><code>git rev-list -n 1 --pretty=short ccd3970..6ddf170 | grep Author | cut -d ' ' -f2- | rev | cut -d ' ' -f2- | rev git show 6ddf170 | grep Author | cut -d ' ' -f2- | rev | cut -d ' ' -f2- | rev </code></pre>
29,876,744
3
0
null
2015-04-26 10:13:47.927 UTC
9
2021-06-09 08:45:17.463 UTC
null
null
null
null
675,100
null
1
58
git|commit|sha1|author
53,242
<p>You can use the following command:</p> <pre><code> git log --format='%ae' HASH^! </code></pre> <p>It works with <code>git show</code> as well. You need to include <code>-s</code> to suppress the diff.</p> <pre><code>git show -s --format='%ae' HASH </code></pre>
35,233,161
IllegalArgumentException: Could not locate call adapter for rx.Observable RxJava, Retrofit2
<p>I am getting the above error while calling the rest api. I am using both retrofit2 and RxJava.</p> <h2>ServiceFactory.java</h2> <pre><code>public class ServiceFactory { public static &lt;T&gt; T createRetrofitService(final Class&lt;T&gt; clazz, final String endpoint){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(endpoint) //.addConverterFactory(GsonConverterFactory.create()) .build(); T service = retrofit.create(clazz); return service; } </code></pre> <p>}</p> <h2>MovieService.java</h2> <pre><code>public interface MovieService{ //public final String API_KEY = "&lt;apikey&gt;"; public final String SERVICE_END = "https://api.mymovies.org/3/"; @GET("movie/{movieId}??api_key=xyz") Observable&lt;Response&lt;Movies&gt;&gt; getMovies(@Field("movieId") int movieId); </code></pre> <p>}</p> <h1>Inside MainActivity</h1> <pre><code> MovieService tmdbService = ServiceFactory.createRetrofitService(MovieService.class, MovieService.SERVICE_END); Observable&lt;Response&lt;Movies&gt;&gt; responseObservable = tmdbService.getMovies(400); responseObservable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber&lt;Response&lt;Movies&gt;&gt;() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Response&lt;Movies&gt; moviesResponse) { } }); </code></pre>
35,238,185
5
0
null
2016-02-05 20:43:50.21 UTC
6
2019-01-29 06:58:49.013 UTC
2016-02-06 06:44:27.643 UTC
null
5,890,040
null
5,890,040
null
1
37
android|rx-java|retrofit2
26,104
<p>Be sure to add <code>implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'</code> or whatever version you are using to your dependencies, and then configure retrofit with that converter:</p> <pre><code>Retrofit retrofit = new Retrofit.Builder() .baseUrl(endpoint) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); </code></pre> <p><strong>Updated</strong></p> <p><code>RxJavaCallAdapterFactory</code> was renamed to <a href="https://github.com/square/retrofit/blob/master/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java" rel="noreferrer">RxJava2CallAdapterFactory</a>. Changed the snipped above.</p>
36,843,215
How can I use the Jenkins Copy Artifacts Plugin from within the pipelines (jenkinsfile)?
<p>I am trying to find an example of using the Jenkins Copy Artifacts Plugin from within Jenkins pipelines (workflows).</p> <p>Can anyone point to a sample Groovy code that is using it?</p>
36,872,567
4
0
null
2016-04-25 14:18:01.25 UTC
8
2022-07-08 13:43:14.25 UTC
null
null
null
null
99,834
null
1
47
groovy|jenkins-workflow|jenkins-pipeline
87,123
<p>If builds are not running in the same pipeline you can use direct <code>CopyArtifact</code> plugin, here is example: <a href="https://www.cloudbees.com/blog/copying-artifacts-between-builds-jenkins-workflow">https://www.cloudbees.com/blog/copying-artifacts-between-builds-jenkins-workflow</a> and example code:</p> <pre><code>node { // setup env.. // copy the deployment unit from another Job... step ([$class: 'CopyArtifact', projectName: 'webapp_build', filter: 'target/orders.war']); // deploy 'target/orders.war' to an app host } </code></pre>
20,777,454
Google Chrome Customize Developer Tools Theme / Color Schema
<p>How to change color schema on Developer Tools, JavaScript Console in Google Chrome ?</p> <p>Like this:</p> <p><img src="https://i.stack.imgur.com/0cBxK.png" alt="enter image description here"></p>
28,316,687
6
0
null
2013-12-25 22:57:26.937 UTC
16
2021-03-14 04:42:41.71 UTC
2017-08-12 00:13:17.99 UTC
null
632,951
null
2,650,174
null
1
46
javascript|css|google-chrome-extension|google-chrome-devtools|google-chrome-theme
31,307
<ol> <li>Install a DevTools Theme like <a href="https://chrome.google.com/webstore/detail/devtools-theme-zero-dark/bomhdjeadceaggdgfoefmpeafkjhegbo" rel="noreferrer">Zero Dark Matrix</a></li> <li>Goto <code>chrome://flags/#enable-devtools-experiments</code>, and enable <code>Developer Tools experiments</code>.</li> <li>Select <code>Relaunch Now</code> at the bottom of the page.</li> <li><kbd>F12</kbd> to Open developer tools, go to <code>Settings</code>, select <code>Experiments</code> tab, and check <code>Allow custom UI themes</code>.</li> <li><kbd>F12</kbd>, Reload DevTools. </li> </ol>
19,046,969
UITextView content size different in iOS7
<p>I am using an <code>UITextView</code> that will be expandable by taping a "more" button. The problem is the following:</p> <p>On iOS6 I use this,</p> <pre><code>self.DescriptionTextView.text = @"loong string"; if(self.DescriptionTextView.contentSize.height&gt;self.DescriptionTextView.frame.size.height) { //set up the more button } </code></pre> <p>The problem is that on iOS7 the <code>contentSize.height</code> returns a different value (far smaller) than the value it returns on iOS6. Why is this? How to fix it?</p>
19,047,464
4
0
null
2013-09-27 09:11:34.05 UTC
21
2014-05-23 05:33:08.74 UTC
2014-05-23 05:33:08.74 UTC
null
1,917,782
null
1,028,028
null
1
15
ios|objective-c|cocoa-touch|ios7|uitextview
18,981
<p>The content size property no longer works as it did on iOS 6. Using sizeToFit as others suggest may or may not work depending on a number of factors.</p> <p>It didn't work for me, so I use this instead:</p> <pre><code>- (CGFloat)measureHeightOfUITextView:(UITextView *)textView { if (floor(NSFoundationVersionNumber) &gt; NSFoundationVersionNumber_iOS_6_1) { // This is the code for iOS 7. contentSize no longer returns the correct value, so // we have to calculate it. // // This is partly borrowed from HPGrowingTextView, but I've replaced the // magic fudge factors with the calculated values (having worked out where // they came from) CGRect frame = textView.bounds; // Take account of the padding added around the text. UIEdgeInsets textContainerInsets = textView.textContainerInset; UIEdgeInsets contentInsets = textView.contentInset; CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right; CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom; frame.size.width -= leftRightPadding; frame.size.height -= topBottomPadding; NSString *textToMeasure = textView.text; if ([textToMeasure hasSuffix:@"\n"]) { textToMeasure = [NSString stringWithFormat:@"%@-", textView.text]; } // NSString class method: boundingRectWithSize:options:attributes:context is // available only on ios7.0 sdk. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle }; CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding); return measuredHeight; } else { return textView.contentSize.height; } } </code></pre>
19,108,044
Nginx Routing path to server
<p>I have a few sites. Each site has its own "server" section with a server_name that looks like this </p> <pre><code>server { ... server_name siteA.example.com; root /var/www/siteA; ... } </code></pre> <p>I can therefore bring up the site using the url <a href="http://siteA.example.com" rel="noreferrer">http://siteA.example.com</a></p> <p>I however also need to bring up the site by using the url <a href="http://example.com/siteA" rel="noreferrer">http://example.com/siteA</a> How can this be done?</p>
19,111,103
1
0
null
2013-10-01 04:33:57.56 UTC
8
2021-02-17 02:22:59.32 UTC
null
null
null
null
1,556,338
null
1
7
nginx
34,367
<p>Two options to add to your config below ...</p> <p><strong>Option 1:</strong></p> <pre><code>server { ... server_name example.com; ... location /siteA { root /var/www/siteA; ... } location /siteB { root /var/www/siteB; ... } ... } </code></pre> <p><strong>Option 2:</strong></p> <pre><code>server { ... server_name example.com; ... location /siteA { return 301 http://siteA.example.com$request_uri; } location /siteB { return 301 http://siteB.example.com$request_uri; } ... } </code></pre> <p>First option simply serves from <code>example.com/siteA</code> in addition while second option redirects to <code>siteA.example.com</code> </p>
21,018,355
SHA256withRSA what does it do and in what order?
<p>I'm a total newbie when it comes to cryptography and such things. I don't (and dont want to) know the details of the SHA256 and RSA. I "know" what they do, not how they do it, and for now that's enough.</p> <p>I'm wondering what the "SHA256withRSA"-algorithm (if you can call it that) actually do and in what order. For example, does it hash the data with SHA256 and then encrypts it using RSA or is it vice-versa, or something else?</p> <p>The reason I'm asking is because I wanna do the java equivalent of: </p> <pre><code>Signature.getInstance("SHA256withRSA") signature.initSign(privateKey); //privateKey == a key extracted from a .p12 file </code></pre> <p>in Objective-C on iOS. And I couldn't seem to find any stuff that does exactly this, therefore I'm asking, can I just hash the data (SHA256) and then encrypt it (RSA) (or vice-versa) and get the same behavior?</p> <p>What is the suggested solution for doing this kind of thing? </p> <p>Thank you!</p> <p>EDIT: I failed to mention that I sign the data using a private key that is obtained by doing:</p> <pre><code>KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(new File(filename)), password.toCharArray()); PrivateKey privateKey = (PrivateKey)keystore.getKey(alias, password.toCharArray()); </code></pre> <p>Where filename is for example: "/somewhere/mykey.p12".</p>
21,019,504
1
0
null
2014-01-09 11:02:16.823 UTC
9
2019-05-28 21:05:51.503 UTC
2019-05-28 21:05:51.503 UTC
null
2,224,584
null
2,422,321
null
1
28
java|ios|cryptography|rsa|sha256
38,276
<p><code>&quot;SHA256withRSA&quot;</code> implements the PKCS#1 v1.5 padding and modular exponentiation with the formal name <a href="https://www.rfc-editor.org/rfc/rfc3447#page-32" rel="nofollow noreferrer">RSASSA-PKCS1-v1_5</a> after calculating the hash over the data using SHA256.</p> <p>So the general order is:</p> <ol> <li>hashing;</li> <li>padding the hash for signature generation;</li> <li>modular exponentiation using the private exponent and the modulus.</li> </ol> <p>The padding used for encryption and signature generation is different, so using encryption may result in erroneous signatures.</p> <hr /> <p>The PKCS#1 v1.5 padding scheme has been superseded by PSS. For new protocols it is advisable to use the PSS scheme instead. For RSA a very readable public standard exists. This standard has also been used as a base for <a href="https://www.rfc-editor.org/rfc/rfc3447" rel="nofollow noreferrer">RFC 3447: Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1</a> (which is basically a copy).</p> <hr /> <p>With regards to the padding in iOS, please check <a href="https://stackoverflow.com/a/5066573/589259">this answer</a> by Thomas Pornin. Basically you should create the SHA-256 hash, prefix a static block of data (defined in the PKCS#1 specifications) then use <code>SecKeyRawSign</code> using <code>kSecPaddingPKCS1</code>.</p> <p>For your convenience, the PKCS#1 defined block of data that needs to be prefixed in hex notation for SHA-256 (it can be bit hard to find in the standard documents, it's in the notes of <a href="https://www.rfc-editor.org/rfc/rfc3447#section-9.2" rel="nofollow noreferrer">section 9.2</a>):</p> <pre><code>30 31 30 0D 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20 </code></pre> <hr /> <p>Notes:</p> <ul> <li>The above steps do not include the conversion from bytes to integer and vice versa. The result of raw RSA operations are generally converted to an unsigned big endian encoding with the same size of the modulus in bytes (which is generally the same as the key size, as the key size is already a multiple of 8). These conversions are called I2OSP and OS2IP in the RFC's.</li> </ul>
22,829,854
How to upload files to a Windows Azure Storage
<p>I'm trying to publish a package that has 800mb+. But the Windows Azure publish only allows up to 600mb, so maybe I need to upload some unstructured files first to Windows Azure storage.</p> <p>What's the best way to upload files to a Windows Azure storage?</p>
22,880,897
4
0
null
2014-04-03 06:46:33.387 UTC
2
2022-05-30 10:39:42.52 UTC
2015-06-29 09:20:11.63 UTC
null
4,023
null
2,341,714
null
1
20
azure|azure-storage|azure-blob-storage
43,645
<blockquote> <p>what's the best way to upload files to a windows azure storage?</p> </blockquote> <p>There's no <em>best way</em> - you'll need to decide that for yourself. But... here are a few options:</p> <ul> <li>Create an app, using one of the language SDKs (.NET, PHP, Ruby, Java, Node, Python, Node). The SDKs each have coverage of blob storage, allowing you to create an upload app. You could also make direct REST API calls instead of using the SDK. You'll find many examples of this around the web, including <a href="http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs-20/#upload-blob" rel="noreferrer">this .NET sample</a> on the <a href="http://www.azure.com" rel="noreferrer">Azure.com</a> site.</li> <li>Call the PowerShell command <code>Set-AzureStorageBlobContent</code>, which copies a local file to a blob</li> <li>Call the Azure cross-platform CLI command <code>azure storage blob upload</code>, which copies a local file to a blob</li> <li>Use a storage copy tool. The Azure team provides <a href="http://blogs.msdn.com/b/windowsazurestorage/archive/2013/09/07/azcopy-transfer-data-with-re-startable-mode-and-sas-token.aspx" rel="noreferrer">AzCopy</a>. There are 3rd-party tools as well. The Azure Storage team recently <a href="http://blogs.msdn.com/b/windowsazurestorage/archive/2014/03/11/windows-azure-storage-explorers-2014.aspx" rel="noreferrer">blogged</a> about various 3rd-party tools available.</li> </ul>
24,890,675
File Upload using Rest API in Java
<p>I am new to REST API. I want to upload user selected file to the user provided path(remote or local path) using REST API. My html file is having 1 text box and 1 file chooser. User will enter FilePath (local or remote machine folder location) in the text box. Please suggest how to solve this issue.</p> <p>Here is my code:</p> <p><strong>FileUpload.html:</strong>:</p> <pre><code>&lt;body&gt; &lt;form action="rest/file/upload" method="post" enctype="multipart/form-data"&gt; &lt;p&gt; Select a file : &lt;input type="file" name="file" size="45" /&gt; &lt;/p&gt; &lt;p&gt;Target Upload Path : &lt;input type="text" name="path" /&gt;&lt;/p&gt; &lt;input type="submit" value="Upload It" /&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p><strong>UploadFileService.java</strong></p> <pre><code>@Path("/file") public class UploadFileService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormParam("path") String path) { /*String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();*/ /*String uploadedFileLocation = //10.217.14.88/Installables/uploaded/" + fileDetail.getFileName();*/ String uploadedFileLocation = path + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p><strong>Web.xml</strong></p> <pre><code>&lt;display-name&gt;JAXRSFileUploadJerseyExample&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;jersey-serlvet&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;com.mkyong.rest&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;jersey-serlvet&lt;/servlet-name&gt; &lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p><strong>Exception:</strong></p> <pre><code>HTTP Status 500 - com.sun.jersey.api.container.ContainerException: Exception obtaining parameters type Exception report message com.sun.jersey.api.container.ContainerException: Exception obtaining parameters description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: com.sun.jersey.api.container.ContainerException: Exception obtaining parameters com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:425) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) root cause com.sun.jersey.api.container.ContainerException: Exception obtaining parameters com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:54) com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) root cause java.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded com.sun.jersey.server.impl.model.parameter.FormParamInjectableProvider$FormParamInjectable.getValue(FormParamInjectableProvider.java:81) com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46) com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) </code></pre>
24,902,176
2
0
null
2014-07-22 14:51:40.64 UTC
6
2016-12-02 10:06:15.84 UTC
2016-12-02 10:06:15.84 UTC
null
4,205,751
null
2,743,948
null
1
10
java|web-services|rest|file-upload|jersey
103,045
<p>I have updated signature of method in below class and its working fine. Instead of <code>@FormParam</code>, used <code>@FormDataParam("path")</code> String path and it solved my issue. Below is the updated code:</p> <pre><code>import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.sun.jersey.core.header.FormDataContentDisposition; import com.sun.jersey.multipart.FormDataParam; @Path("/file") public class UploadFileService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String path) { // Path format //10.217.14.97/Installables/uploaded/ System.out.println("path::"+path); String uploadedFileLocation = path + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre>
46,151,633
How to make default time zone apply in Spring Boot Jackson Date serialization
<p>I have configured my Spring Boot application to serialize dates as ISO8601 strings:</p> <pre><code>spring: jackson: serialization: write-dates-as-timestamps: false </code></pre> <p>This is what I am getting:</p> <pre><code>"someDate": "2017-09-11T07:53:27.000+0000" </code></pre> <p>However my time zone is Europe/Madrid. In fact if I print <code>TimeZone.getDefault()</code> that's what I get.</p> <p>How can I make Jackson serialize those datetime values using the actual timezone? GMT+2</p> <pre><code>"someDate": "2017-09-11T09:53:27.000+0200" </code></pre>
46,151,899
4
0
null
2017-09-11 08:50:48.847 UTC
6
2019-12-05 20:00:34.24 UTC
2017-09-11 09:04:41.2 UTC
null
1,729,795
null
1,729,795
null
1
29
spring|spring-mvc|spring-boot|jackson|jackson2
56,726
<p>Solved registering a Jackson2ObjectMapperBuilderCustomizer bean:</p> <pre><code>@Bean public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() { return jacksonObjectMapperBuilder -&gt; jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault()); } </code></pre>
1,010,370
How do I launch a process with low priority? C#
<p>I want to execute a command line tool to process data. It does not need to be blocking. I want it to be low priority. So I wrote the below</p> <pre><code> Process app = new Process(); app.StartInfo.FileName = @"bin\convert.exe"; app.StartInfo.Arguments = TheArgs; app.PriorityClass = ProcessPriorityClass.BelowNormal; app.Start(); </code></pre> <p>However, I get a <code>System.InvalidOperationException</code> with the message "No process is associated with this object." Why? How do I properly launch this app in low priority?</p> <p>Without the line <code>app.PriorityClass = ProcessPriorityClass.BelowNormal;</code> the app runs fine.</p>
1,010,377
3
0
null
2009-06-18 01:34:37.587 UTC
3
2017-06-28 08:03:20.247 UTC
2017-06-28 08:03:20.247 UTC
null
39,590
user34537
null
null
1
40
c#|process|shellexecute
17,642
<p>Try setting the PriorityClass AFTER you start the process. Task Manager works this way, allowing you to set priority on a process that is already running.</p>
22,286,957
Count the number of non-zero elements of each column
<p>Very new to R and I have a .rda file that contains a matrix of gene IDs and counts for each ID in 96 columns. It looks like this:</p> <p><img src="https://i.stack.imgur.com/x8kGI.png" alt="enter image description here"></p> <p>I want to get separate counts for the number of non-zero items in each column. I've been trying the sum() function in a loop, but perhaps I don't understand loop syntax in R. Any help appreciated. Thanks!</p> <p>Forest</p>
22,286,988
4
0
null
2014-03-09 19:25:57.83 UTC
10
2021-09-10 12:44:12.297 UTC
null
null
null
null
2,904,305
null
1
42
r
111,281
<p>What about:</p> <pre><code>apply(your.matrix, 2, function(c)sum(c!=0)) </code></pre> <p>Does this help?</p> <p><strong>edit:</strong></p> <p>Even better:</p> <pre><code>colSums(your.matrix != 0) </code></pre> <p><strong>edit 2:</strong></p> <p>Here we go, with an example for ya:</p> <pre><code>&gt; example = matrix(sample(c(0,0,0,100),size=70,replace=T),ncol=7) &gt; example [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0 100 0 0 100 0 100 [2,] 100 0 0 0 0 0 100 [3,] 0 0 0 0 0 0 100 [4,] 0 100 0 0 0 0 0 [5,] 0 0 100 100 0 0 0 [6,] 0 0 0 100 0 0 0 [7,] 0 100 100 0 0 0 0 [8,] 100 0 0 0 0 0 0 [9,] 100 100 0 0 100 0 0 [10,] 0 0 0 0 0 100 0 &gt; colSums(example != 0) [1] 3 4 2 2 2 1 3 </code></pre> <p>(new example, the previous example with '1' values was not suited to show that we are summing the <em>number</em> of cells, not their <em>contents</em>)</p>
22,281,059
set object is not JSON serializable
<p>When I try to run the following code:</p> <pre><code>import json d = {'testing': {1, 2, 3}} json_string = json.dumps(d) </code></pre> <p>I get the following exception:</p> <pre><code>Traceback (most recent call last): File "json_test.py", line 4, in &lt;module&gt; json_string = json.dumps(d) File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/usr/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/usr/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: set([1, 2, 3]) is not JSON serializable </code></pre> <p>What can I do to successfully use <code>json.dumps</code> with objects containing <code>set</code>s?</p>
22,281,062
2
0
null
2014-03-09 10:25:55.31 UTC
10
2014-03-10 13:16:54.277 UTC
2014-03-09 10:57:25.54 UTC
null
1,252,759
null
3,398,153
null
1
39
python|json|set
89,543
<p>Turn sets into lists before serializing, or use a custom <code>default</code> handler to do so:</p> <pre><code>def set_default(obj): if isinstance(obj, set): return list(obj) raise TypeError result = json.dumps(yourdata, default=set_default) </code></pre>
41,763,723
How can I run functions within a Vue data object?
<p>So I am trying to use the following component within Vue JS:</p> <pre><code>Vue.component('careers', { template: '&lt;div&gt;A custom component!&lt;/div&gt;', data: function() { var careerData = []; client.getEntries() .then(function (entries) { // log the title for all the entries that have it entries.items.forEach(function (entry) { if(entry.fields.jobTitle) { careerData.push(entry); } }) }); return careerData; } }); </code></pre> <p>The following code emits an error like so:</p> <pre><code>[Vue warn]: data functions should return an object: https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function (found in component &lt;careers&gt;) </code></pre> <p>However as you can see I am running a foreach through all of my Contentful <code>entries</code>, then each object within entries is being pushed to an array, I then try to return the array but I get an error.</p> <p>Any idea how I can extract all of my <code>entries</code> to my data object within my component?</p> <p>When I use the <code>client.getEntries()</code> function outside of my Vue component I get the following data:</p> <p><a href="https://i.stack.imgur.com/f41iM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f41iM.png" alt="enter image description here" /></a></p>
41,763,856
2
1
null
2017-01-20 12:28:44.357 UTC
2
2022-07-13 22:59:25.787 UTC
2022-07-13 22:59:25.787 UTC
null
6,277,151
null
6,722,379
null
1
14
javascript|vue.js|vue-component
46,167
<p>First thing first - keep your data model as clean as possible - so no methods there.</p> <p>Second thing, as error says, when you are dealing with data into component, data should be function that returns an object:</p> <pre><code>Vue.component('careers', { template: '&lt;div&gt;A custom component!&lt;/div&gt;', data: function() { return { careerData: [] } } }); </code></pre> <p>As I write, data fetching and other logic shouldn't be in the data, there is an object reserved for that in Vue.js called <code>methods</code>.</p> <p>So move your logic into the methods, and when you have received the data, you can assign it to <code>careerData</code> like this:</p> <pre><code>this.careerData = newData </code></pre> <p>or push things to the array like you did before. And then at the end, you can call the method on some lifecycle hooks:</p> <pre><code>Vue.component('careers', { template: '&lt;div&gt;A custom component!&lt;/div&gt;', data: function() { return { careerData: [] } }, created: function() { this.fetchData(); }, methods: { fetchData: function() { // your fetch logic here } } }); </code></pre>
20,710,453
How to pull back all parent/child data in complex object
<p>I have these two tables with a one (category) to many (product) relationship in the database:</p> <pre><code>Table Product Name Description ProductCategory Table Category Category Description </code></pre> <p>And these classes:</p> <pre><code>public class Product { public string Name { get; set; } public string Description { get; set; } public Category CategoryName { get; set; } } public class Category { public string CategoryName { get; set; } public string Description { get; set; } } </code></pre> <p>I want to get a list back with all product and category object data in a list. </p> <p>I've read about multipleResults and queryMultiple but can't see how to tie the two together. </p> <p>I know how to do it for a single product but what about all products with their individual category objects as well.</p>
20,712,874
2
0
null
2013-12-20 19:12:39.947 UTC
9
2019-12-12 07:11:00.027 UTC
2019-12-12 07:11:00.027 UTC
null
107,625
null
2,140,565
null
1
26
c#|dapper|multiple-resultsets
17,093
<p>Assume you have your tables like this.</p> <p><strong>Product</strong></p> <pre><code>ID ProductName ProductCategoryID </code></pre> <p><strong>Category</strong></p> <pre><code>ID CategoryName </code></pre> <p>and your classes</p> <pre><code>public class Product { public int ID { set; get; } public string ProductName { set; get; } public int ProductCategoryID {set;get;} public Category Category { set; get; } } public class Category { public int ID { set; get; } public string CategoryName { set; get; } } </code></pre> <p>The below code should work fine for you to load a list of products with associated categories.</p> <pre><code>var conString="Replace your connection string here"; using (var conn = new SqlConnection(conString)) { conn.Open(); string qry = "SELECT P.ID,P.ProductName,P.ProductCategoryID,C.ID, C.CategoryName from Product P INNER JOIN Category C ON P.ProductCategoryID=C.ID"; var products = conn.Query&lt;Product, Category, Product&gt; (qry, (prod, cat) =&gt; { prod.Category = cat; return prod; }); foreach (Product product in products) { //do something with the products now as you like. } conn.Close(); } </code></pre> <p><img src="https://i.stack.imgur.com/A512S.png" alt="enter image description here"> <strong>Note :</strong> <em>Dapper assumes your Id columns are named "Id" or "id", if your primary key is different or you would like to split the wide row at point other than "Id", use the optional 'splitOn' parameter.</em></p>
20,413,995
Reducing on array in OpenMP
<p>I am trying to parallelize the following program, but don't know how to reduce on an array. I know it is not possible to do so, but is there an alternative? Thanks. (I added reduction on m which is wrong but would like to have an advice on how to do it.)</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;omp.h&gt; using namespace std; int main () { int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S [10]; time_t start_time = time(NULL); #pragma omp parallel for private(m) reduction(+:m) for (int n=0 ; n&lt;10 ; ++n ){ for (int m=0; m&lt;=n; ++m){ S[n] += A[m]; } } time_t end_time = time(NULL); cout &lt;&lt; end_time-start_time; return 0; } </code></pre>
20,421,200
5
0
null
2013-12-06 00:57:17.18 UTC
21
2021-10-27 06:47:43.77 UTC
2021-05-10 14:49:17.353 UTC
null
1,366,871
null
2,891,902
null
1
41
c++|multithreading|parallel-processing|openmp|reduction
47,572
<p>Yes it is possible to do an array reduction with OpenMP. In Fortran it even has construct for this. In C/C++ you have to do it yourself. Here are two ways to do it.</p> <p>The first method makes private version of <code>S</code> for each thread, fill them in parallel, and then merges them into <code>S</code> in a critical section (see the code below). The second method makes an array with dimentions 10*nthreads. Fills this array in parallel and then merges it into <code>S</code> without using a critical section. The second method is much more complicated and can have cache issues especially on multi-socket systems if you are not careful. For more details see this <a href="https://stackoverflow.com/questions/16789242/fill-histograms-array-reduction-in-parallel-with-openmp-without-using-a-critic">Fill histograms (array reduction) in parallel with OpenMP without using a critical section</a></p> <p>First method</p> <pre><code>int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S [10] = {0}; #pragma omp parallel { int S_private[10] = {0}; #pragma omp for for (int n=0 ; n&lt;10 ; ++n ) { for (int m=0; m&lt;=n; ++m){ S_private[n] += A[m]; } } #pragma omp critical { for(int n=0; n&lt;10; ++n) { S[n] += S_private[n]; } } } </code></pre> <p>Second method</p> <pre><code>int A [] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S [10] = {0}; int *S_private; #pragma omp parallel { const int nthreads = omp_get_num_threads(); const int ithread = omp_get_thread_num(); #pragma omp single { S_private = new int[10*nthreads]; for(int i=0; i&lt;(10*nthreads); i++) S_private[i] = 0; } #pragma omp for for (int n=0 ; n&lt;10 ; ++n ) { for (int m=0; m&lt;=n; ++m){ S_private[ithread*10+n] += A[m]; } } #pragma omp for for(int i=0; i&lt;10; i++) { for(int t=0; t&lt;nthreads; t++) { S[i] += S_private[10*t + i]; } } } delete[] S_private; </code></pre>
24,024,135
How to create an MKMapRect given two points, each specified with a latitude and longitude value?
<p>I have a custom class that extends <code>NSObject</code> and implements the <code>MKOverlay</code> protocol. As a result, I need to implement the protocol's <code>boundingMapRect</code> property which is an <code>MKMapRect</code>. To create an <code>MKMapRect</code> I can of course use <code>MKMapRectMake</code> to make one. However, I don't know how to create an <code>MKMapRect</code> using that data I have which is two points, each specified by a latitude and longitude. <code>MKMapRectMake</code>'s docs state:</p> <pre><code>MKMapRect MKMapRectMake( double x, double y, double width, double height ); Parameters x The point along the east-west axis of the map projection to use for the origin. y The point along the north-south axis of the map projection to use for the origin. width The width of the rectangle (measured using map points). height The height of the rectangle (measured using map points). Return Value A map rectangle with the specified values. </code></pre> <p>The latitude and longitude values I have to spec out the <code>MKMapRect</code> are:</p> <pre><code>24.7433195, -124.7844079 49.3457868, -66.9513812 </code></pre> <p>The target <code>MKMapRect</code> would therefore need to spec out an area that looks about like this: <img src="https://i.stack.imgur.com/fSxoQ.png" alt="The Target MKMapRect"></p> <p>So, to reiterate, how do I use my lat/lon values to create an <code>MKMapRect</code> that I can set as <code>MKOverlay</code> protocol's <code>@property (nonatomic, readonly) MKMapRect boundingMapRect</code> property?</p>
24,024,388
4
0
null
2014-06-03 20:13:53.98 UTC
7
2019-02-03 22:52:27.98 UTC
2017-08-16 15:26:53.193 UTC
null
3,885,376
null
394,969
null
1
36
ios|mapkit
9,888
<p>This should do it:</p> <pre><code>// these are your two lat/long coordinates CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(lat1,long1); CLLocationCoordinate2D coordinate2 = CLLocationCoordinate2DMake(lat2,long2); // convert them to MKMapPoint MKMapPoint p1 = MKMapPointForCoordinate (coordinate1); MKMapPoint p2 = MKMapPointForCoordinate (coordinate2); // and make a MKMapRect using mins and spans MKMapRect mapRect = MKMapRectMake(fmin(p1.x,p2.x), fmin(p1.y,p2.y), fabs(p1.x-p2.x), fabs(p1.y-p2.y)); </code></pre> <p>this uses the lesser of the two x and y coordinates for your start point, and calculates the x/y spans between the two points for the width and height.</p>
59,387,131
How to change border color of checkbox in flutter / dart
<p>I have a checkbox added to my UI in Flutter app, I can see checkbox color or active color property but can't find any option to change border color of checkbox , which is usually black.</p> <p>Whats the provision or tweak to change the border color ?</p>
59,387,245
7
2
null
2019-12-18 07:15:43.66 UTC
1
2022-01-10 10:47:45.413 UTC
null
null
null
null
939,501
null
1
29
flutter|dart
20,060
<pre><code>Checkbox(value: false, tristate: false, onChanged: () {});   ↓ Theme( data: ThemeData(unselectedWidgetColor: Colors.red), child: Checkbox(value: false, tristate: false, onChanged: (bool value) {})); No onChanged, then the border will be grey(disabled). </code></pre>
66,573,601
Bottom Nav Bar overlaps screen content in Jetpack Compose
<p>I have a <code>BottomNavBar</code> which is called inside the <code>bottomBar</code> of a <code>Scaffold</code>.<br /> Every screen contains a <code>LazyColumn</code> which displays a bunch of images.<br /> For some reason when I finish scrolling, the <code>BottomNavBar</code> overlaps the lower part of the items list.<br /> How can I fix this?</p> <p><a href="https://i.stack.imgur.com/fLfL0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fLfL0.png" alt="enter image description here" /></a></p> <p>Here the set content of MainActivity</p> <pre><code>SetContent{ Scaffold( topBar = { TopAppBar( title = { Text(text = &quot;tartufozon&quot;) }, actions = { IconButton(onClick = { Timber.d(&quot;Mail clicked&quot;) }) { Icon(Icons.Default.Email, contentDescription = null) } } ) }, bottomBar = { BottomNavBar(navController = navController) } ) { BottomNavScreensController(navController = navController) } } </code></pre>
66,574,166
4
0
null
2021-03-10 22:08:35.813 UTC
10
2022-02-16 02:19:57.023 UTC
2021-08-30 18:24:33.927 UTC
null
9,636,037
null
6,945,723
null
1
62
android|android-jetpack|android-jetpack-compose
10,893
<p>As per the <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#scaffold" rel="noreferrer">API definition for Scaffold</a>, your inner content (the trailing lambda you have your <code>BottomNavScreensController</code> in), is given a <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/PaddingValues.html" rel="noreferrer"><code>PaddingValues</code></a> object that gives you the right amount of padding for your top app bar, bottom bar, etc.</p> <p>Right now, you're not referencing that padding at all and hence, your content is <em>not</em> padded in. This is what is causing your overlap.</p> <p>You can add a <code>Box</code> around your <code>BottomNavScreensController</code> to apply the padding, or pass the padding directly into your <code>BottomNavScreensController</code> so that each individual screen can correctly apply the padding; either solution works.</p> <pre><code>Scaffold( topBar = { // }, bottomBar = { // } ) { innerPadding -&gt; // Apply the padding globally to the whole BottomNavScreensController Box(modifier = Modifier.padding(innerPadding)) { BottomNavScreensController(navController = navController) } } } </code></pre>
20,294,015
a value of type "const char *" cannot be assigned to an entity of type "char" C OOP
<p>I am creating a class to calculate a grade for a user in C++ and I am coming across a simple yet annoying problem. I know what the errors means but I don't understand how to fix it and changing to a string actually fixes the issue but this is not what I want to do.</p> <p>here is the error: const char *" cannot be assigned to an entity of type "char</p> <p>Code</p> <pre><code> #include &lt;string&gt; using namespace std; class Gradecalc { public: Gradecalc() { mark = 0; } int getmark() { return mark; } void setmark(int inmark) { mark = inmark; } void calcgrade() { if (mark &gt;=70) { grade = "A"; //**ERROR IS HERE** } } char getgrade() { return grade; } private: int mark; char grade; //VARIABLE IS DECLARED HERE }; </code></pre>
20,294,071
4
0
null
2013-11-29 22:11:50.517 UTC
1
2016-03-03 02:35:09.867 UTC
2013-11-29 22:16:34.35 UTC
null
321,731
null
2,772,682
null
1
10
c++|oop
63,149
<p>C++ has two types of constants consisting of characters - string literals and character literals.</p> <ul> <li>String literals are enclosed in double quotes, and have type of <code>const char *</code></li> <li>Character literals are enclosed in single quotes, and have type <code>char</code>.</li> </ul> <p>String literals allow multiple characters; character literals allow only one character. The two types of literals are not compatible: you need to supply a variable or a constant of a compatible type for the left side of the assignment. Since you declared <code>grade</code> as a <code>char</code>, you need to change the code to use a character literal, like this:</p> <pre><code>grade ='A'; </code></pre>
5,723,036
JQuery Mobile Table
<p>Can anyone point me to any sample or can provide any sample of a Jquery Mobile table please?</p> <p>I've seen the demos on their website and found no tables.</p> <p>I need to be able to create a table that will look good on Mobile / iPad.</p>
6,773,376
3
4
null
2011-04-19 21:39:46.803 UTC
6
2015-12-08 21:47:00.383 UTC
2015-12-08 21:47:00.383 UTC
null
2,411,320
null
683,553
null
1
14
mobile-website|jquery-mobile
50,891
<p><strong>Try this layout instead</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt; &lt;!--first item --&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Heading1&lt;/td&gt; &lt;td&gt;Meaning1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Heading2&lt;/td&gt; &lt;td&gt;Meaning2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Heading3&lt;/td&gt; &lt;td&gt;Meaning3&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/li&gt; &lt;li&gt; &lt;!-- second item --&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Heading1&lt;/td&gt; &lt;td&gt;Meaning1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Heading2&lt;/td&gt; &lt;td&gt;Meaning2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Heading3&lt;/td&gt; &lt;td&gt;Meaning3&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>and the css</strong></p> <pre><code>ul { width: 100%; margin-left: 0px; padding: 0px; } ul li { list-style-type: none; border-bottom: 1px dashed gray; margin-top: 10px; } </code></pre> <p>*fixed small bugs but have to add this to make substantial edit</p>
5,615,273
Is javascript window.location crossbrowser?
<p>Is javascript code window.location functional in all new and old STANDARD POPULAR browsers?</p>
14,544,543
3
5
null
2011-04-10 22:56:36.597 UTC
5
2013-01-27 04:51:35.37 UTC
2012-03-14 16:21:00.097 UTC
null
527,702
null
127,193
null
1
30
javascript|dom|cross-browser|window-object
15,452
<p><code>window.location</code>, which shares the same structure as <code>document.location</code> should be identical between modern browsers for the following properties:</p> <ul> <li><code>hash</code> (<a href="https://stackoverflow.com/questions/1703552/encoding-of-window-location-hash">except in FireFox ~&lt; 16.0 where there was a bug with encoding</a>)</li> <li><code>hostname</code></li> <li><code>href</code></li> <li><code>pathname</code></li> <li><code>port</code></li> <li><code>protocol</code></li> <li><code>search</code></li> <li><code>reload()</code></li> <li><code>replace()</code></li> </ul> <p><strong>Known Differences:</strong></p> <ul> <li>Only Webkit has <code>location.origin</code> at the time of writing.</li> </ul>
6,122,808
Restrictions Between for Date in Hibernate Criteria
<p>Hello I am using hibernate in my example.For bean Table Audit Trial I want to fetch audit trial between a date range with inclusion of upper &amp; lower limits. My code is like below</p> <pre><code>Criteria criteria = session.createCriteria(AuditTrail.class); criteria.add(Restrictions.between("auditDate", sDate, eDate)); </code></pre> <p>My starting date is <code>25/11/2010</code>. and end date is <code>25/05/2011</code>.But it is only giving the result up to <code>24/05/2011</code>.It is not performing inclusive search.Any other way to do this. I am using SQL server.</p>
6,122,906
4
0
null
2011-05-25 10:14:16.773 UTC
4
2019-08-26 06:16:27.357 UTC
2011-05-25 10:21:28.077 UTC
null
621,013
null
489,718
null
1
25
hibernate
83,274
<p>I assume your auditDate is in fact a timestamp. If it's the case, then this is normal, because 25/05/2011 means 25/05/2011 at 0 o'clock (in the morning). So, of course, every row having an audit timestamp in the date 25/05/2011 is after 0 o'clock in the morning. </p> <p>I would add 1 day to your end date, and use <code>auditDate &gt;= sDate and auditDate &lt; eDate</code>. </p> <pre><code>criteria.add(Restrictions.ge("auditDate", sDate)); criteria.add(Restrictions.lt("auditDate", eDate)); </code></pre>
1,598,322
Select * from table1 that does not exist in table2 with conditional
<p>I have 2 tables. One is a table with things that can be learned. There is a JID that desribes each kind of row, and is unique to each row. The second table is a log of things that have been learned (the JID) and also the userid for the person that learned it. I am currently using this to select all of the data for the JID, but only the ones the user has learned based on userid.</p> <pre><code>SELECT * FROM tablelist1 LEFT JOIN tablelog2 ON (tablelist1.JID = tablelog2.JID) AND tablelog2.UID = 'php var' WHERE tablelog2.JID IS NOT NULL </code></pre> <p>I now need to select the rows of things to learn, but only the things the userid has NOT already learned. I am obviously very new to this, bear with me. :) I tried using IS NULL, but while it seems it works, it gives duplicate JID's one being NULL, one being correct.</p>
1,598,330
2
0
null
2009-10-21 01:42:35.687 UTC
9
2017-01-20 08:52:30.95 UTC
2009-10-21 01:43:26.87 UTC
null
135,152
null
192,738
null
1
15
sql|mysql
51,207
<p>Using LEFT JOIN/IS NULL:</p> <pre><code> SELECT t.* FROM TABLE_LIST t LEFT JOIN TABLE_LOG tl ON tl.jid = t.jid WHERE tl.jid IS NULL </code></pre> <p>Using NOT IN:</p> <pre><code>SELECT t.* FROM TABLE_LIST t WHERE t.jid NOT IN (SELECT tl.jid FROM TABLE_LOG tl GROUP BY tl.jid) </code></pre> <p>Using NOT EXISTS:</p> <pre><code>SELECT t.* FROM TABLE_LIST t WHERE NOT EXISTS(SELECT NULL FROM TABLE_LOG tl WHERE tl.jid = t.jid) </code></pre> <p><strong>FYI</strong><br> LEFT JOIN/IS NULL and NOT IN are equivalent in MySQL - they will perform the same, while NOT EXISTS is slower/less efficient. For more details: <a href="http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/" rel="noreferrer">http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/</a></p>
1,687,548
MySQL EXPLAIN: "Using index" vs. "Using index condition"
<p>The <a href="http://dev.mysql.com/doc/refman/5.4/en/using-explain.html" rel="noreferrer">MySQL 5.4 documentation, on Optimizing Queries with EXPLAIN</a>, says this about these Extra remarks:</p> <blockquote> <ul> <li>Using index </li> </ul> <p>The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index. </p> <p>[...]</p> <ul> <li>Using index condition </li> </ul> <p>Tables are read by accessing index tuples and testing them first to determine whether to read full table rows. In this way, index information is used to defer (“push down”) reading full table rows unless it is necessary.</p> </blockquote> <p>Am I missing something, or do these two mean the same thing (i.e. "didn't read the row, index was enough")?</p>
1,687,828
2
0
null
2009-11-06 13:18:45.987 UTC
17
2017-01-07 18:29:45.217 UTC
null
null
null
null
19,746
null
1
43
mysql|optimization
34,594
<p>An example explains it best:</p> <pre><code>SELECT Year, Make --- possibly more fields and/or from extra tables FROM myUsedCarInventory WHERE Make = 'Toyota' AND Year &gt; '2006' Assuming the Available indexes are: CarId VIN Make Make and Year </code></pre> <p>This query would EXPLAIN with 'Using Index' because it doesn't need, <em>at all</em>, to "hit" the myUsedCarInventory table itself since the "Make and Year" index "cover" its need <em>with regards to the elements of the WHERE clause that pertain to that table</em>.</p> <p>Now, imagine, we keep the query the same, but for the addition of a condition on the color</p> <pre><code>... WHERE Make = 'Toyota' AND Year &gt; '2006' AND Color = 'Red' </code></pre> <p>This query would likely EXPLAIN with 'Using Index Condition' (the 'likely', here is for the case that Toyota + year would not be estimated to be selective enough, and the optimizer may decide to just scan the table). This would mean that MySQL would <em>FIRST</em> use the index to resolve the Make + Year, and it would have to lookup the corresponding row in the table as well, <strong><em>only for</em></strong> the rows that satisfy the Make + Year conditions. That's what is sometimes referred as "<a href="https://dev.mysql.com/doc/refman/5.6/en/index-condition-pushdown-optimization.html" rel="noreferrer"><strong>push down optimization</strong></a>".</p>
57,134,259
How to resolve: 'keyWindow' was deprecated in iOS 13.0
<p>I'm using Core Data with Cloud Kit, and have therefore to check the iCloud user status during application startup. In case of problems I want to issue a dialog to the user, and I do it using <code>UIApplication.shared.keyWindow?.rootViewController?.present(...)</code> up to now.</p> <p>In Xcode 11 beta 4, there is now a new deprecation message, telling me:</p> <blockquote> <p>'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes</p> </blockquote> <p>How shall I present the dialog instead?</p>
57,169,802
25
3
null
2019-07-21 14:48:27.877 UTC
55
2022-09-23 03:57:44.213 UTC
2020-10-09 04:42:54.303 UTC
null
2,303,865
null
1,982,755
null
1
294
swift|ios13|uiwindow|uiscene
132,371
<p>This is my solution:</p> <pre><code>let keyWindow = UIApplication.shared.connectedScenes .filter({$0.activationState == .foregroundActive}) .compactMap({$0 as? UIWindowScene}) .first?.windows .filter({$0.isKeyWindow}).first </code></pre> <p>Usage e.g.:</p> <pre><code>keyWindow?.endEditing(true) </code></pre>
53,535,977
Coroutines: runBlocking vs coroutineScope
<p>I was reading <a href="https://kotlinlang.org/docs/reference/coroutines/basics.html" rel="noreferrer">Coroutine Basics</a> trying to understand and learn it.</p> <p>There is a part there with this code:</p> <pre><code>fun main() = runBlocking { // this: CoroutineScope launch { delay(200L) println("Task from runBlocking") } coroutineScope { // Creates a new coroutine scope launch { delay(900L) println("Task from nested launch") } delay(100L) println("Task from coroutine scope") // This line will be printed before nested launch } println("Coroutine scope is over") // This line is not printed until nested launch completes } </code></pre> <p>The output goes like so:</p> <pre><code>Task from coroutine scope Task from runBlocking Task from nested launch Coroutine scope is over </code></pre> <p>My question is why this line:</p> <pre><code> println("Coroutine scope is over") // This line is not printed until nested launch completes </code></pre> <p>is called always last?</p> <p>Shouldn't it be called since the:</p> <pre><code>coroutineScope { // Creates a new coroutine scope .... } </code></pre> <p>is suspended?</p> <p>There is also a note there:</p> <blockquote> <p>The main difference between runBlocking and coroutineScope is that the latter does not block the current thread while waiting for all children to complete.</p> </blockquote> <p>I dont understand how coroutineScope and runBlocking are different here? coroutineScope looks like its blocking since it only gets to the last line when it is done.</p> <p>Can anyone enlighten me here?</p> <p>Thanks in advance.</p>
53,536,713
6
3
null
2018-11-29 09:43:04.607 UTC
39
2022-01-31 06:58:40.697 UTC
2019-03-18 11:01:59.49 UTC
null
1,103,872
null
9,291,997
null
1
94
kotlin|kotlin-coroutines
29,197
<blockquote> <p>I don't understand how coroutineScope and runBlocking are different here? coroutineScope looks like its blocking since it only gets to the last line when it is done.</p> </blockquote> <p>There are two separate worlds: the <em>suspendable</em> world (within a coroutine) and the <em>non-suspendable</em> one. As soon as you enter the body of <code>runBlocking</code>, you are in the suspendable world, where <code>suspend fun</code>s behave like blocking code and you can't get to the next line until the <code>suspend fun</code> returns. <code>coroutineScope</code> is a <code>suspend fun</code> that returns only when all the coroutines inside it are done. Therefore the last line must print at the end.</p> <hr /> <p><em>I copied the above explanation from a comment which seems to have clicked with readers. Here is the original answer:</em></p> <p>From the perspective of the code in the block, your understanding is correct. The difference between <code>runBlocking</code> and <code>coroutineScope</code> happens at a lower level: what's happening to the thread while the coroutine is blocked?</p> <ul> <li><p><code>runBlocking</code> is not a <code>suspend fun</code>. The thread that called it remains inside it until the coroutine is complete.</p> </li> <li><p><code>coroutineScope</code> is a <code>suspend fun</code>. If your coroutine suspends, the <code>coroutineScope</code> function gets suspended as well. This allows the top-level function, a <em>non-suspending</em> function that created the coroutine, to continue executing on the same thread. The thread has &quot;escaped&quot; the <code>coroutineScope</code> block and is ready to do some other work.</p> </li> </ul> <p>In your specific example: when your <code>coroutineScope</code> suspends, control returns to the implementation code inside <code>runBlocking</code>. This code is an event loop that drives all the coroutines you started within it. In your case, there will be some coroutines scheduled to run after a delay. When the time arrives, it will resume the appropriate coroutine, which will run for a short while, suspend, and then control will be again inside <code>runBlocking</code>.</p> <hr /> <p>While the above describes the conceptual similarities, it should also show you that <code>runBlocking</code> is a <em>completely different</em> tool from <code>coroutineScope</code>.</p> <ul> <li><p><code>runBlocking</code> is a low-level construct, to be used only in framework code or self-contained examples like yours. It turns an existing thread into an event loop and creates its coroutine with a <code>Dispatcher</code> that posts resuming coroutines to the event loop's queue.</p> </li> <li><p><code>coroutineScope</code> is a user-facing construct, used to delineate the boundaries of a task that is being parallel-decomposed inside it. You use it to conveniently await on all the <code>async</code> work happening inside it, get the final result, and handle all failures at one central place.</p> </li> </ul>
29,261,218
How to capitalize each word in a string using Swift iOS
<p>Is there a function to capitalize each word in a string or is this a manual process?</p> <p>For e.g. "bob is tall" And I would like "Bob Is Tall"</p> <p>Surely there is something and none of the Swift IOS answers I have found seemed to cover this.</p>
29,261,354
8
2
null
2015-03-25 16:28:14.613 UTC
4
2021-04-28 23:51:39.667 UTC
null
null
null
null
3,750,109
null
1
52
ios|swift
33,389
<p>Are you looking for <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/capitalizedString" rel="noreferrer"><code>capitalizedString</code></a></p> <blockquote> <p><strong>Discussion</strong><br /> A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.</p> </blockquote> <p>and/or <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/capitalizedStringWithLocale:" rel="noreferrer"><code>capitalizedStringWithLocale(_:)</code></a></p> <blockquote> <p>Returns a capitalized representation of the receiver using the specified locale.</p> <p>For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.</p> </blockquote>
5,998,374
if filetype == tex
<p>I want to run a command in the .vimrc in case a file is a latex file. I think I have something with the syntax, it does not work. Any clue?</p> <pre><code>if &amp;filetype=='tex' set spell endif </code></pre>
5,998,392
5
0
null
2011-05-13 22:26:36.41 UTC
6
2020-12-19 08:08:44.087 UTC
2013-04-27 15:45:28.34 UTC
null
497,208
null
497,208
null
1
42
vim|latex
22,589
<p>You can use auto commands to achieve what you want:</p> <pre><code>autocmd BufNewFile,BufRead *.tex set spell </code></pre>
6,313,929
How do I open port 22 in OS X 10.6.7
<p>I am trying to open port 22 on osx so I can connect to localhost using ssh. This is my current situation:</p> <pre><code>ssh localhost ssh: connect to host localhost port 22: Connection refused </code></pre> <p>I have generated a key and tossed it into my authorized_keys file like so:</p> <pre><code>sh-keygen -t dsa -P '' -f ~/.ssh/id_dsa cat ~/.ssh/id_dsa.pub &gt;&gt; ~/.ssh/authorized_keys </code></pre> <p>A "Network Utility" port scan confirms that 22 (and surprisingly 23) are closed.</p> <p>Context: I am working on getting Hadoop set up locally. In my configuration, I am running services on localhost:####s and need to open communications to them via ssh.</p> <p>How can I open 22? or could I be up against another issue (improperly generated key perhaps?)</p>
6,313,937
6
0
null
2011-06-11 03:49:11.557 UTC
31
2021-04-01 04:40:28.897 UTC
2015-04-15 23:46:21.803 UTC
null
3,366,929
null
419,652
null
1
92
macos|ssh|ssh-keys
157,060
<p>I think your port is probably open, but you don't have anything that listens on it. </p> <blockquote> <p>The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.</p> <p>To enable it, go to ‘System Preferences’. Under ‘Internet &amp; Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet &amp; Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)</p> <p>This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application. </p> </blockquote> <p>These instructions are copied from <a href="http://www.bluishcoder.co.nz/articles/mac-ssh.html" rel="noreferrer">Enable SSH in Mac OS X</a>, but I wanted to make sure they won't go away and to provide quick access.</p>
5,751,495
Debugging WebSocket in Google Chrome
<p>Is there a way, or an extension, that lets me watch the "traffic" going through a WebSocket? For debugging purposes I'd like to see the client and server requests/responses.</p>
5,757,171
12
0
null
2011-04-22 01:31:31.167 UTC
76
2022-05-21 16:23:35.42 UTC
null
null
null
null
401,019
null
1
249
google-chrome|websocket
291,506
<p>Chrome developer tools now have the ability to list WebSocket frames and also inspect the data if the frames are not binary.</p> <p>Process:</p> <ol> <li>Launch Chrome Developer tools</li> <li>Load your page and initiate the WebSocket connections</li> <li>Click the <em>Network Tab</em>.</li> <li>Select the <em>WebSocket connection</em> from the list on the left (it will have status of "101 Switching Protocols".</li> <li>Click the <em>Messages</em> sub-tab. Binary frames will show up with a length and time-stamp and indicate whether they are masked. Text frames will show also include the payload content.</li> </ol> <p>If your WebSocket connection uses binary frames then you will probably still want to use Wireshark to debug the connection. <a href="http://www.wireshark.org/docs/relnotes/wireshark-1.8.0.html" rel="noreferrer">Wireshark 1.8.0</a> added dissector and filtering support for WebSockets. An alternative may be found in this <a href="https://stackoverflow.com/questions/3925118/how-to-debug-websockets/3933996#3933996">other answer</a>.</p>
6,163,683
Cycles in family tree software
<p>I am the developer of some family tree software (written in C++ and Qt). I had no problems until one of my customers mailed me a bug report. The problem is that the customer has two children with their own daughter, and, as a result, he can't use my software because of errors.</p> <p>Those errors are the result of my various assertions and invariants about the family graph being processed (for example, after walking a cycle, the program states that X can't be both father and grandfather of Y).</p> <p>How can I resolve those errors without removing all data assertions?</p>
6,198,257
18
16
null
2011-05-28 18:39:28.277 UTC
575
2015-08-13 23:13:46.113 UTC
2015-08-13 23:13:46.113 UTC
null
442,945
null
774,578
null
1
1,590
c++|graph|cycle|assertions|family-tree
279,801
<p>It seems you (and/or your company) have a fundamental misunderstanding of what a family tree is supposed to be. </p> <p>Let me clarify, I also work for a company that has (as one of its products) a family tree in its portfolio, and we have been struggling with similar problems.</p> <p>The problem, in our case, and I assume your case as well, comes from the <a href="http://en.wikipedia.org/wiki/GEDCOM" rel="noreferrer">GEDCOM</a> format that is extremely opinionated about what a family should be. However this format contains some severe misconceptions about what a family tree really looks like.</p> <p>GEDCOM has many issues, such as incompatibility with same sex relations, incest, etc... Which in real life happens more often than you'd imagine (especially when going back in time to the 1700-1800).</p> <p>We have modeled our family tree to what happens in the real world: Events (for example, births, weddings, engagement, unions, deaths, adoptions, etc.). We do not put any restrictions on these, except for logically impossible ones (for example, one can't be one's own parent, relations need two individuals, etc...)</p> <p>The lack of validations gives us a more "real world", simpler and more flexible solution.</p> <p>As for this specific case, I would suggest removing the assertions as they do not hold universally.</p> <p>For displaying issues (that will arise) I would suggest drawing the same node as many times as needed, hinting at the duplication by lighting up all the copies on selecting one of them.</p>
17,845,014
What does the "[^][]" regex mean?
<p>I found it in the following regex:</p> <pre><code>\[(?:[^][]|(?R))*\] </code></pre> <p>It matches square brackets (with their content) together with nested square brackets.</p>
17,845,034
1
0
null
2013-07-24 21:19:59.6 UTC
8
2020-03-05 22:37:29.933 UTC
2014-01-23 09:48:06.693 UTC
null
200,145
null
200,145
null
1
41
php|regex
3,043
<p><code>[^][]</code> is a character class that means all characters except <code>[</code> and <code>]</code>.</p> <p>You can avoid escaping <code>[</code> and <code>]</code> special characters since it is not ambiguous for the PCRE, the regex engine used in <code>preg_</code> functions.</p> <p>Since <code>[^]</code> is incorrect in PCRE, the only way for the regex to parse is that <code>]</code> is inside the character class which will be closed later. The same with the <code>[</code> that follows. It can not reopen a character class (except a POSIX character class <code>[:alnum:]</code>) inside a character class. Then the last <code>]</code> is clear; it is the end of the character class. However, a <code>[</code> outside a character class must be escaped since it is parsed as the beginning of a character class.</p> <p>In the same way, you can write <code>[]]</code> or <code>[[]</code> or <code>[^[]</code> without escaping the <code>[</code> or <code>]</code> in the character class.</p> <p>Note: since PHP 7.3, you can use the inline xx modifier that allows blank characters to be ignored even inside character classes. This way you can write these classes in a less ambigous way like that: <code>(?xx) [^ ][ ] [ ] ] [ [ ] [^ [ ]</code>. </p> <p>You can use this syntax with several regex flavour: PCRE (PHP, R), Perl, Python, Java, .NET, GO, awk, Tcl (<em>if you delimit your pattern with curly brackets, thanks Donal Fellows</em>), ...</p> <p>But not with: Ruby, JavaScript (<em>except for IE &lt; 9</em>), ...</p> <p>As m.buettner noted, <code>[^]]</code> is not ambiguous because <code>]</code> is the <strong>first</strong> character, <code>[^a]]</code> is seen as <em>all that is not a <code>a</code> followed by a <code>]</code></em>. To have <code>a</code> and <code>]</code>, you must write: <code>[^a\]]</code> or <code>[^]a]</code></p> <p>In particular case of JavaScript, the specification allow <code>[]</code> as a regex token that <em>never</em> matches (in other words, <code>[]</code> will always fail) and <code>[^]</code> as a regex that matches <em>any character</em>. Then <code>[^]]</code> is seen as <em>any character followed by a <code>]</code></em>. The actual implementation varies, but modern browser generally sticks to the definition in the specification.</p> <p><strong>Pattern details:</strong></p> <pre><code>\[ # literal [ (?: # open a non capturing group [^][] # a character that is not a ] or a [ | # OR (?R) # the whole pattern (here is the recursion) )* # repeat zero or more time \] # a literal ] </code></pre> <p>In your pattern example, you don't need to escape the last <code>]</code></p> <p>But you can do the same with this pattern a little bit optimized, and more useful cause reusable as subpattern <i>(with the <code>(?-1)</code>)</i>: <code>(\[(?:[^][]+|(?-1))*+])</code></p> <pre><code>( # open the capturing group \[ # a literal [ (?: # open a non-capturing group [^][]+ # all characters but ] or [ one or more time | # OR (?-1) # the last opened capturing group (recursion) # (the capture group where you are) )*+ # repeat the group zero or more time (possessive) ] # literal ] (no need to escape) ) # close the capturing group </code></pre> <p>or better: <code>(\[[^][]*(?:(?-1)[^][]*)*+])</code> that avoids the cost of an alternation.</p>
39,160,807
Default value golang struct using `encoding/json` ?
<p>How to set default value for <code>Encoding</code> as "base64"?</p> <pre><code>type FileData struct { UID string `json:"uid"` Size int `json:"size"` Content string `json:content` Encoding string `json:encoding` User string `json:"user"` } </code></pre> <p>I tried </p> <pre><code>Encoding string `json:encoding`= "base64" // Not working </code></pre>
39,161,250
4
2
null
2016-08-26 07:33:54.297 UTC
5
2021-06-24 11:18:28.857 UTC
null
null
null
null
2,285,490
null
1
14
go
48,285
<p>You can't because in Go types do not have constructors.</p> <p>Instead, have either an explicit initializer function (or method on the pointer receiver) or a constructor/factory function (these are conventionally called <code>New&lt;TypeName&gt;</code> so yours would be <code>NewFileData</code>) which would return an initialized value of your type.</p> <p>All-in-all, I have a feeling this looks like an XY problem. From your question, it appears you want to have a default value on one of your fields if nothing was unmarshaled. If so, just post-process the values of this type unmarshaled from JSON and if nothing was unmarshaled to <code>Encodning</code> set it to whatever default you want.</p> <p>Alternatively you might consider this approach:</p> <ol> <li><p>Have a custom type for your field.</p> <p>Something like <code>type EncodingMethod string</code> should do.</p></li> <li><p>Have a custom JSON unmarshaling method for this type which would do whatever handling it wants.</p></li> </ol>
44,305,953
How to generate RSA public and private keys using Swift 3?
<p>I create the key pairs of public and private using SecKeyGeneratePair.</p> <h1>ViewController</h1> <pre><code>import UIKit import Security class ViewController: UIViewController { @IBOutlet weak var textFld: UITextField! @IBOutlet weak var encryptedTextFld: UITextView! @IBOutlet weak var decryptedTextFld: UITextView! var statusCode: OSStatus? var publicKey: SecKey? var privateKey: SecKey? override func viewDidLoad() { super.viewDidLoad() let publicKeyAttr: [NSObject: NSObject] = [kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.public".data(using: String.Encoding.utf8)! as NSObject] let privateKeyAttr: [NSObject: NSObject] = [kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.private".data(using: String.Encoding.utf8)! as NSObject] var keyPairAttr = [NSObject: NSObject]() keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &amp;publicKey, &amp;privateKey) if statusCode == noErr &amp;&amp; publicKey != nil &amp;&amp; privateKey != nil { print("Key pair generated OK") print("Public Key: \(publicKey!)") print("Private Key: \(privateKey!)") } else { print("Error generating key pair: \(String(describing: statusCode))") } } @IBAction func encryptPressed(_ sender: Any) { } @IBAction func decryptPressed(_ sender: Any) { } </code></pre> <p>Then I got the keys like below</p> <h1>Public Key</h1> <pre><code>&lt;SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: 10001, decimal: 65537}, modulus: B4854E2DA6BA5EBC96C38BD44078D314E4504D130A03018ACD17D0F6679C3B6C9937B5D932A635AEAC32B9245EC400208C1F79932174EF804468D0DCE40DAF5B544CF9E4BCD7C49BA5D0BF3F8246B89B57A3A910CBB5200DCA6145E3EE216CE9C4A3283F1027AA15F7543BD3BEFF35BE24EE709CF8EB12545970AFFDA38CA11410ECA20A8F428D228ED07BF5399A2F55D93D7C143BAFA59A08E4FF932C3A689FA7F3F166B79A43837028319CB383F716B594F317ED6E20D7A8003190A13BC132D5B13708EDAEA3E2012B16CF37437BB617070D9A6DDFE55884A79BD530E4E654B823A8BBBF0AA777C8E46E94BD83E1C59EC6E1D34E69405640C309515243AA8D, addr: 0x608000420e80&gt; </code></pre> <h1>Private Key</h1> <pre><code>&lt;SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x60000003b960&gt; </code></pre> <p>But I don't want to generate like above.</p> <p>I except the keys like below</p> <h1>Public Key</h1> <pre><code>-----BEGIN RSA PUBLIC KEY----- MIIBCgKCAQEA0bipoOhkkvPxcsyOzcqsIUeVe0+iwe8W7N4EbHZMgujRERu1TPpy UcCO0uuKmm1TU09Kl40rRvDbtgB1YcGV3FPnNp3sOyFVsdyZ5bzxZtyyLrSWtj/n bLnGwaG9xJSwd2R/pTQLzOLV5KldwD2eUb3Z4Z4e9Z8II7eWgGaCLLqbrtEAa05N EqARckxrzJ1S3j+59h4AQovF72KI90/kRPryT2OGDiVlJ6CTjn2ZnTYcx65X6Rwf AeJKHZAGhw96j9tXyS+dJcXy4IBUTi3PXw0aEfhHQr/JsSHuMp/8mrhVJEokXb1C gKDZgJXujpGhCBdztHBAJxLBQMlODg7srwIDAQAB -----END RSA PUBLIC KEY----- </code></pre> <h1>Private Key</h1> <pre><code>-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAsfxMagVKY5++61Kot0esyhEOesqyQlZNvWbqMBcOoaOAb3pk LvwaGJ2YtD12u4yDEKcY5rpX7B/2t8GBHf+74NG47zAutf4Gf6qgQRUmIx2b7i4k WBt3KIifb/Zfs9KVJLhD4007bg1OtXA4kIhhXiuvhajDjDLOEthogF45CkJe+N67 JnH5hVW5CqBxPyRCrWCFbEHcXs5H515JV/Kz1+JVrB2/M03fW751wptO2GdGwsde ofqQzY+WUzqUihXigIjAVLFRemky3HpwuhzXUJn6A0ZD4tkk1JLstpSSJdBpH+L2 b9QlOitehxFgRsYmto+idpD1XrS9UyUtmpbTuwIDAQABAoIBAQCYvrAJcJ7lnmtn Ytm96LoF89tcT+Xpfk1bFR43xSHeYAXSJdQiamIu69joHbNuwuib+vsoz5Sy5L+D 9YHMb/MZvoIaa1w6/VUwbQr4r6C6FCgEoP65ymBZnd5OZL6/ASLTj3tbb6VoDe2V UkiI6TG+cnlAmJOxFsy5aZVNTQ9gmCMS0+AdpTbDsxTPg3y0EKFXeVRyKjq0lO9m p3G5yHkFjzWWY6s5XHx27gDTt8eXg/un72Qsz1rh5iUnAoxrga0Oco3Yk9DMvMwz a1I1Lo5fpB6FbTGX3k24heSnLDFEnlBvsBBg0g/n/qgwoZJ81MgG8Q4kAfeScuCI sYVnHEBpAoGBAOpnrKEkyhk1rXG4Md+z1/odhqx89mV7mF1ttW4IhFcwpJSMohsG r27Ic87whkpRxz2Mwj3B5WPGne4UkbvniH46n3jEW7ZIUF+ASVWkjMaGJWtOqSLC I19Snie9WvpREwaCVuvT2l4IeM1WL5gKotBwa3csZgGYH6gcyW5Ipbo/AoGBAMJh /+WXbohF4+A989q0jYjRRhKwUJAYeK8/AePrx8MnAXnRd09TiqeGn0Xig/RNZ0RE 96/TC1dTIBIHk5aDMy3vQhhYF0KbwcQWmCOnGo1qNTTaWTa3UitFMWf0hO0HuZtp RyD1YwhHP0W2tiK2GVjCreqIYASCpYKLq5Qq1K+FAoGARk2h8RLfqn/27UyZaMa/ 2DxS0BkKrZVMNXlaGQ5k4uGr+wHS/NgcddWZJk/tdwzf/Q3ilDM7YZmIdIemzfy7 a2CZw9bgyuMVeA85733S2xgQ0QZepBYmFcjptnGMf9chJaqh90krDVjtImjfDXLj MjEFilC+p2vA0uMPZwxS6HECgYAc5dLUQBoHmlRRTwSEvBjagToopxujAHBYpUZT qwbMpWzbvl89ZM8VLrdY/V7en+89P/+OnRJvjgUTiRrQ4npmVs59rgLvPRamXzGJ A1u4MFTuoZNnxgMqOaQprzlfv6lBSHpxlOl/HpByfcJAENBd2LtgRZv4r6+JY9hD M8bgvQKBgCDTSCLj5c1CYyuJMdrz9L5+xLFmrmL48djhK460ZcmcZ/gP808CyXx/ sDneow+JWt7Jb3p5zyUvvq1aDGNSsn4plB2rg7AqtoHcZYyFFZGI/K/b6JZna1yu FUYOfcanunabxY1wPQxuvR+AEuufBjB0aKg+qkLCCN1HYQtLs+N8 -----END RSA PRIVATE KEY----- </code></pre> <ol> <li>How to convert the keys generated by SecKeyGeneratePair to <code>-----BEGIN RSA PUBLIC KEY----- ................ -----END RSA PUBLIC KEY-----</code> format</li> </ol>
45,931,021
3
1
null
2017-06-01 11:11:13.493 UTC
11
2020-06-02 17:12:18.53 UTC
2017-08-29 03:59:41.97 UTC
null
5,729,421
null
6,130,265
null
1
14
ios|swift|swift3|rsa|public-key
18,197
<p>Please try this : </p> <pre><code>let publicKeyAttr: [NSObject: NSObject] = [ kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.public".data(using: String.Encoding.utf8)! as NSObject, kSecClass: kSecClassKey, // added this value kSecReturnData: kCFBooleanTrue] // added this value let privateKeyAttr: [NSObject: NSObject] = [ kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.private".data(using: String.Encoding.utf8)! as NSObject, kSecClass: kSecClassKey, // added this value kSecReturnData: kCFBooleanTrue] // added this value var keyPairAttr = [NSObject: NSObject]() keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject var publicKey : SecKey? var privateKey : SecKey?; let statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &amp;publicKey, &amp;privateKey) if statusCode == noErr &amp;&amp; publicKey != nil &amp;&amp; privateKey != nil { print("Key pair generated OK") var resultPublicKey: AnyObject? var resultPrivateKey: AnyObject? let statusPublicKey = SecItemCopyMatching(publicKeyAttr as CFDictionary, &amp;resultPublicKey) let statusPrivateKey = SecItemCopyMatching(privateKeyAttr as CFDictionary, &amp;resultPrivateKey) if statusPublicKey == noErr { if let publicKey = resultPublicKey as? Data { print("Public Key: \((publicKey.base64EncodedString()))") } } if statusPrivateKey == noErr { if let privateKey = resultPrivateKey as? Data { print("Private Key: \((privateKey.base64EncodedString()))") } } } else { print("Error generating key pair: \(String(describing: statusCode))") } </code></pre>
5,118,969
current date minus one month crystal report
<p>How to calculate current date(month) minus one month in crystal report?</p>
5,121,251
1
0
null
2011-02-25 15:20:28.107 UTC
1
2017-03-23 20:44:20.82 UTC
2011-02-25 15:22:37.203 UTC
null
110,707
null
616,839
null
1
6
date|crystal-reports
58,416
<p>To subtract one month from the current date use</p> <p><code>DateAdd ("m", -1, CurrentDate)</code></p> <p>If you just want the month number use this</p> <p><code>Month(DateAdd ("m", -1, CurrentDate))</code></p> <p>If you are trying to get the month name use this</p> <p><code>MonthName(Month(DateAdd ("m", -1, CurrentDate)))</code></p>
27,759,084
How to replace negative numbers in Pandas Data Frame by zero
<p>I would like to know if there is someway of replacing all DataFrame negative numbers by zeros?</p>
27,759,140
8
1
null
2015-01-03 20:14:14.083 UTC
24
2022-09-01 23:14:49.797 UTC
2020-03-29 10:06:04.12 UTC
null
202,229
null
4,203,807
null
1
119
python|pandas|dataframe|replace|negative-number
205,733
<p>If all your columns are numeric, you can use boolean indexing:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]}) In [3]: df Out[3]: a b 0 0 -3 1 -1 2 2 2 1 In [4]: df[df &lt; 0] = 0 In [5]: df Out[5]: a b 0 0 0 1 0 2 2 2 1 </code></pre> <hr> <p>For the more general case, <a href="https://stackoverflow.com/a/12726468/1258041">this answer</a> shows the private method <code>_get_numeric_data</code>:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1], 'c': ['foo', 'goo', 'bar']}) In [3]: df Out[3]: a b c 0 0 -3 foo 1 -1 2 goo 2 2 1 bar In [4]: num = df._get_numeric_data() In [5]: num[num &lt; 0] = 0 In [6]: df Out[6]: a b c 0 0 0 foo 1 0 2 goo 2 2 1 bar </code></pre> <hr> <p>With <code>timedelta</code> type, boolean indexing seems to work on separate columns, but not on the whole dataframe. So you can do:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'), ...: 'b': pd.to_timedelta([-3, 2, 1], 'd')}) In [3]: df Out[3]: a b 0 0 days -3 days 1 -1 days 2 days 2 2 days 1 days In [4]: for k, v in df.iteritems(): ...: v[v &lt; 0] = 0 ...: In [5]: df Out[5]: a b 0 0 days 0 days 1 0 days 2 days 2 2 days 1 days </code></pre> <hr> <p><strong>Update:</strong> comparison with a <code>pd.Timedelta</code> works on the whole DataFrame:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'), ...: 'b': pd.to_timedelta([-3, 2, 1], 'd')}) In [3]: df[df &lt; pd.Timedelta(0)] = 0 In [4]: df Out[4]: a b 0 0 days 0 days 1 0 days 2 days 2 2 days 1 days </code></pre>
42,435,446
How to put text outside python plots?
<p>I am plotting two time series and computing varies indices for them.</p> <p>How to write these indices for these plots outside the plot using <code>annotation</code> or <code>text</code> in python?</p> <p>Below is my code</p> <pre><code>import matplotlib.pyplot as plt obs_graph=plt.plot(obs_df['cms'], '-r', label='Observed') plt.legend(loc='best') plt.hold(True) sim_graph=plt.plot(sim_df['cms'], '-g', label="Simulated") plt.legend(loc='best') plt.ylabel('Daily Discharge (m^3/s)') plt.xlabel('Year') plt.title('Observed vs Simulated Daily Discharge') textstr = 'NSE=%.2f\nRMSE=%.2f\n'%(NSE, RMSE) # print textstr plt.text(2000, 2000, textstr, fontsize=14) plt.grid(True) plt.show() </code></pre> <p>I want to print <code>teststr</code> outside the plots. Here is the current plot:</p> <p><img src="https://i.stack.imgur.com/3U10R.png" alt="plot"></p>
42,439,154
3
1
null
2017-02-24 09:49:07.617 UTC
11
2021-02-13 18:42:26.73 UTC
2018-07-13 21:09:31.687 UTC
null
1,079,075
null
6,740,320
null
1
45
python|matplotlib
93,583
<p>It's probably best to define the position in figure coordinates instead of data coordinates as you'd probably not want the text to change its position when changing the data.</p> <p>Using figure coordinates can be done either by specifying the figure transform (<code>fig.transFigure</code>) </p> <pre><code>plt.text(0.02, 0.5, textstr, fontsize=14, transform=plt.gcf().transFigure) </code></pre> <p>or by using the <code>text</code> method of the figure instead of that of the axes.</p> <pre><code>plt.gcf().text(0.02, 0.5, textstr, fontsize=14) </code></pre> <p>In both cases the coordinates to place the text are in figure coordinates, where <code>(0,0)</code> is the bottom left and <code>(1,1)</code> is the top right of the figure.</p> <p>At the end you still may want to provide some extra space for the text to fit next to the axes, using <code>plt.subplots_adjust(left=0.3)</code> or so.</p>
9,292,563
Reset the graphical parameters back to default values without use of dev.off()
<p>Such as margins, orientations and such...</p> <p><code>dev.off()</code> does not work for me. I am often using RStudio, with its inbuilt graphics device. I then have plotting functions, which I want to plot either in the default RStudio graphics device, or if I called <code>X11()</code>, before in a new window.</p> <p>This behaviour doesn't work with <code>dev.off()</code>. If my plotting function always calls <code>dev.off()</code>, it might inadvertently close the <code>X11()</code> window and instead plot in the RStudio device. If I always call <code>dev.off()</code> followed by <code>X11()</code>, it would always plot in a new window, even if I wanted to plot in the RStudio device.</p> <p>Ordinarily that could be solved with <code>getOption("device")</code>, however, that always returns <code>RStudioGD</code>.</p>
9,292,673
6
0
null
2012-02-15 11:32:58.51 UTC
17
2020-05-21 07:52:42.813 UTC
2016-04-18 06:47:43.89 UTC
null
680,068
null
698,504
null
1
58
r|rstudio
133,397
<p>See ?par. The idea is that you save them as they are when you found them, and then restore: </p> <pre><code>old.par &lt;- par(mar = c(0, 0, 0, 0)) ## do plotting stuff with new settings </code></pre> <p>Now restore as they were before we changed <code>mar</code>: </p> <pre><code>par(old.par) </code></pre>
9,053,842
Advanced JavaScript: Why is this function wrapped in parentheses?
<blockquote> <p><strong>Possible Duplicate:</strong> <br/> <a href="https://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript">What is the (function() { } )() construct in JavaScript?</a></p> </blockquote> <p>I came across this bit of JavaScript code, but I have no idea what to make out of it. Why do I get "1" when I run this code? What is this strange little appendix of (1) and why is the function wrapped in parentheses?</p> <pre><code>(function(x){ delete x; return x; })(1); </code></pre>
9,055,017
4
0
null
2012-01-29 14:17:52.343 UTC
60
2017-12-08 17:35:58.62 UTC
2017-12-08 17:32:26.72 UTC
null
63,550
null
393,704
null
1
131
javascript|function|syntax|parentheses|iife
37,843
<p>There are a few things going on here. First is the <a href="http://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="noreferrer">immediately invoked function expression</a> (IIFE) pattern:</p> <pre><code>(function() { // Some code })(); </code></pre> <p>This provides a way to execute some JavaScript code in its own scope. It's usually used so that any variables created within the function won't affect the global scope. You could use this instead:</p> <pre><code>function foo() { // Some code } foo(); </code></pre> <p>But this requires giving a name to the function, which is not always necessary. Using a named function also means at some future point the function could be called again which might not be desirable. By using an anonymous function in this manner you ensure it's only executed once.</p> <p>This syntax is invalid:</p> <pre><code>function() { // Some code }(); </code></pre> <p>Because you have to wrap the function in parentheses in order to make it parse as an expression. More information is here: <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="noreferrer">http://benalman.com/news/2010/11/immediately-invoked-function-expression/</a></p> <p>So to recap quickly on the IIFE pattern:</p> <pre><code>(function() { // Some code })(); </code></pre> <p>Allows 'some code' to be executed immediately, as if it was just written inline, but also within its own scope so as not to affect the global namespace (and thus potentially interfere with or be interfered with by, other scripts).</p> <p>You can pass arguments to your function just as you would a normal function, for example,</p> <pre><code>(function(x) { // Some code })(1); </code></pre> <p>So we're passing the value '1' as the first argument to the function, which receives it as a locally scoped variable, named x.</p> <p>Secondly, you have the guts of the function code itself:</p> <pre><code>delete x; return x; </code></pre> <p>The delete operator will remove properties from objects. It doesn't delete variables. So;</p> <pre><code>var foo = {'bar':4, 'baz':5}; delete foo.bar; console.log(foo); </code></pre> <p>Results in this being logged:</p> <pre><code>{'baz':5} </code></pre> <p>Whereas,</p> <pre><code>var foo = 4; delete foo; console.log(foo); </code></pre> <p>will log the value 4, because foo is a variable not a property and so it can't be deleted.</p> <p>Many people assume that delete can delete variables, because of the way autoglobals work. If you assign to a variable without declaring it first, it will not actually become a variable, but a property on the global object:</p> <pre><code>bar = 4; // Note the lack of 'var'. Bad practice! Don't ever do this! delete bar; console.log(bar); // Error - bar is not defined. </code></pre> <p>This time the delete works, because you're not deleting a variable, but a property on the global object. In effect, the previous snippet is equivalent to this:</p> <pre><code>window.bar = 4; delete window.bar; console.log(window.bar); </code></pre> <p>And now you can see how it's analogous to the foo object example and not the foo variable example.</p>
31,168,135
Call to implicitly-deleted default constructor
<p>I get the error message <em>Call to implicitly-deleted default constructor of 'std::array'</em> when I try to compile my C++ project.</p> <p>Header file cubic_patch.hpp</p> <pre><code>#include &lt;array&gt; class Point3D{ public: Point3D(float, float, float); private: float x,y,z; }; class CubicPatch{ public: CubicPatch(std::array&lt;Point3D, 16&gt;); std::array&lt;CubicPatch*, 2&gt; LeftRightSplit(float, float); std::array&lt;Point3D, 16&gt; cp; CubicPatch *up, *right, *down, *left; }; </code></pre> <p>Source file cubic_patch.cpp</p> <pre><code>#include "cubic_patch.hpp" Point3D::Point3D(float x, float y, float z){ x = x; y = y; z = z; } CubicPatch::CubicPatch(std::array&lt;Point3D, 16&gt; CP){// **Call to implicitly-deleted default constructor of 'std::arraw&lt;Point3D, 16&gt;'** cp = CP; } std::array&lt;CubicPatch*, 2&gt; CubicPatch::LeftRightSplit(float tLeft, float tRight){ std::array&lt;CubicPatch*, 2&gt; newpatch; /* No code for now. */ return newpatch; } </code></pre> <p>Could someone tell me what is the problem here, please ? I found similar topics but not really the same and I didn't understand the explanations given.</p> <p>Thanks.</p>
31,168,241
1
1
null
2015-07-01 17:40:48.833 UTC
2
2015-07-01 18:32:54.777 UTC
null
null
null
null
4,994,952
null
1
23
c++|stdarray
53,308
<p>Two things. Class members are initialized <em>before</em> the body of the constructor, and a default constructor is a constructor with no arguments.</p> <p>Because you didn't tell the compiler how to initialize cp, it tries to call the default constructor for <code>std::array&lt;Point3D, 16&gt;</code>, and there is none, because there is no default constructor for <code>Point3D</code>.</p> <pre><code>CubicPatch::CubicPatch(std::array&lt;Point3D, 16&gt; CP) // cp is attempted to be initialized here! { cp = CP; } </code></pre> <p>You can get around this by simply providing an initializer list with your Constructor definition.</p> <pre><code>CubicPatch::CubicPatch(std::array&lt;Point3D, 16&gt; CP) : cp(CP) {} </code></pre> <p>Also, you might want to have a look at this code.</p> <pre><code>Point3D::Point3D(float x, float y, float z){ x = x; y = y; z = z; } </code></pre> <p><code>x = x</code>, <code>y = y</code>, <code>z = z</code> doesn't make sense. You're assigning a variable to itself. <code>this-&gt;x = x</code> is one option to fix that, but a more c++ style option is to use initializer lists as with <code>cp</code>. They allow you to use the same name for a parameter and a member without the use of <code>this-&gt;x = x</code></p> <pre><code>Point3D::Point3D(float x, float y, float z) : x(x) , y(y) , z(z) {} </code></pre>
31,190,547
Dependency issue trying to install php-mbstring on ec2
<p>I am trying to install <code>yii2</code> on my Amazon Linux AMI instance, it requires the <code>php-mbstring</code> extension to work. </p> <p>When I tried to run <code>sudo yum install php-mbstring</code> it returned this error:</p> <blockquote> <p>Error: php56-common conflicts with php-common-5.3.29-1.8.amzn1.x86_64</p> </blockquote> <pre><code>Loaded plugins: priorities, update-motd, upgrade-helper amzn-main/latest | 2.1 kB 00:00 amzn-updates/latest | 2.3 kB 00:00 2494 packages excluded due to repository priority protections Resolving Dependencies --&gt; Running transaction check ---&gt; Package php-mbstring.x86_64 0:5.3.29-1.8.amzn1 will be installed --&gt; Processing Dependency: php-common(x86-64) = 5.3.29-1.8.amzn1 for package: php-mbstring-5.3.29-1.8.amzn1.x86_64 --&gt; Running transaction check ---&gt; Package php-common.x86_64 0:5.3.29-1.8.amzn1 will be installed --&gt; Processing Conflict: php56-common-5.6.9-1.112.amzn1.x86_64 conflicts php-common &lt; 5.5.22-1.98 --&gt; Finished Dependency Resolution Error: php56-common conflicts with php-common-5.3.29-1.8.amzn1.x86_64 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest </code></pre> <p>Thanks for your time in advance</p>
31,190,798
2
2
null
2015-07-02 16:59:54.217 UTC
6
2017-11-07 22:32:32.347 UTC
2015-11-21 12:49:23.897 UTC
null
5,043,552
null
5,074,672
null
1
34
php|amazon-ec2|dependencies|yii2|mbstring
28,704
<p>It seems you have php 5.6 installed.<br> You need to install <code>mbstring</code> for that particular version of <code>php</code>.</p> <p>Run <code>sudo yum install php56-mbstring</code></p> <p>After that it might be a good idea to restart apache (thanks! <a href="https://stackoverflow.com/users/2333621/hexicle">@hexicle</a>),<br> using <code>sudo service httpd restart</code></p>
30,752,547
What does it mean that a Listener can be replaced with lambda?
<p>I have implemented an <code>AlertDialog</code> with normal negative and positive button click listeners. </p> <p>When I called <code>new DialogInterface.OnClickListener()</code> it was showing me a suggestion saying: <code>Anonymous new DialogInterface.OnClickListener() can be replaced with lambda</code>. I know it's not an error or something big but what exactly is this suggestion and what can I do about it?</p> <pre><code>AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Text", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do something here } }); </code></pre> <p><code>Android Studio V1.2.1.1 compileSdkVersion 22 buildToolsVersion "22.0.0" minSdkVersion 14 targetSdkVersion 22</code></p>
30,752,800
3
2
null
2015-06-10 09:34:59.803 UTC
13
2020-02-04 14:53:34.497 UTC
2019-04-22 19:13:56.767 UTC
null
2,756,409
null
3,475,831
null
1
71
android|lambda|android-alertdialog
61,556
<p>It means that you can shorten up your code.</p> <p>An example of <code>onClickListener()</code> <strong>without</strong> lambda:</p> <pre><code>mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // do something here } }); </code></pre> <p>can be rewritten <strong>with</strong> lambda:</p> <pre><code>mButton.setOnClickListener((View v) -&gt; { // do something here }); </code></pre> <p>It's the same code. This is useful when using a lot of listeners or when writing code without an IDE. For more info, check <a href="https://www.baeldung.com/java-8-lambda-expressions-tips" rel="noreferrer">this</a>.</p> <p>Hope this answers your question.</p>
7,369,445
Is there a Windows equivalent to fdopen for HANDLEs?
<p>In Unix, if you have a file descriptor (e.g. from a socket, pipe, or inherited from your parent process), you can open a buffered I/O <code>FILE*</code> stream on it with <a href="http://linux.die.net/man/3/fdopen"><code>fdopen(3)</code></a>.</p> <p>Is there an equivalent on Windows for <code>HANDLE</code>s? If you have a <code>HANDLE</code> that was inherited from your parent process (different from stdin, stdout, or stderr) or a pipe from <code>CreatePipe</code>, is it possible to get a buffered <code>FILE*</code> stream from it? MSDN does document <a href="http://msdn.microsoft.com/en-us/library/dye30d82%28v=vs.80%29.aspx"><code>_fdopen</code></a>, but that works with integer file descriptors returned by <code>_open</code>, not generic <code>HANDLE</code>s.</p>
7,369,662
2
0
null
2011-09-10 03:36:35.897 UTC
10
2020-09-14 18:21:01.983 UTC
null
null
null
null
9,530
null
1
35
c|winapi|stdio
10,854
<p>Unfortunately, <code>HANDLE</code>s are completely different beasts from <code>FILE*</code>s and file descriptors. The CRT ultimately handles files in terms of <code>HANDLE</code>s and associates those <code>HANDLE</code>s to a file descriptor. Those file descriptors in turn backs the structure pointer by <code>FILE*</code>.</p> <p>Fortunately, there is a section on <a href="http://msdn.microsoft.com/en-US/library/kdfaxaay.aspx" rel="noreferrer">this MSDN page</a> that describes functions that "provide a way to change the representation of the file between a <strong>FILE</strong> structure, a file descriptor, and a Win32 file handle":</p> <blockquote> <ul> <li><code>_fdopen</code>, <code>_wfdopen</code>: Associates a stream with a file that was previously opened for low-level I/O and returns a pointer to the open stream.</li> <li><code>_fileno</code>: Gets the file descriptor associated with a stream.</li> <li><code>_get_osfhandle</code>: Return operating-system file handle associated with existing C run-time file descriptor</li> <li><code>_open_osfhandle</code>: Associates C run-time file descriptor with an existing operating-system file handle.</li> </ul> </blockquote> <p>Looks like what you need is <a href="http://msdn.microsoft.com/en-US/library/bdts1c9x.aspx" rel="noreferrer"><code>_open_osfhandle</code></a> followed by <a href="http://msdn.microsoft.com/en-US/library/dye30d82.aspx" rel="noreferrer"><code>_fdopen</code></a> to obtain a <code>FILE*</code> from a <code>HANDLE</code>.</p> <p>Here's an example involving <code>HANDLE</code>s obtained from <code>CreateFile()</code>. When I tested it, it shows the first 255 characters of the file "test.txt" and appends " --- Hello World! --- " at the end of the file:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;io.h&gt; #include &lt;fcntl.h&gt; #include &lt;cstdio&gt; int main() { HANDLE h = CreateFile("test.txt", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if(h != INVALID_HANDLE_VALUE) { int fd = _open_osfhandle((intptr_t)h, _O_APPEND | _O_RDONLY); if(fd != -1) { FILE* f = _fdopen(fd, "a+"); if(f != 0) { char rbuffer[256]; memset(rbuffer, 0, 256); fread(rbuffer, 1, 255, f); printf("read: %s\n", rbuffer); fseek(f, 0, SEEK_CUR); // Switch from read to write const char* wbuffer = " --- Hello World! --- \n"; fwrite(wbuffer, 1, strlen(wbuffer), f); fclose(f); // Also calls _close() } else { _close(fd); // Also calls CloseHandle() } } else { CloseHandle(h); } } } </code></pre> <p>This should work for pipes as well.</p>
31,654,411
Split string by space and character as delimiter in Oracle with regexp_substr
<p>I'm trying to split a string with regexp_subtr, but i can't make it work.</p> <p>So, first, i have this query</p> <pre><code>select regexp_substr('Helloworld - test!' ,'[[:space:]]-[[:space:]]') from dual </code></pre> <p>which very nicely extracts my delimiter - <em>blank</em>-<em>blank</em></p> <p>But then, when i try to split the string with this option, it just doesn't work. </p> <pre><code>select regexp_substr('Helloworld - test!' ,'[^[[:space:]]-[[:space:]]]+')from dual </code></pre> <p>The query returns nothing.</p> <p>Help will be much appreciated! Thanks</p>
31,656,771
5
4
null
2015-07-27 13:28:20.8 UTC
2
2016-05-06 17:06:18.707 UTC
2015-07-27 13:30:29.52 UTC
null
3,093,319
null
5,160,766
null
1
3
sql|regex|oracle|string-split|regexp-substr
72,091
<p><a href="http://sqlfiddle.com/#!4/6fa6f/2" rel="noreferrer">SQL Fiddle</a></p> <p><strong>Oracle 11g R2 Schema Setup</strong>:</p> <pre><code>CREATE TABLE TEST( str ) AS SELECT 'Hello world - test-test! - test' FROM DUAL UNION ALL SELECT 'Hello world2 - test2 - test-test2' FROM DUAL; </code></pre> <p><strong>Query 1</strong>:</p> <pre><code>SELECT Str, COLUMN_VALUE AS Occurrence, REGEXP_SUBSTR( str ,'(.*?)([[:space:]]-[[:space:]]|$)', 1, COLUMN_VALUE, NULL, 1 ) AS split_value FROM TEST, TABLE( CAST( MULTISET( SELECT LEVEL FROM DUAL CONNECT BY LEVEL &lt; REGEXP_COUNT( str ,'(.*?)([[:space:]]-[[:space:]]|$)' ) ) AS SYS.ODCINUMBERLIST ) ) </code></pre> <p><strong><a href="http://sqlfiddle.com/#!4/6fa6f/2/0" rel="noreferrer">Results</a></strong>:</p> <pre><code>| STR | OCCURRENCE | SPLIT_VALUE | |-----------------------------------|------------|--------------| | Hello world - test-test! - test | 1 | Hello world | | Hello world - test-test! - test | 2 | test-test! | | Hello world - test-test! - test | 3 | test | | Hello world2 - test2 - test-test2 | 1 | Hello world2 | | Hello world2 - test2 - test-test2 | 2 | test2 | | Hello world2 - test2 - test-test2 | 3 | test-test2 | </code></pre>